OpenTTD Source: src/economy.cpp File Reference

OpenTTD Source 15.0-RC2

Data Structures | Typedefs | Functions | Variables
economy.cpp File Reference

Handling of the economy. More...

`#include "stdafx.h"`
`#include <ranges>`
`#include "company_func.h"`
`#include "command_func.h"`
`#include "industry.h"`
`#include "town.h"`
`#include "news_func.h"`
`#include "network/network.h"`
`#include "network/network_func.h"`
`#include "ai/ai.hpp"`
`#include "aircraft.h"`
`#include "train.h"`
`#include "newgrf_engine.h"`
`#include "engine_base.h"`
`#include "ground_vehicle.hpp"`
`#include "newgrf_cargo.h"`
`#include "newgrf_sound.h"`
`#include "newgrf_industrytiles.h"`
`#include "newgrf_station.h"`
`#include "newgrf_airporttiles.h"`
`#include "newgrf_roadstop.h"`
`#include "object.h"`
`#include "strings_func.h"`
`#include "vehicle_func.h"`
`#include "sound_func.h"`
`#include "autoreplace_func.h"`
`#include "company_gui.h"`
`#include "signs_base.h"`
`#include "subsidy_base.h"`
`#include "subsidy_func.h"`
`#include "station_base.h"`
`#include "waypoint_base.h"`
`#include "economy_base.h"`
`#include "core/pool_func.hpp"`
`#include "core/backup_type.hpp"`
`#include "core/container_func.hpp"`
`#include "cargo_type.h"`
`#include "water.h"`
`#include "game/game.hpp"`
`#include "cargomonitor.h"`
`#include "goal_base.h"`
`#include "story_base.h"`
`#include "linkgraph/refresh.h"`
`#include "company_cmd.h"`
`#include "economy_cmd.h"`
`#include "vehicle_cmd.h"`
`#include "timer/timer.h"`
`#include "timer/timer_game_calendar.h"`
`#include "timer/timer_game_economy.h"`
`#include "table/strings.h"`
`#include "table/pricebase.h"`
`#include "safeguards.h"`

Go to the source code of this file.

## Data Structures
struct | IsEmptyAction
| Action to check if a vehicle has no stored cargo. More...
struct | PrepareRefitAction
| Refit preparation action. More...
struct | ReturnCargoAction
| Action for returning reserved cargo. More...
struct | FinalizeRefitAction
| Action for finalizing a refit. More...
struct | ReserveCargoAction

## Typedefs
typedef std::vector< Industry * > | SmallIndustryList

## Functions
static int32_t | BigMulS (const int32_t a, const int32_t b, const uint8_t shift)
| Multiply two integer values and shift the results to right.
static Money | CalculateCompanyAssetValue (const Company *c)
| Calculate the value of the assets of a company.
Money | CalculateCompanyValue (const Company *c, bool including_loan)
| Calculate the value of the company.
Money | CalculateHostileTakeoverValue (const Company *c)
| Calculate what you have to pay to take over a company.
int | UpdateCompanyRatingAndValue (Company *c, bool update)
| if update is set to true, the economy is updated with this score (also the house is updated, should only be true in the on-tick event)
void | ChangeOwnershipOfCompanyItems (Owner old_owner, Owner new_owner)
| Change the ownership of all the items of a company.
static void | CompanyCheckBankrupt (Company *c)
| Check for bankruptcy of a company.
static void | CompaniesGenStatistics ()
| Update the finances of all companies.
bool | AddInflation (bool check_year)
| Add monthly inflation.
void | RecomputePrices ()
| Computes all prices, payments and maximum loan.
static void | CompaniesPayInterest ()
| Let all companies pay the monthly interest on their loan.
static void | HandleEconomyFluctuations ()
void | ResetPriceBaseMultipliers ()
| Reset changes to the price base multipliers.
void | SetPriceBaseMultiplier (Price price, int factor)
| Change a price base by the given factor.
void | StartupIndustryDailyChanges (bool init_counter)
| Initialize the variables that will maintain the daily industry change system.
void | StartupEconomy ()
void | InitializeEconomy ()
| Resets economy to initial values.
Money | GetPrice (Price index, uint cost_factor, const GRFFile *grf_file, int shift)
| Determine a certain price.
Money | GetTransportedGoodsIncome (uint num_pieces, uint dist, uint16_t transit_periods, CargoType cargo_type)
static uint | DeliverGoodsToIndustry (const Station *st, CargoType cargo_type, uint num_pieces, IndustryID source, CompanyID company)
| Transfer goods from station to industry.
static Money | DeliverGoods (int num_pieces, CargoType cargo_type, StationID dest, uint distance, uint16_t periods_in_transit, Company *company, Source src)
| Delivers goods to industries/towns and calculates the payment.
static void | TriggerIndustryProduction (Industry *i)
| Inform the industry about just delivered cargo DeliverGoodsToIndustry() silently incremented incoming_cargo_waiting, now it is time to do something with the new cargo.
void | PrepareUnload (Vehicle *front_v)
| Prepare the vehicle to be unloaded.
static uint | GetLoadAmount (Vehicle *v)
| Gets the amount of cargo the given vehicle can load in the current tick.
template<class Taction >
bool | IterateVehicleParts (Vehicle *v, Taction action)
| Iterate the articulated parts of a vehicle, also considering the special cases of "normal" aircraft and double headed trains.
static void | HandleStationRefit (Vehicle *v, CargoArray &consist_capleft, Station *st, std::span< const StationID > next_station, CargoType new_cargo_type)
| Refit a vehicle in a station.
static bool | MayLoadUnderExclusiveRights (const Station *st, const Vehicle *v)
| Test whether a vehicle can load cargo at a station even if exclusive transport rights are present.
static void | ReserveConsist (Station *st, Vehicle *u, CargoArray *consist_capleft, std::span< const StationID > next_station)
| Reserves cargo if the full load order and improved_load is set or if the current order allows autorefit.
static void | UpdateLoadUnloadTicks (Vehicle *front, const Station *st, int ticks)
| Update the vehicle's load_unload_ticks, the time it will wait until it tries to load or unload again.
static void | LoadUnloadVehicle (Vehicle *front)
| Loads/unload the vehicle if possible.
void | LoadUnloadStation (Station *st)
| Load/unload the vehicles in this station according to the order they entered.
static void | DoAcquireCompany (Company *c, bool hostile_takeover)
CommandCost | CmdBuyCompany (DoCommandFlags flags, CompanyID target_company, bool hostile_takeover)
| Buy up another company.

