OpenTTD: src/core/math_func.hpp File Reference

OpenTTD

- Main Page
- Related Pages
- Modules
- Namespaces
- Data Structures
- Files

- File List
- Globals

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 | ) |
| inlinestatic

Returns the absolute value of (scalar) variable.

Note
  assumes variable to be signed

Parameters

  a | The value we want to unsign

Returns
  The unsigned value

Definition at line 83 of file math_func.hpp.

Referenced by AircraftController(), AircraftGetEntryPoint(), CalcRaildirsDrawstyle(), ChangeIndustryProduction(), CheckClickOnVehicle(), RoadStop::Entry::CheckIntegrity(), CheckTrainsLengths(), RoadStop::ClearDriveThrough(), DeterminePluralForm(), DivideApprox(), LinkGraphOverlay::DrawContent(), BaseGraphWindow::DrawGraph(), TimetableWindow::DrawWidget(), EnumCheckRoadVehCrashTrain(), FindTrainCollideEnum(), FreeTypeFontCache::FreeTypeFontCache(), GamelogPrint(), GetTunnelBridgeLength(), BaseGraphWindow::GetValuesInterval(), GfxDoDrawLine(), HandleMouseEvents(), HandleWindowDragging(), HeightMapCoastLines(), RoadStop::MakeDriveThrough(), OverflowSafeInt< int64, INT64_MAX, INT64_MIN >::operator*=(), DiagonalTileIterator::operator++(), OverflowSafeInt< int64, INT64_MAX, INT64_MIN >::operator+=(), CYapfDestinationTileT< Types >::PfCalcEstimate(), CYapfDestinationTileOrStationRailT< Types >::PfCalcEstimate(), CYapfDestinationTileRoadT< Types >::PfCalcEstimate(), PlaceTreeAtSameHeight(), PlaceTreeGroups(), RoadStop::Entry::Rebuild(), ReportNewsProductionChangeIndustry(), SettingEntry::SetValueDParams(), TerraformTileHeight(), TownHouseChangeInfo(), and VpSelectTilesWithMethod().

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

  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 97 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
| ) |  |
| 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

  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 115 of file math_func.hpp.

References Align().

Referenced by Blitter_32bppOptimized::Encode().

static uint Ceil | ( | uint | a,
|  | uint | b
| ) |  |
| inlinestatic

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 327 of file math_func.hpp.

References CeilDiv().

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

static uint CeilDiv | ( | uint | a,
|  | uint | b
| ) |  |
| inlinestatic

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

Parameters

  a | Numerator
  b | Denominator

Returns
  Quotient, rounded up

Definition at line 316 of file math_func.hpp.

Referenced by AfterLoadGame(), AircraftController(), NWidgetMatrix::AssignSizePosition(), BuildLandLegend(), CalcPercentVehicleFilled(), CalcRaildirsDrawstyle(), Ceil(), IndustryCargoesWindow::ComputeCargoDisplay(), IndustryCargoesWindow::ComputeIndustryDisplay(), StationViewWindow::DrawAcceptedCargo(), StationViewWindow::DrawCargoRatings(), DepotWindow::DrawVehicleInDepot(), GetLoadAmount(), SmallMapWindow::GetNumberRowsLegend(), GfxDoDrawLine(), DepotWindow::OnPaint(), Industry::RecomputeProductionMultipliers(), ReplaceChain(), ScaleByMapSize(), ScaleByMapSize1D(), ServerNetworkAdminSocketHandler::SendCompanyInfo(), ServerNetworkAdminSocketHandler::SendCompanyUpdate(), NWidgetMatrix::SetCount(), TranslateXYToTileCoord(), and UpdateVehicleTimetable().

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

  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 139 of file math_func.hpp.

References max(), and min().

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

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

  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 163 of file math_func.hpp.

References max(), and min().

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

  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 203 of file math_func.hpp.

Referenced by EngineCostSorter(), EnginePowerVsRunningCostSorter(), EngineRunningCostSorter(), GroundVehicle< T, Type >::GetAcceleration(), HandleBankruptcyTakeover(), ParseIntList(), UpdateCompanyRatingAndValue(), VehicleProfitLastYearSorter(), VehicleProfitThisYearSorter(), VehicleTimeToLiveSorter(), and VehicleValueSorter().

static uint16 ClampToU16 | ( | const uint64 | a | ) |
| inlinestatic

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

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

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

  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 184 of file math_func.hpp.

