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

Detailed Description

Integer math functions.

Definition in file math_func.hpp.


Function Documentation

template<typename T >
static T abs ( const T  a  )  [inline, static]
template<typename T >
static T Align ( const T  x,
uint  n 
) [inline, static]

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

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

Definition at line 109 of file math_func.hpp.

Referenced by TarScanner::AddFile(), AlignPtr(), SmallVector< RefitOption, 32 >::Append(), SmallVector< RefitOption, 32 >::Compact(), DrawDirtyBlocks(), MakeBMPImage(), SmallVector< RefitOption, 32 >::Resize(), and ViewportSign::UpdatePosition().

template<typename T >
static T* AlignPtr ( T *  x,
uint  n 
) [inline, static]

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

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

Definition at line 127 of file math_func.hpp.

References Align().

Referenced by Blitter_32bppOptimized::Encode().

static uint Ceil ( uint  a,
uint  b 
) [inline, static]

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

Parameters:
a Numerator
b Denominator
Returns:
a rounded up to the nearest multiple of b.

Definition at line 339 of file math_func.hpp.

References CeilDiv().

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

static uint CeilDiv ( uint  a,
uint  b 
) [inline, static]
static int Clamp ( const int  a,
const int  min,
const int  max 
) [inline, static]

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:
a The value to clamp/truncate.
min The minimum of the interval.
max the 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 175 of file math_func.hpp.

template<typename T >
static T Clamp ( const T  a,
const T  min,
const T  max 
) [inline, static]

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:
a The value to clamp/truncate.
min The minimum of the interval.
max the 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 151 of file math_func.hpp.

Referenced by AfterLoadGame(), AirportChangeInfo(), AmbientSoundEffectCallback(), AnimationBase< IndustryAnimationBase, IndustryTileSpec, Industry, int, GetSimpleIndustryCallback >::AnimateTile(), BridgeChangeInfo(), ChangeIndustryProduction(), ClickChangeDateCheat(), Train::ConsistChanged(), CreateEffectVehicleAbove(), DrawRoadVehEngine(), RefitWindow::DrawWidget(), PerformanceRatingDetailWindow::DrawWidget(), EnsureVisibleCaption(), FreeTypeFontCache::FreeTypeFontCache(), QueryString::GetBoundingRect(), Path::GetCapacityRatio(), Train::GetCurveSpeedLimit(), GetGlobalVariable(), GetNearbyTileInformation(), GetPlatformInfo(), GetRoadVehLength(), GetSavegameFormat(), GetServiceIntervalClamped(), StationScopeResolver::GetVariable(), IndustriesScopeResolver::GetVariable(), VehicleScopeResolver::GetVariable(), AirportScopeResolver::GetVariable(), GfxDoDrawLine(), HandleCrashedAircraft(), IConsoleHistoryNavigate(), IndustryProductionCallback(), InitializeWindowViewport(), MakeBMPImage(), MakePCXImage(), MakePNGImage(), CustomCurrencyWindow::OnClick(), NetworkStartServerWindow::OnClick(), CreateScenarioWindow::OnClick(), GenerateLandscapeWindow::OnClick(), TooltipsWindow::OnInitialPosition(), BuildBridgeWindow::OnInitialPosition(), CustomCurrencyWindow::OnQueryTextFinished(), OrdersWindow::OnQueryTextFinished(), NetworkStartServerWindow::OnQueryTextFinished(), CreateScenarioWindow::OnQueryTextFinished(), GenerateLandscapeWindow::OnQueryTextFinished(), MultiCommodityFlow::PushFlow(), RailTypeChangeInfo(), NetworkUDPSocketHandler::ReceiveNetworkGameInfo(), RecomputePrices(), RelocateAllWindows(), ScrollWindowTo(), SetAircraftPosition(), SetPriceBaseMultiplier(), SetSelectionTilesDirty(), ScriptConfig::SetSetting(), AIConfig::SetSetting(), SetStartingYear(), SmallMapWindow::SetZoomLevel(), TownHouseChangeInfo(), TranslateXYToTileCoord(), Train::UpdateAcceleration(), UpdateCompanyRatingAndValue(), Scrollbar::UpdatePosition(), UpdateViewportPosition(), VpSelectTilesWithMethod(), and Write_ValidateSetting().