## Variables
CargoPaymentPool | _cargo_payment_pool ("CargoPayment")
const ScoreInfo | _score_info []
| Score info, values used for computing the detailed performance rating.
TypedIndexContainer< std::array< std::array< int64_t, SCORE_END >, MAX_COMPANIES >, CompanyID > | _score_part
Economy | _economy
Prices | _price
static PriceMultipliers | _price_base_multiplier
static SmallIndustryList | _cargo_delivery_destinations
| The industries we've currently brought cargo to.
static const IntervalTimer< TimerGameCalendar > | _calendar_inflation_monthly ({TimerGameCalendar::MONTH, TimerGameCalendar::Priority::COMPANY}, [](auto) { if(_settings_game.economy.inflation) { AddInflation();RecomputePrices();} })
| Every calendar month update of inflation.
static const IntervalTimer< TimerGameEconomy > | _economy_companies_monthly ({ TimerGameEconomy::MONTH, TimerGameEconomy::Priority::COMPANY }, [](auto) { CompaniesGenStatistics();CompaniesPayInterest();HandleEconomyFluctuations();})
| Every economy month update of company economic data, plus economy fluctuations.

## Detailed Description

Handling of the economy.

Definition in file economy.cpp.

## Typedef Documentation

## ◆ SmallIndustryList

typedef std::vector<Industry *> SmallIndustryList

Definition at line 86 of file economy.cpp.

## Function Documentation

## ◆ AddInflation()

bool AddInflation | ( | bool | check_year | ) |

Add monthly inflation.

Parameters

  check_year | Shall the inflation get stopped after 170 years?

Returns
  true if inflation is maxed and nothing was changed

Definition at line 704 of file economy.cpp.

References Economy::infl_amount, Economy::infl_amount_pr, Economy::inflation_payment, Economy::inflation_prices, MAX_INFLATION, and TimerGameConst< struct Calendar >::ORIGINAL_MAX_YEAR.

Referenced by AfterLoadGame().

## ◆ BigMulS()

static int32_t BigMulS | ( | const int32_t | a,
|  | const int32_t | b,
|  | const uint8_t | shift
| ) |  |
| inlinestatic

Multiply two integer values and shift the results to right.

This function multiplies two integer values. The result is shifted by the amount of shift to right.

Parameters

  a | The first integer
  b | The second integer
  shift | The amount to shift the value to right.

Returns
  The shifted result

Definition at line 81 of file economy.cpp.

## ◆ CalculateCompanyAssetValue()

static Money CalculateCompanyAssetValue | ( | const Company * | c | ) |
| static

Calculate the value of the assets of a company.

Parameters

  c | The company to calculate the value of.

Returns
  The value of the assets of the company.

Definition at line 115 of file economy.cpp.

References SpecializedVehicle< Aircraft, VEH_AIRCRAFT >::From(), Pool< Titem, Tindex, Tgrowth_step, Tpool_type, Tcache >::PoolItem< Tpool >::index, Aircraft::IsNormalAircraft(), SpecializedStation< Station, false >::Iterate(), Pool< Titem, Tindex, Tgrowth_step, Tpool_type, Tcache >::PoolItem<&_vehicle_pool >::Iterate(), VEH_AIRCRAFT, VEH_ROAD, VEH_SHIP, and VEH_TRAIN.

Referenced by CalculateCompanyValue(), and CalculateHostileTakeoverValue().

## ◆ CalculateCompanyValue()

Money CalculateCompanyValue | ( | const Company * | c,
|  | bool | including_loan
| ) |  |

Calculate the value of the company.

That is the value of all assets (vehicles, stations) and money (including loan), except when including_loan is `false` which is useful when we want to calculate the value for bankruptcy.

Parameters

  c | the company to get the value of.
  including_loan | include the loan in the company value.

Returns
  the value of the company.

Definition at line 150 of file economy.cpp.