References max(), and min().

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

template<typename T >

static T Delta | ( | const T | a,
|  | const T | b
| ) |  |
| inlinestatic

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 232 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 59 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 41 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 79 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
| ) |  |
| 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

  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 250 of file math_func.hpp.

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

template<typename T >

static bool IsInsideMM | ( | const T | x,
|  | const uint | min,
|  | const uint | max
| ) |  |
| inlinestatic

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 266 of file math_func.hpp.

References min().

Referenced by AddChildSpriteToFoundation(), AddDateIntroducedRailTypes(), AfterLoadGame(), AllocateMap(), CmdPlantTree(), CmdRemoveLongRoad(), RoadVehicle::Crash(), DeleteLastRoadVeh(), GoalListWindow::DrawPartialGoalList(), SmallMapWindow::DrawVehicles(), GraphLegendWindow::DrawWidget(), LinkGraphLegendWindow::DrawWidget(), SubsidyListWindow::DrawWidget(), BuildRoadDepotWindow::DrawWidget(), BuildRoadStationWindow::DrawWidget(), PerformanceRatingDetailWindow::DrawWidget(), BuildSignalWindow::DrawWidget(), BuildRailDepotWindow::DrawWidget(), Extract(), FileList::FindItem(), MissingGlyphSearcher::FindMissingGlyphs(), FormatString(), GenerateCompanyName(), QueryString::GetCharAtPosition(), Layouter::GetCharAtPosition(), GetClosestWaterDistance(), GetHalftileFoundationCorner(), IConsoleWindow::GetTextCharacterAtPosition(), IsNonContinuousFoundation(), IsPtInWindowViewport(), IsSpecialRailFoundation(), IsValidCorner(), LoadOldVehicle(), MapGRFStringID(), GraphLegendWindow::OnClick(), LinkGraphLegendWindow::OnClick(), SelectGameWindow::OnClick(), TownAuthorityWindow::OnClick(), NewGRFParametersWindow::OnClick(), CheatWindow::OnClick(), MusicTrackSelectionWindow::OnClick(), AISettingsWindow::OnClick(), ScenarioEditorLandscapeGenerationWindow::OnClick(), IndustryViewWindow::OnClick(), AIDebugWindow::OnClick(), PerformanceRatingDetailWindow::OnClick(), NetworkClientListWindow::OnMouseOver(), SmallMapWindow::OnMouseWheel(), Vehicle::PreDestructor(), RemapOldStringID(), SkipGarbage(), SwitchNewGRFBlitter(), TTDPStringIDToOTTDStringIDMapping(), Vehicle::UpdateVisualEffect(), LinkGraphLegendWindow::UpdateWidgetSize(), BuildRoadDepotWindow::UpdateWidgetSize(), BuildRoadStationWindow::UpdateWidgetSize(), BuildSignalWindow::UpdateWidgetSize(), and BuildRailDepotWindow::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 26 of file math_func.cpp.

References GreatestCommonDivisor().

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

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

  a | The first value
  b | The second value

Returns
  The greater value or a if equals

Definition at line 26 of file math_func.hpp.