static int32 ClampToI32 ( const int64  a  )  [inline, static]

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:
a The 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 215 of file math_func.hpp.

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

static uint16 ClampToU16 ( const uint64  a  )  [inline, static]

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

Parameters:
a The 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 227 of file math_func.hpp.

Referenced by CmdExpandTown(), and TownScopeResolver::GetVariable().

static uint ClampU ( const uint  a,
const uint  min,
const uint  max 
) [inline, static]

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:
a The value to clamp/truncate.
min The minimum of the interval.
max the 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 196 of file math_func.hpp.

Referenced by CalcClosestStationTile(), ChangeIndustryProduction(), ConvertFromOldCompanyManagerFace(), IndustryViewWindow::OnQueryTextFinished(), openttd_main(), and Write_ValidateSetting().

template<typename T >
static T Delta ( const T  a,
const T  b 
) [inline, static]

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

Parameters:
a The first scalar
b The second scalar
Returns:
The absolute difference between the given scalars

Definition at line 244 of file math_func.hpp.

Referenced by DisasterTick_Big_Ufo(), DisasterTick_Big_Ufo_Destroyer(), DisasterTick_Ufo(), DistanceManhattan(), DistanceMax(), DistanceMaxPlusManhattan(), DrawTileSelection(), NPFDistanceTrack(), PlaceTreeAtSameHeight(), TerraformTileHeight(), and VpSelectTilesWithMethod().

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:
a Dividend.
b Divisor.
Returns:
a/b or (a/b)+1.

Definition at line 57 of file math_func.cpp.

References abs().

Referenced by StationViewWindow::BuildCargoList(), and StationViewWindow::EstimateDestinations().

int GreatestCommonDivisor ( int  a,
int  b 
)

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

Parameters:
a First number.
b second number.
Returns:
Greatest common divisor of a and b.

Definition at line 39 of file math_func.cpp.

Referenced by LeastCommonMultiple().

uint32 IntSqrt ( uint32  num  ) 

Compute the integer square root.

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

Definition at line 77 of file math_func.cpp.

Referenced by CanalMaintenanceCost(), RailMaintenanceCost(), RoadMaintenanceCost(), SignalMaintenanceCost(), and StationMaintenanceCost().

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

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:
x The value to check
base The base value of the interval
size The size of the interval
Returns:
True if the value is in the interval, false else.

Definition at line 262 of file math_func.hpp.

Referenced by CmdPlantTree(), OrthogonalTileArea::Contains(), DrawTileSelection(), FindStationsNearby(), FindWindowFromPt(), NWidgetBackground::GetWidgetFromPos(), NWidgetMatrix::GetWidgetFromPos(), NWidgetPIPContainer::GetWidgetFromPos(), NWidgetStacked::GetWidgetFromPos(), NWidgetCore::GetWidgetFromPos(), NWidgetToolbarContainer::GetWidgetFromPos(), NWidgetSmallmapDisplay::GetWidgetFromPos(), NWidgetNewGRFDisplay::GetWidgetFromPos(), NWidgetServerListHeader::GetWidgetFromPos(), NewGRFInspectWindow::HasVariableParameter(), Scrollbar::IsVisible(), MoveBuoysToWaypoints(), TransparenciesWindow::OnClick(), and IndustryViewWindow::OnClick().

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

Checks if a value is in an interval.

Returns true if a value is in the interval of [min, max).

Parameters:
x The value to check
min The minimum of the interval
max The maximum of the interval
See also:
IsInsideBS()

Definition at line 278 of file math_func.hpp.