References CalculateCompanyAssetValue(), CompanyProperties::current_loan, and CompanyProperties::money.

Referenced by CompanyCheckBankrupt(), CompanyWindow::GetWidgetString(), and UpdateCompanyRatingAndValue().

## ◆ CalculateHostileTakeoverValue()

Money CalculateHostileTakeoverValue | ( | const Company * | c | ) |

Calculate what you have to pay to take over a company.

This is different from bankruptcy and company value, and involves a few more parameters to make it more realistic.

You have to pay for:

- The value of all the assets in the company.
- The loan the company has (the investors really want their money back).
- The profit for the next two years (if positive) based on the last four quarters.

And on top of that, they walk away with all the money they have in the bank.

Parameters

  c | the company to get the value of.

Returns
  The value of the company.

Definition at line 177 of file economy.cpp.

References CalculateCompanyAssetValue(), CompanyProperties::current_loan, CompanyProperties::money, and CompanyProperties::old_economy.

Referenced by CmdBuyCompany().

## ◆ ChangeOwnershipOfCompanyItems()

void ChangeOwnershipOfCompanyItems | ( | Owner | old_owner,
|  | Owner | new_owner
| ) |  |

Change the ownership of all the items of a company.

Parameters

  old_owner | The company that gets removed.
  new_owner | The company to merge to, or INVALID_OWNER to remove the company.

Definition at line 322 of file economy.cpp.

References _current_company, _local_company, _networking, AddTrackToSignalBuffer(), Bankrupt, ChangeTileOwner(), ChangeWindowOwner(), ClearCargoDeliveryMonitoring(), ClearCargoPickupMonitoring(), CompanyServiceInterval(), GroupStatistics::CountEngine(), GroupStatistics::CountVehicle(), Execute, Pool< Titem, Tindex, Tgrowth_step, Tpool_type, Tcache >::PoolItem<&_company_pool >::Get(), GetTrackBits(), HasSignalOnTrack(), HasSignals(), INVALID_OWNER, IsCompanyBuildableVehicleType(), IsLevelCrossingTile(), IsTileOwner(), IsTileType(), Map::Iterate(), SpecializedStation< Station, false >::Iterate(), SpecializedStation< Waypoint, true >::Iterate(), Pool< Titem, Tindex, Tgrowth_step, Tpool_type, Tcache >::PoolItem<&_subsidy_pool >::Iterate(), Pool< Titem, Tindex, Tgrowth_step, Tpool_type, Tcache >::PoolItem<&_story_page_pool >::Iterate(), Pool< Titem, Tindex, Tgrowth_step, Tpool_type, Tcache >::PoolItem<&_sign_pool >::Iterate(), Pool< Titem, Tindex, Tgrowth_step, Tpool_type, Tcache >::PoolItem<&_vehicle_pool >::Iterate(), Pool< Titem, Tindex, Tgrowth_step, Tpool_type, Tcache >::PoolItem<&_group_pool >::Iterate(), Pool< Titem, Tindex, Tgrowth_step, Tpool_type, Tcache >::PoolItem<&_company_pool >::Iterate(), Pool< Titem, Tindex, Tgrowth_step, Tpool_type, Tcache >::PoolItem<&_goal_pool >::Iterate(), Pool< Titem, Tindex, Tgrowth_step, Tpool_type, Tcache >::PoolItem<&_town_pool >::Iterate(), MarkWholeScreenDirty(), MP_RAILWAY, NetworkClientsToSpectators(), FreeUnitIDGenerator::NextID(), OWNER_NONE, RATING_INITIAL, RebuildSubsidisedSourceAndDestinationCache(), RemoveAllEngineReplacementForCompany(), RemoveFirstTrack(), Backup< T >::Restore(), VehicleDefaultSettings::servint_aircraft, VehicleDefaultSettings::servint_ispercent, VehicleDefaultSettings::servint_roadveh, VehicleDefaultSettings::servint_ships, VehicleDefaultSettings::servint_trains, SetLocalCompany(), CompanyProperties::settings, TRACK_BIT_NONE, GroupStatistics::UpdateAutoreplace(), UpdateLevelCrossing(), UpdateSignalsInBuffer(), FreeUnitIDGenerator::UseID(), and CompanySettings::vehicle.

Referenced by CmdCompanyCtrl(), and ResetLandscapeConfirmationCallback().

## ◆ CmdBuyCompany()

CommandCost CmdBuyCompany | ( | DoCommandFlags | flags,
|  | CompanyID | target_company,
|  | bool | hostile_takeover
| ) |  |

Buy up another company.

When a competing company is gone bankrupt you get the chance to purchase that company.

Todo:
  currently this only works for AI companies

Parameters

  flags | type of operation
  target_company | company to buy up
  hostile_takeover | whether to buy up the company even if it is not bankrupt

Returns
  the cost of this operation or an error

Definition at line 2021 of file economy.cpp.

