52 #include "table/strings.h" 73 static inline int32
BigMulS(const int32 a, const int32 b, const uint8 shift)
75 return (int32)((int64)a * (int64)b >> shift);
78 typedef std::vector<Industry *> SmallIndustryList;
99 Money _additional_cash_required;
100 static PriceMultipliers _price_base_multiplier;
118 if (st->owner == owner) num +=
CountBits((byte)st->facilities);
121 Money value = num * _price[PR_STATION_VALUE] * 25;
124 if (v->owner != owner)
continue;
130 value += v->value * 3 >> 1;
154 memset(_score_part[owner], 0,
sizeof(_score_part[owner]));
158 Money min_profit = 0;
159 bool min_profit_first =
true;
163 if (v->owner != owner)
continue;
165 if (v->profit_last_year > 0) num++;
168 if (min_profit_first || min_profit > v->profit_last_year) {
169 min_profit = v->profit_last_year;
170 min_profit_first =
false;
178 _score_part[owner][SCORE_VEHICLES] = num;
180 if (min_profit > 0) {
181 _score_part[owner][SCORE_MIN_PROFIT] = min_profit;
190 if (st->owner == owner && (st->time_since_load <= 20 || st->time_since_unload <= 20)) num +=
CountBits((byte)st->facilities);
192 _score_part[owner][SCORE_STATIONS] = num;
206 }
while (++cee, --numec);
208 if (min_income > 0) {
209 _score_part[owner][SCORE_MIN_INCOME] = min_income;
212 _score_part[owner][SCORE_MAX_INCOME] = max_income;
224 }
while (++cee, --numec);
226 _score_part[owner][SCORE_DELIVERED] = total_delivered;
238 _score_part[owner][SCORE_MONEY] = c->
money;
256 s = Clamp<int64>(_score_part[owner][i], 0, _score_info[i].
needed) * _score_info[i].score / _score_info[i].needed;
258 total_score += _score_info[i].
score;
296 if (c->index != old_owner) {
305 assert(old_owner != new_owner);
312 for (i = 0; i < 4; i++) {
313 if (c->share_owners[i] == old_owner) {
326 for (i = 0; i < 4; i++) {
347 if (s->awarded == old_owner) {
351 s->awarded = new_owner;
361 if (
HasBit(t->have_ratings, old_owner)) {
362 if (
HasBit(t->have_ratings, new_owner)) {
364 t->ratings[new_owner] =
max(t->ratings[new_owner], t->ratings[old_owner]);
366 SetBit(t->have_ratings, new_owner);
367 t->ratings[new_owner] = t->ratings[old_owner];
374 ClrBit(t->have_ratings, old_owner);
377 if (t->exclusive_counter > 0 && t->exclusivity == old_owner) {
379 t->exclusivity = new_owner;
381 t->exclusive_counter = 0;
391 if (v->Previous() ==
nullptr)
delete v;
405 RemoveAllGroupsForCompany(old_owner);
408 if (g->owner == old_owner) g->owner = new_owner;
439 if (!v->ServiceIntervalIsCustom()) {
449 v->owner = new_owner;
452 v->colourmap = PAL_NONE;
453 v->InvalidateNewGRFCache();
455 if (v->IsEngineCountable()) {
458 if (v->IsPrimaryVehicle()) {
460 v->unitnumber = unitidgen[v->type].
NextID();
464 if (v->cargo_payment !=
nullptr) v->cargo_payment->owner =
nullptr;
507 if (st->owner == old_owner) {
516 if (wp->owner == old_owner) {
527 if (g->company == old_owner)
delete g;
534 if (sp->company == old_owner)
delete sp;
580 SetDParam(0, STR_NEWS_COMPANY_IN_TROUBLE_TITLE);
581 SetDParam(1, STR_NEWS_COMPANY_IN_TROUBLE_DESCRIPTION);
583 AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, cni);
594 c->bankrupt_value = val;
599 assert(c->bankrupt_value > 0);
651 cur_company.
Change(st->owner);
658 cur_company.
Change(c->index);
661 uint32 rail_total = c->infrastructure.GetRailTotal();
666 uint32 road_total = c->infrastructure.GetRoadTotal();
667 uint32 tram_total = c->infrastructure.GetTramTotal();
669 if (c->infrastructure.road[rt] != 0) cost.
AddCost(
RoadMaintenanceCost(rt, c->infrastructure.road[rt], RoadTypeIsRoad(rt) ? road_total : tram_total));
686 c->old_economy[0] = c->cur_economy;
692 if (c->block_preview != 0) c->block_preview--;
752 for (
Price i = PR_BEGIN; i < PR_END; i++) {
757 switch (_price_base_specs[i].category) {
769 case 0: price *= 6;
break;
770 case 1: price *= 8;
break;
771 case 2: price *= 9;
break;
772 default: NOT_REACHED();
779 int shift = _price_base_multiplier[i] - 16 - 3;
792 price =
Clamp(_price_base_specs[i].start_price, -1, 1);
802 FOR_ALL_CARGOSPECS(cs) {
803 cs->current_payment = ((int64)cs->initial_payment * _economy.
inflation_payment) >> 16;
818 cur_company.
Change(c->index);
845 static void HandleEconomyFluctuations()
852 _economy.
fluct = -12;
858 if (_economy.
fluct == 0) {
859 _economy.
fluct = -(int)
GB(Random(), 0, 2);
861 }
else if (_economy.
fluct == -12) {
862 _economy.
fluct =
GB(Random(), 0, 8) + 312;
873 memset(_price_base_multiplier, 0,
sizeof(_price_base_multiplier));
885 assert(price < PR_END);
910 void StartupEconomy()
915 _economy.
fluct =
GB(Random(), 0, 8) + 168;
944 if (index >= PR_END)
return 0;
946 Money cost = _price[index] * cost_factor;
958 Money GetTransportedGoodsIncome(uint num_pieces, uint dist, byte transit_days,
CargoID cargo_type)
968 uint32 var18 =
min(dist, 0xFFFF) | (
min(num_pieces, 0xFF) << 16) | (transit_days << 24);
971 int result =
GB(callback, 0, 14);
974 if (
HasBit(callback, 14)) result -= 0x4000;
979 return result * num_pieces * cs->current_payment / 8192;
983 static const int MIN_TIME_FACTOR = 31;
984 static const int MAX_TIME_FACTOR = 255;
986 const int days1 = cs->transit_days[0];
987 const int days2 = cs->transit_days[1];
988 const int days_over_days1 =
max( transit_days - days1, 0);
989 const int days_over_days2 =
max(days_over_days1 - days2, 0);
1001 const int time_factor =
max(MAX_TIME_FACTOR - days_over_days1 - days_over_days2, MIN_TIME_FACTOR);
1003 return BigMulS(dist * time_factor * num_pieces, cs->current_payment, 21);
1031 if (num_pieces == 0)
break;
1033 if (ind->
index == source)
continue;
1051 num_pieces -= amount;
1076 assert(num_pieces > 0);
1087 if (accepted_total > 0) {
1101 Money profit = GetTransportedGoodsIncome(accepted_total,
DistanceManhattan(source_tile, st->
xy), days_in_transit, cargo_type);
1109 case 0: profit += profit >> 1;
break;
1110 case 1: profit *= 2;
break;
1111 case 2: profit *= 3;
break;
1112 default: profit *= 4;
break;
1140 if (cargo_waiting == 0)
continue;
1160 current_station(front->last_station_visited)
1164 CargoPayment::~CargoPayment()
1178 SndPlayVehicleFx(SND_14_CASHTILL, this->
front);
1183 this->front->z_pos, this->visual_transfer, -this->visual_profit);
1186 this->front->z_pos, -this->visual_profit);
1199 if (this->
owner ==
nullptr) {
1219 Money profit = GetTransportedGoodsIncome(
1239 curr_station->loading_vehicles.push_back(front_v);
1257 for (
Vehicle *v = front_v; v !=
nullptr; v = v->
Next()) {
1259 if (v->cargo_cap > 0 && v->cargo.TotalCount() > 0) {
1280 uint load_amount = e->info.load_amount;
1284 if (air_mail) load_amount =
CeilDiv(load_amount, 4);
1288 if (e->
GetGRF() !=
nullptr && e->
GetGRF()->grf_version >= 8) {
1296 if (e->
GetGRF()->grf_version < 8) cb_load_amount =
GB(cb_load_amount, 0, 8);
1297 if (cb_load_amount >= 0x100) {
1299 }
else if (cb_load_amount != 0) {
1300 load_amount = cb_load_amount;
1309 return max(1u, load_amount);
1321 template<
class Taction>
1324 for (
Vehicle *w = v; w !=
nullptr;
1326 if (!action(w))
return false;
1329 if (train->
IsMultiheaded() && !action(train->other_multiheaded_part))
return false;
1366 consist_capleft(consist_capleft), refit_mask(refit_mask) {}
1377 this->refit_mask |= EngInfo(v->
engine_type)->refit_mask;
1427 consist_capleft(consist_capleft), st(st), next_station(next_station), do_reserve(do_reserve) {}
1437 if (this->do_reserve) {
1439 &v->
cargo, st->
xy, this->next_station);
1461 CargoTypes refit_mask = v->
GetEngine()->info.refit_mask;
1467 if (is_auto_refit) {
1471 FOR_EACH_SET_CARGO_ID(cid, refit_mask) {
1483 (consist_capleft[cid] == consist_capleft[new_cid] &&
1492 if (new_cid < NUM_CARGO && new_cid != v_start->cargo_type) {
1525 st(st), next_station(next_station) {}
1531 &v->
cargo, st->
xy, *next_station);
1553 for (
Vehicle *v = u; v !=
nullptr; v = v->
Next()) {
1554 assert(v->cargo_cap >= v->cargo.RemainingCount());
1559 if (!v->IsArticulatedPart() &&
1565 if (consist_capleft ==
nullptr || v->cargo_cap == 0)
continue;
1566 (*consist_capleft)[v->cargo_type] += v->cargo_cap - v->cargo.RemainingCount();
1584 ticks += (overhang * ticks) / 8;
1623 int new_load_unload_ticks = 0;
1624 bool dirty_vehicle =
false;
1625 bool dirty_station =
false;
1627 bool completely_emptied =
true;
1628 bool anything_unloaded =
false;
1629 bool anything_loaded =
false;
1630 CargoTypes full_load_amount = 0;
1631 CargoTypes cargo_not_full = 0;
1632 CargoTypes cargo_full = 0;
1633 CargoTypes reservation_left = 0;
1639 uint artic_part = 0;
1640 for (
Vehicle *v = front; v !=
nullptr; v = v->
Next()) {
1642 if (v->cargo_cap == 0)
continue;
1648 uint cargo_count = v->
cargo.UnloadCount();
1650 bool remaining =
false;
1652 assert(payment !=
nullptr);
1663 if (v->cargo_cap < new_remaining) {
1665 v->cargo.Return(new_remaining - v->cargo_cap, &ge->
cargo, INVALID_STATION);
1676 anything_unloaded =
true;
1682 dirty_station =
true;
1692 amount_unloaded = v->cargo.Unload(amount_unloaded, &ge->
cargo, payment);
1693 remaining = v->cargo.UnloadCount() > 0;
1694 if (amount_unloaded > 0) {
1695 dirty_vehicle =
true;
1696 anything_unloaded =
true;
1697 new_load_unload_ticks += amount_unloaded;
1700 st->time_since_unload = 0;
1704 completely_emptied =
false;
1719 ge = &st->
goods[v->cargo_type];
1723 v->refit_cap = v->cargo_cap;
1727 switch (front->
type) {
1741 default: NOT_REACHED();
1748 assert(v->cargo_cap >= v->cargo.StoredCount());
1750 uint cap_left = v->cargo_cap - v->cargo.StoredCount();
1759 if (v->cargo.StoredCount() == 0) TriggerVehicle(v, VEHICLE_TRIGGER_NEW_CARGO);
1762 uint loaded = ge->
cargo.
Load(cap_left, &v->cargo, st->
xy, next_station);
1766 SetBit(reservation_left, v->cargo_type);
1770 if (loaded == cap_left) {
1771 SetBit(full_load_amount, v->cargo_type);
1773 ClrBit(full_load_amount, v->cargo_type);
1784 completely_emptied =
false;
1785 anything_loaded =
true;
1787 st->time_since_load = 0;
1788 st->last_vehicle_type = v->type;
1796 new_load_unload_ticks += loaded;
1798 dirty_vehicle = dirty_station =
true;
1803 if (v->cargo.StoredCount() >= v->cargo_cap) {
1804 SetBit(cargo_full, v->cargo_type);
1806 SetBit(cargo_not_full, v->cargo_type);
1810 if (anything_loaded || anything_unloaded) {
1818 completely_emptied &= anything_unloaded;
1820 if (!anything_unloaded)
delete payment;
1823 if (anything_loaded || anything_unloaded) {
1827 const uint gradual_loading_wait_time[] = { 40, 20, 10, 20 };
1829 new_load_unload_ticks = gradual_loading_wait_time[front->
type];
1841 bool finished_loading =
true;
1847 (cargo_not_full != 0 && (cargo_full & ~cargo_not_full) == 0)) {
1848 finished_loading =
false;
1850 }
else if (cargo_not_full != 0) {
1851 finished_loading =
false;
1872 StringID percent_up_down = STR_NULL;
1881 if (completely_emptied) {
1884 dirty_vehicle =
true;
1885 TriggerVehicle(front, VEHICLE_TRIGGER_EMPTY);
1888 if (dirty_vehicle) {
1893 if (dirty_station) {
1908 if (st->loading_vehicles.empty())
return;
1910 Vehicle *last_loading =
nullptr;
1911 std::list<Vehicle *>::iterator iter;
1914 for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end(); ++iter) {
1930 if (last_loading ==
nullptr)
return;
1932 for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end(); ++iter) {
1935 if (v == last_loading)
break;
1942 _cargo_delivery_destinations.clear();
1956 HandleEconomyFluctuations();
1959 static void DoAcquireCompany(
Company *c)
1966 SetDParam(0, STR_NEWS_COMPANY_MERGER_TITLE);
1967 SetDParam(1, c->bankrupt_value == 0 ? STR_NEWS_MERGER_TAKEOVER_TITLE : STR_NEWS_COMPANY_MERGER_DESCRIPTION);
1971 AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, cni);
1977 if (c->bankrupt_value == 0) {
2021 if (!c->
is_ai)
return cost;
2036 c->bankrupt_value = 0;
2037 DoAcquireCompany(c);
2073 cost = -(cost - (cost >> 7));
2119 DoAcquireCompany(c);
Functions related to OTTD's strings.
void TriggerStationRandomisation(Station *st, TileIndex tile, StationRandomTrigger trigger, CargoID cargo_type)
Trigger station randomisation.
SourceType
Types of cargo source and destination.
Owner
Enum for all companies/owners.
void ChangeTileOwner(TileIndex tile, Owner old_owner, Owner new_owner)
Change the owner of a tile.
byte infl_amount_pr
inflation rate for payment rates
static bool IsLocalCompany()
Is the current company the local company?
uint RemainingCount() const
Returns the sum of cargo to be kept in the vehicle at the current station.
Vehicle * Previous() const
Get the previous vehicle of this vehicle.
Vehicle is stopped by the player.
Money Prices[PR_END]
Prices of everything.
void AddTrackToSignalBuffer(TileIndex tile, Track track, Owner owner)
Add track to signal update buffer.
int CompanyServiceInterval(const Company *c, VehicleType type)
Get the service interval for the given company and vehicle type.
Trigger station when cargo is completely taken.
VehicleCargoList cargo
The cargo this vehicle is carrying.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
static void NewEvent(class ScriptEvent *event)
Queue a new event for a Game Script.
used in multiplayer to create a new companies etc.
static Titem * GetIfValid(size_t index)
Returns Titem with given index.
const ScoreInfo _score_info[]
Score info, values used for computing the detailed performance rating.
bool _networking
are we in networking mode?
bool operator()(Vehicle *v)
Reserve cargo from the station and update the remaining consist capacities with the vehicle's remaini...
Functions for NewGRF engines.
static void CompaniesGenStatistics()
Update the finances of all companies.
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
void LoadUnloadStation(Station *st)
Load/unload the vehicles in this station according to the order they entered.
virtual void MarkDirty()
Marks the vehicles to be redrawn and updates cached variables.
TransportedCargoStat< uint16 > received[NUM_TE]
Cargo statistics about received cargotypes.
byte infl_amount
inflation amount
Definition of link refreshing utility.
Station * st
Station to give the returned cargo to.
Minimal stack that uses a pool to avoid pointers.
Money start_price
Default value at game start, before adding multipliers.
static int32 BigMulS(const int32 a, const int32 b, const uint8 shift)
Multiply two integer values and shift the results to right.
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Vehicle * GetFirstEnginePart()
Get the first part of an articulated engine.
byte GetCount() const
Get the amount of cargos that have an amount.
EconomySettings economy
settings to change the economy
Vehicle has finished loading.
union Vehicle::@49 orders
The orders currently assigned to the vehicle.
static Titem * Get(size_t index)
Returns Titem with given index.
int32 performance_history
Company score (scale 0-1000)
Functions related to dates.
static const Year ORIGINAL_MAX_YEAR
The maximum year of the original TTD.
Cargo has been delivered.
Company * owner
The owner of the vehicle.
Base for the train class.
static uint MapLogX()
Logarithm of the map size along the X side.
Year inaugurated_year
Year of starting the company.
static bool HasSignalOnTrack(TileIndex tile, Track track)
Checks for the presence of signals (either way) on the given track on the given rail tile...
static T SetBit(T &x, const uint8 y)
Set a bit in a variable.
change the server interval of a vehicle
uint16 cur_speed
current speed
static Money DeliverGoods(int num_pieces, CargoID cargo_type, StationID dest, TileIndex source_tile, byte days_in_transit, Company *company, SourceType src_type, SourceID src)
Delivers goods to industries/towns and calculates the payment.
query cost only, don't build.
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
Replace vehicle window; Window numbers:
uint64 inflation_prices
Cumulated inflation of prices since game start; 16 bit fractional part.
Set when cargo was delivered for final delivery during the current STATION_ACCEPTANCE_TICKS interval...
uint16 _returned_refit_capacity
Stores the capacity after a refit operation.
Specification of a cargo type.
Money FeederShare() const
Gets the amount of money already paid to earlier vehicles in the feeder chain.
OrderList * list
Pointer to the order list for this vehicle.
byte interest_rate
Interest.
CompanyMask bankrupt_asked
which companies were asked about buying it?
Functions related to vehicles.
Set when cargo was delivered for final delivery this month.
uint16 callback_mask
Bitmask of industry callbacks that have to be called.
uint32 current_order_time
How many ticks have passed since this order started.
uint TotalCount() const
Returns total count of cargo at the station, including cargo which is already reserved for loading...
Struct about goals, current and completed.
Price
Enumeration of all base prices for use with Prices.
CommandCost CmdBuyShareInCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Acquire shares in an opposing company.
Build vehicle; Window numbers:
Called to calculate the income of delivered cargo.
Action for returning reserved cargo.
void Change(const U &new_value)
Change the value of the variable.
Defines the internal data of a functional industry.
custom profit calculation
DifficultySettings difficulty
settings related to the difficulty
static void BroadcastNewEvent(ScriptEvent *event, CompanyID skip_company=MAX_COMPANIES)
Broadcast a new event to all active AIs.
Stores station stats for a single cargo.
Tindex index
Index of this pool item.
void IndustryProductionCallback(Industry *ind, int reason)
Get the industry production callback and apply it to the industry.
static Money SignalMaintenanceCost(uint32 num)
Calculates the maintenance cost of a number of signals.
byte months_of_bankruptcy
Number of months that the company is unable to pay its debts.
This must always be the last entry.
TileIndex SourceStationXY() const
Gets the coordinates of the cargo's source station.
Payment rates graph; Window numbers:
Company value graph; Window numbers:
byte subsidy_multiplier
amount of subsidy
Date last_cargo_accepted_at[INDUSTRY_NUM_INPUTS]
Last day each cargo type was accepted by this industry.
static SigSegState UpdateSignalsInBuffer(Owner owner)
Updates blocks in _globset buffer.
Vehicle is unloading cargo.
bool IsMultiheaded() const
Check if the vehicle is a multiheaded engine.
Representation of a waypoint.
StationID last_station_visited
The last station we stopped at.
uint16 input_cargo_multiplier[INDUSTRY_NUM_INPUTS][INDUSTRY_NUM_OUTPUTS]
Input cargo multipliers (multiply amount of incoming cargo for the produced cargoes) ...
void MarkTilesDirty(bool cargo_change) const
Marks the tiles of the station as dirty.
static Pool::IterateWrapper< Station > Iterate(size_t from=0)
Returns an iterable ensemble of all valid stations of type T.
Money GetCost() const
The costs as made up to this moment.
byte was_cargo_delivered
flag that indicate this has been the closest industry chosen for cargo delivery by a station...
Refit preparation action.
static uint MapLogY()
Logarithm of the map size along the y side.
int32 lateness_counter
How many ticks late (or early if negative) this vehicle is.
FinalizeRefitAction(CargoArray &consist_capleft, Station *st, StationIDStack &next_station, bool do_reserve)
Create a finalizing action.
Automatically choose cargo type when doing auto refitting.
Common return value for all commands.
StationIDStack & next_station
Next hops to reserve cargo for.
RoadType
The different roadtypes we support.
StationCargoList cargo
The cargo packets of cargo waiting in this station.
static T max(const T a, const T b)
Returns the maximum of two values.
Town * town
The town this station is associated with.
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...
bool HasRating() const
Does this cargo have a rating at this station?
uint32 max_loan
the maximum initial loan
Types related to cargoes...
Year _cur_year
Current year, starting at 0.
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...
uint StoredCount() const
Returns sum of cargo on board the vehicle (ie not only reserved).
bool improved_load
improved loading algorithm
uint Return(uint max_move, StationCargoList *dest, StationID next_station)
Returns reserved cargo to the station and removes it from the cache.
bool infrastructure_maintenance
enable monthly maintenance fee for owner infrastructure
static Aircraft * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
Tstorage new_act
Actually transported this month.
static const int MIN_PRICE_MODIFIER
Maximum NewGRF price modifiers.
uint16 cached_max_speed
Maximum speed of the consist (minimum of the max speed of all vehicles in the consist).
CompanySettings settings
settings specific for each company
Trigger platform when train loads/unloads.
Generates sequence of free UnitID numbers.
const Engine * GetEngine() const
Retrieves the engine of the vehicle.
uint Load(uint max_move, VehicleCargoList *dest, TileIndex load_place, StationIDStack next)
Loads cargo onto a vehicle.
void DeleteCompanyWindows(CompanyID company)
Delete all windows of a company.
bool IsNormalAircraft() const
Check if the aircraft type is a normal flying device; eg not a rotor or a shadow. ...
static const uint TILE_SIZE
Tile size in world coordinates.
GoodsEntry goods[NUM_CARGO]
Goods at this station.
uint32 industry_daily_increment
The value which will increment industry_daily_change_counter. Computed value. NOSAVE.
bool operator()(const Vehicle *v)
Checks if the vehicle has stored cargo.
Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift)
Determine a certain price.
CargoArray & consist_capleft
Capacities left in the consist.
void AddCost(const Money &cost)
Adds the given cost to the cost of the command.
static T SB(T &x, const uint8 s, const uint8 n, const U d)
Set n bits in x starting at bit s to d.
bool IndustryTemporarilyRefusesCargo(Industry *ind, CargoID cargo_type)
Check whether an industry temporarily refuses to accept a certain cargo.
uint32 GetGRFID() const
Retrieve the GRF ID of the NewGRF the engine is tied to.
uint16 servint_ships
service interval for ships
CargoID ct
The currently handled cargo type.
void InitializeEconomy()
Resets economy to initial values.
Class to backup a specific variable and restore it later.
company bankrupts, skip money check, skip vehicle on tile check in some cases
bool allow_shares
allow the buying/selling of shares
uint16 multiplier
Capacity multiplier for vehicles. (8 fractional bits)
PriceMultipliers price_base_multipliers
Price base multipliers as set by the grf.
Income graph; Window numbers:
Money expenses
The amount of expenses.
static const size_t MAX_SIZE
Make template parameter accessible from outside.
SourceID SourceSubsidyID() const
Gets the ID of the cargo's source.
TextEffectID fill_percent_te_id
a text-effect id to a loading indicator object
void InvalidateWindowClassesData(WindowClass cls, int data, bool gui_scope)
Mark window data of all windows of a given class as invalid (in need of re-computing) Note that by de...
TextEffectID ShowFillingPercent(int x, int y, int z, uint8 percent, StringID string)
Display vehicle loading indicators.
uint16 cargo_cap
total capacity
void SetPriceBaseMultiplier(Price price, int factor)
Change a price base by the given factor.
static bool IsTileOwner(TileIndex tile, Owner owner)
Checks if a tile belongs to the given owner.
void SetDParamStr(uint n, const char *str)
This function is used to "bind" a C string to a OpenTTD dparam slot.
Transfer the cargo to the station.
Struct about stories, current and completed.
Some methods of Pool are placed here in order to reduce compilation time and binary size...
The tile has no ownership.
static bool IsTileType(TileIndex tile, TileType type)
Checks if a tile is a given tiletype.
Triggered when a cargo type is completely removed from the station (for all tiles at the same time)...
How many scores are there..
bool MayCompanyTakeOver(CompanyID cbig, CompanyID csmall)
May company cbig buy company csmall?
byte num_valid_stat_ent
Number of valid statistical entries in old_economy.
static void LoadUnloadVehicle(Vehicle *front)
Loads/unload the vehicle if possible.
CommandCost DoCommand(const CommandContainer *container, DoCommandFlag flags)
Shorthand for calling the long DoCommand with a container.
This indicates whether a cargo has a rating at the station.
byte DaysInTransit() const
Gets the number of days this cargo has been in transit.
The client is spectating.
Vehicle * front
The front vehicle to do the payment of.
bool IsRefit() const
Is this order a refit order.
Price is affected by "construction cost" difficulty setting.
VehicleDefaultSettings vehicle
default settings for vehicles
IndustryList industries_near
Cached list of industries near the station that can accept cargo,.
GroundVehicleCache * GetGroundVehicleCache()
Access the ground vehicle cache of the vehicle.
CommandCost CmdBuyCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Buy up another company.
Don't load anymore during the next load cycle.
bool IsType(OrderType type) const
Check whether this order is of the given type.
DoCommandFlag
List of flags for a command.
Money current_loan
Amount of money borrowed from the bank.
Money PayTransfer(const CargoPacket *cp, uint count)
Handle payment for transfer of the given cargo packet.
byte callback_mask
Bitmask of vehicle callbacks that have to be called.
ClientSettings _settings_client
The current settings for this game.
bool operator()(const Vehicle *v)
Prepares for refitting of a vehicle, subtracting its free capacity from consist_capleft and adding th...
byte status
Status of this cargo, see GoodsEntryStatus.
Money visual_profit
The visual profit to show.
Interest payments over the loan.
void UpdateCompanyHQ(TileIndex tile, uint score)
Update the CompanyHQ to the state associated with the given score.
Money AirportMaintenanceCost(Owner owner)
Calculates the maintenance cost of all airports of a company.
bool Succeeded() const
Did this command succeed?
Container for cargo from the same location and time.
void PrepareUnload(Vehicle *front_v)
Prepare the vehicle to be unloaded.
const IndustrySpec * GetIndustrySpec(IndustryType thistype)
Accessor for array _industry_specs.
TileIndex location_of_HQ
Northern tile of HQ; INVALID_TILE when there is none.
Definition of base types and functions in a cross-platform compatible way.
static Money RoadMaintenanceCost(RoadType roadtype, uint32 num, uint32 total_num)
Calculates the maintenance cost of a number of road bits.
virtual ExpensesType GetExpenseType(bool income) const
Sets the expense type associated to this vehicle type.
void NetworkClientsToSpectators(CompanyID cid)
Move the clients of a company to the spectators.
A number of safeguards to prevent using unsafe methods.
void SetLocalCompany(CompanyID new_company)
Sets the local company and updates the settings that are set on a per-company basis to reflect the co...
static void Run(Vehicle *v, bool allow_merge=true, bool is_full_loading=false)
Refresh all links the given vehicle will visit.
uint8 min_years_for_shares
minimum age of a company for it to trade shares
IndustryType type
type of industry.
void PayFinalDelivery(const CargoPacket *cp, uint count)
Handle payment for final delivery of the given cargo packet.
bool inflation
disable inflation
static uint CeilDiv(uint a, uint b)
Computes ceil(a / b) for non-negative a and b.
int score
How much score it will give.
uint8 callback_mask
Bitmask of cargo callbacks that have to be called.
Money route_profit
The amount of money to add/remove from the bank account.
Station * st
Station to reserve cargo from.
Operating profit graph; Window numbers:
Company league window; Window numbers:
CargoID cargo_type
type of cargo this vehicle is carrying
CargoPayment()
Constructor for pool saveload.
GUI Functions related to companies.
Trigger when cargo is received .
uint16 load_unload_ticks
Ticks to wait before starting next cycle.
TrackBits
Bitfield corresponding to Track.
Normal news item. (Newspaper with text only)
Money CalculateCompanyValue(const Company *c, bool including_loan)
Calculate the value of the company.
byte misc_flags
Miscellaneous flags.
byte vehicle_costs
amount of money spent on vehicle running cost
TileIndex tile
Current tile index.
Road vehicle list; Window numbers:
Defines the data structure for constructing industry.
void ClearCargoPickupMonitoring(CompanyID company)
Clear all pick-up cargo monitors.
static void CountVehicle(const Vehicle *v, int delta)
Update num_vehicle when adding or removing a vehicle.
bool is_ai
If true, the company is (also) controlled by the computer (a NoAI program).
bool HasArticulatedPart() const
Check if an engine has an articulated part.
Money money
Money owned by the company.
Station view; Window numbers:
OrderLoadFlags GetLoadType() const
How must the consist be loaded?
Basic functions/variables used all over the place.
bool IsRearDualheaded() const
Tell if we are dealing with the rear end of a multiheaded engine.
CargoID accepts_cargo[INDUSTRY_NUM_INPUTS]
16 input cargo slots
Owner owner
Which company owns the vehicle?
bool DoCommandP(const CommandContainer *container, bool my_cmd)
Shortcut for the long DoCommandP when having a container with the data.
Industry view; Window numbers:
uint16 incoming_cargo_waiting[INDUSTRY_NUM_INPUTS]
incoming cargo waiting to be processed
#define lengthof(x)
Return the length of an fixed size array.
byte last_speed
Maximum speed (up to 255) of the last vehicle that tried to load this cargo.
static void ReserveConsist(Station *st, Vehicle *u, CargoArray *consist_capleft, StationIDStack *next_station)
Reserves cargo if the full load order and improved_load is set or if the current order allows autoref...
CommandCost CmdSellShareInCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Sell shares in an opposing company.
SourceType SourceSubsidyType() const
Gets the type of the cargo's source.
uint Reserve(uint max_move, VehicleCargoList *dest, TileIndex load_place, StationIDStack next)
Reserves cargo for loading onto the vehicle.
static T min(const T a, const T b)
Returns the minimum of two values.
#define MAX_UVALUE(type)
The largest value that can be entered in a variable.
static bool EconomyIsInRecession()
Is the economy in recession?
Helper class to perform the cargo payment.
Deliver the cargo to some town or industry.
static bool IsCargoInClass(CargoID c, CargoClass cc)
Does cargo c have cargo class cc?
bool CheckSubsidised(CargoID cargo_type, CompanyID company, SourceType src_type, SourceID src, const Station *st)
Tests whether given delivery is subsidised and possibly awards the subsidy to delivering company...
Functions related to sound.
static void RemoveAllEngineReplacementForCompany(Company *c)
Remove all engine replacement settings for the given company.
void ChangeOwnershipOfCompanyItems(Owner old_owner, Owner new_owner)
Change the ownership of all the items of a company.
static const Year ORIGINAL_BASE_YEAR
The minimum starting year/base year of the original TTD.
uint32 StringID
Numeric value that represents a string, independent of the selected language.
Money max_loan
NOSAVE: Maximum possible loan.
Vehicle * First() const
Get the first vehicle of this vehicle chain.
void CompanyAdminUpdate(const Company *company)
Called whenever company related information changes in order to notify admins.
NewGRF handling of industry tiles.
The max score that can be in the performance history.
byte last_age
Age in years (up to 255) of the last vehicle that tried to load this cargo.
Action for finalizing a refit.
void UpdateLevelCrossing(TileIndex tile, bool sound=true)
Sets correct crossing state.
static void Stop(CompanyID company)
Stop a company to be controlled by an AI.
void ClearCargoDeliveryMonitoring(CompanyID company)
Clear all delivery cargo monitors.
ReturnCargoAction(Station *st, StationID next_one)
Construct a cargo return action.
int16 bankrupt_timeout
If bigger than 0, amount of time to wait for an answer on an offer to buy this company.
bool IterateVehicleParts(Vehicle *v, Taction action)
Iterate the articulated parts of a vehicle, also considering the special cases of "normal" aircraft a...
Year build_year
Year the vehicle has been built.
bool PlayVehicleSound(const Vehicle *v, VehicleSoundEvent event)
Checks whether a NewGRF wants to play a different vehicle sound effect.
Transfer all cargo onto the platform.
NewGRF handling of airport tiles.
#define return_cmd_error(errcode)
Returns from a function with a specific StringID as error.
StationID next_hop
Next hop the cargo should be assigned to.
Base class for all pools.
Station list; Window numbers:
static T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
static bool HasSignals(TileIndex t)
Checks if a rail tile has signals.
OrderUnloadFlags GetUnloadType() const
How must the consist be unloaded?
Struct about subsidies, offered and awarded.
'Train' is either a loco or a wagon.
Performance detail window; Window numbers:
void UpdateFillingPercent(TextEffectID te_id, uint8 percent, StringID string)
Update vehicle loading indicators.
Month _cur_month
Current month (0..11)
static TrackBits GetTrackBits(TileIndex tile)
Gets the track bits of the given tile.
#define INSTANTIATE_POOL_METHODS(name)
Force instantiation of pool methods so we don't get linker errors.
Owner share_owners[4]
Owners of the 4 shares of the company. INVALID_OWNER if nobody has bought them yet.
CargoTypes & refit_mask
Bitmask of possible refit cargoes.
static void TriggerIndustryProduction(Industry *i)
Inform the industry about just delivered cargo DeliverGoodsToIndustry() silently incremented incoming...
execute the given command
Company infrastructure overview; Window numbers:
Keep the cargo in the vehicle.
static bool CleaningPool()
Returns current state of pool cleaning - yes or no.
Set when a vehicle ever delivered cargo to the station for final delivery.
static uint GetLoadAmount(Vehicle *v)
Gets the amount of cargo the given vehicle can load in the current tick.
Functions related to companies.
void TriggerIndustry(Industry *ind, IndustryTileTrigger trigger)
Trigger a random trigger for all industry tiles.
TileIndex LoadedAtXY() const
Gets the coordinates of the cargo's last loading station.
static StationID GetStationIndex(TileIndex t)
Get StationID from a tile.
void SetCargo(CargoID ct)
Sets the currently handled cargo type.
uint16 GetTimetabledWait() const
Get the time in ticks a vehicle should wait at the destination or 0 if it's not timetabled.
static uint MapSize()
Get the size of the map.
TownEffect town_effect
The effect that delivering this cargo type has on towns. Also affects destination of subsidies...
void ErrorUnknownCallbackResult(uint32 grfid, uint16 cbid, uint16 cb_res)
Record that a NewGRF returned an unknown/invalid callback result.
Class for storing amounts of cargo.
Determine the amount of cargo to load per unit of time when using gradual loading.
static const uint MAX_HISTORY_QUARTERS
The maximum number of quarters kept as performance's history.
Header file for NewGRF stations.
static void CompanyCheckBankrupt(Company *c)
Check for bankruptcy of a company.
RailType
Enumeration for all possible railtypes.
static T ClrBit(T &x, const uint8 y)
Clears a bit in a variable.
void CompaniesMonthlyLoop()
Monthly update of the economic data (of the companies as well as economic fluctuations).
uint16 produced_cargo_waiting[INDUSTRY_NUM_OUTPUTS]
amount of cargo produced per cargo
GUISettings gui
settings related to the GUI
const GRFFile * GetGRF() const
Retrieve the NewGRF the engine is tied to.
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
static Track RemoveFirstTrack(TrackBits *tracks)
Removes first Track from TrackBits and returns it.
void RecomputePrices()
Computes all prices, payments and maximum loan.
Whenever cargo payment is made for a vehicle.
static Money StationMaintenanceCost(uint32 num)
Calculates the maintenance cost of a number of station tiles.
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo ID.
Action to check if a vehicle has no stored cargo.
bool gradual_loading
load vehicles gradually
static SmallIndustryList _cargo_delivery_destinations
The industries we've currently brought cargo to.
Ships list; Window numbers:
uint32 TileIndex
The index/ID of a Tile.
Functions related to objects.
uint DistanceManhattan(TileIndex t0, TileIndex t1)
Gets the Manhattan distance between the two given tiles.
Cargo support for NewGRFs.
uint16 servint_trains
service interval for trains
static const uint64 MAX_INFLATION
Maximum inflation (including fractional part) without causing overflows in int64 price computations...
Vehicle * Next() const
Get the next vehicle of this vehicle.
sell a share from a company
The company went belly-up.
bool include(std::vector< T > &vec, const T &item)
Helper function to append an item to a vector if it is not already contained Consider using std::set...
CargoPayment * cargo_payment
The cargo payment we're currently in.
static bool IsLevelCrossingTile(TileIndex t)
Return whether a tile is a level crossing tile.
OrderSettings order
settings related to orders
CargoArray delivered_cargo
The amount of delivered cargo.
Track
These are used to specify a single track.
int UpdateCompanyRatingAndValue(Company *c, bool update)
if update is set to true, the economy is updated with this score (also the house is updated...
uint16 SourceID
Contains either industry ID, town ID or company ID (or INVALID_SOURCE)
Cargo transport monitoring declarations.
bool servint_ispercent
service intervals are in percents
void AddCargoDelivery(CargoID cargo_type, CompanyID company, uint32 amount, SourceType src_type, SourceID src, const Station *st, IndustryID dest)
Cargo was delivered to its final destination, update the pickup and delivery maps.
StationIDStack GetNextStoppingStation() const
Get the next station the vehicle will stop at.
UnitID NextID()
Returns next free UnitID.
TileIndex xy
Base tile of the station.
Trigger platform when train loads/unloads.
static void UpdateAutoreplace(CompanyID company)
Update autoreplace_defined and autoreplace_finished of all statistics of a company.
void RebuildSubsidisedSourceAndDestinationCache()
Perform a full rebuild of the subsidies cache.
static uint GB(const T x, const uint8 s, const uint8 n)
Fetch n bits from x, started at bit s.
uint16 cached_total_length
Length of the whole vehicle (valid only for the first engine).
Trains list; Window numbers:
CompanyEconomyEntry old_economy[MAX_HISTORY_QUARTERS]
Economic data of the company of the last MAX_HISTORY_QUARTERS quarters.
Full load all cargoes of the consist.
VehicleType type
Type of vehicle.
void SubtractMoneyFromCompany(CommandCost cost)
Subtract money from the _current_company, if the company is valid.
void ResetPriceBaseMultipliers()
Reset changes to the price base multipliers.
PrepareRefitAction(CargoArray &consist_capleft, CargoTypes &refit_mask)
Create a refit preparation action.
Maximum number of companies.
call production callback when cargo arrives at the industry
uint32 industry_daily_change_counter
Bits 31-16 are number of industry to be performed, 15-0 are fractional collected daily.
int16 fluct
Economy fluctuation status.
uint8 loading_indicators
show loading indicators
uint64 inflation_payment
Cumulated inflation of cargo paypent since game start; 16 bit fractional part.
uint16 servint_aircraft
service interval for aircraft
uint8 exclusive_counter
months till the exclusivity expires
Totally no unloading will be done.
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function() ...
static Money CanalMaintenanceCost(uint32 num)
Calculates the maintenance cost of a number of canal tiles.
Aircraft list; Window numbers:
Vehicle details; Window numbers:
static uint CountBits(T value)
Counts the number of set bits in a variable.
Base functions for all Games.
Functions related to commands.
Network functions used by other parts of OpenTTD.
bool _network_server
network-server is active
CargoPaymentPool _cargo_payment_pool("CargoPayment")
The actual pool to store cargo payments in.
uint8 CalcPercentVehicleFilled(const Vehicle *front, StringID *colour)
Calculates how full a vehicle is.
bool HasCargoFor(StationIDStack next) const
Check for cargo headed for a specific station.
CompanyID _current_company
Company currently doing an action.
Owner owner
The owner of this station.
static void CountEngine(const Vehicle *v, int delta)
Update num_engines when adding/removing an engine.
Base classes related to the economy.
uint ReservedCount() const
Returns sum of reserved cargo.
static WindowClass GetWindowClassForVehicleType(VehicleType vt)
Get WindowClass for vehicle list of given vehicle type.
Load the cargo from the station.
void StartupIndustryDailyChanges(bool init_counter)
Initialize the variables that will maintain the daily industry change system.
uint16 GetVehicleCallback(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v)
Evaluate a newgrf callback for vehicles.
Delivered cargo graph; Window numbers:
ScoreID
Score categories in the detailed performance rating.
void ChangeWindowOwner(Owner old_owner, Owner new_owner)
Change the owner of all the windows one company can take over from another company in the case of a c...
bool economy
how volatile is the economy
void ShowFeederIncomeAnimation(int x, int y, int z, Money transfer, Money income)
Display animated feeder income.
Price is affected by "vehicle running cost" difficulty setting.
Statistics about the economy.
EngineID engine_type
The type of engine used for this vehicle.
byte initial_interest
amount of interest (to pay over the loan)
uint16 vehicle_flags
Used for gradual loading and other miscellaneous things (.
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
bool IsValid() const
Tests for validity of this cargospec.
Functions related to NewGRF provided sounds.
void Restore()
Restore the variable.
Base functions for all AIs.
void AddNewsItem(StringID string, NewsType type, NewsFlag flags, NewsReferenceType reftype1=NR_NONE, uint32 ref1=UINT32_MAX, NewsReferenceType reftype2=NR_NONE, uint32 ref2=UINT32_MAX, void *free_data=nullptr)
Add a new newsitem to be shown.
Data structure for storing how the score is computed for a single score id.
bool AddInflation(bool check_year)
Add monthly inflation.
int needed
How much you need to get the perfect score.
GameCreationSettings game_creation
settings used during the creation of a game (map)
uint AvailableCount() const
Returns sum of cargo still available for loading at the sation.
uint16 servint_roadveh
service interval for road vehicles
byte CargoID
Cargo slots to indicate a cargo type within a game.
Money income
The amount of income.
static void CompaniesPayInterest()
Let all companies pay the monthly interest on their loan.
Money company_value
The value of the company.
byte time_since_pickup
Number of rating-intervals (up to 255) since the last vehicle tried to load this cargo.
Functions related to water (management)
void ShowCostOrIncomeAnimation(int x, int y, int z, Money cost)
Display animated income or costs on the map.
Force unloading all cargo onto the platform, possibly not getting paid.
Money profit_this_year
Profit this year << 8, low 8 bits are fract.
CompanyEconomyEntry cur_economy
Economic data of the company of this quarter.
Use the new capacity algorithm. The default cargotype of the vehicle does not affect capacity multipl...
static Money RailMaintenanceCost(RailType railtype, uint32 num, uint32 total_num)
Calculates the maintenance cost of a number of track bits.
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
Trigger station when cargo is completely taken.
Functions related to news.
Base classes/functions for stations.
call production callback every 256 ticks
CargoArray & consist_capleft
Capacities left in the consist.
VehicleCache vcache
Cache of often used vehicle values.
static Station * Get(size_t index)
Gets station with given index.
Date _date
Current date in days (day counter)
static uint DeliverGoodsToIndustry(const Station *st, CargoID cargo_type, uint num_pieces, IndustryID source, CompanyID company)
Transfer goods from station to industry.
Functions related to autoreplacing.
StationID current_station
The current station.
Company view; Window numbers:
CompanyID exclusivity
which company has exclusivity
static void HandleStationRefit(Vehicle *v, CargoArray &consist_capleft, Station *st, StationIDStack next_station, CargoID new_cid)
Refit a vehicle in a station.
uint GetPlatformLength(TileIndex tile, DiagDirection dir) const override
Determines the REMAINING length of a platform, starting at (and including) the given tile...
byte construction_cost
how expensive is building
Full load a single cargo of the consist.
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
uint8 feeder_payment_share
percentage of leg payment to virtually pay in feeder systems
static bool IsCompanyBuildableVehicleType(VehicleType type)
Is the given vehicle type buildable by a company?
Year starting_year
starting date
Base class and functions for all vehicles that move through ground.
Class for backupping variables and making sure they are restored later.
Functions related to subsidies.
Set when the station accepts the cargo currently for final deliveries.
Order current_order
The current order (+ status, like: loading)
bool do_reserve
If the vehicle should reserve.
const T GetSum() const
Get the sum of all cargo amounts.
Performance history graph; Window numbers:
void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
Mark window data of the window of a given class and specific window number as invalid (in need of re-...
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
CargoID GetRefitCargo() const
Get the cargo to to refit to.
Source/destination is an industry.
bool operator()(Vehicle *v)
Return all reserved cargo from a vehicle.
Economic changes (recession, industry up/dowm)
Dynamic data of a loaded NewGRF.
static void SetDParam(uint n, uint64 v)
Set a string parameter v at index n in the global string parameter array.
CargoTypes always_accepted
Bitmask of always accepted cargo types (by houses, HQs, industry tiles when industry doesn't accept c...
Money visual_transfer
The transfer credits to be shown.