Referenced by AddChildSpriteToFoundation(), AddDateIntroducedRailTypes(), AfterLoadGame(), AllocateMap(), CmdPlantTree(), CmdRemoveLongRoad(), RoadVehicle::Crash(), DeleteLastRoadVeh(), GoalListWindow::DrawPartialGoalList(), SmallMapWindow::DrawVehicles(), SubsidyListWindow::DrawWidget(), BuildRoadStationWindow::DrawWidget(), BuildRoadDepotWindow::DrawWidget(), BuildRailDepotWindow::DrawWidget(), BuildSignalWindow::DrawWidget(), LinkGraphLegendWindow::DrawWidget(), PerformanceRatingDetailWindow::DrawWidget(), GraphLegendWindow::DrawWidget(), Extract(), MissingGlyphSearcher::FindMissingGlyphs(), FormatString(), GenerateCompanyName(), QueryString::GetCharAtPosition(), Layouter::GetCharAtPosition(), GetClosestWaterDistance(), GetFiosItem(), GetHalftileFoundationCorner(), IConsoleWindow::GetTextCharacterAtPosition(), IsNonContinuousFoundation(), IsPtInWindowViewport(), IsSpecialRailFoundation(), IsValidCorner(), LoadOldVehicle(), TownAuthorityWindow::OnClick(), ScenarioEditorLandscapeGenerationWindow::OnClick(), NewGRFParametersWindow::OnClick(), MusicTrackSelectionWindow::OnClick(), LinkGraphLegendWindow::OnClick(), SelectGameWindow::OnClick(), IndustryViewWindow::OnClick(), PerformanceRatingDetailWindow::OnClick(), GraphLegendWindow::OnClick(), CheatWindow::OnClick(), AIDebugWindow::OnClick(), AISettingsWindow::OnClick(), NetworkClientListWindow::OnMouseOver(), SmallMapWindow::OnMouseWheel(), Vehicle::PreDestructor(), RemapOldStringID(), SkipGarbage(), StartupEngines(), SwitchNewGRFBlitter(), TTDPStringIDToOTTDStringIDMapping(), Vehicle::UpdateVisualEffect(), BuildSignalWindow::UpdateWidgetSize(), and LinkGraphLegendWindow::UpdateWidgetSize().

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:
a First number.
b second 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 24 of file math_func.cpp.

References GreatestCommonDivisor().

Referenced by NWidgetVertical::SetupSmallestSize(), NWidgetHorizontal::SetupSmallestSize(), NWidgetStacked::SetupSmallestSize(), and NWidgetNewGRFDisplay::SetupSmallestSize().

template<typename T >
static T max ( const T  a,
const T  b 
) [inline, static]

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:
a The first value
b The second value
Returns:
The greater value or a if equals

Definition at line 38 of file math_func.hpp.