References _current_company, _local_company, _networking, CompanyProperties::bankrupt_asked, CalculateHostileTakeoverValue(), CheckTakeoverVehicleLimit(), CMD_ERROR, Execute, EXPENSES_OTHER, Pool< Titem, Tindex, Tgrowth_step, Tpool_type, Tcache >::PoolItem<&_company_pool >::GetIfValid(), Pool< Titem, Tindex, Tgrowth_step, Tpool_type, Tcache >::PoolItem< Tpool >::index, CompanyProperties::is_ai, and BaseBitSet< Timpl, Tvalue_type, Tstorage, Tmask >::Test().

## ◆ CompaniesGenStatistics()

static void CompaniesGenStatistics | ( |  | ) |
| static

Update the finances of all companies.

Pay for the stations, update the history graph, update ratings and company values, and deal with bankruptcy.

Definition at line 641 of file economy.cpp.

References _current_company, _settings_game, CommandCost::AddCost(), AirportMaintenanceCost(), CanalMaintenanceCost(), Backup< T >::Change(), CompanyCheckBankrupt(), GameSettings::economy, EXPENSES_PROPERTY, HasBit(), EconomySettings::infrastructure_maintenance, Pool< Titem, Tindex, Tgrowth_step, Tpool_type, Tcache >::PoolItem<&_company_pool >::Iterate(), MAX_HISTORY_QUARTERS, TimerGameEconomy::month, RailMaintenanceCost(), RAILTYPE_BEGIN, RAILTYPE_END, Backup< T >::Restore(), RoadMaintenanceCost(), ROADTYPE_BEGIN, ROADTYPE_END, SetWindowDirty(), SignalMaintenanceCost(), StationMaintenanceCost(), SubtractMoneyFromCompany(), UpdateCompanyRatingAndValue(), WC_COMPANY_LEAGUE, WC_COMPANY_VALUE, WC_DELIVERED_CARGO, WC_INCOME_GRAPH, WC_OPERATING_PROFIT, and WC_PERFORMANCE_HISTORY.

## ◆ CompaniesPayInterest()

static void CompaniesPayInterest | ( |  | ) |
| static

Let all companies pay the monthly interest on their loan.

Definition at line 809 of file economy.cpp.

References _current_company, Backup< T >::Change(), EXPENSES_LOAN_INTEREST, EXPENSES_OTHER, GetAvailableMoney(), Economy::interest_rate, Pool< Titem, Tindex, Tgrowth_step, Tpool_type, Tcache >::PoolItem<&_company_pool >::Iterate(), TimerGameEconomy::month, Backup< T >::Restore(), and SubtractMoneyFromCompany().

## ◆ CompanyCheckBankrupt()

static void CompanyCheckBankrupt | ( | Company * | c | ) |
| static

Check for bankruptcy of a company.

Called every three months.

Parameters

  c | Company to check.

Definition at line 550 of file economy.cpp.

References _local_company, _network_server, _networking, _settings_game, CompanyProperties::bankrupt_asked, CompanyProperties::bankrupt_timeout, AI::BroadcastNewEvent(), CalculateCompanyValue(), CCA_DELETE, CeilDiv(), CompanyAdminUpdate(), CRR_BANKRUPT, CompanyProperties::current_loan, GameSettings::difficulty, GetEncodedString(), Company::GetMaxLoan(), Pool< Titem, Tindex, Tgrowth_step, Tpool_type, Tcache >::PoolItem< Tpool >::index, DifficultySettings::infinite_money, INVALID_CLIENT_ID, CompanyProperties::money, CompanyProperties::months_of_bankruptcy, Game::NewEvent(), and BaseBitSet< Timpl, Tvalue_type, Tstorage, Tmask >::Set().

Referenced by CompaniesGenStatistics().

## ◆ DeliverGoods()

static Money DeliverGoods | ( | int | num_pieces,
|  | CargoType | cargo_type,
|  | StationID | dest,
|  | uint | distance,
|  | uint16_t | periods_in_transit,
|  | Company * | company,
|  | Source | src
| ) |  |
| static

Delivers goods to industries/towns and calculates the payment.

Parameters

  num_pieces | amount of cargo delivered
  cargo_type | the type of cargo that is delivered
  dest | Station the cargo has been unloaded
  distance | The distance the cargo has traveled.
  periods_in_transit | Travel time in cargo aging periods
  company | The company delivering the cargo
  src | Source of cargo

Returns
  Revenue for delivering cargo

Note
  The cargo is just added to the stockpile of the industry. It is due to the caller to trigger the industry's production machinery

Definition at line 1094 of file economy.cpp.

References _settings_game, GoodsEntry::AcceptedBigtick, AddCargoDelivery(), Station::always_accepted, CheckSubsidised(), CompanyProperties::cur_economy, GoodsEntry::CurrentMonth, CompanyEconomyEntry::delivered_cargo, DeliverGoodsToIndustry(), GameSettings::difficulty, GoodsEntry::EverAccepted, SpecializedStation< Station, false >::Get(), CargoSpec::Get(), Station::goods, HasBit(), Pool< Titem, Tindex, Tgrowth_step, Tpool_type, Tcache >::PoolItem< Tpool >::index, Industry, Town::received, DifficultySettings::subsidy_multiplier, BaseStation::town, CargoSpec::town_acceptance_effect, and Source::type.

Referenced by CargoPayment::PayFinalDelivery().

## ◆ DeliverGoodsToIndustry()

