2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 /** @file economy.cpp Handling of the economy. */
11 #include "company_func.h"
12 #include "command_func.h"
15 #include "news_func.h"
16 #include "network/network.h"
17 #include "network/network_func.h"
21 #include "newgrf_engine.h"
22 #include "engine_base.h"
23 #include "ground_vehicle.hpp"
24 #include "newgrf_cargo.h"
25 #include "newgrf_sound.h"
26 #include "newgrf_industrytiles.h"
27 #include "newgrf_station.h"
28 #include "newgrf_airporttiles.h"
29 #include "newgrf_roadstop.h"
31 #include "strings_func.h"
32 #include "vehicle_func.h"
33 #include "sound_func.h"
34 #include "autoreplace_func.h"
35 #include "company_gui.h"
36 #include "signs_base.h"
37 #include "subsidy_base.h"
38 #include "subsidy_func.h"
39 #include "station_base.h"
40 #include "waypoint_base.h"
41 #include "economy_base.h"
42 #include "core/pool_func.hpp"
43 #include "core/backup_type.hpp"
44 #include "core/container_func.hpp"
45 #include "cargo_type.h"
47 #include "game/game.hpp"
48 #include "cargomonitor.h"
49 #include "goal_base.h"
50 #include "story_base.h"
51 #include "linkgraph/refresh.h"
52 #include "company_cmd.h"
53 #include "economy_cmd.h"
54 #include "vehicle_cmd.h"
55 #include "timer/timer.h"
56 #include "timer/timer_game_calendar.h"
57 #include "timer/timer_game_economy.h"
59 #include "table/strings.h"
60 #include "table/pricebase.h"
62 #include "safeguards.h"
65 /* Initialize the cargo payment-pool */
66 CargoPaymentPool
_cargo_payment_pool("CargoPayment");
67 INSTANTIATE_POOL_METHODS(CargoPayment
)
70 * Multiply two integer values and shift the results to right.
72 * This function multiplies two integer values. The result is
73 * shifted by the amount of shift to right.
75 * @param a The first integer
76 * @param b The second integer
77 * @param shift The amount to shift the value to right.
78 * @return The shifted result
80 static inline int32_t BigMulS(const int32_t a
, const int32_t b
, const uint8_t shift
)
82 return (int32_t)((int64_t)a
* (int64_t)b
>> shift
);
85 typedef std::vector
<Industry
*> SmallIndustryList
;
88 * Score info, values used for computing the detailed performance rating.
90 const ScoreInfo _score_info
[] = {
91 { 120, 100}, // SCORE_VEHICLES
92 { 80, 100}, // SCORE_STATIONS
93 { 10000, 100}, // SCORE_MIN_PROFIT
94 { 50000, 50}, // SCORE_MIN_INCOME
95 { 100000, 100}, // SCORE_MAX_INCOME
96 { 40000, 400}, // SCORE_DELIVERED
97 { 8, 50}, // SCORE_CARGO
98 {10000000, 50}, // SCORE_MONEY
99 { 250000, 50}, // SCORE_LOAN
100 { 0, 0} // SCORE_TOTAL
103 int64_t _score_part
[MAX_COMPANIES
][SCORE_END
];
106 static PriceMultipliers _price_base_multiplier
;
109 * Calculate the value of the assets of a company.
111 * @param c The company to calculate the value of.
112 * @return The value of the assets of the company.
114 static Money
CalculateCompanyAssetValue(const Company
*c
)
116 Owner owner
= c
->index
;
120 for (const Station
*st
: Station::Iterate()) {
121 if (st
->owner
== owner
) num
+= CountBits((uint8_t)st
->facilities
);
124 Money value
= num
* _price
[PR_STATION_VALUE
] * 25;
126 for (const Vehicle
*v
: Vehicle::Iterate()) {
127 if (v
->owner
!= owner
) continue;
129 if (v
->type
== VEH_TRAIN
||
130 v
->type
== VEH_ROAD
||
131 (v
->type
== VEH_AIRCRAFT
&& Aircraft::From(v
)->IsNormalAircraft()) ||
132 v
->type
== VEH_SHIP
) {
133 value
+= v
->value
* 3 >> 1;
141 * Calculate the value of the company. That is the value of all
142 * assets (vehicles, stations) and money (including loan),
143 * except when including_loan is \c false which is useful when
144 * we want to calculate the value for bankruptcy.
145 * @param c the company to get the value of.
146 * @param including_loan include the loan in the company value.
147 * @return the value of the company.
149 Money
CalculateCompanyValue(const Company
*c
, bool including_loan
)
151 Money value
= CalculateCompanyAssetValue(c
);
153 /* Add real money value */
154 if (including_loan
) value
-= c
->current_loan
;
157 return std::max
<Money
>(value
, 1);
161 * Calculate what you have to pay to take over a company.
163 * This is different from bankruptcy and company value, and involves a few
164 * more parameters to make it more realistic.
166 * You have to pay for:
167 * - The value of all the assets in the company.
168 * - The loan the company has (the investors really want their money back).
169 * - The profit for the next two years (if positive) based on the last four quarters.
171 * And on top of that, they walk away with all the money they have in the bank.
173 * @param c the company to get the value of.
174 * @return The value of the company.
176 Money
CalculateHostileTakeoverValue(const Company
*c
)
178 Money value
= CalculateCompanyAssetValue(c
);
180 value
+= c
->current_loan
;
181 /* Negative balance is basically a loan. */
186 for (int quarter
= 0; quarter
< 4; quarter
++) {
187 value
+= std::max
<Money
>(c
->old_economy
[quarter
].income
+ c
->old_economy
[quarter
].expenses
, 0) * 2;
190 return std::max
<Money
>(value
, 1);
194 * if update is set to true, the economy is updated with this score
195 * (also the house is updated, should only be true in the on-tick event)
196 * @param update the economy with calculated score
197 * @param c company been evaluated
198 * @return actual score of this company
201 int UpdateCompanyRatingAndValue(Company
*c
, bool update
)
203 Owner owner
= c
->index
;
206 memset(_score_part
[owner
], 0, sizeof(_score_part
[owner
]));
210 Money min_profit
= 0;
211 bool min_profit_first
= true;
214 for (const Vehicle
*v
: Vehicle::Iterate()) {
215 if (v
->owner
!= owner
) continue;
216 if (IsCompanyBuildableVehicleType(v
->type
) && v
->IsPrimaryVehicle()) {
217 if (v
->profit_last_year
> 0) num
++; // For the vehicle score only count profitable vehicles
218 if (v
->economy_age
> VEHICLE_PROFIT_MIN_AGE
) {
219 /* Find the vehicle with the lowest amount of profit */
220 if (min_profit_first
|| min_profit
> v
->profit_last_year
) {
221 min_profit
= v
->profit_last_year
;
222 min_profit_first
= false;
228 min_profit
>>= 8; // remove the fract part
230 _score_part
[owner
][SCORE_VEHICLES
] = num
;
231 /* Don't allow negative min_profit to show */
232 if (min_profit
> 0) {
233 _score_part
[owner
][SCORE_MIN_PROFIT
] = min_profit
;
240 for (const Station
*st
: Station::Iterate()) {
241 /* Only count stations that are actually serviced */
242 if (st
->owner
== owner
&& (st
->time_since_load
<= 20 || st
->time_since_unload
<= 20)) num
+= CountBits((uint8_t)st
->facilities
);
244 _score_part
[owner
][SCORE_STATIONS
] = num
;
247 /* Generate statistics depending on recent income statistics */
249 int numec
= std::min
<uint
>(c
->num_valid_stat_ent
, 12u);
251 const CompanyEconomyEntry
*cee
= c
->old_economy
;
252 Money min_income
= cee
->income
+ cee
->expenses
;
253 Money max_income
= cee
->income
+ cee
->expenses
;
256 min_income
= std::min(min_income
, cee
->income
+ cee
->expenses
);
257 max_income
= std::max(max_income
, cee
->income
+ cee
->expenses
);
258 } while (++cee
, --numec
);
260 if (min_income
> 0) {
261 _score_part
[owner
][SCORE_MIN_INCOME
] = min_income
;
264 _score_part
[owner
][SCORE_MAX_INCOME
] = max_income
;
268 /* Generate score depending on amount of transported cargo */
270 int numec
= std::min
<uint
>(c
->num_valid_stat_ent
, 4u);
272 const CompanyEconomyEntry
*cee
= c
->old_economy
;
273 OverflowSafeInt64 total_delivered
= 0;
275 total_delivered
+= cee
->delivered_cargo
.GetSum
<OverflowSafeInt64
>();
276 } while (++cee
, --numec
);
278 _score_part
[owner
][SCORE_DELIVERED
] = total_delivered
;
282 /* Generate score for variety of cargo */
284 _score_part
[owner
][SCORE_CARGO
] = c
->old_economy
->delivered_cargo
.GetCount();
287 /* Generate score for company's money */
290 _score_part
[owner
][SCORE_MONEY
] = c
->money
;
294 /* Generate score for loan */
296 _score_part
[owner
][SCORE_LOAN
] = _score_info
[SCORE_LOAN
].needed
- c
->current_loan
;
299 /* Now we calculate the score for each item.. */
304 for (ScoreID i
= SCORE_BEGIN
; i
< SCORE_END
; i
++) {
306 if (i
== SCORE_TOTAL
) continue;
307 /* Check the score */
308 s
= Clamp
<int64_t>(_score_part
[owner
][i
], 0, _score_info
[i
].needed
) * _score_info
[i
].score
/ _score_info
[i
].needed
;
310 total_score
+= _score_info
[i
].score
;
313 _score_part
[owner
][SCORE_TOTAL
] = score
;
315 /* We always want the score scaled to SCORE_MAX (1000) */
316 if (total_score
!= SCORE_MAX
) score
= score
* SCORE_MAX
/ total_score
;
320 c
->old_economy
[0].performance_history
= score
;
321 UpdateCompanyHQ(c
->location_of_HQ
, score
);
322 c
->old_economy
[0].company_value
= CalculateCompanyValue(c
);
325 SetWindowDirty(WC_PERFORMANCE_DETAIL
, 0);
330 * Change the ownership of all the items of a company.
331 * @param old_owner The company that gets removed.
332 * @param new_owner The company to merge to, or INVALID_OWNER to remove the company.
334 void ChangeOwnershipOfCompanyItems(Owner old_owner
, Owner new_owner
)
336 /* We need to set _current_company to old_owner before we try to move
337 * the client. This is needed as it needs to know whether "you" really
338 * are the current local company. */
339 Backup
<CompanyID
> cur_company(_current_company
, old_owner
);
340 /* In all cases, make spectators of clients connected to that company */
341 if (_networking
) NetworkClientsToSpectators(old_owner
);
342 if (old_owner
== _local_company
) {
343 /* Single player cheated to AI company.
344 * There are no spectators in singleplayer mode, so we must pick some other company. */
345 assert(!_networking
);
346 Backup
<CompanyID
> cur_company2(_current_company
);
347 for (const Company
*c
: Company::Iterate()) {
348 if (c
->index
!= old_owner
) {
349 SetLocalCompany(c
->index
);
353 cur_company2
.Restore();
354 assert(old_owner
!= _local_company
);
357 assert(old_owner
!= new_owner
);
359 /* Temporarily increase the company's money, to be sure that
360 * removing their property doesn't fail because of lack of money.
361 * Not too drastically though, because it could overflow */
362 if (new_owner
== INVALID_OWNER
) {
363 Company::Get(old_owner
)->money
= UINT64_MAX
>> 2; // jackpot ;p
366 for (Subsidy
*s
: Subsidy::Iterate()) {
367 if (s
->awarded
== old_owner
) {
368 if (new_owner
== INVALID_OWNER
) {
371 s
->awarded
= new_owner
;
375 if (new_owner
== INVALID_OWNER
) RebuildSubsidisedSourceAndDestinationCache();
377 /* Take care of rating and transport rights in towns */
378 for (Town
*t
: Town::Iterate()) {
379 /* If a company takes over, give the ratings to that company. */
380 if (new_owner
!= INVALID_OWNER
) {
381 if (HasBit(t
->have_ratings
, old_owner
)) {
382 if (HasBit(t
->have_ratings
, new_owner
)) {
383 /* use max of the two ratings. */
384 t
->ratings
[new_owner
] = std::max(t
->ratings
[new_owner
], t
->ratings
[old_owner
]);
386 SetBit(t
->have_ratings
, new_owner
);
387 t
->ratings
[new_owner
] = t
->ratings
[old_owner
];
392 /* Reset the ratings for the old owner */
393 t
->ratings
[old_owner
] = RATING_INITIAL
;
394 ClrBit(t
->have_ratings
, old_owner
);
396 /* Transfer exclusive rights */
397 if (t
->exclusive_counter
> 0 && t
->exclusivity
== old_owner
) {
398 if (new_owner
!= INVALID_OWNER
) {
399 t
->exclusivity
= new_owner
;
401 t
->exclusive_counter
= 0;
402 t
->exclusivity
= INVALID_COMPANY
;
408 for (Vehicle
*v
: Vehicle::Iterate()) {
409 if (v
->owner
== old_owner
&& IsCompanyBuildableVehicleType(v
->type
)) {
410 if (new_owner
== INVALID_OWNER
) {
411 if (v
->Previous() == nullptr) delete v
;
413 if (v
->IsEngineCountable()) GroupStatistics::CountEngine(v
, -1);
414 if (v
->IsPrimaryVehicle()) GroupStatistics::CountVehicle(v
, -1);
420 /* In all cases clear replace engine rules.
421 * Even if it was copied, it could interfere with new owner's rules */
422 RemoveAllEngineReplacementForCompany(Company::Get(old_owner
));
424 if (new_owner
== INVALID_OWNER
) {
425 RemoveAllGroupsForCompany(old_owner
);
427 Company
*c
= Company::Get(old_owner
);
428 for (Group
*g
: Group::Iterate()) {
429 if (g
->owner
== old_owner
) {
430 g
->owner
= new_owner
;
431 g
->number
= c
->freegroups
.UseID(c
->freegroups
.NextID());
437 Company
*new_company
= new_owner
== INVALID_OWNER
? nullptr : Company::Get(new_owner
);
439 /* Override company settings to new company defaults in case we need to convert them.
440 * This is required as the CmdChangeServiceInt doesn't copy the supplied value when it is non-custom
442 if (new_owner
!= INVALID_OWNER
) {
443 Company
*old_company
= Company::Get(old_owner
);
445 old_company
->settings
.vehicle
.servint_aircraft
= new_company
->settings
.vehicle
.servint_aircraft
;
446 old_company
->settings
.vehicle
.servint_trains
= new_company
->settings
.vehicle
.servint_trains
;
447 old_company
->settings
.vehicle
.servint_roadveh
= new_company
->settings
.vehicle
.servint_roadveh
;
448 old_company
->settings
.vehicle
.servint_ships
= new_company
->settings
.vehicle
.servint_ships
;
449 old_company
->settings
.vehicle
.servint_ispercent
= new_company
->settings
.vehicle
.servint_ispercent
;
452 for (Vehicle
*v
: Vehicle::Iterate()) {
453 if (v
->owner
== old_owner
&& IsCompanyBuildableVehicleType(v
->type
)) {
454 assert(new_owner
!= INVALID_OWNER
);
456 /* Correct default values of interval settings while maintaining custom set ones.
457 * This prevents invalid values on mismatching company defaults being accepted.
459 if (!v
->ServiceIntervalIsCustom()) {
460 /* Technically, passing the interval is not needed as the command will query the default value itself.
461 * However, do not rely on that behaviour.
463 int interval
= CompanyServiceInterval(new_company
, v
->type
);
464 Command
<CMD_CHANGE_SERVICE_INT
>::Do(DC_EXEC
| DC_BANKRUPT
, v
->index
, interval
, false, new_company
->settings
.vehicle
.servint_ispercent
);
467 v
->owner
= new_owner
;
469 /* Owner changes, clear cache */
470 v
->colourmap
= PAL_NONE
;
471 v
->InvalidateNewGRFCache();
473 if (v
->IsEngineCountable()) {
474 GroupStatistics::CountEngine(v
, 1);
476 if (v
->IsPrimaryVehicle()) {
477 GroupStatistics::CountVehicle(v
, 1);
478 auto &unitidgen
= new_company
->freeunits
[v
->type
];
479 v
->unitnumber
= unitidgen
.UseID(unitidgen
.NextID());
482 /* Invalidate the vehicle's cargo payment "owner cache". */
483 if (v
->cargo_payment
!= nullptr) v
->cargo_payment
->owner
= nullptr;
487 if (new_owner
!= INVALID_OWNER
) GroupStatistics::UpdateAutoreplace(new_owner
);
490 /* Change ownership of tiles */
494 ChangeTileOwner(tile
, old_owner
, new_owner
);
495 } while (++tile
!= Map::Size());
497 if (new_owner
!= INVALID_OWNER
) {
498 /* Update all signals because there can be new segment that was owned by two companies
499 * and signals were not propagated
500 * Similar with crossings - it is needed to bar crossings that weren't before
501 * because of different owner of crossing and approaching train */
505 if (IsTileType(tile
, MP_RAILWAY
) && IsTileOwner(tile
, new_owner
) && HasSignals(tile
)) {
506 TrackBits tracks
= GetTrackBits(tile
);
507 do { // there may be two tracks with signals for TRACK_BIT_HORZ and TRACK_BIT_VERT
508 Track track
= RemoveFirstTrack(&tracks
);
509 if (HasSignalOnTrack(tile
, track
)) AddTrackToSignalBuffer(tile
, track
, new_owner
);
510 } while (tracks
!= TRACK_BIT_NONE
);
511 } else if (IsLevelCrossingTile(tile
) && IsTileOwner(tile
, new_owner
)) {
512 UpdateLevelCrossing(tile
);
514 } while (++tile
!= Map::Size());
517 /* update signals in buffer */
518 UpdateSignalsInBuffer();
521 /* Add airport infrastructure count of the old company to the new one. */
522 if (new_owner
!= INVALID_OWNER
) Company::Get(new_owner
)->infrastructure
.airport
+= Company::Get(old_owner
)->infrastructure
.airport
;
524 /* convert owner of stations (including deleted ones, but excluding buoys) */
525 for (Station
*st
: Station::Iterate()) {
526 if (st
->owner
== old_owner
) {
527 /* if a company goes bankrupt, set owner to OWNER_NONE so the sign doesn't disappear immediately
528 * also, drawing station window would cause reading invalid company's colour */
529 st
->owner
= new_owner
== INVALID_OWNER
? OWNER_NONE
: new_owner
;
533 /* do the same for waypoints (we need to do this here so deleted waypoints are converted too) */
534 for (Waypoint
*wp
: Waypoint::Iterate()) {
535 if (wp
->owner
== old_owner
) {
536 wp
->owner
= new_owner
== INVALID_OWNER
? OWNER_NONE
: new_owner
;
540 for (Sign
*si
: Sign::Iterate()) {
541 if (si
->owner
== old_owner
) si
->owner
= new_owner
== INVALID_OWNER
? OWNER_NONE
: new_owner
;
544 /* Remove Game Script created Goals, CargoMonitors and Story pages. */
545 for (Goal
*g
: Goal::Iterate()) {
546 if (g
->company
== old_owner
) delete g
;
549 ClearCargoPickupMonitoring(old_owner
);
550 ClearCargoDeliveryMonitoring(old_owner
);
552 for (StoryPage
*sp
: StoryPage::Iterate()) {
553 if (sp
->company
== old_owner
) delete sp
;
556 /* Change colour of existing windows */
557 if (new_owner
!= INVALID_OWNER
) ChangeWindowOwner(old_owner
, new_owner
);
559 cur_company
.Restore();
561 MarkWholeScreenDirty();
565 * Check for bankruptcy of a company. Called every three months.
566 * @param c Company to check.
568 static void CompanyCheckBankrupt(Company
*c
)
570 /* If "Infinite money" setting is on, companies should not go bankrupt. */
571 if (_settings_game
.difficulty
.infinite_money
) return;
573 /* If the company has money again, it does not go bankrupt */
574 if (c
->money
- c
->current_loan
>= -c
->GetMaxLoan()) {
575 int previous_months_of_bankruptcy
= CeilDiv(c
->months_of_bankruptcy
, 3);
576 c
->months_of_bankruptcy
= 0;
577 c
->bankrupt_asked
= 0;
578 if (previous_months_of_bankruptcy
!= 0) CompanyAdminUpdate(c
);
582 c
->months_of_bankruptcy
++;
584 switch (c
->months_of_bankruptcy
) {
585 /* All the boring cases (months) with a bad balance where no action is taken */
598 /* Warn about bankruptcy after 3 months */
600 CompanyNewsInformation
*cni
= new CompanyNewsInformation(c
);
601 SetDParam(0, STR_NEWS_COMPANY_IN_TROUBLE_TITLE
);
602 SetDParam(1, STR_NEWS_COMPANY_IN_TROUBLE_DESCRIPTION
);
603 SetDParamStr(2, cni
->company_name
);
604 AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT
, cni
);
605 AI::BroadcastNewEvent(new ScriptEventCompanyInTrouble(c
->index
));
606 Game::NewEvent(new ScriptEventCompanyInTrouble(c
->index
));
610 /* Offer company for sale after 6 months */
612 /* Don't consider the loan */
613 Money val
= CalculateCompanyValue(c
, false);
615 c
->bankrupt_value
= val
;
616 c
->bankrupt_asked
= 1 << c
->index
; // Don't ask the owner
617 c
->bankrupt_timeout
= 0;
619 /* The company assets should always have some value */
620 assert(c
->bankrupt_value
> 0);
624 /* Bankrupt company after 6 months (if the company has no value) or latest
625 * after 9 months (if it still had value after 6 months) */
628 if (!_networking
&& _local_company
== c
->index
) {
629 /* If we are in singleplayer mode, leave the company playing. Eg. there
630 * is no THE-END, otherwise mark the client as spectator to make sure
631 * they are no longer in control of this company. However... when you
632 * join another company (cheat) the "unowned" company can bankrupt. */
633 c
->bankrupt_asked
= MAX_UVALUE(CompanyMask
);
637 /* Actually remove the company, but not when we're a network client.
638 * In case of network clients we will be getting a command from the
639 * server. It is done in this way as we are called from the
640 * StateGameLoop which can't change the current company, and thus
641 * updating the local company triggers an assert later on. In the
642 * case of a network game the command will be processed at a time
643 * that changing the current company is okay. In case of single
644 * player we are sure (the above check) that we are not the local
645 * company and thus we won't be moved. */
646 if (!_networking
|| _network_server
) {
647 Command
<CMD_COMPANY_CTRL
>::Post(CCA_DELETE
, c
->index
, CRR_BANKRUPT
, INVALID_CLIENT_ID
);
654 if (CeilDiv(c
->months_of_bankruptcy
, 3) != CeilDiv(c
->months_of_bankruptcy
- 1, 3)) CompanyAdminUpdate(c
);
658 * Update the finances of all companies.
659 * Pay for the stations, update the history graph, update ratings and company values, and deal with bankruptcy.
661 static void CompaniesGenStatistics()
663 /* Check for bankruptcy each month */
664 for (Company
*c
: Company::Iterate()) {
665 CompanyCheckBankrupt(c
);
668 Backup
<CompanyID
> cur_company(_current_company
);
670 /* Pay Infrastructure Maintenance, if enabled */
671 if (_settings_game
.economy
.infrastructure_maintenance
) {
672 /* Improved monthly infrastructure costs. */
673 for (const Company
*c
: Company::Iterate()) {
674 cur_company
.Change(c
->index
);
676 CommandCost
cost(EXPENSES_PROPERTY
);
677 uint32_t rail_total
= c
->infrastructure
.GetRailTotal();
678 for (RailType rt
= RAILTYPE_BEGIN
; rt
< RAILTYPE_END
; rt
++) {
679 if (c
->infrastructure
.rail
[rt
] != 0) cost
.AddCost(RailMaintenanceCost(rt
, c
->infrastructure
.rail
[rt
], rail_total
));
681 cost
.AddCost(SignalMaintenanceCost(c
->infrastructure
.signal
));
682 uint32_t road_total
= c
->infrastructure
.GetRoadTotal();
683 uint32_t tram_total
= c
->infrastructure
.GetTramTotal();
684 for (RoadType rt
= ROADTYPE_BEGIN
; rt
< ROADTYPE_END
; rt
++) {
685 if (c
->infrastructure
.road
[rt
] != 0) cost
.AddCost(RoadMaintenanceCost(rt
, c
->infrastructure
.road
[rt
], RoadTypeIsRoad(rt
) ? road_total
: tram_total
));
687 cost
.AddCost(CanalMaintenanceCost(c
->infrastructure
.water
));
688 cost
.AddCost(StationMaintenanceCost(c
->infrastructure
.station
));
689 cost
.AddCost(AirportMaintenanceCost(c
->index
));
691 SubtractMoneyFromCompany(cost
);
694 cur_company
.Restore();
696 /* Only run the economic statics and update company stats every 3rd economy month (1st of quarter). */
697 if (!HasBit(1 << 0 | 1 << 3 | 1 << 6 | 1 << 9, TimerGameEconomy::month
)) return;
699 for (Company
*c
: Company::Iterate()) {
700 /* Drop the oldest history off the end */
701 std::copy_backward(c
->old_economy
, c
->old_economy
+ MAX_HISTORY_QUARTERS
- 1, c
->old_economy
+ MAX_HISTORY_QUARTERS
);
702 c
->old_economy
[0] = c
->cur_economy
;
705 if (c
->num_valid_stat_ent
!= MAX_HISTORY_QUARTERS
) c
->num_valid_stat_ent
++;
707 UpdateCompanyRatingAndValue(c
, true);
708 if (c
->block_preview
!= 0) c
->block_preview
--;
711 SetWindowDirty(WC_INCOME_GRAPH
, 0);
712 SetWindowDirty(WC_OPERATING_PROFIT
, 0);
713 SetWindowDirty(WC_DELIVERED_CARGO
, 0);
714 SetWindowDirty(WC_PERFORMANCE_HISTORY
, 0);
715 SetWindowDirty(WC_COMPANY_VALUE
, 0);
716 SetWindowDirty(WC_COMPANY_LEAGUE
, 0);
720 * Add monthly inflation
721 * @param check_year Shall the inflation get stopped after 170 years?
722 * @return true if inflation is maxed and nothing was changed
724 bool AddInflation(bool check_year
)
726 /* The cargo payment inflation differs from the normal inflation, so the
727 * relative amount of money you make with a transport decreases slowly over
728 * the 170 years. After a few hundred years we reach a level in which the
729 * games will become unplayable as the maximum income will be less than
730 * the minimum running cost.
732 * Furthermore there are a lot of inflation related overflows all over the
733 * place. Solving them is hardly possible because inflation will always
734 * reach the overflow threshold some day. So we'll just perform the
735 * inflation mechanism during the first 170 years (the amount of years that
736 * one had in the original TTD) and stop doing the inflation after that
737 * because it only causes problems that can't be solved nicely and the
738 * inflation doesn't add anything after that either; it even makes playing
739 * it impossible due to the diverging cost and income rates.
741 if (check_year
&& (TimerGameCalendar::year
< CalendarTime::ORIGINAL_BASE_YEAR
|| TimerGameCalendar::year
>= CalendarTime::ORIGINAL_MAX_YEAR
)) return true;
743 if (_economy
.inflation_prices
== MAX_INFLATION
|| _economy
.inflation_payment
== MAX_INFLATION
) return true;
745 /* Approximation for (100 + infl_amount)% ** (1 / 12) - 100%
747 * 12 -> months per year
748 * This is only a good approximation for small values
750 _economy
.inflation_prices
+= (_economy
.inflation_prices
* _economy
.infl_amount
* 54) >> 16;
751 _economy
.inflation_payment
+= (_economy
.inflation_payment
* _economy
.infl_amount_pr
* 54) >> 16;
753 if (_economy
.inflation_prices
> MAX_INFLATION
) _economy
.inflation_prices
= MAX_INFLATION
;
754 if (_economy
.inflation_payment
> MAX_INFLATION
) _economy
.inflation_payment
= MAX_INFLATION
;
760 * Computes all prices, payments and maximum loan.
762 void RecomputePrices()
764 /* Setup maximum loan as a rounded down multiple of LOAN_INTERVAL. */
765 _economy
.max_loan
= ((uint64_t)_settings_game
.difficulty
.max_loan
* _economy
.inflation_prices
>> 16) / LOAN_INTERVAL
* LOAN_INTERVAL
;
767 /* Setup price bases */
768 for (Price i
= PR_BEGIN
; i
< PR_END
; i
++) {
769 Money price
= _price_base_specs
[i
].start_price
;
771 /* Apply difficulty settings */
773 switch (_price_base_specs
[i
].category
) {
775 mod
= _settings_game
.difficulty
.vehicle_costs
;
778 case PCAT_CONSTRUCTION
:
779 mod
= _settings_game
.difficulty
.construction_cost
;
785 case 0: price
*= 6; break;
786 case 1: price
*= 8; break; // normalised to 1 below
787 case 2: price
*= 9; break;
788 default: NOT_REACHED();
791 /* Apply inflation */
792 price
= (int64_t)price
* _economy
.inflation_prices
;
794 /* Apply newgrf modifiers, remove fractional part of inflation, and normalise on medium difficulty. */
795 int shift
= _price_base_multiplier
[i
] - 16 - 3;
802 /* Make sure the price does not get reduced to zero.
803 * Zero breaks quite a few commands that use a zero
804 * cost to see whether something got changed or not
805 * and based on that cause an error. When the price
806 * is zero that fails even when things are done. */
808 price
= Clamp(_price_base_specs
[i
].start_price
, -1, 1);
809 /* No base price should be zero, but be sure. */
816 /* Setup cargo payment */
817 for (CargoSpec
*cs
: CargoSpec::Iterate()) {
818 cs
->current_payment
= (cs
->initial_payment
* (int64_t)_economy
.inflation_payment
) >> 16;
821 SetWindowClassesDirty(WC_BUILD_VEHICLE
);
822 SetWindowClassesDirty(WC_REPLACE_VEHICLE
);
823 SetWindowClassesDirty(WC_VEHICLE_DETAILS
);
824 SetWindowClassesDirty(WC_COMPANY_INFRASTRUCTURE
);
825 InvalidateWindowData(WC_PAYMENT_RATES
, 0);
828 /** Let all companies pay the monthly interest on their loan. */
829 static void CompaniesPayInterest()
831 Backup
<CompanyID
> cur_company(_current_company
);
832 for (const Company
*c
: Company::Iterate()) {
833 cur_company
.Change(c
->index
);
835 /* Over a year the paid interest should be "loan * interest percentage",
836 * but... as that number is likely not dividable by 12 (pay each month),
837 * one needs to account for that in the monthly fee calculations.
839 * To easily calculate what one should pay "this" month, you calculate
840 * what (total) should have been paid up to this month and you subtract
841 * whatever has been paid in the previous months. This will mean one month
842 * it'll be a bit more and the other it'll be a bit less than the average
843 * monthly fee, but on average it will be exact.
845 * In order to prevent cheating or abuse (just not paying interest by not
846 * taking a loan) we make companies pay interest on negative cash as well,
847 * except if infinite money is enabled.
849 Money yearly_fee
= c
->current_loan
* _economy
.interest_rate
/ 100;
850 Money available_money
= GetAvailableMoney(c
->index
);
851 if (available_money
< 0) {
852 yearly_fee
+= -available_money
* _economy
.interest_rate
/ 100;
854 Money up_to_previous_month
= yearly_fee
* TimerGameEconomy::month
/ 12;
855 Money up_to_this_month
= yearly_fee
* (TimerGameEconomy::month
+ 1) / 12;
857 SubtractMoneyFromCompany(CommandCost(EXPENSES_LOAN_INTEREST
, up_to_this_month
- up_to_previous_month
));
859 SubtractMoneyFromCompany(CommandCost(EXPENSES_OTHER
, _price
[PR_STATION_VALUE
] >> 2));
861 cur_company
.Restore();
864 static void HandleEconomyFluctuations()
866 if (_settings_game
.difficulty
.economy
!= 0) {
867 /* When economy is Fluctuating, decrease counter */
869 } else if (EconomyIsInRecession()) {
870 /* When it's Steady and we are in recession, end it now */
871 _economy
.fluct
= -12;
873 /* No need to do anything else in other cases */
877 if (_economy
.fluct
== 0) {
878 _economy
.fluct
= -(int)GB(Random(), 0, 2);
879 AddNewsItem(STR_NEWS_BEGIN_OF_RECESSION
, NT_ECONOMY
, NF_NORMAL
);
880 } else if (_economy
.fluct
== -12) {
881 _economy
.fluct
= GB(Random(), 0, 8) + 312;
882 AddNewsItem(STR_NEWS_END_OF_RECESSION
, NT_ECONOMY
, NF_NORMAL
);
888 * Reset changes to the price base multipliers.
890 void ResetPriceBaseMultipliers()
892 memset(_price_base_multiplier
, 0, sizeof(_price_base_multiplier
));
896 * Change a price base by the given factor.
897 * The price base is altered by factors of two.
898 * NewBaseCost = OldBaseCost * 2^n
899 * @param price Index of price base to change.
900 * @param factor Amount to change by.
902 void SetPriceBaseMultiplier(Price price
, int factor
)
904 assert(price
< PR_END
);
905 _price_base_multiplier
[price
] = Clamp(factor
, MIN_PRICE_MODIFIER
, MAX_PRICE_MODIFIER
);
909 * Initialize the variables that will maintain the daily industry change system.
910 * @param init_counter specifies if the counter is required to be initialized
912 void StartupIndustryDailyChanges(bool init_counter
)
914 uint map_size
= Map::LogX() + Map::LogY();
915 /* After getting map size, it needs to be scaled appropriately and divided by 31,
916 * which stands for the days in a month.
917 * Using just 31 will make it so that a monthly reset (based on the real number of days of that month)
918 * would not be needed.
919 * Since it is based on "fractional parts", the leftover days will not make much of a difference
920 * on the overall total number of changes performed */
921 _economy
.industry_daily_increment
= (1 << map_size
) / 31;
924 /* A new game or a savegame from an older version will require the counter to be initialized */
925 _economy
.industry_daily_change_counter
= 0;
929 void StartupEconomy()
931 _economy
.interest_rate
= _settings_game
.difficulty
.initial_interest
;
932 _economy
.infl_amount
= _settings_game
.difficulty
.initial_interest
;
933 _economy
.infl_amount_pr
= std::max(0, _settings_game
.difficulty
.initial_interest
- 1);
934 _economy
.fluct
= GB(Random(), 0, 8) + 168;
936 if (_settings_game
.economy
.inflation
) {
937 /* Apply inflation that happened before our game start year. */
938 int months
= (std::min(TimerGameCalendar::year
, CalendarTime::ORIGINAL_MAX_YEAR
) - CalendarTime::ORIGINAL_BASE_YEAR
).base() * 12;
939 for (int i
= 0; i
< months
; i
++) {
947 StartupIndustryDailyChanges(true); // As we are starting a new game, initialize the counter too
952 * Resets economy to initial values
954 void InitializeEconomy()
956 _economy
.inflation_prices
= _economy
.inflation_payment
= 1 << 16;
957 ClearCargoPickupMonitoring();
958 ClearCargoDeliveryMonitoring();
962 * Determine a certain price
963 * @param index Price base
964 * @param cost_factor Price factor
965 * @param grf_file NewGRF to use local price multipliers from.
966 * @param shift Extra bit shifting after the computation
969 Money
GetPrice(Price index
, uint cost_factor
, const GRFFile
*grf_file
, int shift
)
971 if (index
>= PR_END
) return 0;
973 Money cost
= _price
[index
] * cost_factor
;
974 if (grf_file
!= nullptr) shift
+= grf_file
->price_base_multipliers
[index
];
985 Money
GetTransportedGoodsIncome(uint num_pieces
, uint dist
, uint16_t transit_periods
, CargoID cargo_type
)
987 const CargoSpec
*cs
= CargoSpec::Get(cargo_type
);
988 if (!cs
->IsValid()) {
989 /* User changed newgrfs and some vehicle still carries some cargo which is no longer available. */
993 /* Use callback to calculate cargo profit, if available */
994 if (HasBit(cs
->callback_mask
, CBM_CARGO_PROFIT_CALC
)) {
995 uint32_t var18
= ClampTo
<uint16_t>(dist
) | (ClampTo
<uint8_t>(num_pieces
) << 16) | (ClampTo
<uint8_t>(transit_periods
) << 24);
996 uint16_t callback
= GetCargoCallback(CBID_CARGO_PROFIT_CALC
, 0, var18
, cs
);
997 if (callback
!= CALLBACK_FAILED
) {
998 int result
= GB(callback
, 0, 14);
1000 /* Simulate a 15 bit signed value */
1001 if (HasBit(callback
, 14)) result
-= 0x4000;
1003 /* "The result should be a signed multiplier that gets multiplied
1004 * by the amount of cargo moved and the price factor, then gets
1005 * divided by 8192." */
1006 return result
* num_pieces
* cs
->current_payment
/ 8192;
1010 static const int MIN_TIME_FACTOR
= 31;
1011 static const int MAX_TIME_FACTOR
= 255;
1012 static const int TIME_FACTOR_FRAC_BITS
= 4;
1013 static const int TIME_FACTOR_FRAC
= 1 << TIME_FACTOR_FRAC_BITS
;
1015 const int periods1
= cs
->transit_periods
[0];
1016 const int periods2
= cs
->transit_periods
[1];
1017 const int periods_over_periods1
= std::max(transit_periods
- periods1
, 0);
1018 const int periods_over_periods2
= std::max(periods_over_periods1
- periods2
, 0);
1019 int periods_over_max
= MIN_TIME_FACTOR
- MAX_TIME_FACTOR
;
1020 if (periods2
> -periods_over_max
) {
1021 periods_over_max
+= transit_periods
- periods1
;
1023 periods_over_max
+= 2 * (transit_periods
- periods1
) - periods2
;
1027 * The time factor is calculated based on the time it took
1028 * (transit_periods) compared two cargo-depending values. The
1029 * range is divided into four parts:
1031 * - constant for fast transits
1032 * - linear decreasing with time with a slope of -1 for medium transports
1033 * - linear decreasing with time with a slope of -2 for slow transports
1034 * - after hitting MIN_TIME_FACTOR, the time factor will be asymptotically decreased to a limit of 1 with a scaled 1/(x+1) function.
1037 if (periods_over_max
> 0) {
1038 const int time_factor
= std::max(2 * MIN_TIME_FACTOR
* TIME_FACTOR_FRAC
* TIME_FACTOR_FRAC
/ (periods_over_max
+ 2 * TIME_FACTOR_FRAC
), 1); // MIN_TIME_FACTOR / (x/(2 * TIME_FACTOR_FRAC) + 1) + 1, expressed as fixed point with TIME_FACTOR_FRAC_BITS.
1039 return BigMulS(dist
* time_factor
* num_pieces
, cs
->current_payment
, 21 + TIME_FACTOR_FRAC_BITS
);
1041 const int time_factor
= std::max(MAX_TIME_FACTOR
- periods_over_periods1
- periods_over_periods2
, MIN_TIME_FACTOR
);
1042 return BigMulS(dist
* time_factor
* num_pieces
, cs
->current_payment
, 21);
1046 /** The industries we've currently brought cargo to. */
1047 static SmallIndustryList _cargo_delivery_destinations
;
1050 * Transfer goods from station to industry.
1051 * All cargo is delivered to the nearest (Manhattan) industry to the station sign, which is inside the acceptance rectangle and actually accepts the cargo.
1052 * @param st The station that accepted the cargo
1053 * @param cargo_type Type of cargo delivered
1054 * @param num_pieces Amount of cargo delivered
1055 * @param source The source of the cargo
1056 * @param company The company delivering the cargo
1057 * @return actually accepted pieces of cargo
1059 static uint
DeliverGoodsToIndustry(const Station
*st
, CargoID cargo_type
, uint num_pieces
, IndustryID source
, CompanyID company
)
1061 /* Find the nearest industrytile to the station sign inside the catchment area, whose industry accepts the cargo.
1062 * This fails in three cases:
1063 * 1) The station accepts the cargo because there are enough houses around it accepting the cargo.
1064 * 2) The industries in the catchment area temporarily reject the cargo, and the daily station loop has not yet updated station acceptance.
1065 * 3) The results of callbacks CBID_INDUSTRY_REFUSE_CARGO and CBID_INDTILE_CARGO_ACCEPTANCE are inconsistent. (documented behaviour)
1070 for (const auto &i
: st
->industries_near
) {
1071 if (num_pieces
== 0) break;
1073 Industry
*ind
= i
.industry
;
1074 if (ind
->index
== source
) continue;
1076 auto it
= ind
->GetCargoAccepted(cargo_type
);
1077 /* Check if matching cargo has been found */
1078 if (it
== std::end(ind
->accepted
)) continue;
1080 /* Check if industry temporarily refuses acceptance */
1081 if (IndustryTemporarilyRefusesCargo(ind
, cargo_type
)) continue;
1083 if (ind
->exclusive_supplier
!= INVALID_OWNER
&& ind
->exclusive_supplier
!= st
->owner
) continue;
1085 /* Insert the industry into _cargo_delivery_destinations, if not yet contained */
1086 include(_cargo_delivery_destinations
, ind
);
1088 uint amount
= std::min(num_pieces
, 0xFFFFu
- it
->waiting
);
1089 it
->waiting
+= amount
;
1090 it
->last_accepted
= TimerGameEconomy::date
;
1091 num_pieces
-= amount
;
1094 /* Update the cargo monitor. */
1095 AddCargoDelivery(cargo_type
, company
, amount
, SourceType::Industry
, source
, st
, ind
->index
);
1102 * Delivers goods to industries/towns and calculates the payment
1103 * @param num_pieces amount of cargo delivered
1104 * @param cargo_type the type of cargo that is delivered
1105 * @param dest Station the cargo has been unloaded
1106 * @param distance The distance the cargo has traveled.
1107 * @param periods_in_transit Travel time in cargo aging periods
1108 * @param company The company delivering the cargo
1109 * @param src_type Type of source of cargo (industry, town, headquarters)
1110 * @param src Index of source of cargo
1111 * @return Revenue for delivering cargo
1112 * @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
1114 static Money
DeliverGoods(int num_pieces
, CargoID cargo_type
, StationID dest
, uint distance
, uint16_t periods_in_transit
, Company
*company
, SourceType src_type
, SourceID src
)
1116 assert(num_pieces
> 0);
1118 Station
*st
= Station::Get(dest
);
1120 /* Give the goods to the industry. */
1121 uint accepted_ind
= DeliverGoodsToIndustry(st
, cargo_type
, num_pieces
, src_type
== SourceType::Industry
? src
: INVALID_INDUSTRY
, company
->index
);
1123 /* If this cargo type is always accepted, accept all */
1124 uint accepted_total
= HasBit(st
->always_accepted
, cargo_type
) ? num_pieces
: accepted_ind
;
1126 /* Update station statistics */
1127 if (accepted_total
> 0) {
1128 SetBit(st
->goods
[cargo_type
].status
, GoodsEntry::GES_EVER_ACCEPTED
);
1129 SetBit(st
->goods
[cargo_type
].status
, GoodsEntry::GES_CURRENT_MONTH
);
1130 SetBit(st
->goods
[cargo_type
].status
, GoodsEntry::GES_ACCEPTED_BIGTICK
);
1133 /* Update company statistics */
1134 company
->cur_economy
.delivered_cargo
[cargo_type
] += accepted_total
;
1136 /* Increase town's counter for town effects */
1137 const CargoSpec
*cs
= CargoSpec::Get(cargo_type
);
1138 st
->town
->received
[cs
->town_acceptance_effect
].new_act
+= accepted_total
;
1140 /* Determine profit */
1141 Money profit
= GetTransportedGoodsIncome(accepted_total
, distance
, periods_in_transit
, cargo_type
);
1143 /* Update the cargo monitor. */
1144 AddCargoDelivery(cargo_type
, company
->index
, accepted_total
- accepted_ind
, src_type
, src
, st
);
1146 /* Modify profit if a subsidy is in effect */
1147 if (CheckSubsidised(cargo_type
, company
->index
, src_type
, src
, st
)) {
1148 switch (_settings_game
.difficulty
.subsidy_multiplier
) {
1149 case 0: profit
+= profit
>> 1; break;
1150 case 1: profit
*= 2; break;
1151 case 2: profit
*= 3; break;
1152 default: profit
*= 4; break;
1160 * Inform the industry about just delivered cargo
1161 * DeliverGoodsToIndustry() silently incremented incoming_cargo_waiting, now it is time to do something with the new cargo.
1162 * @param i The industry to process
1164 static void TriggerIndustryProduction(Industry
*i
)
1166 const IndustrySpec
*indspec
= GetIndustrySpec(i
->type
);
1167 uint16_t callback
= indspec
->callback_mask
;
1169 i
->was_cargo_delivered
= true;
1171 if (HasBit(callback
, CBM_IND_PRODUCTION_CARGO_ARRIVAL
) || HasBit(callback
, CBM_IND_PRODUCTION_256_TICKS
)) {
1172 if (HasBit(callback
, CBM_IND_PRODUCTION_CARGO_ARRIVAL
)) {
1173 IndustryProductionCallback(i
, 0);
1175 SetWindowDirty(WC_INDUSTRY_VIEW
, i
->index
);
1178 for (auto ita
= std::begin(i
->accepted
); ita
!= std::end(i
->accepted
); ++ita
) {
1179 if (ita
->waiting
== 0 || !IsValidCargoID(ita
->cargo
)) continue;
1181 for (auto itp
= std::begin(i
->produced
); itp
!= std::end(i
->produced
); ++itp
) {
1182 if (!IsValidCargoID(itp
->cargo
)) continue;
1183 itp
->waiting
= ClampTo
<uint16_t>(itp
->waiting
+ (ita
->waiting
* indspec
->input_cargo_multiplier
[ita
- std::begin(i
->accepted
)][itp
- std::begin(i
->produced
)] / 256));
1190 TriggerIndustry(i
, INDUSTRY_TRIGGER_RECEIVED_CARGO
);
1191 StartStopIndustryTileAnimation(i
, IAT_INDUSTRY_RECEIVED_CARGO
);
1195 * Makes us a new cargo payment helper.
1196 * @param front The front of the train
1198 CargoPayment::CargoPayment(Vehicle
*front
) :
1199 current_station(front
->last_station_visited
),
1204 CargoPayment::~CargoPayment()
1206 if (this->CleaningPool()) return;
1208 this->front
->cargo_payment
= nullptr;
1210 if (this->visual_profit
== 0 && this->visual_transfer
== 0) return;
1212 Backup
<CompanyID
> cur_company(_current_company
, this->front
->owner
);
1214 SubtractMoneyFromCompany(CommandCost(this->front
->GetExpenseType(true), -this->route_profit
));
1215 this->front
->profit_this_year
+= (this->visual_profit
+ this->visual_transfer
) << 8;
1217 if (this->route_profit
!= 0 && IsLocalCompany() && !PlayVehicleSound(this->front
, VSE_LOAD_UNLOAD
)) {
1218 SndPlayVehicleFx(SND_14_CASHTILL
, this->front
);
1221 if (this->visual_transfer
!= 0) {
1222 ShowFeederIncomeAnimation(this->front
->x_pos
, this->front
->y_pos
,
1223 this->front
->z_pos
, this->visual_transfer
, -this->visual_profit
);
1225 ShowCostOrIncomeAnimation(this->front
->x_pos
, this->front
->y_pos
,
1226 this->front
->z_pos
, -this->visual_profit
);
1229 cur_company
.Restore();
1233 * Handle payment for final delivery of the given cargo packet.
1234 * @param cargo The cargo type of the cargo.
1235 * @param cp The cargo packet to pay for.
1236 * @param count The number of packets to pay for.
1237 * @param current_tile Current tile the payment is happening on.
1239 void CargoPayment::PayFinalDelivery(CargoID cargo
, const CargoPacket
*cp
, uint count
, TileIndex current_tile
)
1241 if (this->owner
== nullptr) {
1242 this->owner
= Company::Get(this->front
->owner
);
1245 /* Handle end of route payment */
1246 Money profit
= DeliverGoods(count
, cargo
, this->current_station
, cp
->GetDistance(current_tile
), cp
->GetPeriodsInTransit(), this->owner
, cp
->GetSourceType(), cp
->GetSourceID());
1247 this->route_profit
+= profit
;
1249 /* The vehicle's profit is whatever route profit there is minus feeder shares. */
1250 this->visual_profit
+= profit
- cp
->GetFeederShare(count
);
1254 * Handle payment for transfer of the given cargo packet.
1255 * @param cargo The cargo type of the cargo.
1256 * @param cp The cargo packet to pay for; actual payment won't be made!.
1257 * @param count The number of packets to pay for.
1258 * @param current_tile Current tile the payment is happening on.
1259 * @return The amount of money paid for the transfer.
1261 Money
CargoPayment::PayTransfer(CargoID cargo
, const CargoPacket
*cp
, uint count
, TileIndex current_tile
)
1263 /* Pay transfer vehicle the difference between the payment for the journey from
1264 * the source to the current point, and the sum of the previous transfer payments */
1265 Money profit
= -cp
->GetFeederShare(count
) + GetTransportedGoodsIncome(
1267 cp
->GetDistance(current_tile
),
1268 cp
->GetPeriodsInTransit(),
1271 profit
= profit
* _settings_game
.economy
.feeder_payment_share
/ 100;
1273 this->visual_transfer
+= profit
; // accumulate transfer profits for whole vehicle
1274 return profit
; // account for the (virtual) profit already made for the cargo packet
1278 * Prepare the vehicle to be unloaded.
1279 * @param front_v the vehicle to be unloaded
1281 void PrepareUnload(Vehicle
*front_v
)
1283 Station
*curr_station
= Station::Get(front_v
->last_station_visited
);
1284 curr_station
->loading_vehicles
.push_back(front_v
);
1286 /* At this moment loading cannot be finished */
1287 ClrBit(front_v
->vehicle_flags
, VF_LOADING_FINISHED
);
1289 /* Start unloading at the first possible moment */
1290 front_v
->load_unload_ticks
= 1;
1292 assert(front_v
->cargo_payment
== nullptr);
1293 /* One CargoPayment per vehicle and the vehicle limit equals the
1294 * limit in number of CargoPayments. Can't go wrong. */
1295 static_assert(CargoPaymentPool::MAX_SIZE
== VehiclePool::MAX_SIZE
);
1296 assert(CargoPayment::CanAllocateItem());
1297 front_v
->cargo_payment
= new CargoPayment(front_v
);
1299 StationIDStack next_station
= front_v
->GetNextStoppingStation();
1300 if (front_v
->orders
== nullptr || (front_v
->current_order
.GetUnloadType() & OUFB_NO_UNLOAD
) == 0) {
1301 Station
*st
= Station::Get(front_v
->last_station_visited
);
1302 for (Vehicle
*v
= front_v
; v
!= nullptr; v
= v
->Next()) {
1303 const GoodsEntry
*ge
= &st
->goods
[v
->cargo_type
];
1304 if (v
->cargo_cap
> 0 && v
->cargo
.TotalCount() > 0) {
1306 HasBit(ge
->status
, GoodsEntry::GES_ACCEPTANCE
),
1307 front_v
->last_station_visited
, next_station
,
1308 front_v
->current_order
.GetUnloadType(), ge
,
1309 v
->cargo_type
, front_v
->cargo_payment
,
1311 if (v
->cargo
.UnloadCount() > 0) SetBit(v
->vehicle_flags
, VF_CARGO_UNLOADING
);
1318 * Gets the amount of cargo the given vehicle can load in the current tick.
1319 * This is only about loading speed. The free capacity is ignored.
1320 * @param v Vehicle to be queried.
1321 * @return Amount of cargo the vehicle can load at once.
1323 static uint
GetLoadAmount(Vehicle
*v
)
1325 const Engine
*e
= v
->GetEngine();
1326 uint load_amount
= e
->info
.load_amount
;
1328 /* The default loadamount for mail is 1/4 of the load amount for passengers */
1329 bool air_mail
= v
->type
== VEH_AIRCRAFT
&& !Aircraft::From(v
)->IsNormalAircraft();
1330 if (air_mail
) load_amount
= CeilDiv(load_amount
, 4);
1332 if (_settings_game
.order
.gradual_loading
) {
1333 uint16_t cb_load_amount
= CALLBACK_FAILED
;
1334 if (e
->GetGRF() != nullptr && e
->GetGRF()->grf_version
>= 8) {
1335 /* Use callback 36 */
1336 cb_load_amount
= GetVehicleProperty(v
, PROP_VEHICLE_LOAD_AMOUNT
, CALLBACK_FAILED
);
1337 } else if (HasBit(e
->info
.callback_mask
, CBM_VEHICLE_LOAD_AMOUNT
)) {
1338 /* Use callback 12 */
1339 cb_load_amount
= GetVehicleCallback(CBID_VEHICLE_LOAD_AMOUNT
, 0, 0, v
->engine_type
, v
);
1341 if (cb_load_amount
!= CALLBACK_FAILED
) {
1342 if (e
->GetGRF()->grf_version
< 8) cb_load_amount
= GB(cb_load_amount
, 0, 8);
1343 if (cb_load_amount
>= 0x100) {
1344 ErrorUnknownCallbackResult(e
->GetGRFID(), CBID_VEHICLE_LOAD_AMOUNT
, cb_load_amount
);
1345 } else if (cb_load_amount
!= 0) {
1346 load_amount
= cb_load_amount
;
1351 /* Scale load amount the same as capacity */
1352 if (HasBit(e
->info
.misc_flags
, EF_NO_DEFAULT_CARGO_MULTIPLIER
) && !air_mail
) load_amount
= CeilDiv(load_amount
* CargoSpec::Get(v
->cargo_type
)->multiplier
, 0x100);
1354 /* Zero load amount breaks a lot of things. */
1355 return std::max(1u, load_amount
);
1359 * Iterate the articulated parts of a vehicle, also considering the special cases of "normal"
1360 * aircraft and double headed trains. Apply an action to each vehicle and immediately return false
1361 * if that action does so. Otherwise return true.
1362 * @tparam Taction Class of action to be applied. Must implement bool operator()([const] Vehicle *).
1363 * @param v First articulated part.
1364 * @param action Instance of Taction.
1365 * @return false if any of the action invocations returned false, true otherwise.
1367 template<class Taction
>
1368 bool IterateVehicleParts(Vehicle
*v
, Taction action
)
1370 for (Vehicle
*w
= v
; w
!= nullptr;
1371 w
= w
->HasArticulatedPart() ? w
->GetNextArticulatedPart() : nullptr) {
1372 if (!action(w
)) return false;
1373 if (w
->type
== VEH_TRAIN
) {
1374 Train
*train
= Train::From(w
);
1375 if (train
->IsMultiheaded() && !action(train
->other_multiheaded_part
)) return false;
1378 if (v
->type
== VEH_AIRCRAFT
&& Aircraft::From(v
)->IsNormalAircraft()) return action(v
->Next());
1383 * Action to check if a vehicle has no stored cargo.
1385 struct IsEmptyAction
1388 * Checks if the vehicle has stored cargo.
1389 * @param v Vehicle to be checked.
1390 * @return true if v is either empty or has only reserved cargo, false otherwise.
1392 bool operator()(const Vehicle
*v
)
1394 return v
->cargo
.StoredCount() == 0;
1399 * Refit preparation action.
1401 struct PrepareRefitAction
1403 CargoArray
&consist_capleft
; ///< Capacities left in the consist.
1404 CargoTypes
&refit_mask
; ///< Bitmask of possible refit cargoes.
1407 * Create a refit preparation action.
1408 * @param consist_capleft Capacities left in consist, to be updated here.
1409 * @param refit_mask Refit mask to be constructed from refit information of vehicles.
1411 PrepareRefitAction(CargoArray
&consist_capleft
, CargoTypes
&refit_mask
) :
1412 consist_capleft(consist_capleft
), refit_mask(refit_mask
) {}
1415 * Prepares for refitting of a vehicle, subtracting its free capacity from consist_capleft and
1416 * adding the cargoes it can refit to to the refit mask.
1417 * @param v The vehicle to be refitted.
1420 bool operator()(const Vehicle
*v
)
1422 this->consist_capleft
[v
->cargo_type
] -= v
->cargo_cap
- v
->cargo
.ReservedCount();
1423 this->refit_mask
|= EngInfo(v
->engine_type
)->refit_mask
;
1429 * Action for returning reserved cargo.
1431 struct ReturnCargoAction
1433 Station
*st
; ///< Station to give the returned cargo to.
1434 StationID next_hop
; ///< Next hop the cargo should be assigned to.
1437 * Construct a cargo return action.
1438 * @param st Station to give the returned cargo to.
1439 * @param next_one Next hop the cargo should be assigned to.
1441 ReturnCargoAction(Station
*st
, StationID next_one
) : st(st
), next_hop(next_one
) {}
1444 * Return all reserved cargo from a vehicle.
1445 * @param v Vehicle to return cargo from.
1448 bool operator()(Vehicle
*v
)
1450 v
->cargo
.Return(UINT_MAX
, &this->st
->goods
[v
->cargo_type
].cargo
, this->next_hop
, v
->GetCargoTile());
1456 * Action for finalizing a refit.
1458 struct FinalizeRefitAction
1460 CargoArray
&consist_capleft
; ///< Capacities left in the consist.
1461 Station
*st
; ///< Station to reserve cargo from.
1462 StationIDStack
&next_station
; ///< Next hops to reserve cargo for.
1463 bool do_reserve
; ///< If the vehicle should reserve.
1466 * Create a finalizing action.
1467 * @param consist_capleft Capacities left in the consist.
1468 * @param st Station to reserve cargo from.
1469 * @param next_station Next hops to reserve cargo for.
1470 * @param do_reserve If we should reserve cargo or just add up the capacities.
1472 FinalizeRefitAction(CargoArray
&consist_capleft
, Station
*st
, StationIDStack
&next_station
, bool do_reserve
) :
1473 consist_capleft(consist_capleft
), st(st
), next_station(next_station
), do_reserve(do_reserve
) {}
1476 * Reserve cargo from the station and update the remaining consist capacities with the
1477 * vehicle's remaining free capacity.
1478 * @param v Vehicle to be finalized.
1481 bool operator()(Vehicle
*v
)
1483 if (this->do_reserve
) {
1484 this->st
->goods
[v
->cargo_type
].cargo
.Reserve(v
->cargo_cap
- v
->cargo
.RemainingCount(),
1485 &v
->cargo
, this->next_station
, v
->GetCargoTile());
1487 this->consist_capleft
[v
->cargo_type
] += v
->cargo_cap
- v
->cargo
.RemainingCount();
1493 * Refit a vehicle in a station.
1494 * @param v Vehicle to be refitted.
1495 * @param consist_capleft Added cargo capacities in the consist.
1496 * @param st Station the vehicle is loading at.
1497 * @param next_station Possible next stations the vehicle can travel to.
1498 * @param new_cid Target cargo for refit.
1500 static void HandleStationRefit(Vehicle
*v
, CargoArray
&consist_capleft
, Station
*st
, StationIDStack next_station
, CargoID new_cid
)
1502 Vehicle
*v_start
= v
->GetFirstEnginePart();
1503 if (!IterateVehicleParts(v_start
, IsEmptyAction())) return;
1505 Backup
<CompanyID
> cur_company(_current_company
, v
->owner
);
1507 CargoTypes refit_mask
= v
->GetEngine()->info
.refit_mask
;
1509 /* Remove old capacity from consist capacity and collect refit mask. */
1510 IterateVehicleParts(v_start
, PrepareRefitAction(consist_capleft
, refit_mask
));
1512 bool is_auto_refit
= new_cid
== CARGO_AUTO_REFIT
;
1513 if (is_auto_refit
) {
1514 /* Get a refittable cargo type with waiting cargo for next_station or INVALID_STATION. */
1515 new_cid
= v_start
->cargo_type
;
1516 for (CargoID cid
: SetCargoBitIterator(refit_mask
)) {
1517 if (st
->goods
[cid
].cargo
.HasCargoFor(next_station
)) {
1518 /* Try to find out if auto-refitting would succeed. In case the refit is allowed,
1519 * the returned refit capacity will be greater than zero. */
1520 auto [cc
, refit_capacity
, mail_capacity
, cargo_capacities
] = Command
<CMD_REFIT_VEHICLE
>::Do(DC_QUERY_COST
, v_start
->index
, cid
, 0xFF, true, false, 1); // Auto-refit and only this vehicle including artic parts.
1521 /* Try to balance different loadable cargoes between parts of the consist, so that
1522 * all of them can be loaded. Avoid a situation where all vehicles suddenly switch
1523 * to the first loadable cargo for which there is only one packet. If the capacities
1524 * are equal refit to the cargo of which most is available. This is important for
1525 * consists of only a single vehicle as those will generally have a consist_capleft
1526 * of 0 for all cargoes. */
1527 if (refit_capacity
> 0 && (consist_capleft
[cid
] < consist_capleft
[new_cid
] ||
1528 (consist_capleft
[cid
] == consist_capleft
[new_cid
] &&
1529 st
->goods
[cid
].cargo
.AvailableCount() > st
->goods
[new_cid
].cargo
.AvailableCount()))) {
1536 /* Refit if given a valid cargo. */
1537 if (new_cid
< NUM_CARGO
&& new_cid
!= v_start
->cargo_type
) {
1538 /* INVALID_STATION because in the DT_MANUAL case that's correct and in the DT_(A)SYMMETRIC
1539 * cases the next hop of the vehicle doesn't really tell us anything if the cargo had been
1540 * "via any station" before reserving. We rather produce some more "any station" cargo than
1542 IterateVehicleParts(v_start
, ReturnCargoAction(st
, INVALID_STATION
));
1543 CommandCost cost
= std::get
<0>(Command
<CMD_REFIT_VEHICLE
>::Do(DC_EXEC
, v_start
->index
, new_cid
, 0xFF, true, false, 1)); // Auto-refit and only this vehicle including artic parts.
1544 if (cost
.Succeeded()) v
->First()->profit_this_year
-= cost
.GetCost() << 8;
1547 /* Add new capacity to consist capacity and reserve cargo */
1548 IterateVehicleParts(v_start
, FinalizeRefitAction(consist_capleft
, st
, next_station
,
1549 is_auto_refit
|| (v
->First()->current_order
.GetLoadType() & OLFB_FULL_LOAD
) != 0));
1551 cur_company
.Restore();
1555 * Test whether a vehicle can load cargo at a station even if exclusive transport rights are present.
1556 * @param st Station with cargo waiting to be loaded.
1557 * @param v Vehicle loading the cargo.
1558 * @return true when a vehicle can load the cargo.
1560 static bool MayLoadUnderExclusiveRights(const Station
*st
, const Vehicle
*v
)
1562 return st
->owner
!= OWNER_NONE
|| st
->town
->exclusive_counter
== 0 || st
->town
->exclusivity
== v
->owner
;
1565 struct ReserveCargoAction
{
1567 StationIDStack
*next_station
;
1569 ReserveCargoAction(Station
*st
, StationIDStack
*next_station
) :
1570 st(st
), next_station(next_station
) {}
1572 bool operator()(Vehicle
*v
)
1574 if (v
->cargo_cap
> v
->cargo
.RemainingCount() && MayLoadUnderExclusiveRights(st
, v
)) {
1575 st
->goods
[v
->cargo_type
].cargo
.Reserve(v
->cargo_cap
- v
->cargo
.RemainingCount(),
1576 &v
->cargo
, *next_station
, v
->GetCargoTile());
1585 * Reserves cargo if the full load order and improved_load is set or if the
1586 * current order allows autorefit.
1587 * @param st Station where the consist is loading at the moment.
1588 * @param u Front of the loading vehicle consist.
1589 * @param consist_capleft If given, save free capacities after reserving there.
1590 * @param next_station Station(s) the vehicle will stop at next.
1592 static void ReserveConsist(Station
*st
, Vehicle
*u
, CargoArray
*consist_capleft
, StationIDStack
*next_station
)
1594 /* If there is a cargo payment not all vehicles of the consist have tried to do the refit.
1595 * In that case, only reserve if it's a fixed refit and the equivalent of "articulated chain"
1596 * a vehicle belongs to already has the right cargo. */
1597 bool must_reserve
= !u
->current_order
.IsRefit() || u
->cargo_payment
== nullptr;
1598 for (Vehicle
*v
= u
; v
!= nullptr; v
= v
->Next()) {
1599 assert(v
->cargo_cap
>= v
->cargo
.RemainingCount());
1601 /* Exclude various ways in which the vehicle might not be the head of an equivalent of
1602 * "articulated chain". Also don't do the reservation if the vehicle is going to refit
1603 * to a different cargo and hasn't tried to do so, yet. */
1604 if (!v
->IsArticulatedPart() &&
1605 (v
->type
!= VEH_TRAIN
|| !Train::From(v
)->IsRearDualheaded()) &&
1606 (v
->type
!= VEH_AIRCRAFT
|| Aircraft::From(v
)->IsNormalAircraft()) &&
1607 (must_reserve
|| u
->current_order
.GetRefitCargo() == v
->cargo_type
)) {
1608 IterateVehicleParts(v
, ReserveCargoAction(st
, next_station
));
1610 if (consist_capleft
== nullptr || v
->cargo_cap
== 0) continue;
1611 (*consist_capleft
)[v
->cargo_type
] += v
->cargo_cap
- v
->cargo
.RemainingCount();
1616 * Update the vehicle's load_unload_ticks, the time it will wait until it tries to load or unload
1617 * again. Adjust for overhang of trains and set it at least to 1.
1618 * @param front The vehicle to be updated.
1619 * @param st The station the vehicle is loading at.
1620 * @param ticks The time it would normally wait, based on cargo loaded and unloaded.
1622 static void UpdateLoadUnloadTicks(Vehicle
*front
, const Station
*st
, int ticks
)
1624 if (front
->type
== VEH_TRAIN
&& _settings_game
.order
.station_length_loading_penalty
) {
1625 /* Each platform tile is worth 2 rail vehicles. */
1626 int overhang
= front
->GetGroundVehicleCache()->cached_total_length
- st
->GetPlatformLength(front
->tile
) * TILE_SIZE
;
1629 ticks
+= (overhang
* ticks
) / 8;
1632 /* Always wait at least 1, otherwise we'll wait 'infinitively' long. */
1633 front
->load_unload_ticks
= std::max(1, ticks
);
1637 * Loads/unload the vehicle if possible.
1638 * @param front the vehicle to be (un)loaded
1640 static void LoadUnloadVehicle(Vehicle
*front
)
1642 assert(front
->current_order
.IsType(OT_LOADING
));
1644 StationID last_visited
= front
->last_station_visited
;
1645 Station
*st
= Station::Get(last_visited
);
1647 StationIDStack next_station
= front
->GetNextStoppingStation();
1648 bool use_autorefit
= front
->current_order
.IsRefit() && front
->current_order
.GetRefitCargo() == CARGO_AUTO_REFIT
;
1649 CargoArray consist_capleft
{};
1650 if (_settings_game
.order
.improved_load
&& use_autorefit
?
1651 front
->cargo_payment
== nullptr : (front
->current_order
.GetLoadType() & OLFB_FULL_LOAD
) != 0) {
1652 ReserveConsist(st
, front
,
1653 (use_autorefit
&& front
->load_unload_ticks
!= 0) ? &consist_capleft
: nullptr,
1657 /* We have not waited enough time till the next round of loading/unloading */
1658 if (front
->load_unload_ticks
!= 0) return;
1660 if (front
->type
== VEH_TRAIN
&& (!IsTileType(front
->tile
, MP_STATION
) || GetStationIndex(front
->tile
) != st
->index
)) {
1661 /* The train reversed in the station. Take the "easy" way
1662 * out and let the train just leave as it always did. */
1663 SetBit(front
->vehicle_flags
, VF_LOADING_FINISHED
);
1664 front
->load_unload_ticks
= 1;
1668 int new_load_unload_ticks
= 0;
1669 bool dirty_vehicle
= false;
1670 bool dirty_station
= false;
1672 bool completely_emptied
= true;
1673 bool anything_unloaded
= false;
1674 bool anything_loaded
= false;
1675 CargoTypes full_load_amount
= 0;
1676 CargoTypes cargo_not_full
= 0;
1677 CargoTypes cargo_full
= 0;
1678 CargoTypes reservation_left
= 0;
1680 front
->cur_speed
= 0;
1682 CargoPayment
*payment
= front
->cargo_payment
;
1684 uint artic_part
= 0; // Articulated part we are currently trying to load. (not counting parts without capacity)
1685 for (Vehicle
*v
= front
; v
!= nullptr; v
= v
->Next()) {
1686 if (v
== front
|| !v
->Previous()->HasArticulatedPart()) artic_part
= 0;
1687 if (v
->cargo_cap
== 0) continue;
1690 GoodsEntry
*ge
= &st
->goods
[v
->cargo_type
];
1692 if (HasBit(v
->vehicle_flags
, VF_CARGO_UNLOADING
) && (front
->current_order
.GetUnloadType() & OUFB_NO_UNLOAD
) == 0) {
1693 uint cargo_count
= v
->cargo
.UnloadCount();
1694 uint amount_unloaded
= _settings_game
.order
.gradual_loading
? std::min(cargo_count
, GetLoadAmount(v
)) : cargo_count
;
1695 bool remaining
= false; // Are there cargo entities in this vehicle that can still be unloaded here?
1697 if (!HasBit(ge
->status
, GoodsEntry::GES_ACCEPTANCE
) && v
->cargo
.ActionCount(VehicleCargoList::MTA_DELIVER
) > 0) {
1698 /* The station does not accept our goods anymore. */
1699 if (front
->current_order
.GetUnloadType() & (OUFB_TRANSFER
| OUFB_UNLOAD
)) {
1700 /* Transfer instead of delivering. */
1701 v
->cargo
.Reassign
<VehicleCargoList::MTA_DELIVER
, VehicleCargoList::MTA_TRANSFER
>(
1702 v
->cargo
.ActionCount(VehicleCargoList::MTA_DELIVER
));
1704 uint new_remaining
= v
->cargo
.RemainingCount() + v
->cargo
.ActionCount(VehicleCargoList::MTA_DELIVER
);
1705 if (v
->cargo_cap
< new_remaining
) {
1706 /* Return some of the reserved cargo to not overload the vehicle. */
1707 v
->cargo
.Return(new_remaining
- v
->cargo_cap
, &ge
->cargo
, INVALID_STATION
, v
->GetCargoTile());
1710 /* Keep instead of delivering. This may lead to no cargo being unloaded, so ...*/
1711 v
->cargo
.Reassign
<VehicleCargoList::MTA_DELIVER
, VehicleCargoList::MTA_KEEP
>(
1712 v
->cargo
.ActionCount(VehicleCargoList::MTA_DELIVER
));
1714 /* ... say we unloaded something, otherwise we'll think we didn't unload
1715 * something and we didn't load something, so we must be finished
1716 * at this station. Setting the unloaded means that we will get a
1717 * retry for loading in the next cycle. */
1718 anything_unloaded
= true;
1722 if (v
->cargo
.ActionCount(VehicleCargoList::MTA_TRANSFER
) > 0) {
1723 /* Mark the station dirty if we transfer, but not if we only deliver. */
1724 dirty_station
= true;
1726 if (!ge
->HasRating()) {
1727 /* Upon transferring cargo, make sure the station has a rating. Fake a pickup for the
1728 * first unload to prevent the cargo from quickly decaying after the initial drop. */
1729 ge
->time_since_pickup
= 0;
1730 SetBit(ge
->status
, GoodsEntry::GES_RATING
);
1734 assert(payment
!= nullptr);
1735 amount_unloaded
= v
->cargo
.Unload(amount_unloaded
, &ge
->cargo
, v
->cargo_type
, payment
, v
->GetCargoTile());
1736 remaining
= v
->cargo
.UnloadCount() > 0;
1737 if (amount_unloaded
> 0) {
1738 dirty_vehicle
= true;
1739 anything_unloaded
= true;
1740 new_load_unload_ticks
+= amount_unloaded
;
1742 /* Deliver goods to the station */
1743 st
->time_since_unload
= 0;
1746 if (_settings_game
.order
.gradual_loading
&& remaining
) {
1747 completely_emptied
= false;
1749 /* We have finished unloading (cargo count == 0) */
1750 ClrBit(v
->vehicle_flags
, VF_CARGO_UNLOADING
);
1756 /* Do not pick up goods when we have no-load set or loading is stopped. */
1757 if (front
->current_order
.GetLoadType() & OLFB_NO_LOAD
|| HasBit(front
->vehicle_flags
, VF_STOP_LOADING
)) continue;
1759 /* This order has a refit, if this is the first vehicle part carrying cargo and the whole vehicle is empty, try refitting. */
1760 if (front
->current_order
.IsRefit() && artic_part
== 1) {
1761 HandleStationRefit(v
, consist_capleft
, st
, next_station
, front
->current_order
.GetRefitCargo());
1762 ge
= &st
->goods
[v
->cargo_type
];
1765 /* As we're loading here the following link can carry the full capacity of the vehicle. */
1766 v
->refit_cap
= v
->cargo_cap
;
1770 switch (front
->type
) {
1773 t
= front
->vcache
.cached_max_speed
;
1777 t
= front
->vcache
.cached_max_speed
/ 2;
1781 t
= Aircraft::From(front
)->GetSpeedOldUnits(); // Convert to old units.
1784 default: NOT_REACHED();
1787 /* if last speed is 0, we treat that as if no vehicle has ever visited the station. */
1788 ge
->last_speed
= ClampTo
<uint8_t>(t
);
1789 ge
->last_age
= ClampTo
<uint8_t>(TimerGameCalendar::year
- front
->build_year
);
1791 assert(v
->cargo_cap
>= v
->cargo
.StoredCount());
1792 /* Capacity available for loading more cargo. */
1793 uint cap_left
= v
->cargo_cap
- v
->cargo
.StoredCount();
1796 /* If vehicle can load cargo, reset time_since_pickup. */
1797 ge
->time_since_pickup
= 0;
1799 /* If there's goods waiting at the station, and the vehicle
1800 * has capacity for it, load it on the vehicle. */
1801 if ((v
->cargo
.ActionCount(VehicleCargoList::MTA_LOAD
) > 0 || ge
->cargo
.AvailableCount() > 0) && MayLoadUnderExclusiveRights(st
, v
)) {
1802 if (v
->cargo
.StoredCount() == 0) TriggerVehicle(v
, VEHICLE_TRIGGER_NEW_CARGO
);
1803 if (_settings_game
.order
.gradual_loading
) cap_left
= std::min(cap_left
, GetLoadAmount(v
));
1805 uint loaded
= ge
->cargo
.Load(cap_left
, &v
->cargo
, next_station
, v
->GetCargoTile());
1806 if (v
->cargo
.ActionCount(VehicleCargoList::MTA_LOAD
) > 0) {
1807 /* Remember if there are reservations left so that we don't stop
1808 * loading before they're loaded. */
1809 SetBit(reservation_left
, v
->cargo_type
);
1812 /* Store whether the maximum possible load amount was loaded or not.*/
1813 if (loaded
== cap_left
) {
1814 SetBit(full_load_amount
, v
->cargo_type
);
1816 ClrBit(full_load_amount
, v
->cargo_type
);
1819 /* TODO: Regarding this, when we do gradual loading, we
1820 * should first unload all vehicles and then start
1821 * loading them. Since this will cause
1822 * VEHICLE_TRIGGER_EMPTY to be called at the time when
1823 * the whole vehicle chain is really totally empty, the
1824 * completely_emptied assignment can then be safely
1825 * removed; that's how TTDPatch behaves too. --pasky */
1827 completely_emptied
= false;
1828 anything_loaded
= true;
1830 st
->time_since_load
= 0;
1831 st
->last_vehicle_type
= v
->type
;
1833 if (ge
->cargo
.TotalCount() == 0) {
1834 TriggerStationRandomisation(st
, st
->xy
, SRT_CARGO_TAKEN
, v
->cargo_type
);
1835 TriggerStationAnimation(st
, st
->xy
, SAT_CARGO_TAKEN
, v
->cargo_type
);
1836 AirportAnimationTrigger(st
, AAT_STATION_CARGO_TAKEN
, v
->cargo_type
);
1837 TriggerRoadStopRandomisation(st
, st
->xy
, RSRT_CARGO_TAKEN
, v
->cargo_type
);
1838 TriggerRoadStopAnimation(st
, st
->xy
, SAT_CARGO_TAKEN
, v
->cargo_type
);
1841 new_load_unload_ticks
+= loaded
;
1843 dirty_vehicle
= dirty_station
= true;
1848 if (v
->cargo
.StoredCount() >= v
->cargo_cap
) {
1849 SetBit(cargo_full
, v
->cargo_type
);
1851 SetBit(cargo_not_full
, v
->cargo_type
);
1855 if (anything_loaded
|| anything_unloaded
) {
1856 if (front
->type
== VEH_TRAIN
) {
1857 TriggerStationRandomisation(st
, front
->tile
, SRT_TRAIN_LOADS
);
1858 TriggerStationAnimation(st
, front
->tile
, SAT_TRAIN_LOADS
);
1859 } else if (front
->type
== VEH_ROAD
) {
1860 TriggerRoadStopRandomisation(st
, front
->tile
, RSRT_VEH_LOADS
);
1861 TriggerRoadStopAnimation(st
, front
->tile
, SAT_TRAIN_LOADS
);
1865 /* Only set completely_emptied, if we just unloaded all remaining cargo */
1866 completely_emptied
&= anything_unloaded
;
1868 if (!anything_unloaded
) delete payment
;
1870 ClrBit(front
->vehicle_flags
, VF_STOP_LOADING
);
1871 if (anything_loaded
|| anything_unloaded
) {
1872 if (_settings_game
.order
.gradual_loading
) {
1873 /* The time it takes to load one 'slice' of cargo or passengers depends
1874 * on the vehicle type - the values here are those found in TTDPatch */
1875 const uint gradual_loading_wait_time
[] = { 40, 20, 10, 20 };
1877 new_load_unload_ticks
= gradual_loading_wait_time
[front
->type
];
1879 /* We loaded less cargo than possible for all cargo types and it's not full
1880 * load and we're not supposed to wait any longer: stop loading. */
1881 if (!anything_unloaded
&& full_load_amount
== 0 && reservation_left
== 0 && !(front
->current_order
.GetLoadType() & OLFB_FULL_LOAD
) &&
1882 front
->current_order_time
>= std::max(front
->current_order
.GetTimetabledWait() - front
->lateness_counter
, 0)) {
1883 SetBit(front
->vehicle_flags
, VF_STOP_LOADING
);
1886 UpdateLoadUnloadTicks(front
, st
, new_load_unload_ticks
);
1888 UpdateLoadUnloadTicks(front
, st
, 20); // We need the ticks for link refreshing.
1889 bool finished_loading
= true;
1890 if (front
->current_order
.GetLoadType() & OLFB_FULL_LOAD
) {
1891 if (front
->current_order
.GetLoadType() == OLF_FULL_LOAD_ANY
) {
1892 /* if the aircraft carries passengers and is NOT full, then
1893 * continue loading, no matter how much mail is in */
1894 if ((front
->type
== VEH_AIRCRAFT
&& IsCargoInClass(front
->cargo_type
, CC_PASSENGERS
) && front
->cargo_cap
> front
->cargo
.StoredCount()) ||
1895 (cargo_not_full
!= 0 && (cargo_full
& ~cargo_not_full
) == 0)) { // There are still non-full cargoes
1896 finished_loading
= false;
1898 } else if (cargo_not_full
!= 0) {
1899 finished_loading
= false;
1902 /* Refresh next hop stats if we're full loading to make the links
1903 * known to the distribution algorithm and allow cargo to be sent
1904 * along them. Otherwise the vehicle could wait for cargo
1905 * indefinitely if it hasn't visited the other links yet, or if the
1906 * links die while it's loading. */
1907 if (!finished_loading
) LinkRefresher::Run(front
, true, true);
1910 SB(front
->vehicle_flags
, VF_LOADING_FINISHED
, 1, finished_loading
);
1913 /* Calculate the loading indicator fill percent and display
1914 * In the Game Menu do not display indicators
1915 * If _settings_client.gui.loading_indicators == 2, show indicators (bool can be promoted to int as 0 or 1 - results in 2 > 0,1 )
1916 * if _settings_client.gui.loading_indicators == 1, _local_company must be the owner or must be a spectator to show ind., so 1 > 0
1917 * if _settings_client.gui.loading_indicators == 0, do not display indicators ... 0 is never greater than anything
1919 if (_game_mode
!= GM_MENU
&& (_settings_client
.gui
.loading_indicators
> (uint
)(front
->owner
!= _local_company
&& _local_company
!= COMPANY_SPECTATOR
))) {
1920 StringID percent_up_down
= STR_NULL
;
1921 int percent
= CalcPercentVehicleFilled(front
, &percent_up_down
);
1922 if (front
->fill_percent_te_id
== INVALID_TE_ID
) {
1923 front
->fill_percent_te_id
= ShowFillingPercent(front
->x_pos
, front
->y_pos
, front
->z_pos
+ 20, percent
, percent_up_down
);
1925 UpdateFillingPercent(front
->fill_percent_te_id
, percent
, percent_up_down
);
1929 if (completely_emptied
) {
1930 /* Make sure the vehicle is marked dirty, since we need to update the NewGRF
1931 * properties such as weight, power and TE whenever the trigger runs. */
1932 dirty_vehicle
= true;
1933 TriggerVehicle(front
, VEHICLE_TRIGGER_EMPTY
);
1936 if (dirty_vehicle
) {
1937 SetWindowDirty(GetWindowClassForVehicleType(front
->type
), front
->owner
);
1938 SetWindowDirty(WC_VEHICLE_DETAILS
, front
->index
);
1941 if (dirty_station
) {
1942 st
->MarkTilesDirty(true);
1943 SetWindowDirty(WC_STATION_VIEW
, st
->index
);
1944 SetWindowDirty(WC_STATION_LIST
, st
->owner
);
1949 * Load/unload the vehicles in this station according to the order
1951 * @param st the station to do the loading/unloading for
1953 void LoadUnloadStation(Station
*st
)
1955 /* No vehicle is here... */
1956 if (st
->loading_vehicles
.empty()) return;
1958 Vehicle
*last_loading
= nullptr;
1960 /* Check if anything will be loaded at all. Otherwise we don't need to reserve either. */
1961 for (Vehicle
*v
: st
->loading_vehicles
) {
1962 if ((v
->vehstatus
& (VS_STOPPED
| VS_CRASHED
))) continue;
1964 assert(v
->load_unload_ticks
!= 0);
1965 if (--v
->load_unload_ticks
== 0) last_loading
= v
;
1968 /* We only need to reserve and load/unload up to the last loading vehicle.
1969 * Anything else will be forgotten anyway after returning from this function.
1971 * Especially this means we do _not_ need to reserve cargo for a single
1972 * consist in a station which is not allowed to load yet because its
1973 * load_unload_ticks is still not 0.
1975 if (last_loading
== nullptr) return;
1977 for (Vehicle
*v
: st
->loading_vehicles
) {
1978 if (!(v
->vehstatus
& (VS_STOPPED
| VS_CRASHED
))) LoadUnloadVehicle(v
);
1979 if (v
== last_loading
) break;
1982 /* Call the production machinery of industries */
1983 for (Industry
*iid
: _cargo_delivery_destinations
) {
1984 TriggerIndustryProduction(iid
);
1986 _cargo_delivery_destinations
.clear();
1990 * Every calendar month update of inflation.
1992 static IntervalTimer
<TimerGameCalendar
> _calendar_inflation_monthly({TimerGameCalendar::MONTH
, TimerGameCalendar::Priority::COMPANY
}, [](auto)
1994 if (_settings_game
.economy
.inflation
) {
2001 * Every economy month update of company economic data, plus economy fluctuations.
2003 static IntervalTimer
<TimerGameEconomy
> _economy_companies_monthly({ TimerGameEconomy::MONTH
, TimerGameEconomy::Priority::COMPANY
}, [](auto)
2005 CompaniesGenStatistics();
2006 CompaniesPayInterest();
2007 HandleEconomyFluctuations();
2010 static void DoAcquireCompany(Company
*c
, bool hostile_takeover
)
2012 CompanyID ci
= c
->index
;
2014 CompanyNewsInformation
*cni
= new CompanyNewsInformation(c
, Company::Get(_current_company
));
2016 SetDParam(0, STR_NEWS_COMPANY_MERGER_TITLE
);
2017 SetDParam(1, hostile_takeover
? STR_NEWS_MERGER_TAKEOVER_TITLE
: STR_NEWS_COMPANY_MERGER_DESCRIPTION
);
2018 SetDParamStr(2, cni
->company_name
);
2019 SetDParamStr(3, cni
->other_company_name
);
2020 SetDParam(4, c
->bankrupt_value
);
2021 AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT
, cni
);
2022 AI::BroadcastNewEvent(new ScriptEventCompanyMerger(ci
, _current_company
));
2023 Game::NewEvent(new ScriptEventCompanyMerger(ci
, _current_company
));
2025 ChangeOwnershipOfCompanyItems(ci
, _current_company
);
2027 if (c
->is_ai
) AI::Stop(c
->index
);
2029 CloseCompanyWindows(ci
);
2030 InvalidateWindowClassesData(WC_TRAINS_LIST
, 0);
2031 InvalidateWindowClassesData(WC_SHIPS_LIST
, 0);
2032 InvalidateWindowClassesData(WC_ROADVEH_LIST
, 0);
2033 InvalidateWindowClassesData(WC_AIRCRAFT_LIST
, 0);
2039 * Buy up another company.
2040 * When a competing company is gone bankrupt you get the chance to purchase
2042 * @todo currently this only works for AI companies
2043 * @param flags type of operation
2044 * @param target_company company to buy up
2045 * @param hostile_takeover whether to buy up the company even if it is not bankrupt
2046 * @return the cost of this operation or an error
2048 CommandCost
CmdBuyCompany(DoCommandFlag flags
, CompanyID target_company
, bool hostile_takeover
)
2050 Company
*c
= Company::GetIfValid(target_company
);
2051 if (c
== nullptr) return CMD_ERROR
;
2053 /* If you do a hostile takeover but the company went bankrupt, buy it via bankruptcy rules. */
2054 if (hostile_takeover
&& HasBit(c
->bankrupt_asked
, _current_company
)) hostile_takeover
= false;
2056 /* Disable takeovers when not asked */
2057 if (!hostile_takeover
&& !HasBit(c
->bankrupt_asked
, _current_company
)) return CMD_ERROR
;
2059 /* Only allow hostile takeover of AI companies and when in single player */
2060 if (hostile_takeover
&& !c
->is_ai
) return CMD_ERROR
;
2061 if (hostile_takeover
&& _networking
) return CMD_ERROR
;
2063 /* Disable taking over the local company in singleplayer mode */
2064 if (!_networking
&& _local_company
== c
->index
) return CMD_ERROR
;
2066 /* Do not allow companies to take over themselves */
2067 if (target_company
== _current_company
) return CMD_ERROR
;
2069 /* Do not allow takeover if the resulting company would have too many vehicles. */
2070 if (!CheckTakeoverVehicleLimit(_current_company
, target_company
)) return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME
);
2072 /* Get the cost here as the company is deleted in DoAcquireCompany.
2073 * For bankruptcy this amount is calculated when the offer was made;
2074 * for hostile takeover you pay the current price. */
2075 CommandCost
cost(EXPENSES_OTHER
, hostile_takeover
? CalculateHostileTakeoverValue(c
) : c
->bankrupt_value
);
2077 if (flags
& DC_EXEC
) {
2078 DoAcquireCompany(c
, hostile_takeover
);