Referenced by OrthogonalTileArea::Add(), AddKey(), LinkGraph::AddNode(), AddSortableSpriteToDraw(), LinkGraphOverlay::AddStats(), AircraftController(), NWidgetVertical::AssignSizePosition(), NWidgetHorizontal::AssignSizePosition(), NWidgetToolbarContainer::AssignSizePosition(), NWidgetSmallmapDisplay::AssignSizePosition(), NWidgetNewGRFDisplay::AssignSizePosition(), CalcEngineReliability(), CalcHeightdiff(), CalcPercentVehicleFilled(), CalculateCompanyValue(), CanExpandRailStation(), ChangeIndustryProduction(), ChangeOwnershipOfCompanyItems(), CheckBridgeAvailability(), CheckClickOnVehicle(), CheckIfFarEnoughFromConflictingIndustry(), GraphicsSet::CheckMD5(), CheckTrainsLengths(), CmdDecreaseLoan(), CmdTerraformLand(), CommonRaiseLowerBigLand(), IndustryCargoesWindow::ComputeCargoDisplay(), VehicleGroupWindow::ComputeGroupInfoSize(), IndustryCargoesWindow::ComputeIndustryDisplay(), ConvertFromOldCompanyManagerFace(), SimplePool< Titem, Tindex, Tgrowth_step, Tmax_size >::Create(), DEFINE_POOL_METHOD(), DeleteOrder(), DistanceMax(), GroundVehicle< RoadVehicle, VEH_ROAD >::DoUpdateSpeed(), StoryBookWindow::DrawActionElement(), DrawBridgePillars(), DrawButtonDropdown(), DrawCaption(), LinkGraphOverlay::DrawContent(), BaseGraphWindow::DrawGraph(), DrawLabel(), Blitter::DrawLine(), SmallMapWindow::DrawSmallMapColumn(), DrawString(), DrawText(), DrawTrainDetails(), DepotWindow::DrawVehicleInDepot(), BaseVehicleListWindow::DrawVehicleListItems(), DrawVehicleRefitWindow(), VehicleViewWindow::DrawWidget(), RefitWindow::DrawWidget(), CompanyStationsWindow::DrawWidget(), OrdersWindow::DrawWidget(), ScanProgressWindow::DrawWidget(), SpriteAlignerWindow::DrawWidget(), NetworkGameWindow::DrawWidget(), VehicleGroupWindow::DrawWidget(), AsymmetricScaler::EffectiveSupply(), SymmetricScaler::EffectiveSupply(), Blitter_32bppSimple::Encode(), Blitter_32bppOptimized::Encode(), EnginePowerVsRunningCostSorter(), FindStationsNearby(), Window::FindWindowPlacementAndResize(), GamelogInfo(), GroundVehicle< T, Type >::GetAcceleration(), GetAcceptanceAroundTiles(), NWidgetMainToolbarContainer::GetButtonArrangement(), Path::GetCapacityRatio(), ExpensesList::GetCategoriesWidth(), Train::GetCurrentMaxSpeed(), GetDigitWidth(), GetGlobalVariable(), FreeTypeFontCache::GetGlyph(), FallbackParagraphLayout::FallbackLine::GetLeading(), SettingsPage::GetMaxHelpHeight(), SmallMapWindow::GetNumberRowsLegend(), GetOrderDistance(), GetProductionAroundTiles(), EndGameHighScoreBaseWindow::GetTopLeft640x480(), GetTrainDetailsWndVScroll(), BaseGraphWindow::GetValuesInterval(), GetVehicleListHeight(), GfxBlitter(), GfxDoDrawLine(), Vehicle::HandleLoading(), HandleScrollbarScrolling(), HeightMapCoastLines(), HighlightDragPosition(), IndustryProductionCallback(), IsCloseToTown(), LinkGraph::EdgeWrapper< BaseEdge >::LastUpdate(), IniLoadFile::LoadFromDisk(), LoadOldVehicle(), LoadUnloadVehicle(), LocalGetWindowPlacement(), MakeNWidget(), MakeWindowNWidgetTree(), MarkViewportDirty(), maxdim(), NetworkDrawChatMessage(), NetworkUndrawChatMessage(), NewGRFDisplay(), BuildRailStationWindow::OnClick(), IndustryViewWindow::OnClick(), AIConfigWindow::OnClick(), IConsoleWindow::OnHundredthTick(), CompanyFinancesWindow::OnHundredthTick(), SmallMapWindow::OnInit(), IndustryCargoesWindow::OnInit(), SelectCompanyManagerFaceWindow::OnInit(), RefitWindow::OnInvalidateData(), RefitWindow::OnPaint(), DepotWindow::OnPaint(), BuildVehicleWindow::OnPaint(), ReplaceVehicleWindow::OnPaint(), AIDebugWindow::OnPaint(), NewsWindow::OnTick(), DiagonalTileIterator::operator++(), ParseResolution(), GroundVehicle< T, Type >::PowerChanged(), ProcessConditionalOrder(), RailClearCost(), RailConvertCost(), ReadRecolourSprite(), Station::RecomputeIndustriesNear(), Window::ReInit(), RemapNewGRFStringControlCode(), ResizeWindow(), VehicleResolverObject::ResolveReal(), SanitizeSpriteOffset(), LinkGraph::Scale(), FlowStat::ScaleToMonthly(), Scrollbar::SetCapacity(), AsymmetricScaler::SetDemandPerNode(), SymmetricScaler::SetDemandPerNode(), SymmetricScaler::SetDemands(), SetDParamMaxValue(), SetSnowLine(), TextfileWindow::SetupScrollbars(), NWidgetLeaf::SetupSmallestSize(), NWidgetBackground::SetupSmallestSize(), NWidgetVertical::SetupSmallestSize(), NWidgetHorizontal::SetupSmallestSize(), NWidgetStacked::SetupSmallestSize(), NWidgetToolbarContainer::SetupSmallestSize(), NWidgetSmallmapDisplay::SetupSmallestSize(), NWidgetNewGRFDisplay::SetupSmallestSize(), NWidgetServerListHeader::SetupSmallestSize(), NewsWindow::SetWindowTop(), SetYearEngineAgingStops(), ShowDropDownListAt(), CompanyStationsWindow::StationRatingMaxSorter(), TranslateXYToTileCoord(), IndustryBuildData::TryBuildNewIndustry(), LinkGraph::Edge::Update(), UpdateAircraftSpeed(), UpdateCompanyRatingAndValue(), Scrollbar::UpdatePosition(), BaseGraphWindow::UpdateStatistics(), UpdateVehicleTimetable(), VehicleViewWindow::UpdateWidgetSize(), VehicleDetailsWindow::UpdateWidgetSize(), TownDirectoryWindow::UpdateWidgetSize(), TownAuthorityWindow::UpdateWidgetSize(), ScenarioEditorToolbarWindow::UpdateWidgetSize(), TimetableWindow::UpdateWidgetSize(), StationViewWindow::UpdateWidgetSize(), GameSettingsWindow::UpdateWidgetSize(), GameOptionsWindow::UpdateWidgetSize(), BuildSignalWindow::UpdateWidgetSize(), BuildRailStationWindow::UpdateWidgetSize(), BuildObjectWindow::UpdateWidgetSize(), MessageHistoryWindow::UpdateWidgetSize(), ScanProgressWindow::UpdateWidgetSize(), SpriteAlignerWindow::UpdateWidgetSize(), NewGRFInspectWindow::UpdateWidgetSize(), NetworkJoinStatusWindow::UpdateWidgetSize(), NetworkClientListWindow::UpdateWidgetSize(), MusicTrackSelectionWindow::UpdateWidgetSize(), AboutWindow::UpdateWidgetSize(), LandInfoWindow::UpdateWidgetSize(), IndustryCargoesWindow::UpdateWidgetSize(), VehicleGroupWindow::UpdateWidgetSize(), PerformanceRatingDetailWindow::UpdateWidgetSize(), CompanyLeagueWindow::UpdateWidgetSize(), BaseGraphWindow::UpdateWidgetSize(), GenerateProgressWindow::UpdateWidgetSize(), CompanyWindow::UpdateWidgetSize(), CompanyInfrastructureWindow::UpdateWidgetSize(), SelectCompanyLiveryWindow::UpdateWidgetSize(), CompanyFinancesWindow::UpdateWidgetSize(), CheatWindow::UpdateWidgetSize(), BuildBridgeWindow::UpdateWidgetSize(), BuildAirportWindow::UpdateWidgetSize(), and VehicleUpdateViewport().