static uint DeliverGoodsToIndustry | ( | const Station * | st,
|  | CargoType | cargo_type,
|  | uint | num_pieces,
|  | IndustryID | source,
|  | CompanyID | company
| ) |  |
| static

Transfer goods from station to industry.

All cargo is delivered to the nearest (Manhattan) industry to the station sign, which is inside the acceptance rectangle and actually accepts the cargo.

Parameters

  st | The station that accepted the cargo
  cargo_type | Type of cargo delivered
  num_pieces | Amount of cargo delivered
  source | The source of the cargo
  company | The company delivering the cargo

Returns
  actually accepted pieces of cargo

Definition at line 1039 of file economy.cpp.

References _cargo_delivery_destinations, Industry::accepted, AddCargoDelivery(), TimerGameEconomy::date, Industry::exclusive_supplier, Industry::GetCargoAccepted(), include(), Pool< Titem, Tindex, Tgrowth_step, Tpool_type, Tcache >::PoolItem< Tpool >::index, Station::industries_near, Industry, IndustryTemporarilyRefusesCargo(), INVALID_OWNER, and BaseStation::owner.

Referenced by DeliverGoods().

## ◆ DoAcquireCompany()

static void DoAcquireCompany | ( | Company * | c,
|  | bool | hostile_takeover
| ) |  |
| static

Definition at line 1986 of file economy.cpp.

## ◆ GetLoadAmount()

static uint GetLoadAmount | ( | Vehicle * | v | ) |
| static

Gets the amount of cargo the given vehicle can load in the current tick.

This is only about loading speed. The free capacity is ignored.

Parameters

  v | Vehicle to be queried.

Returns
  Amount of cargo the vehicle can load at once.

Definition at line 1298 of file economy.cpp.

References _settings_game, CALLBACK_FAILED, EngineInfo::callback_mask, Vehicle::cargo_type, CBID_VEHICLE_LOAD_AMOUNT, CeilDiv(), Vehicle::engine_type, ErrorUnknownCallbackResult(), SpecializedVehicle< Aircraft, VEH_AIRCRAFT >::From(), GB(), CargoSpec::Get(), Vehicle::GetEngine(), Engine::GetGRF(), Engine::GetGRFID(), GetVehicleCallback(), OrderSettings::gradual_loading, Aircraft::IsNormalAircraft(), LoadAmount, EngineInfo::misc_flags, CargoSpec::multiplier, NoDefaultCargoMultiplier, GameSettings::order, PROP_VEHICLE_LOAD_AMOUNT, BaseBitSet< Timpl, Tvalue_type, Tstorage, Tmask >::Test(), BaseVehicle::type, and VEH_AIRCRAFT.

Referenced by LoadUnloadVehicle().

## ◆ GetPrice()

Money GetPrice | ( | Price | index,
|  | uint | cost_factor,
|  | const GRFFile * | grf_file,
|  | int | shift
| ) |  |

Determine a certain price.

Parameters

  index | Price base
  cost_factor | Price factor
  grf_file | NewGRF to use local price multipliers from.
  shift | Extra bit shifting after the computation

Returns
  Price

Definition at line 949 of file economy.cpp.

References GRFFile::price_base_multipliers.

Referenced by ObjectSpec::GetBuildCost(), RoadStopSpec::GetBuildCost(), ObjectSpec::GetClearCost(), RoadStopSpec::GetClearCost(), Engine::GetCost(), GetRefitCost(), Engine::GetRunningCost(), Aircraft::GetRunningCost(), RoadVehicle::GetRunningCost(), Ship::GetRunningCost(), and Train::GetRunningCost().

## ◆ GetTransportedGoodsIncome()

Money GetTransportedGoodsIncome | ( | uint | num_pieces,
|  | uint | dist,
|  | uint16_t | transit_periods,
|  | CargoType | cargo_type
| ) |  |

Definition at line 965 of file economy.cpp.

## ◆ HandleEconomyFluctuations()

static void HandleEconomyFluctuations | ( |  | ) |
| static

Definition at line 844 of file economy.cpp.

## ◆ HandleStationRefit()

static void HandleStationRefit | ( | Vehicle * | v,
|  | CargoArray & | consist_capleft,
|  | Station * | st,
|  | std::span< const StationID > | next_station,
|  | CargoType | new_cargo_type
| ) |  |
| static

Refit a vehicle in a station.

Parameters

  v | Vehicle to be refitted.
  consist_capleft | Added cargo capacities in the consist.
  st | Station the vehicle is loading at.
  next_station | Possible next stations the vehicle can travel to.
  new_cargo_type | Target cargo for refit.

Definition at line 1475 of file economy.cpp.

References _current_company, CARGO_AUTO_REFIT, Vehicle::cargo_type, Vehicle::current_order, Execute, Vehicle::First(), CommandCost::GetCost(), Vehicle::GetEngine(), Vehicle::GetFirstEnginePart(), Station::goods, Pool< Titem, Tindex, Tgrowth_step, Tpool_type, Tcache >::PoolItem< Tpool >::index, Order::IsFullLoadOrder(), IterateVehicleParts(), Vehicle::owner, Vehicle::profit_this_year, QueryCost, Backup< T >::Restore(), and CommandCost::Succeeded().