Referenced by OrthogonalTileArea::Add(), AddKey(), LinkGraph::AddNode(), AddSortableSpriteToDraw(), LinkGraphOverlay::AddStats(), AircraftController(), NWidgetHorizontal::AssignSizePosition(), NWidgetVertical::AssignSizePosition(), NWidgetToolbarContainer::AssignSizePosition(), NWidgetNewGRFDisplay::AssignSizePosition(), NWidgetSmallmapDisplay::AssignSizePosition(), CalcEngineReliability(), CalcHeightdiff(), CalcPercentVehicleFilled(), CalculateCompanyValue(), CanBuildVehicleInfrastructure(), CanExpandRailStation(), ChangeIndustryProduction(), ChangeOwnershipOfCompanyItems(), ChangeTownRating(), CheckBridgeAvailability(), CheckClickOnVehicle(), CheckIfFarEnoughFromConflictingIndustry(), GraphicsSet::CheckMD5(), CheckOverflow(), CheckTrainsLengths(), Clamp(), ClampU(), ClampXYToMap(), 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(), DrawEngineList(), BaseGraphWindow::DrawGraph(), DrawLabel(), Blitter::DrawLine(), NetworkContentListWindow::DrawMatrix(), DrawOverlappedWindowForAll(), SmallMapWindow::DrawSmallMapColumn(), DrawString(), DrawText(), DrawTrainDetails(), BaseVehicleListWindow::DrawVehicleListItems(), DrawVehicleRefitWindow(), CompanyStationsWindow::DrawWidget(), VehicleGroupWindow::DrawWidget(), NetworkGameWindow::DrawWidget(), RefitWindow::DrawWidget(), SpriteAlignerWindow::DrawWidget(), OrdersWindow::DrawWidget(), ScanProgressWindow::DrawWidget(), VehicleViewWindow::DrawWidget(), SymmetricScaler::EffectiveSupply(), Blitter_32bppOptimized::Encode(), Blitter_32bppSimple::Encode(), EnginePowerVsRunningCostSorter(), HeaderFileWriter::Finalise(), FindStationsNearby(), Window::FindWindowPlacementAndResize(), GamelogInfo(), GroundVehicle< T, Type >::GetAcceleration(), GetAcceptanceAroundTiles(), GetAmplitude(), Path::GetCapacityRatio(), ExpensesList::GetCategoriesWidth(), Train::GetCurrentMaxSpeed(), GetDigitWidth(), GetGlobalVariable(), FreeTypeFontCache::GetGlyph(), FallbackParagraphLayout::FallbackLine::GetLeading(), GetLoadAmount(), SettingsContainer::GetMaxHelpHeight(), SmallMapWindow::GetNumberRowsLegend(), GetOrderDistance(), GetProductionAroundTiles(), GetTileMaxPixelZOutsideMap(), GetTileSlopeGivenHeight(), EndGameHighScoreBaseWindow::GetTopLeft(), GetTrainDetailsWndVScroll(), BaseGraphWindow::GetValuesInterval(), GetVehicleListHeight(), GfxBlitter(), GfxDoDrawLine(), Vehicle::HandleLoading(), HandleScrollbarScrolling(), HeightMapCoastLines(), HeightMapGenerate(), HighlightDragPosition(), IndustryProductionCallback(), IsCloseToTown(), LinkGraph::EdgeWrapper< BaseEdge >::LastUpdate(), IniLoadFile::LoadFromDisk(), LoadOldVehicle(), LoadUnloadVehicle(), LocalGetWindowPlacement(), MakeNWidget(), MakeWindowNWidgetTree(), MarkViewportDirty(), maxdim(), NetworkDrawChatMessage(), NetworkUndrawChatMessage(), NewGRFDisplay(), AIConfigWindow::OnClick(), IndustryViewWindow::OnClick(), BuildRailStationWindow::OnClick(), IConsoleWindow::OnHundredthTick(), CompanyFinancesWindow::OnHundredthTick(), SmallMapWindow::OnInit(), SelectCompanyManagerFaceWindow::OnInit(), IndustryCargoesWindow::OnInit(), RefitWindow::OnInvalidateData(), ReplaceVehicleWindow::OnPaint(), RefitWindow::OnPaint(), DepotWindow::OnPaint(), AIDebugWindow::OnPaint(), BuildVehicleWindow::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(), SeedModChance(), Scrollbar::SetCapacity(), SymmetricScaler::SetDemandPerNode(), SymmetricScaler::SetDemands(), SetDParamMaxValue(), NWidgetResizeBase::SetMinimalSize(), SetSnowLine(), TextfileWindow::SetupScrollbars(), NWidgetServerListHeader::SetupSmallestSize(), NWidgetStacked::SetupSmallestSize(), NWidgetHorizontal::SetupSmallestSize(), NWidgetVertical::SetupSmallestSize(), NWidgetBackground::SetupSmallestSize(), NWidgetLeaf::SetupSmallestSize(), NWidgetToolbarContainer::SetupSmallestSize(), NWidgetNewGRFDisplay::SetupSmallestSize(), NWidgetSmallmapDisplay::SetupSmallestSize(), NewsWindow::SetWindowTop(), SetYearEngineAgingStops(), ShowDropDownListAt(), SmallMapWindow::SmallMapCenterOnCurrentPos(), CompanyStationsWindow::StationRatingMaxSorter(), TileHeightOutsideMap(), TranslateXYToTileCoord(), TruncateCargo(), IndustryBuildData::TryBuildNewIndustry(), LinkGraph::Edge::Update(), UpdateAircraftSpeed(), UpdateCompanyRatingAndValue(), UpdateCursorSize(), UpdateLoadUnloadTicks(), DisasterVehicle::UpdatePosition(), Scrollbar::UpdatePosition(), BaseGraphWindow::UpdateStatistics(), UpdateVehicleTimetable(), Vehicle::UpdateViewport(), TextfileWindow::UpdateWidgetSize(), EnginePreviewWindow::UpdateWidgetSize(), LandInfoWindow::UpdateWidgetSize(), BuildObjectWindow::UpdateWidgetSize(), BuildBridgeWindow::UpdateWidgetSize(), ErrmsgWindow::UpdateWidgetSize(), TimetableWindow::UpdateWidgetSize(), NewGRFParametersWindow::UpdateWidgetSize(), TownAuthorityWindow::UpdateWidgetSize(), CheatWindow::UpdateWidgetSize(), BuildAirportWindow::UpdateWidgetSize(), CompanyFinancesWindow::UpdateWidgetSize(), MusicTrackSelectionWindow::UpdateWidgetSize(), AISettingsWindow::UpdateWidgetSize(), GameOptionsWindow::UpdateWidgetSize(), VehicleGroupWindow::UpdateWidgetSize(), NewGRFInspectWindow::UpdateWidgetSize(), GenerateLandscapeWindow::UpdateWidgetSize(), AboutWindow::UpdateWidgetSize(), BaseGraphWindow::UpdateWidgetSize(), NetworkGameWindow::UpdateWidgetSize(), SelectCompanyLiveryWindow::UpdateWidgetSize(), NewGRFWindow::UpdateWidgetSize(), TownDirectoryWindow::UpdateWidgetSize(), SpriteAlignerWindow::UpdateWidgetSize(), MessageHistoryWindow::UpdateWidgetSize(), BuildRailStationWindow::UpdateWidgetSize(), SelectCompanyManagerFaceWindow::UpdateWidgetSize(), CompanyLeagueWindow::UpdateWidgetSize(), GenerateProgressWindow::UpdateWidgetSize(), PerformanceRatingDetailWindow::UpdateWidgetSize(), StationViewWindow::UpdateWidgetSize(), BuildVehicleWindow::UpdateWidgetSize(), BuildSignalWindow::UpdateWidgetSize(), CompanyInfrastructureWindow::UpdateWidgetSize(), GameSettingsWindow::UpdateWidgetSize(), NetworkClientListWindow::UpdateWidgetSize(), VehicleDetailsWindow::UpdateWidgetSize(), NetworkJoinStatusWindow::UpdateWidgetSize(), SavePresetWindow::UpdateWidgetSize(), CompanyWindow::UpdateWidgetSize(), IndustryCargoesWindow::UpdateWidgetSize(), ScanProgressWindow::UpdateWidgetSize(), ScenarioEditorToolbarWindow::UpdateWidgetSize(), and VehicleViewWindow::UpdateWidgetSize().

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

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

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

  a | The first integer
  b | The second integer