template<typename T >
static T min ( const T  a,
const T  b 
) [inline, static]

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:
a The first value
b The second value
Returns:
The smaller value or b if equals

Definition at line 54 of file math_func.hpp.

Referenced by OrthogonalTileArea::Add(), OutputBuffer::Add(), Path::AddFlow(), AddSortableSpriteToDraw(), AfterLoadGame(), AircraftController(), ApplyNoise(), NWidgetNewGRFDisplay::AssignSizePosition(), DemandCalculator::CalcDemand(), CalcGRFMD5Sum(), CHashTableT< Titem_, Thash_bits_open_ >::CalcHash(), CanExpandRailStation(), ChangeGRFNumUsedParams(), ChangeGRFParamMask(), ChangeIndustryProduction(), CheckBridgeAvailability(), CheckCargoCapacity(), CheckEngines(), CheckIfFarEnoughFromConflictingIndustry(), MD5File::CheckMD5(), ChopLumberMillTrees(), OrthogonalTileArea::ClampToMap(), CmdBuildRailStation(), CmdDecreaseLoan(), CmdGiveMoney(), CmdTerraformLand(), CommonRaiseLowerBigLand(), Train::ConsistChanged(), DecodeSingleSprite(), DeliverGoodsToIndustry(), SimplePool< Titem, Tindex, Tgrowth_step, Tmax_size >::Destroy(), DispatchLeftClickEvent(), DistanceFromEdge(), DoCreateNewIndustry(), GroundVehicle< RoadVehicle, VEH_ROAD >::DoUpdateSpeed(), ClientNetworkContentSocketHandler::DownloadSelectedContentFallback(), DrawCargoIcons(), LinkGraphOverlay::DrawContent(), SmallMapWindow::DrawSmallMap(), LinkGraphOverlay::DrawStationDots(), BaseVehicleListWindow::DrawVehicleListItems(), CompanyStationsWindow::DrawWidget(), OrdersWindow::DrawWidget(), BuildObjectWindow::DrawWidget(), NetworkGameWindow::DrawWidget(), VehicleGroupWindow::DrawWidget(), DepotWindow::DrawWidget(), CompanyFinancesWindow::DrawWidget(), BuildVehicleWindow::DrawWidget(), ReplaceVehicleWindow::DrawWidget(), ExtractTar(), MCF1stPass::FindCycleFlow(), FindStationsNearby(), Window::FindWindowPlacementAndResize(), FioSkipBytes(), FixTTOEngines(), MemoryDumper::Flush(), Path::Fork(), FormatString(), FreeTypeFontCache::FreeTypeFontCache(), GenerateTowns(), GroundVehicle< T, Type >::GetAcceleration(), GetAcceptanceAroundTiles(), GetAircraftFlyingAltitude(), TileMatrix< uint32, 4 >::GetAreaForTile(), QueryString::GetBoundingRect(), QueryString::GetCaretPosition(), IConsoleWindow::GetCaretPosition(), QueryString::GetCharAtPosition(), GetClosestObject(), GetCountAndDistanceOfClosestInstance(), Train::GetCurrentMaxSpeed(), Ship::GetCurrentMaxSpeed(), RoadVehicle::GetCurrentMaxSpeed(), GetMinimalAirportDistanceToTile(), GetNewEngine(), GetNumberOfIndustries(), GetOtherAqueductEnd(), GetPCPElevation(), GetPlatformInfo(), GetProductionAroundTiles(), IConsoleWindow::GetTextBoundingRect(), IConsoleWindow::GetTextCharacterAtPosition(), GetTileSlope(), GetTileZ(), GetTrainSpriteSize(), BaseGraphWindow::GetValuesInterval(), ObjectScopeResolver::GetVariable(), IndustriesScopeResolver::GetVariable(), HandleScrollbarScrolling(), HeightMapCoastLines(), HeightMapGenerate(), HeightMapSmoothCoastInDirection(), HeightMapSmoothSlopes(), HighlightDragPosition(), IncreaseStats(), IndustryDailyLoop(), CapacityAnnotation::IsBetter(), IsCloseToTown(), LargeWorldCallback(), StationCargoList::Load(), LoadUnloadVehicle(), CrashLogWindows::LogModules(), MakeBMPImage(), MakePCXImage(), MakePNGImage(), IndustryBuildData::MonthlyLoop(), NetworkDrawChatMessage(), NetworkServer_Tick(), NetworkUndrawChatMessage(), NPFDistanceTrack(), GameSettingsWindow::OnClick(), BuildRailStationWindow::OnClick(), AIConfigWindow::OnClick(), TooltipsWindow::OnInitialPosition(), AIListWindow::OnInvalidateData(), NetworkGameWindow::OnKeyPress(), GoalListWindow::OnPaint(), CustomCurrencyWindow::OnQueryTextFinished(), DiagonalTileIterator::operator++(), CYapfDestinationTileRoadT< Types >::PfCalcEstimate(), CYapfDestinationTileOrStationRailT< Types >::PfCalcEstimate(), CYapfDestinationTileT< Types >::PfCalcEstimate(), PlaceTree(), GroundVehicle< T, Type >::PowerChanged(), RailConvertCost(), VehicleCargoList::Reassign(), NetworkHTTPSocketHandler::Receive(), ServerNetworkUDPSocketHandler::Receive_CLIENT_GET_NEWGRFS(), Industry::RecomputeProductionMultipliers(), RefitVehicle(), RelocateAllWindows(), ClientNetworkContentSocketHandler::RequestContentList(), VehicleCargoList::Reroute(), PacketReader::Reset(), SmallMatrix< BaseEdge >::Resize(), StationResolverObject::ResolveReal(), VehicleResolverObject::ResolveReal(), VehicleCargoList::Return(), SaveToHighScore(), BuildObjectWindow::SelectOtherObject(), ServerNetworkAdminSocketHandler::SendCompanyEconomy(), SetSnowLine(), NWidgetSmallmapDisplay::SetupSmallestSize(), NewsWindow::SetWindowTop(), VehicleCargoList::Shift(), Vehicle::ShowVisualEffect(), SlCalcNetStringLen(), SoundDriver_Win32::Start(), StartupEngines(), CompanyStationsWindow::StationRatingMinSorter(), TileLoopClearAlps(), TownHouseChangeInfo(), TransferCargo(), TriggerIndustryProduction(), StationCargoList::Truncate(), VehicleCargoList::Truncate(), IndustryBuildData::TryBuildNewIndustry(), VehicleCargoList::Unload(), UpdateAircraftSpeed(), UpdateCompanyRatingAndValue(), UpdateIndustryStatistics(), UpdateLandscapingLimits(), BaseGraphWindow::UpdateStatistics(), UpdateTownGrowRate(), TooltipsWindow::UpdateWidgetSize(), LandInfoWindow::UpdateWidgetSize(), VehicleUpdateViewport(), vseprintf(), PacketWriter::Write(), and Write_ValidateSetting().