Referenced by LoadUnloadVehicle().

## ◆ InitializeEconomy()

void InitializeEconomy | ( |  | ) |

Resets economy to initial values.

Definition at line 934 of file economy.cpp.

References ClearCargoDeliveryMonitoring(), ClearCargoPickupMonitoring(), Economy::inflation_payment, and Economy::inflation_prices.

## ◆ IterateVehicleParts()

template<class Taction >

bool IterateVehicleParts | ( | Vehicle * | v,
|  | Taction | action
| ) |  |

Iterate the articulated parts of a vehicle, also considering the special cases of "normal" aircraft and double headed trains.

Apply an action to each vehicle and immediately return false if that action does so. Otherwise return true.

Template Parameters

  Taction | Class of action to be applied. Must implement bool operator()([const] Vehicle *).

Parameters

  v | First articulated part.
  action | Instance of Taction.

Returns
  false if any of the action invocations returned false, true otherwise.

Definition at line 1343 of file economy.cpp.

References SpecializedVehicle< Aircraft, VEH_AIRCRAFT >::From(), SpecializedVehicle< T, Type >::From(), Vehicle::HasArticulatedPart(), GroundVehicle< T, Type >::IsMultiheaded(), Aircraft::IsNormalAircraft(), Vehicle::Next(), BaseVehicle::type, VEH_AIRCRAFT, and VEH_TRAIN.

Referenced by HandleStationRefit(), and ReserveConsist().

## ◆ LoadUnloadStation()

void LoadUnloadStation | ( | Station * | st | ) |

Load/unload the vehicles in this station according to the order they entered.

Parameters

  st | the station to do the loading/unloading for

Definition at line 1929 of file economy.cpp.

References _cargo_delivery_destinations, LoadUnloadVehicle(), and TriggerIndustryProduction().

## ◆ LoadUnloadVehicle()

static void LoadUnloadVehicle | ( | Vehicle * | front | ) |
| static

Loads/unload the vehicle if possible.

Parameters

  front | the vehicle to be (un)loaded

Definition at line 1615 of file economy.cpp.

References _local_company, _settings_client, _settings_game, GoodsEntry::Acceptance, StationCargoList::AvailableCount(), Vehicle::build_year, VehicleCache::cached_max_speed, CalcPercentVehicleFilled(), GoodsEntry::GoodsEntryData::cargo, Vehicle::cargo, CARGO_AUTO_REFIT, Vehicle::cargo_cap, Vehicle::cargo_payment, Vehicle::cargo_type, CargoTaken, CargoUnloading, ClrBit(), COMPANY_SPECTATOR, Vehicle::cur_speed, Vehicle::current_order, BaseConsist::current_order_time, Empty, Vehicle::fill_percent_te_id, SpecializedVehicle< Aircraft, VEH_AIRCRAFT >::From(), FullLoadAny, SpecializedStation< Station, false >::Get(), GoodsEntry::GetData(), GetLoadAmount(), Order::GetLoadType(), Vehicle::GetNextStoppingStation(), GoodsEntry::GetOrCreateData(), Order::GetRefitCargo(), GetStationIndex(), Order::GetTimetabledWait(), Order::GetUnloadType(), GetWindowClassForVehicleType(), Station::goods, OrderSettings::gradual_loading, ClientSettings::gui, HandleStationRefit(), Vehicle::HasArticulatedPart(), GoodsEntry::HasData(), GoodsEntry::HasRating(), OrderSettings::improved_load, Pool< Titem, Tindex, Tgrowth_step, Tpool_type, Tcache >::PoolItem< Tpool >::index, IsCargoInClass(), Order::IsFullLoadOrder(), Order::IsRefit(), IsTileType(), Order::IsType(), GoodsEntry::last_age, GoodsEntry::last_speed, Vehicle::last_station_visited, BaseConsist::lateness_counter, StationCargoList::Load(), Vehicle::load_unload_ticks, GUISettings::loading_indicators, LoadingFinished, Vehicle::MarkDirty(), Station::MarkTilesDirty(), MayLoadUnderExclusiveRights(), MP_STATION, CargoList< VehicleCargoList, CargoPacketList >::MTA_DELIVER, CargoList< VehicleCargoList, CargoPacketList >::MTA_KEEP, CargoList< VehicleCargoList, CargoPacketList >::MTA_LOAD, CargoList< VehicleCargoList, CargoPacketList >::MTA_TRANSFER, NewCargo, Vehicle::Next(), NoLoad, NoUnload, GameSettings::order, BaseStation::owner, Vehicle::owner, Passengers, Vehicle::Previous(), GoodsEntry::Rating, ReserveConsist(), BaseBitSet< Timpl, Tvalue_type, Tstorage, Tmask >::Reset(), LinkRefresher::Run(), BaseBitSet< Timpl, Tvalue_type, Tstorage, Tmask >::Set(), SetBit(), SetWindowDirty(), ShowFillingPercent(), GoodsEntry::status, StopLoading, VehicleCargoList::StoredCount(), BaseBitSet< Timpl, Tvalue_type, Tstorage, Tmask >::Test(), Vehicle::tile, GoodsEntry::time_since_pickup, StationCargoList::TotalCount(), Transfer, TriggerStationRandomisation(), BaseVehicle::type, Unload, UpdateFillingPercent(), UpdateLoadUnloadTicks(), Vehicle::vcache, VEH_AIRCRAFT, VEH_ROAD, VEH_SHIP, VEH_TRAIN, BaseConsist::vehicle_flags, VehicleLoads, WC_STATION_LIST, WC_STATION_VIEW, WC_VEHICLE_DETAILS, Vehicle::x_pos, BaseStation::xy, Vehicle::y_pos, TimerGameCalendar::year, and Vehicle::z_pos.