Returns
  The smaller value

Definition at line 56 of file math_func.hpp.

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

  a | The first unsigned integer
  b | The second unsigned integer

Returns
  The smaller value

Definition at line 70 of file math_func.hpp.

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

static int RoundDivSU | ( | int | a,
|  | uint | b
| ) |  |
| inlinestatic

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

Parameters

  a | Numerator
  b | Denominator

Returns
  Quotient, rounded to nearest

Definition at line 338 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
| ) |  |
| inlinestatic

Type safe swap operation.

Parameters

  a | variable to swap with b
  b | variable to swap with a

Definition at line 277 of file math_func.hpp.

Referenced by AfterLoadGame(), BuildRailClick_Remove(), CalcHeightdiff(), CmdBuildAirport(), CmdBuildBridge(), GenerateCompanyColour(), IndustryDirectoryWindow::GetCargoTransportedSortValue(), GetNearbyTile(), GetPlatformInfo(), FlowStat::GetVia(), GSortT(), IsInRangeInclusive(), MemReverseT(), AIConfigWindow::OnClick(), BuildRailStationWindow::OnPaint(), OrthogonalTileArea::OrthogonalTileArea(), PlaceRail_Station(), ReverseTrainSwapVeh(), FontState::SetPreviousColour(), FlowStat::SwapShares(), and UpdateTileSelection().

static uint ToPercent16 | ( | uint | i | ) |
| inlinestatic

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 300 of file math_func.hpp.

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

static uint ToPercent8 | ( | uint | i | ) |
| inlinestatic

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 289 of file math_func.hpp.

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