static int min ( const int  a,
const int  b 
) [inline, static]

Returns the minimum of two integer.

This function returns the smaller value of two given integers.

Parameters:
a The first integer
b The second integer
Returns:
The smaller value

Definition at line 68 of file math_func.hpp.

static uint minu ( const uint  a,
const uint  b 
) [inline, static]

Returns the minimum of two unsigned integers.

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

Parameters:
a The first unsigned integer
b The second unsigned integer
Returns:
The smaller value

Definition at line 82 of file math_func.hpp.

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

static int RoundDivSU ( int  a,
uint  b 
) [inline, static]

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

Parameters:
a Numerator
b Denominator
Returns:
Quotient, rounded to nearest

Definition at line 350 of file math_func.hpp.

Referenced by IndustryViewWindow::DrawInfo(), DrawLayoutLine(), DrawStringMultiLine(), ScenarioEditorLandscapeGenerationWindow::DrawWidget(), IndustryViewWindow::OnClick(), and IndustryViewWindow::OnQueryTextFinished().

template<typename T >
static void Swap ( T &  a,
T &  b 
) [inline, static]
static uint ToPercent16 ( uint  i  )  [inline, static]

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

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

Definition at line 312 of file math_func.hpp.

Referenced by DrawVehiclePurchaseInfo(), VehicleDetailsWindow::DrawWidget(), and ProcessConditionalOrder().

static uint ToPercent8 ( uint  i  )  [inline, static]

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

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

Definition at line 301 of file math_func.hpp.

Referenced by StationViewWindow::DrawCargoRatings(), IndustryViewWindow::DrawInfo(), IndustryDirectoryWindow::GetCargoTransportedPercentsIfValid(), and IndustryDirectoryWindow::GetIndustryString().