Referenced by LoadUnloadStation().

## ◆ MayLoadUnderExclusiveRights()

static bool MayLoadUnderExclusiveRights | ( | const Station * | st,
|  | const Vehicle * | v
| ) |  |
| static

Test whether a vehicle can load cargo at a station even if exclusive transport rights are present.

Parameters

  st | Station with cargo waiting to be loaded.
  v | Vehicle loading the cargo.

Returns
  true when a vehicle can load the cargo.

Definition at line 1535 of file economy.cpp.

References Town::exclusive_counter, Town::exclusivity, BaseStation::owner, Vehicle::owner, OWNER_NONE, and BaseStation::town.

Referenced by LoadUnloadVehicle().

## ◆ PrepareUnload()

void PrepareUnload | ( | Vehicle * | front_v | ) |

Prepare the vehicle to be unloaded.

Parameters

  front_v | the vehicle to be unloaded

Definition at line 1255 of file economy.cpp.

References GoodsEntry::Acceptance, Pool< Titem, Tindex, Tgrowth_step, Tpool_type, Tcache >::PoolItem<&_cargo_payment_pool >::CanAllocateItem(), Vehicle::cargo_payment, CargoUnloading, Vehicle::current_order, SpecializedStation< Station, false >::Get(), Vehicle::GetNextStoppingStation(), Order::GetUnloadType(), Station::goods, Vehicle::last_station_visited, Vehicle::load_unload_ticks, LoadingFinished, Pool< Titem, Tindex, Tgrowth_step, Tpool_type, Tcache >::MAX_SIZE, Vehicle::Next(), NoUnload, Vehicle::orders, BaseBitSet< Timpl, Tvalue_type, Tstorage, Tmask >::Reset(), GoodsEntry::status, BaseBitSet< Timpl, Tvalue_type, Tstorage, Tmask >::Test(), and BaseConsist::vehicle_flags.

Referenced by Vehicle::BeginLoading().

## ◆ RecomputePrices()

void RecomputePrices | ( |  | ) |

Computes all prices, payments and maximum loan.

Definition at line 742 of file economy.cpp.

References _settings_game, Clamp(), DifficultySettings::construction_cost, GameSettings::difficulty, Economy::inflation_payment, Economy::inflation_prices, InvalidateWindowData(), CargoSpec::Iterate(), LOAN_INTERVAL, Economy::max_loan, DifficultySettings::max_loan, PCAT_CONSTRUCTION, PCAT_RUNNING, SetWindowClassesDirty(), PriceBaseSpec::start_price, DifficultySettings::vehicle_costs, WC_BUILD_VEHICLE, WC_COMPANY_INFRASTRUCTURE, WC_PAYMENT_RATES, WC_REPLACE_VEHICLE, and WC_VEHICLE_DETAILS.

Referenced by InitializeWindowsAndCaches(), and ReloadNewGRFData().

## ◆ ReserveConsist()

static void ReserveConsist | ( | Station * | st,
|  | Vehicle * | u,
|  | CargoArray * | consist_capleft,
|  | std::span< const StationID > | next_station
| ) |  |
| static

Reserves cargo if the full load order and improved_load is set or if the current order allows autorefit.

Parameters

  st | Station where the consist is loading at the moment.
  u | Front of the loading vehicle consist.
  consist_capleft | If given, save free capacities after reserving there.
  next_station | Station(s) the vehicle will stop at next.

Definition at line 1567 of file economy.cpp.

References Vehicle::cargo_payment, Vehicle::current_order, SpecializedVehicle< Aircraft, VEH_AIRCRAFT >::From(), SpecializedVehicle< T, Type >::From(), Order::GetRefitCargo(), Aircraft::IsNormalAircraft(), Order::IsRefit(), IterateVehicleParts(), Vehicle::Next(), VEH_AIRCRAFT, and VEH_TRAIN.

Referenced by LoadUnloadVehicle().

## ◆ ResetPriceBaseMultipliers()

void ResetPriceBaseMultipliers | ( |  | ) |

Reset changes to the price base multipliers.

Definition at line 870 of file economy.cpp.

Referenced by ResetNewGRFData().

## ◆ SetPriceBaseMultiplier()

void SetPriceBaseMultiplier | ( | Price | price,
|  | int | factor
| ) |  |

Change a price base by the given factor.

The price base is altered by factors of two. NewBaseCost = OldBaseCost * 2^n

Parameters

  price | Index of price base to change.
  factor | Amount to change by.

Definition at line 882 of file economy.cpp.

References Clamp(), and MIN_PRICE_MODIFIER.

Referenced by FinalisePriceBaseMultipliers().

## ◆ StartupEconomy()

void StartupEconomy | ( |  | ) |

Definition at line 909 of file economy.cpp.

## ◆ StartupIndustryDailyChanges()

void StartupIndustryDailyChanges | ( | bool | init_counter | ) |

Initialize the variables that will maintain the daily industry change system.

Parameters

  init_counter | specifies if the counter is required to be initialized

Definition at line 892 of file economy.cpp.

References Economy::industry_daily_change_counter, Economy::industry_daily_increment, Map::LogX(), and Map::LogY().

Referenced by ECMYChunkHandler::Load().

## ◆ TriggerIndustryProduction()

static void TriggerIndustryProduction | ( | Industry * | i | ) |
| static

Inform the industry about just delivered cargo DeliverGoodsToIndustry() silently incremented incoming_cargo_waiting, now it is time to do something with the new cargo.

Parameters

  i | The industry to process

Definition at line 1142 of file economy.cpp.

References Industry::accepted, IndustrySpec::callback_mask, CargoReceived, GetIndustrySpec(), Pool< Titem, Tindex, Tgrowth_step, Tpool_type, Tcache >::PoolItem< Tpool >::index, IndustryProductionCallback(), IndustrySpec::input_cargo_multiplier, IsValidCargoType(), Industry::produced, Production256Ticks, ProductionCargoArrival, SetWindowDirty(), BaseBitSet< Timpl, Tvalue_type, Tstorage, Tmask >::Test(), TriggerIndustryRandomisation(), Industry::type, Industry::was_cargo_delivered, and WC_INDUSTRY_VIEW.

Referenced by LoadUnloadStation().

## ◆ UpdateCompanyRatingAndValue()

int UpdateCompanyRatingAndValue | ( | Company * | c,
|  | bool | update
| ) |  |

if update is set to true, the economy is updated with this score (also the house is updated, should only be true in the on-tick event)

Parameters

  update | the economy with calculated score
  c | company been evaluated

Returns
  actual score of this company

Definition at line 202 of file economy.cpp.

References _score_info, CalculateCompanyValue(), CompanyProperties::current_loan, Pool< Titem, Tindex, Tgrowth_step, Tpool_type, Tcache >::PoolItem< Tpool >::index, IsCompanyBuildableVehicleType(), SpecializedStation< Station, false >::Iterate(), Pool< Titem, Tindex, Tgrowth_step, Tpool_type, Tcache >::PoolItem<&_vehicle_pool >::Iterate(), CompanyProperties::location_of_HQ, CompanyProperties::money, ScoreInfo::needed, CompanyProperties::num_valid_stat_ent, CompanyProperties::old_economy, ScoreInfo::score, SCORE_END, SCORE_MAX, SCORE_TOTAL, SetWindowDirty(), UpdateCompanyHQ(), VEHICLE_PROFIT_MIN_AGE, and WC_PERFORMANCE_DETAIL.

Referenced by CmdBuildObject(), and CompaniesGenStatistics().

## ◆ UpdateLoadUnloadTicks()

static void UpdateLoadUnloadTicks | ( | Vehicle * | front,
|  | const Station * | st,
|  | int | ticks
| ) |  |
| static

Update the vehicle's load_unload_ticks, the time it will wait until it tries to load or unload again.

Adjust for overhang of trains and set it at least to 1.

Parameters

  front | The vehicle to be updated.
  st | The station the vehicle is loading at.
  ticks | The time it would normally wait, based on cargo loaded and unloaded.

Definition at line 1597 of file economy.cpp.

References _settings_game, GroundVehicleCache::cached_total_length, Vehicle::GetGroundVehicleCache(), Station::GetPlatformLength(), Vehicle::load_unload_ticks, GameSettings::order, OrderSettings::station_length_loading_penalty, Vehicle::tile, TILE_SIZE, BaseVehicle::type, and VEH_TRAIN.

Referenced by LoadUnloadVehicle().

## Variable Documentation

## ◆ _cargo_delivery_destinations

SmallIndustryList _cargo_delivery_destinations
| static

The industries we've currently brought cargo to.

Definition at line 1027 of file economy.cpp.

Referenced by DeliverGoodsToIndustry(), and LoadUnloadStation().

## ◆ _economy

Economy _economy

Definition at line 105 of file economy.cpp.

## ◆ _price

Prices _price

Definition at line 106 of file economy.cpp.

## ◆ _price_base_multiplier

PriceMultipliers _price_base_multiplier
| static

Definition at line 107 of file economy.cpp.

## ◆ _score_info

const ScoreInfo _score_info[]

Initial value:
= {
{ 120, 100},
{ 80, 100},
{ 10000, 100},
{ 50000, 50},
{ 100000, 100},
{ 40000, 400},
{ 8, 50},
{10000000, 50},
{ 250000, 50},
{ 0, 0}
}

Score info, values used for computing the detailed performance rating.

Definition at line 91 of file economy.cpp.

Referenced by PerformanceRatingDetailWindow::DrawWidget(), and UpdateCompanyRatingAndValue().

## ◆ _score_part

TypedIndexContainer<std::array<std::array<int64_t, SCORE_END>, MAX_COMPANIES>, CompanyID> _score_part

Definition at line 104 of file economy.cpp.