4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
10 /** @file economy.cpp Handling of the economy. */
13 #include "company_func.h"
14 #include "command_func.h"
17 #include "news_func.h"
18 #include "network/network.h"
19 #include "network/network_func.h"
23 #include "newgrf_engine.h"
24 #include "engine_base.h"
25 #include "ground_vehicle.hpp"
26 #include "newgrf_cargo.h"
27 #include "newgrf_sound.h"
28 #include "newgrf_industrytiles.h"
29 #include "newgrf_station.h"
30 #include "newgrf_airporttiles.h"
32 #include "strings_func.h"
33 #include "date_func.h"
34 #include "vehicle_func.h"
35 #include "signalbuffer.h"
36 #include "sound_func.h"
37 #include "autoreplace_func.h"
38 #include "company_gui.h"
39 #include "signs_base.h"
40 #include "subsidy_base.h"
41 #include "subsidy_func.h"
42 #include "station_base.h"
43 #include "waypoint_base.h"
44 #include "economy_base.h"
45 #include "core/pool_func.hpp"
46 #include "core/backup_type.hpp"
47 #include "core/bitmath_func.hpp"
48 #include "cargo_type.h"
50 #include "game/game.hpp"
51 #include "cargomonitor.h"
52 #include "goal_base.h"
53 #include "story_base.h"
54 #include "linkgraph/refresh.h"
56 #include "table/strings.h"
57 #include "table/pricebase.h"
60 /* Initialize the cargo payment-pool */
61 template<> CargoPayment::Pool
CargoPayment::PoolItem::pool ("CargoPayment");
62 INSTANTIATE_POOL_METHODS(CargoPayment
)
65 * Multiply two integer values and shift the results to right.
67 * This function multiplies two integer values. The result is
68 * shifted by the amount of shift to right.
70 * @param a The first integer
71 * @param b The second integer
72 * @param shift The amount to shift the value to right.
73 * @return The shifted result
75 static inline int32
BigMulS(const int32 a
, const int32 b
, const uint8 shift
)
77 return (int32
)((int64
)a
* (int64
)b
>> shift
);
80 typedef SmallVector
<Industry
*, 16> SmallIndustryList
;
83 * Score info, values used for computing the detailed performance rating.
85 const ScoreInfo _score_info
[] = {
86 { 120, 100}, // SCORE_VEHICLES
87 { 80, 100}, // SCORE_STATIONS
88 { 10000, 100}, // SCORE_MIN_PROFIT
89 { 50000, 50}, // SCORE_MIN_INCOME
90 { 100000, 100}, // SCORE_MAX_INCOME
91 { 40000, 400}, // SCORE_DELIVERED
92 { 8, 50}, // SCORE_CARGO
93 {10000000, 50}, // SCORE_MONEY
94 { 250000, 50}, // SCORE_LOAN
95 { 0, 0} // SCORE_TOTAL
98 int _score_part
[MAX_COMPANIES
][SCORE_END
];
101 Money _additional_cash_required
;
102 static PriceMultipliers _price_base_multiplier
;
105 * Calculate the value of the company. That is the value of all
106 * assets (vehicles, stations, etc) and money minus the loan,
107 * except when including_loan is \c false which is useful when
108 * we want to calculate the value for bankruptcy.
109 * @param c the company to get the value of.
110 * @param including_loan include the loan in the company value.
111 * @return the value of the company.
113 Money
CalculateCompanyValue(const Company
*c
, bool including_loan
)
115 Owner owner
= c
->index
;
120 FOR_ALL_STATIONS(st
) {
121 if (st
->owner
== owner
) num
+= CountBits((byte
)st
->facilities
);
124 Money value
= num
* _price
[PR_STATION_VALUE
] * 25;
127 FOR_ALL_VEHICLES(v
) {
128 if (v
->owner
!= owner
) continue;
130 if (v
->type
== VEH_TRAIN
||
131 v
->type
== VEH_ROAD
||
132 (v
->type
== VEH_AIRCRAFT
&& Aircraft::From(v
)->IsNormalAircraft()) ||
133 v
->type
== VEH_SHIP
) {
134 value
+= v
->value
* 3 >> 1;
138 /* Add real money value */
139 if (including_loan
) value
-= c
->current_loan
;
142 return max(value
, (Money
)1);
146 * if update is set to true, the economy is updated with this score
147 * (also the house is updated, should only be true in the on-tick event)
148 * @param update the economy with calculated score
149 * @param c company been evaluated
150 * @return actual score of this company
153 int UpdateCompanyRatingAndValue(Company
*c
, bool update
)
155 Owner owner
= c
->index
;
158 memset(_score_part
[owner
], 0, sizeof(_score_part
[owner
]));
163 Money min_profit
= 0;
164 bool min_profit_first
= true;
167 FOR_ALL_VEHICLES(v
) {
168 if (v
->owner
!= owner
) continue;
169 if (IsCompanyBuildableVehicleType(v
->type
) && v
->IsPrimaryVehicle()) {
170 if (v
->profit_last_year
> 0) num
++; // For the vehicle score only count profitable vehicles
172 /* Find the vehicle with the lowest amount of profit */
173 if (min_profit_first
|| min_profit
> v
->profit_last_year
) {
174 min_profit
= v
->profit_last_year
;
175 min_profit_first
= false;
181 min_profit
>>= 8; // remove the fract part
183 _score_part
[owner
][SCORE_VEHICLES
] = num
;
184 /* Don't allow negative min_profit to show */
185 if (min_profit
> 0) {
186 _score_part
[owner
][SCORE_MIN_PROFIT
] = ClampToI32(min_profit
);
195 FOR_ALL_STATIONS(st
) {
196 /* Only count stations that are actually serviced */
197 if (st
->owner
== owner
&& (st
->time_since_load
<= 20 || st
->time_since_unload
<= 20)) num
+= CountBits((byte
)st
->facilities
);
199 _score_part
[owner
][SCORE_STATIONS
] = num
;
202 /* Generate statistics depending on recent income statistics */
204 int numec
= min(c
->num_valid_stat_ent
, 12);
206 const CompanyEconomyEntry
*cee
= c
->old_economy
;
207 Money min_income
= cee
->income
+ cee
->expenses
;
208 Money max_income
= cee
->income
+ cee
->expenses
;
211 min_income
= min(min_income
, cee
->income
+ cee
->expenses
);
212 max_income
= max(max_income
, cee
->income
+ cee
->expenses
);
213 } while (++cee
, --numec
);
215 if (min_income
> 0) {
216 _score_part
[owner
][SCORE_MIN_INCOME
] = ClampToI32(min_income
);
219 _score_part
[owner
][SCORE_MAX_INCOME
] = ClampToI32(max_income
);
223 /* Generate score depending on amount of transported cargo */
225 int numec
= min(c
->num_valid_stat_ent
, 4);
227 const CompanyEconomyEntry
*cee
= c
->old_economy
;
228 OverflowSafeInt64 total_delivered
= 0;
230 total_delivered
+= cee
->delivered_cargo
.GetSum
<OverflowSafeInt64
>();
231 } while (++cee
, --numec
);
233 _score_part
[owner
][SCORE_DELIVERED
] = ClampToI32(total_delivered
);
237 /* Generate score for variety of cargo */
239 _score_part
[owner
][SCORE_CARGO
] = c
->old_economy
->delivered_cargo
.GetCount();
242 /* Generate score for company's money */
245 _score_part
[owner
][SCORE_MONEY
] = ClampToI32(c
->money
);
249 /* Generate score for loan */
251 _score_part
[owner
][SCORE_LOAN
] = ClampToI32(_score_info
[SCORE_LOAN
].needed
- c
->current_loan
);
254 /* Now we calculate the score for each item.. */
259 for (ScoreID i
= SCORE_BEGIN
; i
< SCORE_END
; i
++) {
261 if (i
== SCORE_TOTAL
) continue;
262 /* Check the score */
263 s
= Clamp(_score_part
[owner
][i
], 0, _score_info
[i
].needed
) * _score_info
[i
].score
/ _score_info
[i
].needed
;
265 total_score
+= _score_info
[i
].score
;
268 _score_part
[owner
][SCORE_TOTAL
] = score
;
270 /* We always want the score scaled to SCORE_MAX (1000) */
271 if (total_score
!= SCORE_MAX
) score
= score
* SCORE_MAX
/ total_score
;
275 c
->old_economy
[0].performance_history
= score
;
276 UpdateCompanyHQ(c
->location_of_HQ
, score
);
277 c
->old_economy
[0].company_value
= CalculateCompanyValue(c
);
280 SetWindowDirty(WC_PERFORMANCE_DETAIL
, 0);
285 * Change the ownership of all the items of a company.
286 * @param old_owner The company that gets removed.
287 * @param new_owner The company to merge to, or INVALID_OWNER to remove the company.
289 void ChangeOwnershipOfCompanyItems(Owner old_owner
, Owner new_owner
)
291 /* We need to set _current_company to old_owner before we try to move
292 * the client. This is needed as it needs to know whether "you" really
293 * are the current local company. */
294 Backup
<CompanyByte
> cur_company(_current_company
, old_owner
, FILE_LINE
);
295 #ifdef ENABLE_NETWORK
296 /* In all cases, make spectators of clients connected to that company */
297 if (_networking
) NetworkClientsToSpectators(old_owner
);
298 #endif /* ENABLE_NETWORK */
299 if (old_owner
== _local_company
) {
300 /* Single player cheated to AI company.
301 * There are no spectators in single player, so we must pick some other company. */
302 assert(!_networking
);
303 Backup
<CompanyByte
> cur_company2(_current_company
, FILE_LINE
);
305 FOR_ALL_COMPANIES(c
) {
306 if (c
->index
!= old_owner
) {
307 SetLocalCompany(c
->index
);
311 cur_company2
.Restore();
312 assert(old_owner
!= _local_company
);
317 assert(old_owner
!= new_owner
);
323 /* See if the old_owner had shares in other companies */
324 FOR_ALL_COMPANIES(c
) {
325 for (i
= 0; i
< 4; i
++) {
326 if (c
->share_owners
[i
] == old_owner
) {
327 /* Sell his shares */
328 CommandCost res
= DoCommand(0, c
->index
, 0, DC_EXEC
| DC_BANKRUPT
, CMD_SELL_SHARE_IN_COMPANY
);
329 /* Because we are in a DoCommand, we can't just execute another one and
330 * expect the money to be removed. We need to do it ourself! */
331 SubtractMoneyFromCompany(res
);
336 /* Sell all the shares that people have on this company */
337 Backup
<CompanyByte
> cur_company2(_current_company
, FILE_LINE
);
338 c
= Company::Get(old_owner
);
339 for (i
= 0; i
< 4; i
++) {
340 cur_company2
.Change(c
->share_owners
[i
]);
341 if (_current_company
!= INVALID_OWNER
) {
342 /* Sell the shares */
343 CommandCost res
= DoCommand(0, old_owner
, 0, DC_EXEC
| DC_BANKRUPT
, CMD_SELL_SHARE_IN_COMPANY
);
344 /* Because we are in a DoCommand, we can't just execute another one and
345 * expect the money to be removed. We need to do it ourself! */
346 SubtractMoneyFromCompany(res
);
349 cur_company2
.Restore();
352 /* Temporarily increase the company's money, to be sure that
353 * removing his/her property doesn't fail because of lack of money.
354 * Not too drastically though, because it could overflow */
355 if (new_owner
== INVALID_OWNER
) {
356 Company::Get(old_owner
)->money
= UINT64_MAX
>> 2; // jackpot ;p
360 FOR_ALL_SUBSIDIES(s
) {
361 if (s
->awarded
== old_owner
) {
362 if (new_owner
== INVALID_OWNER
) {
365 s
->awarded
= new_owner
;
369 if (new_owner
== INVALID_OWNER
) RebuildSubsidisedSourceAndDestinationCache();
371 /* Take care of rating and transport rights in towns */
373 /* If a company takes over, give the ratings to that company. */
374 if (new_owner
!= INVALID_OWNER
) {
375 if (HasBit(t
->have_ratings
, old_owner
)) {
376 if (HasBit(t
->have_ratings
, new_owner
)) {
377 /* use max of the two ratings. */
378 t
->ratings
[new_owner
] = max(t
->ratings
[new_owner
], t
->ratings
[old_owner
]);
380 SetBit(t
->have_ratings
, new_owner
);
381 t
->ratings
[new_owner
] = t
->ratings
[old_owner
];
386 /* Reset the ratings for the old owner */
387 t
->ratings
[old_owner
] = RATING_INITIAL
;
388 ClrBit(t
->have_ratings
, old_owner
);
390 /* Transfer exclusive rights */
391 if (t
->exclusive_counter
> 0 && t
->exclusivity
== old_owner
) {
392 if (new_owner
!= INVALID_OWNER
) {
393 t
->exclusivity
= new_owner
;
395 t
->exclusive_counter
= 0;
396 t
->exclusivity
= INVALID_COMPANY
;
403 FOR_ALL_VEHICLES(v
) {
404 if (v
->owner
== old_owner
&& IsCompanyBuildableVehicleType(v
->type
)) {
405 if (new_owner
== INVALID_OWNER
) {
406 if (v
->Previous() == NULL
) delete v
;
408 if (v
->IsEngineCountable()) GroupStatistics::CountEngine(v
, -1);
409 if (v
->IsPrimaryVehicle()) GroupStatistics::CountVehicle(v
, -1);
415 /* In all cases clear replace engine rules.
416 * Even if it was copied, it could interfere with new owner's rules */
417 RemoveAllEngineReplacementForCompany(Company::Get(old_owner
));
419 if (new_owner
== INVALID_OWNER
) {
420 RemoveAllGroupsForCompany(old_owner
);
424 if (g
->owner
== old_owner
) g
->owner
= new_owner
;
429 FreeUnitIDGenerator unitidgen
[] = {
430 FreeUnitIDGenerator(VEH_TRAIN
, new_owner
), FreeUnitIDGenerator(VEH_ROAD
, new_owner
),
431 FreeUnitIDGenerator(VEH_SHIP
, new_owner
), FreeUnitIDGenerator(VEH_AIRCRAFT
, new_owner
)
434 /* Override company settings to new company defaults in case we need to convert them.
435 * This is required as the CmdChangeServiceInt doesn't copy the supplied value when it is non-custom
437 if (new_owner
!= INVALID_OWNER
) {
438 Company
*old_company
= Company::Get(old_owner
);
439 Company
*new_company
= Company::Get(new_owner
);
441 old_company
->settings
.vehicle
.servint_aircraft
= new_company
->settings
.vehicle
.servint_aircraft
;
442 old_company
->settings
.vehicle
.servint_trains
= new_company
->settings
.vehicle
.servint_trains
;
443 old_company
->settings
.vehicle
.servint_roadveh
= new_company
->settings
.vehicle
.servint_roadveh
;
444 old_company
->settings
.vehicle
.servint_ships
= new_company
->settings
.vehicle
.servint_ships
;
445 old_company
->settings
.vehicle
.servint_ispercent
= new_company
->settings
.vehicle
.servint_ispercent
;
449 FOR_ALL_VEHICLES(v
) {
450 if (v
->owner
== old_owner
&& IsCompanyBuildableVehicleType(v
->type
)) {
451 assert(new_owner
!= INVALID_OWNER
);
453 /* Correct default values of interval settings while maintaining custom set ones.
454 * This prevents invalid values on mismatching company defaults being accepted.
456 if (!v
->ServiceIntervalIsCustom()) {
457 Company
*new_company
= Company::Get(new_owner
);
459 /* Technically, passing the interval is not needed as the command will query the default value itself.
460 * However, do not rely on that behaviour.
462 int interval
= CompanyServiceInterval(new_company
, v
->type
);
463 DoCommand(v
->tile
, v
->index
, interval
| (new_company
->settings
.vehicle
.servint_ispercent
<< 17), DC_EXEC
| DC_BANKRUPT
, CMD_CHANGE_SERVICE_INT
);
466 v
->owner
= new_owner
;
468 /* Owner changes, clear cache */
469 v
->colourmap
= PAL_NONE
;
470 v
->InvalidateNewGRFCache();
472 if (v
->IsEngineCountable()) {
473 GroupStatistics::CountEngine(v
, 1);
475 if (v
->IsPrimaryVehicle()) {
476 GroupStatistics::CountVehicle(v
, 1);
477 v
->unitnumber
= unitidgen
[v
->type
].NextID();
480 /* Invalidate the vehicle's cargo payment "owner cache". */
481 if (v
->cargo_payment
!= NULL
) v
->cargo_payment
->owner
= NULL
;
485 if (new_owner
!= INVALID_OWNER
) GroupStatistics::UpdateAutoreplace(new_owner
);
488 /* Change ownership of tiles */
492 ChangeTileOwner(tile
, old_owner
, new_owner
);
493 } while (++tile
!= MapSize());
495 if (new_owner
!= INVALID_OWNER
) {
496 /* Update all signals because there can be new segment that was owned by two companies
497 * and signals were not propagated
498 * Similar with crossings - it is needed to bar crossings that weren't before
499 * because of different owner of crossing and approaching train */
503 if (IsRailwayTile(tile
) && IsTileOwner(tile
, new_owner
)) {
504 TrackBits tracks
= GetTrackBits(tile
);
505 do { // there may be two tracks with signals for TRACK_BIT_HORZ and TRACK_BIT_VERT
506 Track track
= RemoveFirstTrack(&tracks
);
507 if (HasSignalOnTrack(tile
, track
)) AddTrackToSignalBuffer(tile
, track
, new_owner
);
508 } while (tracks
!= TRACK_BIT_NONE
);
509 } else if (IsLevelCrossingTile(tile
) && IsTileOwner(tile
, new_owner
)) {
510 UpdateLevelCrossing(tile
);
512 } while (++tile
!= MapSize());
515 /* update signals in buffer */
516 UpdateSignalsInBuffer();
519 /* Add airport infrastructure count of the old company to the new one. */
520 if (new_owner
!= INVALID_OWNER
) Company::Get(new_owner
)->infrastructure
.airport
+= Company::Get(old_owner
)->infrastructure
.airport
;
522 /* convert owner of stations (including deleted ones, but excluding buoys) */
524 FOR_ALL_STATIONS(st
) {
525 if (st
->owner
== old_owner
) {
526 /* if a company goes bankrupt, set owner to OWNER_NONE so the sign doesn't disappear immediately
527 * also, drawing station window would cause reading invalid company's colour */
528 st
->owner
= new_owner
== INVALID_OWNER
? OWNER_NONE
: new_owner
;
532 /* do the same for waypoints (we need to do this here so deleted waypoints are converted too) */
534 FOR_ALL_WAYPOINTS(wp
) {
535 if (wp
->owner
== old_owner
) {
536 wp
->owner
= new_owner
== INVALID_OWNER
? OWNER_NONE
: new_owner
;
542 if (si
->owner
== old_owner
) si
->owner
= new_owner
== INVALID_OWNER
? OWNER_NONE
: new_owner
;
545 /* Remove Game Script created Goals, CargoMonitors and Story pages. */
548 if (g
->company
== old_owner
) delete g
;
551 ClearCargoPickupMonitoring(old_owner
);
552 ClearCargoDeliveryMonitoring(old_owner
);
555 FOR_ALL_STORY_PAGES(sp
) {
556 if (sp
->company
== old_owner
) delete sp
;
559 /* Change colour of existing windows */
560 if (new_owner
!= INVALID_OWNER
) ChangeWindowOwner(old_owner
, new_owner
);
562 cur_company
.Restore();
564 MarkWholeScreenDirty();
568 * Check for bankruptcy of a company. Called every three months.
569 * @param c Company to check.
571 static void CompanyCheckBankrupt(Company
*c
)
573 /* If the company has money again, it does not go bankrupt */
574 if (c
->money
- c
->current_loan
>= -_economy
.max_loan
) {
575 c
->months_of_bankruptcy
= 0;
576 c
->bankrupt_asked
= 0;
580 c
->months_of_bankruptcy
++;
582 switch (c
->months_of_bankruptcy
) {
583 /* All the boring cases (months) with a bad balance where no action is taken */
596 /* Warn about bankruptcy after 3 months */
598 AddNewsItem
<CompanyNewsItem
> (STR_NEWS_COMPANY_IN_TROUBLE_TITLE
,
599 STR_NEWS_COMPANY_IN_TROUBLE_DESCRIPTION
, c
);
600 AI::BroadcastNewEvent(new ScriptEventCompanyInTrouble(c
->index
));
601 Game::NewEvent(new ScriptEventCompanyInTrouble(c
->index
));
604 /* Offer company for sale after 6 months */
606 /* Don't consider the loan */
607 Money val
= CalculateCompanyValue(c
, false);
609 c
->bankrupt_value
= val
;
610 c
->bankrupt_asked
= 1 << c
->index
; // Don't ask the owner
611 c
->bankrupt_timeout
= 0;
613 /* The company assets should always have some value */
614 assert(c
->bankrupt_value
> 0);
618 /* Bankrupt company after 6 months (if the company has no value) or latest
619 * after 9 months (if it still had value after 6 months) */
622 if (!_networking
&& _local_company
== c
->index
) {
623 /* If we are in offline mode, leave the company playing. Eg. there
624 * is no THE-END, otherwise mark the client as spectator to make sure
625 * he/she is no long in control of this company. However... when you
626 * join another company (cheat) the "unowned" company can bankrupt. */
627 c
->bankrupt_asked
= MAX_UVALUE(CompanyMask
);
631 /* Actually remove the company, but not when we're a network client.
632 * In case of network clients we will be getting a command from the
633 * server. It is done in this way as we are called from the
634 * StateGameLoop which can't change the current company, and thus
635 * updating the local company triggers an assert later on. In the
636 * case of a network game the command will be processed at a time
637 * that changing the current company is okay. In case of single
638 * player we are sure (the above check) that we are not the local
639 * company and thus we won't be moved. */
640 if (!_networking
|| _network_server
) DoCommandP(0, 2 | (c
->index
<< 16), CRR_BANKRUPT
, CMD_COMPANY_CTRL
);
647 * Update the finances of all companies.
648 * Pay for the stations, update the history graph, update ratings and company values, and deal with bankruptcy.
650 static void CompaniesGenStatistics()
654 Backup
<CompanyByte
> cur_company(_current_company
, FILE_LINE
);
657 if (!_settings_game
.economy
.infrastructure_maintenance
) {
658 FOR_ALL_STATIONS(st
) {
659 cur_company
.Change(st
->owner
);
660 CommandCost
cost(EXPENSES_PROPERTY
, _price
[PR_STATION_VALUE
] >> 1);
661 SubtractMoneyFromCompany(cost
);
664 /* Improved monthly infrastructure costs. */
665 FOR_ALL_COMPANIES(c
) {
666 cur_company
.Change(c
->index
);
668 CommandCost
cost(EXPENSES_PROPERTY
);
669 uint32 rail_total
= c
->infrastructure
.GetRailTotal();
670 for (RailType rt
= RAILTYPE_BEGIN
; rt
< RAILTYPE_END
; rt
++) {
671 if (c
->infrastructure
.rail
[rt
] != 0) cost
.AddCost(RailMaintenanceCost(rt
, c
->infrastructure
.rail
[rt
], rail_total
));
673 cost
.AddCost(SignalMaintenanceCost(c
->infrastructure
.signal
));
674 for (RoadType rt
= ROADTYPE_BEGIN
; rt
< ROADTYPE_END
; rt
++) {
675 if (c
->infrastructure
.road
[rt
] != 0) cost
.AddCost(RoadMaintenanceCost(rt
, c
->infrastructure
.road
[rt
]));
677 cost
.AddCost(CanalMaintenanceCost(c
->infrastructure
.water
));
678 cost
.AddCost(StationMaintenanceCost(c
->infrastructure
.station
));
679 cost
.AddCost(AirportMaintenanceCost(c
->index
));
681 SubtractMoneyFromCompany(cost
);
684 cur_company
.Restore();
686 /* Check for bankruptcy each month */
687 FOR_ALL_COMPANIES(c
) {
688 CompanyCheckBankrupt(c
);
691 /* Only run the economic statics and update company stats every 3rd month (1st of quarter). */
692 if (!HasBit(1 << 0 | 1 << 3 | 1 << 6 | 1 << 9, _cur_month
)) return;
694 FOR_ALL_COMPANIES(c
) {
695 memmove(&c
->old_economy
[1], &c
->old_economy
[0], sizeof(c
->old_economy
) - sizeof(c
->old_economy
[0]));
696 c
->old_economy
[0] = c
->cur_economy
;
697 memset(&c
->cur_economy
, 0, sizeof(c
->cur_economy
));
699 if (c
->num_valid_stat_ent
!= MAX_HISTORY_QUARTERS
) c
->num_valid_stat_ent
++;
701 UpdateCompanyRatingAndValue(c
, true);
702 if (c
->block_preview
!= 0) c
->block_preview
--;
705 SetWindowDirty(WC_INCOME_GRAPH
, 0);
706 SetWindowDirty(WC_OPERATING_PROFIT
, 0);
707 SetWindowDirty(WC_DELIVERED_CARGO
, 0);
708 SetWindowDirty(WC_PERFORMANCE_HISTORY
, 0);
709 SetWindowDirty(WC_COMPANY_VALUE
, 0);
710 SetWindowDirty(WC_COMPANY_LEAGUE
, 0);
714 * Add monthly inflation
715 * @param check_year Shall the inflation get stopped after 170 years?
716 * @return true if inflation is maxed and nothing was changed
718 bool AddInflation(bool check_year
)
720 /* The cargo payment inflation differs from the normal inflation, so the
721 * relative amount of money you make with a transport decreases slowly over
722 * the 170 years. After a few hundred years we reach a level in which the
723 * games will become unplayable as the maximum income will be less than
724 * the minimum running cost.
726 * Furthermore there are a lot of inflation related overflows all over the
727 * place. Solving them is hardly possible because inflation will always
728 * reach the overflow threshold some day. So we'll just perform the
729 * inflation mechanism during the first 170 years (the amount of years that
730 * one had in the original TTD) and stop doing the inflation after that
731 * because it only causes problems that can't be solved nicely and the
732 * inflation doesn't add anything after that either; it even makes playing
733 * it impossible due to the diverging cost and income rates.
735 if (check_year
&& (_cur_year
- _settings_game
.game_creation
.starting_year
) >= (ORIGINAL_MAX_YEAR
- ORIGINAL_BASE_YEAR
)) return true;
737 if (_economy
.inflation_prices
== MAX_INFLATION
|| _economy
.inflation_payment
== MAX_INFLATION
) return true;
739 /* Approximation for (100 + infl_amount)% ** (1 / 12) - 100%
741 * 12 -> months per year
742 * This is only a good approximation for small values
744 _economy
.inflation_prices
+= (_economy
.inflation_prices
* _economy
.infl_amount
* 54) >> 16;
745 _economy
.inflation_payment
+= (_economy
.inflation_payment
* _economy
.infl_amount_pr
* 54) >> 16;
747 if (_economy
.inflation_prices
> MAX_INFLATION
) _economy
.inflation_prices
= MAX_INFLATION
;
748 if (_economy
.inflation_payment
> MAX_INFLATION
) _economy
.inflation_payment
= MAX_INFLATION
;
754 * Computes all prices, payments and maximum loan.
756 void RecomputePrices()
758 /* Setup maximum loan */
759 _economy
.max_loan
= (_settings_game
.difficulty
.max_loan
* _economy
.inflation_prices
>> 16) / 50000 * 50000;
761 /* Setup price bases */
762 for (Price i
= PR_BEGIN
; i
< PR_END
; i
++) {
763 Money price
= _price_base_specs
[i
].start_price
;
765 /* Apply difficulty settings */
767 switch (_price_base_specs
[i
].category
) {
769 mod
= _settings_game
.difficulty
.vehicle_costs
;
772 case PCAT_CONSTRUCTION
:
773 mod
= _settings_game
.difficulty
.construction_cost
;
779 case 0: price
*= 6; break;
780 case 1: price
*= 8; break; // normalised to 1 below
781 case 2: price
*= 9; break;
782 default: NOT_REACHED();
785 /* Apply inflation */
786 price
= (int64
)price
* _economy
.inflation_prices
;
788 /* Apply newgrf modifiers, remove fractional part of inflation, and normalise on medium difficulty. */
789 int shift
= _price_base_multiplier
[i
] - 16 - 3;
796 /* Make sure the price does not get reduced to zero.
797 * Zero breaks quite a few commands that use a zero
798 * cost to see whether something got changed or not
799 * and based on that cause an error. When the price
800 * is zero that fails even when things are done. */
802 price
= Clamp(_price_base_specs
[i
].start_price
, -1, 1);
803 /* No base price should be zero, but be sure. */
810 /* Setup cargo payment */
812 FOR_ALL_CARGOSPECS(cs
) {
813 cs
->current_payment
= ((int64
)cs
->initial_payment
* _economy
.inflation_payment
) >> 16;
816 SetWindowClassesDirty(WC_BUILD_VEHICLE
);
817 SetWindowClassesDirty(WC_REPLACE_VEHICLE
);
818 SetWindowClassesDirty(WC_VEHICLE_DETAILS
);
819 SetWindowClassesDirty(WC_COMPANY_INFRASTRUCTURE
);
820 InvalidateWindowData(WC_PAYMENT_RATES
, 0);
823 /** Let all companies pay the monthly interest on their loan. */
824 static void CompaniesPayInterest()
828 Backup
<CompanyByte
> cur_company(_current_company
, FILE_LINE
);
829 FOR_ALL_COMPANIES(c
) {
830 cur_company
.Change(c
->index
);
832 /* Over a year the paid interest should be "loan * interest percentage",
833 * but... as that number is likely not dividable by 12 (pay each month),
834 * one needs to account for that in the monthly fee calculations.
835 * To easily calculate what one should pay "this" month, you calculate
836 * what (total) should have been paid up to this month and you subtract
837 * whatever has been paid in the previous months. This will mean one month
838 * it'll be a bit more and the other it'll be a bit less than the average
839 * monthly fee, but on average it will be exact.
840 * In order to prevent cheating or abuse (just not paying interest by not
841 * taking a loan we make companies pay interest on negative cash as well
843 Money yearly_fee
= c
->current_loan
* _economy
.interest_rate
/ 100;
845 yearly_fee
+= -c
->money
*_economy
.interest_rate
/ 100;
847 Money up_to_previous_month
= yearly_fee
* _cur_month
/ 12;
848 Money up_to_this_month
= yearly_fee
* (_cur_month
+ 1) / 12;
850 SubtractMoneyFromCompany(CommandCost(EXPENSES_LOAN_INT
, up_to_this_month
- up_to_previous_month
));
852 SubtractMoneyFromCompany(CommandCost(EXPENSES_OTHER
, _price
[PR_STATION_VALUE
] >> 2));
854 cur_company
.Restore();
857 static void HandleEconomyFluctuations()
859 if (_settings_game
.difficulty
.economy
!= 0) {
860 /* When economy is Fluctuating, decrease counter */
862 } else if (EconomyIsInRecession()) {
863 /* When it's Steady and we are in recession, end it now */
864 _economy
.fluct
= -12;
866 /* No need to do anything else in other cases */
871 if (_economy
.fluct
== 0) {
872 _economy
.fluct
= -(int)GB(Random(), 0, 2);
873 str
= STR_NEWS_BEGIN_OF_RECESSION
;
874 } else if (_economy
.fluct
== -12) {
875 _economy
.fluct
= GB(Random(), 0, 8) + 312;
876 str
= STR_NEWS_END_OF_RECESSION
;
880 AddNewsItem
<NewsItem
> (str
, NT_ECONOMY
, NF_NORMAL
);
885 * Reset changes to the price base multipliers.
887 void ResetPriceBaseMultipliers()
889 memset(_price_base_multiplier
, 0, sizeof(_price_base_multiplier
));
893 * Change a price base by the given factor.
894 * The price base is altered by factors of two.
895 * NewBaseCost = OldBaseCost * 2^n
896 * @param price Index of price base to change.
897 * @param factor Amount to change by.
899 void SetPriceBaseMultiplier(Price price
, int factor
)
901 assert(price
< PR_END
);
902 _price_base_multiplier
[price
] = Clamp(factor
, MIN_PRICE_MODIFIER
, MAX_PRICE_MODIFIER
);
906 * Initialize the variables that will maintain the daily industry change system.
907 * @param init_counter specifies if the counter is required to be initialized
909 void StartupIndustryDailyChanges(bool init_counter
)
911 uint map_size
= MapLogX() + MapLogY();
912 /* After getting map size, it needs to be scaled appropriately and divided by 31,
913 * which stands for the days in a month.
914 * Using just 31 will make it so that a monthly reset (based on the real number of days of that month)
915 * would not be needed.
916 * Since it is based on "fractional parts", the leftover days will not make much of a difference
917 * on the overall total number of changes performed */
918 _economy
.industry_daily_increment
= (1 << map_size
) / 31;
921 /* A new game or a savegame from an older version will require the counter to be initialized */
922 _economy
.industry_daily_change_counter
= 0;
926 void StartupEconomy()
928 _economy
.interest_rate
= _settings_game
.difficulty
.initial_interest
;
929 _economy
.infl_amount
= _settings_game
.difficulty
.initial_interest
;
930 _economy
.infl_amount_pr
= max(0, _settings_game
.difficulty
.initial_interest
- 1);
931 _economy
.fluct
= GB(Random(), 0, 8) + 168;
936 StartupIndustryDailyChanges(true); // As we are starting a new game, initialize the counter too
941 * Resets economy to initial values
943 void InitializeEconomy()
945 _economy
.inflation_prices
= _economy
.inflation_payment
= 1 << 16;
946 ClearCargoPickupMonitoring();
947 ClearCargoDeliveryMonitoring();
951 * Determine a certain price
952 * @param index Price base
953 * @param cost_factor Price factor
954 * @param grf_file NewGRF to use local price multipliers from.
955 * @param shift Extra bit shifting after the computation
958 Money
GetPrice(Price index
, uint cost_factor
, const GRFFile
*grf_file
, int shift
)
960 if (index
>= PR_END
) return 0;
962 Money cost
= _price
[index
] * cost_factor
;
963 if (grf_file
!= NULL
) shift
+= grf_file
->price_base_multipliers
[index
];
974 Money
GetTransportedGoodsIncome(uint num_pieces
, uint dist
, byte transit_days
, CargoID cargo_type
)
976 const CargoSpec
*cs
= CargoSpec::Get(cargo_type
);
977 if (!cs
->IsValid()) {
978 /* User changed newgrfs and some vehicle still carries some cargo which is no longer available. */
982 /* Use callback to calculate cargo profit, if available */
983 if (HasBit(cs
->callback_mask
, CBM_CARGO_PROFIT_CALC
)) {
984 uint32 var18
= min(dist
, 0xFFFF) | (min(num_pieces
, 0xFF) << 16) | (transit_days
<< 24);
985 uint16 callback
= GetCargoCallback(CBID_CARGO_PROFIT_CALC
, 0, var18
, cs
);
986 if (callback
!= CALLBACK_FAILED
) {
987 int result
= GB(callback
, 0, 14);
989 /* Simulate a 15 bit signed value */
990 if (HasBit(callback
, 14)) result
-= 0x4000;
992 /* "The result should be a signed multiplier that gets multiplied
993 * by the amount of cargo moved and the price factor, then gets
994 * divided by 8192." */
995 return result
* num_pieces
* cs
->current_payment
/ 8192;
999 static const int MIN_TIME_FACTOR
= 31;
1000 static const int MAX_TIME_FACTOR
= 255;
1002 const int days1
= cs
->transit_days
[0];
1003 const int days2
= cs
->transit_days
[1];
1004 const int days_over_days1
= max( transit_days
- days1
, 0);
1005 const int days_over_days2
= max(days_over_days1
- days2
, 0);
1008 * The time factor is calculated based on the time it took
1009 * (transit_days) compared two cargo-depending values. The
1010 * range is divided into three parts:
1012 * - constant for fast transits
1013 * - linear decreasing with time with a slope of -1 for medium transports
1014 * - linear decreasing with time with a slope of -2 for slow transports
1017 const int time_factor
= max(MAX_TIME_FACTOR
- days_over_days1
- days_over_days2
, MIN_TIME_FACTOR
);
1019 return BigMulS(dist
* time_factor
* num_pieces
, cs
->current_payment
, 21);
1022 /** The industries we've currently brought cargo to. */
1023 static SmallIndustryList _cargo_delivery_destinations
;
1026 * Transfer goods from station to industry.
1027 * All cargo is delivered to the nearest (Manhattan) industry to the station sign, which is inside the acceptance rectangle and actually accepts the cargo.
1028 * @param st The station that accepted the cargo
1029 * @param cargo_type Type of cargo delivered
1030 * @param num_pieces Amount of cargo delivered
1031 * @param source The source of the cargo
1032 * @return actually accepted pieces of cargo
1034 static uint
DeliverGoodsToIndustry(const Station
*st
, CargoID cargo_type
, uint num_pieces
, IndustryID source
)
1036 /* Find the nearest industrytile to the station sign inside the catchment area, whose industry accepts the cargo.
1037 * This fails in three cases:
1038 * 1) The station accepts the cargo because there are enough houses around it accepting the cargo.
1039 * 2) The industries in the catchment area temporarily reject the cargo, and the daily station loop has not yet updated station acceptance.
1040 * 3) The results of callbacks CBID_INDUSTRY_REFUSE_CARGO and CBID_INDTILE_CARGO_ACCEPTANCE are inconsistent. (documented behaviour)
1045 for (uint i
= 0; i
< st
->industries_near
.Length() && num_pieces
!= 0; i
++) {
1046 Industry
*ind
= st
->industries_near
[i
];
1047 if (ind
->index
== source
) continue;
1050 for (cargo_index
= 0; cargo_index
< lengthof(ind
->accepts_cargo
); cargo_index
++) {
1051 if (cargo_type
== ind
->accepts_cargo
[cargo_index
]) break;
1053 /* Check if matching cargo has been found */
1054 if (cargo_index
>= lengthof(ind
->accepts_cargo
)) continue;
1056 /* Check if industry temporarily refuses acceptance */
1057 if (IndustryTemporarilyRefusesCargo(ind
, cargo_type
)) continue;
1059 /* Insert the industry into _cargo_delivery_destinations, if not yet contained */
1060 _cargo_delivery_destinations
.Include(ind
);
1062 uint amount
= min(num_pieces
, 0xFFFFU
- ind
->incoming_cargo_waiting
[cargo_index
]);
1063 ind
->incoming_cargo_waiting
[cargo_index
] += amount
;
1064 num_pieces
-= amount
;
1072 * Delivers goods to industries/towns and calculates the payment
1073 * @param num_pieces amount of cargo delivered
1074 * @param cargo_type the type of cargo that is delivered
1075 * @param dest Station the cargo has been unloaded
1076 * @param source_tile The origin of the cargo for distance calculation
1077 * @param days_in_transit Travel time
1078 * @param company The company delivering the cargo
1079 * @param src Source of cargo
1080 * @return Revenue for delivering cargo
1081 * @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
1083 static Money
DeliverGoods(int num_pieces
, CargoID cargo_type
, StationID dest
, TileIndex source_tile
, byte days_in_transit
, Company
*company
, const CargoSource
&src
)
1085 assert(num_pieces
> 0);
1087 Station
*st
= Station::Get(dest
);
1089 /* Give the goods to the industry. */
1090 uint accepted
= DeliverGoodsToIndustry (st
, cargo_type
, num_pieces
, src
.type
== ST_INDUSTRY
? src
.id
: INVALID_INDUSTRY
);
1092 /* If this cargo type is always accepted, accept all */
1093 if (HasBit(st
->always_accepted
, cargo_type
)) accepted
= num_pieces
;
1095 /* Update station statistics */
1097 SetBit(st
->goods
[cargo_type
].status
, GoodsEntry::GES_EVER_ACCEPTED
);
1098 SetBit(st
->goods
[cargo_type
].status
, GoodsEntry::GES_CURRENT_MONTH
);
1099 SetBit(st
->goods
[cargo_type
].status
, GoodsEntry::GES_ACCEPTED_BIGTICK
);
1102 /* Update company statistics */
1103 company
->cur_economy
.delivered_cargo
[cargo_type
] += accepted
;
1105 /* Increase town's counter for town effects */
1106 const CargoSpec
*cs
= CargoSpec::Get(cargo_type
);
1107 st
->town
->received
[cs
->town_effect
].new_act
+= accepted
;
1109 /* Determine profit */
1110 Money profit
= GetTransportedGoodsIncome(accepted
, DistanceManhattan(source_tile
, st
->xy
), days_in_transit
, cargo_type
);
1112 /* Update the cargo monitor. */
1113 AddCargoDelivery (cargo_type
, company
->index
, accepted
, src
, st
);
1115 /* Modify profit if a subsidy is in effect */
1116 if (CheckSubsidised (cargo_type
, company
->index
, src
, st
)) {
1117 switch (_settings_game
.difficulty
.subsidy_multiplier
) {
1118 case 0: profit
+= profit
>> 1; break;
1119 case 1: profit
*= 2; break;
1120 case 2: profit
*= 3; break;
1121 default: profit
*= 4; break;
1129 * Inform the industry about just delivered cargo
1130 * DeliverGoodsToIndustry() silently incremented incoming_cargo_waiting, now it is time to do something with the new cargo.
1131 * @param i The industry to process
1133 static void TriggerIndustryProduction(Industry
*i
)
1135 const IndustrySpec
*indspec
= GetIndustrySpec(i
->type
);
1136 uint16 callback
= indspec
->callback_mask
;
1138 i
->was_cargo_delivered
= true;
1139 i
->last_cargo_accepted_at
= _date
;
1141 if (HasBit(callback
, CBM_IND_PRODUCTION_CARGO_ARRIVAL
) || HasBit(callback
, CBM_IND_PRODUCTION_256_TICKS
)) {
1142 if (HasBit(callback
, CBM_IND_PRODUCTION_CARGO_ARRIVAL
)) {
1143 IndustryProductionCallback(i
, 0);
1145 SetWindowDirty(WC_INDUSTRY_VIEW
, i
->index
);
1148 for (uint cargo_index
= 0; cargo_index
< lengthof(i
->incoming_cargo_waiting
); cargo_index
++) {
1149 uint cargo_waiting
= i
->incoming_cargo_waiting
[cargo_index
];
1150 if (cargo_waiting
== 0) continue;
1152 i
->produced_cargo_waiting
[0] = min(i
->produced_cargo_waiting
[0] + (cargo_waiting
* indspec
->input_cargo_multiplier
[cargo_index
][0] / 256), 0xFFFF);
1153 i
->produced_cargo_waiting
[1] = min(i
->produced_cargo_waiting
[1] + (cargo_waiting
* indspec
->input_cargo_multiplier
[cargo_index
][1] / 256), 0xFFFF);
1155 i
->incoming_cargo_waiting
[cargo_index
] = 0;
1159 TriggerIndustry(i
, INDUSTRY_TRIGGER_RECEIVED_CARGO
);
1160 StartStopIndustryTileAnimation(i
, IAT_INDUSTRY_RECEIVED_CARGO
);
1164 * Makes us a new cargo payment helper.
1165 * @param front The front of the train
1167 CargoPayment::CargoPayment(Vehicle
*front
) :
1169 current_station(front
->last_station_visited
)
1173 CargoPayment::~CargoPayment()
1175 if (this->CleaningPool()) return;
1177 this->front
->cargo_payment
= NULL
;
1179 if (this->visual_profit
== 0 && this->visual_transfer
== 0) return;
1181 Backup
<CompanyByte
> cur_company(_current_company
, this->front
->owner
, FILE_LINE
);
1183 SubtractMoneyFromCompany(CommandCost(this->front
->GetExpenseType(true), -this->route_profit
));
1184 this->front
->profit_this_year
+= (this->visual_profit
+ this->visual_transfer
) << 8;
1186 if (this->route_profit
!= 0 && IsLocalCompany() && !PlayVehicleSound(this->front
, VSE_LOAD_UNLOAD
)) {
1187 SndPlayVehicleFx(SND_14_CASHTILL
, this->front
);
1190 if (this->visual_transfer
!= 0) {
1191 ShowFeederIncomeAnimation(this->front
->x_pos
, this->front
->y_pos
,
1192 this->front
->z_pos
, this->visual_transfer
, -this->visual_profit
);
1193 } else if (this->visual_profit
!= 0) {
1194 ShowCostOrIncomeAnimation(this->front
->x_pos
, this->front
->y_pos
,
1195 this->front
->z_pos
, -this->visual_profit
);
1198 cur_company
.Restore();
1202 * Handle payment for final delivery of the given cargo packet.
1203 * @param cp The cargo packet to pay for.
1204 * @param count The number of packets to pay for.
1206 void CargoPayment::PayFinalDelivery(const CargoPacket
*cp
, uint count
)
1208 if (this->owner
== NULL
) {
1209 this->owner
= Company::Get(this->front
->owner
);
1212 /* Handle end of route payment */
1213 Money profit
= DeliverGoods (count
, this->ct
, this->current_station
, cp
->SourceStationXY(), cp
->DaysInTransit(), this->owner
, cp
->Source());
1214 this->route_profit
+= profit
;
1216 /* The vehicle's profit is whatever route profit there is minus feeder shares. */
1217 this->visual_profit
+= profit
- cp
->FeederShare(count
);
1221 * Handle payment for transfer of the given cargo packet.
1222 * @param cp The cargo packet to pay for; actual payment won't be made!.
1223 * @param count The number of packets to pay for.
1224 * @return The amount of money paid for the transfer.
1226 Money
CargoPayment::PayTransfer(const CargoPacket
*cp
, uint count
)
1228 Money profit
= GetTransportedGoodsIncome(
1230 /* pay transfer vehicle for only the part of transfer it has done: ie. cargo_loaded_at_xy to here */
1231 DistanceManhattan(cp
->LoadedAtXY(), Station::Get(this->current_station
)->xy
),
1232 cp
->DaysInTransit(),
1235 profit
= profit
* _settings_game
.economy
.feeder_payment_share
/ 100;
1237 this->visual_transfer
+= profit
; // accumulate transfer profits for whole vehicle
1238 return profit
; // account for the (virtual) profit already made for the cargo packet
1242 * Prepare the vehicle to be unloaded.
1243 * @param curr_station the station where the consist is at the moment
1244 * @param front_v the vehicle to be unloaded
1246 void PrepareUnload(Vehicle
*front_v
)
1248 Station
*curr_station
= Station::Get(front_v
->last_station_visited
);
1249 curr_station
->loading_vehicles
.push_back(front_v
);
1251 /* At this moment loading cannot be finished */
1252 ClrBit(front_v
->vehicle_flags
, VF_LOADING_FINISHED
);
1254 /* Start unloading at the first possible moment */
1255 front_v
->load_unload_ticks
= 1;
1257 assert(front_v
->cargo_payment
== NULL
);
1258 /* One CargoPayment per vehicle and the vehicle limit equals the
1259 * limit in number of CargoPayments. Can't go wrong. */
1260 assert_compile(CargoPayment::Pool::MAX_SIZE
== Vehicle::Pool::MAX_SIZE
);
1261 assert(CargoPayment::CanAllocateItem());
1262 front_v
->cargo_payment
= new CargoPayment(front_v
);
1264 StationIDStack next_station
= front_v
->GetNextStoppingStation();
1265 if (front_v
->orders
.list
== NULL
|| (front_v
->current_order
.GetUnloadType() & OUFB_NO_UNLOAD
) == 0) {
1266 Station
*st
= Station::Get(front_v
->last_station_visited
);
1267 for (Vehicle
*v
= front_v
; v
!= NULL
; v
= v
->Next()) {
1268 const GoodsEntry
*ge
= &st
->goods
[v
->cargo_type
];
1269 if (v
->cargo_cap
> 0 && v
->cargo
.TotalCount() > 0) {
1271 HasBit(ge
->status
, GoodsEntry::GES_ACCEPTANCE
),
1272 front_v
->last_station_visited
, next_station
,
1273 front_v
->current_order
.GetUnloadType(), ge
,
1274 front_v
->cargo_payment
);
1275 if (v
->cargo
.UnloadCount() > 0) SetBit(v
->vehicle_flags
, VF_CARGO_UNLOADING
);
1282 * Gets the amount of cargo the given vehicle can load in the current tick.
1283 * This is only about loading speed. The free capacity is ignored.
1284 * @param v Vehicle to be queried.
1285 * @return Amount of cargo the vehicle can load at once.
1287 static uint
GetLoadAmount(Vehicle
*v
)
1289 const Engine
*e
= v
->GetEngine();
1290 uint load_amount
= e
->info
.load_amount
;
1292 /* The default loadamount for mail is 1/4 of the load amount for passengers */
1293 bool air_mail
= v
->type
== VEH_AIRCRAFT
&& !Aircraft::From(v
)->IsNormalAircraft();
1294 if (air_mail
) load_amount
= CeilDiv(load_amount
, 4);
1296 if (_settings_game
.order
.gradual_loading
) {
1297 uint16 cb_load_amount
= CALLBACK_FAILED
;
1298 if (e
->GetGRF() != NULL
&& e
->GetGRF()->grf_version
>= 8) {
1299 /* Use callback 36 */
1300 cb_load_amount
= GetVehicleProperty(v
, PROP_VEHICLE_LOAD_AMOUNT
, CALLBACK_FAILED
);
1301 } else if (HasBit(e
->info
.callback_mask
, CBM_VEHICLE_LOAD_AMOUNT
)) {
1302 /* Use callback 12 */
1303 cb_load_amount
= GetVehicleCallback(CBID_VEHICLE_LOAD_AMOUNT
, 0, 0, v
->engine_type
, v
);
1305 if (cb_load_amount
!= CALLBACK_FAILED
) {
1306 if (e
->GetGRF()->grf_version
< 8) cb_load_amount
= GB(cb_load_amount
, 0, 8);
1307 if (cb_load_amount
>= 0x100) {
1308 ErrorUnknownCallbackResult(e
->GetGRFID(), CBID_VEHICLE_LOAD_AMOUNT
, cb_load_amount
);
1309 } else if (cb_load_amount
!= 0) {
1310 load_amount
= cb_load_amount
;
1315 /* Scale load amount the same as capacity */
1316 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);
1322 * Iterate the articulated parts of a vehicle, also considering the special cases of "normal"
1323 * aircraft and double headed trains. Apply an action to each vehicle and immediately return false
1324 * if that action does so. Otherwise return true.
1325 * @tparam Taction Class of action to be applied. Must implement bool operator()([const] Vehicle *).
1326 * @param v First articulated part.
1327 * @param action Instance of Taction.
1328 * @return false if any of the action invocations returned false, true otherwise.
1330 template<class Taction
>
1331 bool IterateVehicleParts(Vehicle
*v
, Taction action
)
1333 for (Vehicle
*w
= v
; w
!= NULL
;
1334 w
= w
->HasArticulatedPart() ? w
->GetNextArticulatedPart() : NULL
) {
1335 if (!action(w
)) return false;
1336 if (w
->type
== VEH_TRAIN
) {
1337 Train
*train
= Train::From(w
);
1338 if (train
->IsMultiheaded() && !action(train
->other_multiheaded_part
)) return false;
1341 if (v
->type
== VEH_AIRCRAFT
&& Aircraft::From(v
)->IsNormalAircraft()) return action(v
->Next());
1346 * Action to check if a vehicle has no stored cargo.
1348 struct IsEmptyAction
1351 * Checks if the vehicle has stored cargo.
1352 * @param v Vehicle to be checked.
1353 * @return true if v is either empty or has only reserved cargo, false otherwise.
1355 bool operator()(const Vehicle
*v
)
1357 return v
->cargo
.StoredCount() == 0;
1362 * Refit preparation action.
1364 struct PrepareRefitAction
1366 CargoArray
&consist_capleft
; ///< Capacities left in the consist.
1367 uint32
&refit_mask
; ///< Bitmask of possible refit cargoes.
1370 * Create a refit preparation action.
1371 * @param consist_capleft Capacities left in consist, to be updated here.
1372 * @param refit_mask Refit mask to be constructed from refit information of vehicles.
1374 PrepareRefitAction(CargoArray
&consist_capleft
, uint32
&refit_mask
) :
1375 consist_capleft(consist_capleft
), refit_mask(refit_mask
) {}
1378 * Prepares for refitting of a vehicle, subtracting its free capacity from consist_capleft and
1379 * adding the cargoes it can refit to to the refit mask.
1380 * @param v The vehicle to be refitted.
1383 bool operator()(const Vehicle
*v
)
1385 this->consist_capleft
[v
->cargo_type
] -= v
->cargo_cap
- v
->cargo
.ReservedCount();
1386 this->refit_mask
|= EngInfo(v
->engine_type
)->refit_mask
;
1392 * Action for returning reserved cargo.
1394 struct ReturnCargoAction
1396 Station
*st
; ///< Station to give the returned cargo to.
1397 StationID next_hop
; ///< Next hop the cargo should be assigned to.
1400 * Construct a cargo return action.
1401 * @param st Station to give the returned cargo to.
1402 * @param next_one Next hop the cargo should be assigned to.
1404 ReturnCargoAction(Station
*st
, StationID next_one
) : st(st
), next_hop(next_one
) {}
1407 * Return all reserved cargo from a vehicle.
1408 * @param v Vehicle to return cargo from.
1411 bool operator()(Vehicle
*v
)
1413 v
->cargo
.Return(UINT_MAX
, &this->st
->goods
[v
->cargo_type
].cargo
, this->next_hop
);
1419 * Action for finalizing a refit.
1421 struct FinalizeRefitAction
1423 CargoArray
&consist_capleft
; ///< Capacities left in the consist.
1424 Station
*st
; ///< Station to reserve cargo from.
1425 StationIDStack
&next_station
; ///< Next hops to reserve cargo for.
1426 bool do_reserve
; ///< If the vehicle should reserve.
1429 * Create a finalizing action.
1430 * @param consist_capleft Capacities left in the consist.
1431 * @param st Station to reserve cargo from.
1432 * @param next_station Next hops to reserve cargo for.
1433 * @param do_reserve If we should reserve cargo or just add up the capacities.
1435 FinalizeRefitAction(CargoArray
&consist_capleft
, Station
*st
, StationIDStack
&next_station
, bool do_reserve
) :
1436 consist_capleft(consist_capleft
), st(st
), next_station(next_station
), do_reserve(do_reserve
) {}
1439 * Reserve cargo from the station and update the remaining consist capacities with the
1440 * vehicle's remaining free capacity.
1441 * @param v Vehicle to be finalized.
1444 bool operator()(Vehicle
*v
)
1446 if (this->do_reserve
) {
1447 this->st
->goods
[v
->cargo_type
].cargo
.Reserve(v
->cargo_cap
- v
->cargo
.RemainingCount(),
1448 &v
->cargo
, st
->xy
, this->next_station
);
1450 this->consist_capleft
[v
->cargo_type
] += v
->cargo_cap
- v
->cargo
.RemainingCount();
1456 * Refit a vehicle in a station.
1457 * @param v Vehicle to be refitted.
1458 * @param consist_capleft Added cargo capacities in the consist.
1459 * @param st Station the vehicle is loading at.
1460 * @param next_station Possible next stations the vehicle can travel to.
1461 * @param new_cid Target cargo mask for refit.
1463 static void HandleStationRefit (Vehicle
*v
, CargoArray
&consist_capleft
,
1464 Station
*st
, StationIDStack next_station
, CargoMask new_mask
)
1466 Vehicle
*v_start
= v
->GetFirstEnginePart();
1467 if (!IterateVehicleParts(v_start
, IsEmptyAction())) return;
1469 Backup
<CompanyByte
> cur_company(_current_company
, v
->owner
, FILE_LINE
);
1471 uint32 refit_mask
= v
->GetEngine()->info
.refit_mask
;
1473 /* Remove old capacity from consist capacity and collect refit mask. */
1474 IterateVehicleParts(v_start
, PrepareRefitAction(consist_capleft
, refit_mask
));
1476 bool is_auto_refit
= !HasAtMostOneBit (new_mask
);
1479 if (is_auto_refit
) {
1480 /* Get a refittable cargo type with waiting cargo for next_station or INVALID_STATION. */
1482 new_cid
= v_start
->cargo_type
;
1483 new_mask
&= refit_mask
;
1484 if (!HasBit(new_mask
, new_cid
) && (new_mask
!= 0)) {
1485 /* Old cargo is not present in the allowed refits. */
1486 new_cid
= FindFirstBit (new_mask
);
1488 FOR_EACH_SET_CARGO_ID(cid
, new_mask
) {
1489 if (st
->goods
[cid
].cargo
.HasCargoFor(next_station
)) {
1490 /* Try to find out if auto-refitting would succeed. In case the refit is allowed,
1491 * the returned refit capacity will be greater than zero. */
1492 DoCommand(v_start
->tile
, v_start
->index
, cid
| 1U << 6 | 0xFF << 8 | 1U << 16, DC_QUERY_COST
, CMD_REFIT_VEHICLE
); // Auto-refit and only this vehicle including artic parts.
1493 /* Try to balance different loadable cargoes between parts of the consist, so that
1494 * all of them can be loaded. Avoid a situation where all vehicles suddenly switch
1495 * to the first loadable cargo for which there is only one packet. If the capacities
1496 * are equal refit to the cargo of which most is available. This is important for
1497 * consists of only a single vehicle as those will generally have a consist_capleft
1498 * of 0 for all cargoes. */
1499 if (_returned_refit_capacity
> 0 && (consist_capleft
[cid
] < consist_capleft
[new_cid
] ||
1500 (consist_capleft
[cid
] == consist_capleft
[new_cid
] &&
1501 st
->goods
[cid
].cargo
.AvailableCount() > st
->goods
[new_cid
].cargo
.AvailableCount()))) {
1506 } else if (new_mask
!= 0) {
1507 new_cid
= FindFirstBit (new_mask
);
1509 new_cid
= CT_INVALID
;
1512 /* Refit if given a valid cargo. */
1513 if (new_cid
< NUM_CARGO
&& new_cid
!= v_start
->cargo_type
) {
1514 /* INVALID_STATION because in the DT_MANUAL case that's correct and in the DT_(A)SYMMETRIC
1515 * cases the next hop of the vehicle doesn't really tell us anything if the cargo had been
1516 * "via any station" before reserving. We rather produce some more "any station" cargo than
1518 IterateVehicleParts(v_start
, ReturnCargoAction(st
, INVALID_STATION
));
1519 CommandCost cost
= DoCommand(v_start
->tile
, v_start
->index
, new_cid
| 1U << 6 | 0xFF << 8 | 1U << 16, DC_EXEC
, CMD_REFIT_VEHICLE
); // Auto-refit and only this vehicle including artic parts.
1520 if (cost
.Succeeded()) v
->First()->profit_this_year
-= cost
.GetCost() << 8;
1523 /* Add new capacity to consist capacity and reserve cargo */
1524 IterateVehicleParts(v_start
, FinalizeRefitAction(consist_capleft
, st
, next_station
,
1525 is_auto_refit
|| (v
->First()->current_order
.GetLoadType() & OLFB_FULL_LOAD
) != 0));
1527 cur_company
.Restore();
1530 struct ReserveCargoAction
{
1532 StationIDStack
*next_station
;
1534 ReserveCargoAction(Station
*st
, StationIDStack
*next_station
) :
1535 st(st
), next_station(next_station
) {}
1537 bool operator()(Vehicle
*v
)
1539 if (v
->cargo_cap
> v
->cargo
.RemainingCount()) {
1540 st
->goods
[v
->cargo_type
].cargo
.Reserve(v
->cargo_cap
- v
->cargo
.RemainingCount(),
1541 &v
->cargo
, st
->xy
, *next_station
);
1550 * Reserves cargo if the full load order and improved_load is set or if the
1551 * current order allows autorefit.
1552 * @param st Station where the consist is loading at the moment.
1553 * @param u Front of the loading vehicle consist.
1554 * @param consist_capleft If given, save free capacities after reserving there.
1555 * @param next_station Station(s) the vehicle will stop at next.
1557 static void ReserveConsist(Station
*st
, Vehicle
*u
, CargoArray
*consist_capleft
, StationIDStack
*next_station
)
1559 /* If there is a cargo payment not all vehicles of the consist have tried to do the refit.
1560 * In that case, only reserve if it's a fixed refit and the equivalent of "articulated chain"
1561 * a vehicle belongs to already has the right cargo. */
1562 bool must_reserve
= !u
->current_order
.IsRefit() || u
->cargo_payment
== NULL
;
1563 for (Vehicle
*v
= u
; v
!= NULL
; v
= v
->Next()) {
1564 assert(v
->cargo_cap
>= v
->cargo
.RemainingCount());
1566 /* Exclude various ways in which the vehicle might not be the head of an equivalent of
1567 * "articulated chain". Also don't do the reservation if the vehicle is going to refit
1568 * to a different cargo and hasn't tried to do so, yet. */
1569 if (!v
->IsArticulatedPart() &&
1570 (v
->type
!= VEH_TRAIN
|| !Train::From(v
)->IsRearDualheaded()) &&
1571 (v
->type
!= VEH_AIRCRAFT
|| Aircraft::From(v
)->IsNormalAircraft()) &&
1572 (must_reserve
|| u
->current_order
.GetRefitCargoMask() == (1u << v
->cargo_type
))) {
1573 IterateVehicleParts(v
, ReserveCargoAction(st
, next_station
));
1575 if (consist_capleft
== NULL
|| v
->cargo_cap
== 0) continue;
1576 (*consist_capleft
)[v
->cargo_type
] += v
->cargo_cap
- v
->cargo
.RemainingCount();
1581 * Update the vehicle's load_unload_ticks, the time it will wait until it tries to load or unload
1582 * again. Adjust for overhang of trains and set it at least to 1.
1583 * @param front The vehicle to be updated.
1584 * @param st The station the vehicle is loading at.
1585 * @param ticks The time it would normally wait, based on cargo loaded and unloaded.
1587 static void UpdateLoadUnloadTicks(Vehicle
*front
, const Station
*st
, int ticks
)
1589 if (front
->type
== VEH_TRAIN
) {
1590 /* Each platform tile is worth 2 rail vehicles. */
1591 int overhang
= Train::From(front
)->gcache
.cached_total_length
- st
->GetPlatformLength(front
->tile
) * TILE_SIZE
;
1594 ticks
+= (overhang
* ticks
) / 8;
1597 /* Always wait at least 1, otherwise we'll wait 'infinitively' long. */
1598 front
->load_unload_ticks
= max(1, ticks
);
1602 * Loads/unload the vehicle if possible.
1603 * @param front the vehicle to be (un)loaded
1605 static void LoadUnloadVehicle(Vehicle
*front
)
1607 assert(front
->current_order
.IsType(OT_LOADING
));
1609 StationID last_visited
= front
->last_station_visited
;
1610 Station
*st
= Station::Get(last_visited
);
1612 StationIDStack next_station
= front
->GetNextStoppingStation();
1613 bool use_autorefit
= front
->current_order
.IsAutoRefit();
1614 CargoArray consist_capleft
;
1615 if (_settings_game
.order
.improved_load
&& use_autorefit
?
1616 front
->cargo_payment
== NULL
: (front
->current_order
.GetLoadType() & OLFB_FULL_LOAD
) != 0) {
1617 ReserveConsist(st
, front
,
1618 (use_autorefit
&& front
->load_unload_ticks
!= 0) ? &consist_capleft
: NULL
,
1622 /* We have not waited enough time till the next round of loading/unloading */
1623 if (front
->load_unload_ticks
!= 0) return;
1625 if (front
->type
== VEH_TRAIN
&& !st
->TileBelongsToStation(front
->tile
)) {
1626 /* The train reversed in the station. Take the "easy" way
1627 * out and let the train just leave as it always did. */
1628 SetBit(front
->vehicle_flags
, VF_LOADING_FINISHED
);
1629 front
->load_unload_ticks
= 1;
1633 int new_load_unload_ticks
= 0;
1634 bool dirty_vehicle
= false;
1635 bool dirty_station
= false;
1637 bool completely_emptied
= true;
1638 bool anything_unloaded
= false;
1639 bool anything_loaded
= false;
1640 uint32 full_load_amount
= 0;
1641 uint32 cargo_not_full
= 0;
1642 uint32 cargo_full
= 0;
1643 uint32 reservation_left
= 0;
1645 front
->cur_speed
= 0;
1647 CargoPayment
*payment
= front
->cargo_payment
;
1649 uint artic_part
= 0; // Articulated part we are currently trying to load. (not counting parts without capacity)
1650 for (Vehicle
*v
= front
; v
!= NULL
; v
= v
->Next()) {
1651 if (v
== front
|| !v
->Previous()->HasArticulatedPart()) artic_part
= 0;
1652 if (v
->cargo_cap
== 0) continue;
1655 uint load_amount
= GetLoadAmount(v
);
1657 GoodsEntry
*ge
= &st
->goods
[v
->cargo_type
];
1659 if (HasBit(v
->vehicle_flags
, VF_CARGO_UNLOADING
) && (front
->current_order
.GetUnloadType() & OUFB_NO_UNLOAD
) == 0) {
1660 uint cargo_count
= v
->cargo
.UnloadCount();
1661 uint amount_unloaded
= _settings_game
.order
.gradual_loading
? min(cargo_count
, load_amount
) : cargo_count
;
1662 bool remaining
= false; // Are there cargo entities in this vehicle that can still be unloaded here?
1664 payment
->SetCargo(v
->cargo_type
);
1666 if (!HasBit(ge
->status
, GoodsEntry::GES_ACCEPTANCE
) && v
->cargo
.ActionCount(VehicleCargoList::MTA_DELIVER
) > 0) {
1667 /* The station does not accept our goods anymore. */
1668 if (front
->current_order
.GetUnloadType() & (OUFB_TRANSFER
| OUFB_UNLOAD
)) {
1669 /* Transfer instead of delivering. */
1670 v
->cargo
.Reassign
<VehicleCargoList::MTA_DELIVER
, VehicleCargoList::MTA_TRANSFER
>(
1671 v
->cargo
.ActionCount(VehicleCargoList::MTA_DELIVER
), INVALID_STATION
);
1673 uint new_remaining
= v
->cargo
.RemainingCount() + v
->cargo
.ActionCount(VehicleCargoList::MTA_DELIVER
);
1674 if (v
->cargo_cap
< new_remaining
) {
1675 /* Return some of the reserved cargo to not overload the vehicle. */
1676 v
->cargo
.Return(new_remaining
- v
->cargo_cap
, &ge
->cargo
, INVALID_STATION
);
1679 /* Keep instead of delivering. This may lead to no cargo being unloaded, so ...*/
1680 v
->cargo
.Reassign
<VehicleCargoList::MTA_DELIVER
, VehicleCargoList::MTA_KEEP
>(
1681 v
->cargo
.ActionCount(VehicleCargoList::MTA_DELIVER
));
1683 /* ... say we unloaded something, otherwise we'll think we didn't unload
1684 * something and we didn't load something, so we must be finished
1685 * at this station. Setting the unloaded means that we will get a
1686 * retry for loading in the next cycle. */
1687 anything_unloaded
= true;
1691 if (v
->cargo
.ActionCount(VehicleCargoList::MTA_TRANSFER
) > 0) {
1692 /* Mark the station dirty if we transfer, but not if we only deliver. */
1693 dirty_station
= true;
1695 if (!ge
->HasRating()) {
1696 /* Upon transfering cargo, make sure the station has a rating. Fake a pickup for the
1697 * first unload to prevent the cargo from quickly decaying after the initial drop. */
1698 ge
->time_since_pickup
= 0;
1699 SetBit(ge
->status
, GoodsEntry::GES_RATING
);
1703 amount_unloaded
= v
->cargo
.Unload(amount_unloaded
, &ge
->cargo
, payment
);
1704 remaining
= v
->cargo
.UnloadCount() > 0;
1705 if (amount_unloaded
> 0) {
1706 dirty_vehicle
= true;
1707 anything_unloaded
= true;
1708 new_load_unload_ticks
+= amount_unloaded
;
1710 /* Deliver goods to the station */
1711 st
->time_since_unload
= 0;
1714 if (_settings_game
.order
.gradual_loading
&& remaining
) {
1715 completely_emptied
= false;
1717 /* We have finished unloading (cargo count == 0) */
1718 ClrBit(v
->vehicle_flags
, VF_CARGO_UNLOADING
);
1724 /* Do not pick up goods when we have no-load set or loading is stopped. */
1725 if (front
->current_order
.GetLoadType() & OLFB_NO_LOAD
|| HasBit(front
->vehicle_flags
, VF_STOP_LOADING
)) continue;
1727 /* This order has a refit, if this is the first vehicle part carrying cargo and the whole vehicle is empty, try refitting. */
1728 if (front
->current_order
.IsRefit() && artic_part
== 1) {
1729 HandleStationRefit (v
, consist_capleft
, st
, next_station
, front
->current_order
.GetRefitCargoMask());
1730 ge
= &st
->goods
[v
->cargo_type
];
1733 /* As we're loading here the following link can carry the full capacity of the vehicle. */
1734 v
->refit_cap
= v
->cargo_cap
;
1738 switch (front
->type
) {
1739 case VEH_TRAIN
: /* FALL THROUGH */
1741 t
= front
->vcache
.cached_max_speed
;
1745 t
= front
->vcache
.cached_max_speed
/ 2;
1749 t
= Aircraft::From(front
)->GetSpeedOldUnits(); // Convert to old units.
1752 default: NOT_REACHED();
1755 /* if last speed is 0, we treat that as if no vehicle has ever visited the station. */
1756 ge
->last_speed
= min(t
, 255);
1757 ge
->last_age
= min(_cur_year
- front
->build_year
, 255);
1758 ge
->time_since_pickup
= 0;
1760 assert(v
->cargo_cap
>= v
->cargo
.StoredCount());
1761 /* If there's goods waiting at the station, and the vehicle
1762 * has capacity for it, load it on the vehicle. */
1763 uint cap_left
= v
->cargo_cap
- v
->cargo
.StoredCount();
1764 if (cap_left
> 0 && (v
->cargo
.ActionCount(VehicleCargoList::MTA_LOAD
) > 0 || ge
->cargo
.AvailableCount() > 0)) {
1765 if (_settings_game
.order
.gradual_loading
) cap_left
= min(cap_left
, load_amount
);
1766 if (v
->cargo
.StoredCount() == 0) TriggerVehicle(v
, VEHICLE_TRIGGER_NEW_CARGO
);
1768 uint loaded
= ge
->cargo
.Load(cap_left
, &v
->cargo
, st
->xy
, next_station
);
1769 if (v
->cargo
.ActionCount(VehicleCargoList::MTA_LOAD
) > 0) {
1770 /* Remember if there are reservations left so that we don't stop
1771 * loading before they're loaded. */
1772 SetBit(reservation_left
, v
->cargo_type
);
1775 /* Store whether the maximum possible load amount was loaded or not.*/
1776 if (loaded
== cap_left
) {
1777 SetBit(full_load_amount
, v
->cargo_type
);
1779 ClrBit(full_load_amount
, v
->cargo_type
);
1782 /* TODO: Regarding this, when we do gradual loading, we
1783 * should first unload all vehicles and then start
1784 * loading them. Since this will cause
1785 * VEHICLE_TRIGGER_EMPTY to be called at the time when
1786 * the whole vehicle chain is really totally empty, the
1787 * completely_emptied assignment can then be safely
1788 * removed; that's how TTDPatch behaves too. --pasky */
1790 completely_emptied
= false;
1791 anything_loaded
= true;
1793 st
->time_since_load
= 0;
1794 st
->last_vehicle_type
= v
->type
;
1796 if (ge
->cargo
.TotalCount() == 0) {
1797 TriggerStationRandomisation(st
, st
->xy
, SRT_CARGO_TAKEN
, v
->cargo_type
);
1798 TriggerStationAnimation(st
, st
->xy
, SAT_CARGO_TAKEN
, v
->cargo_type
);
1799 AirportAnimationTrigger(st
, AAT_STATION_CARGO_TAKEN
, v
->cargo_type
);
1802 new_load_unload_ticks
+= loaded
;
1804 dirty_vehicle
= dirty_station
= true;
1808 if (v
->cargo
.StoredCount() >= v
->cargo_cap
) {
1809 SetBit(cargo_full
, v
->cargo_type
);
1811 SetBit(cargo_not_full
, v
->cargo_type
);
1815 if (anything_loaded
|| anything_unloaded
) {
1816 if (front
->type
== VEH_TRAIN
) {
1817 TriggerStationRandomisation(st
, front
->tile
, SRT_TRAIN_LOADS
);
1818 TriggerStationAnimation(st
, front
->tile
, SAT_TRAIN_LOADS
);
1822 /* Only set completely_emptied, if we just unloaded all remaining cargo */
1823 completely_emptied
&= anything_unloaded
;
1825 if (!anything_unloaded
) delete payment
;
1827 ClrBit(front
->vehicle_flags
, VF_STOP_LOADING
);
1828 if (anything_loaded
|| anything_unloaded
) {
1829 if (_settings_game
.order
.gradual_loading
) {
1830 /* The time it takes to load one 'slice' of cargo or passengers depends
1831 * on the vehicle type - the values here are those found in TTDPatch */
1832 const uint gradual_loading_wait_time
[] = { 40, 20, 10, 20 };
1834 new_load_unload_ticks
= gradual_loading_wait_time
[front
->type
];
1836 /* We loaded less cargo than possible for all cargo types and it's not full
1837 * load and we're not supposed to wait any longer: stop loading. */
1838 if (!anything_unloaded
&& full_load_amount
== 0 && reservation_left
== 0 && !(front
->current_order
.GetLoadType() & OLFB_FULL_LOAD
) &&
1839 front
->current_order_time
>= (uint
)max(front
->current_order
.GetTimetabledWait() - front
->lateness_counter
, 0)) {
1840 SetBit(front
->vehicle_flags
, VF_STOP_LOADING
);
1843 UpdateLoadUnloadTicks(front
, st
, new_load_unload_ticks
);
1845 UpdateLoadUnloadTicks(front
, st
, 20); // We need the ticks for link refreshing.
1846 bool finished_loading
= true;
1847 if (front
->current_order
.GetLoadType() & OLFB_FULL_LOAD
) {
1848 if (front
->current_order
.GetLoadType() == OLF_FULL_LOAD_ANY
) {
1849 /* if the aircraft carries passengers and is NOT full, then
1850 * continue loading, no matter how much mail is in */
1851 if ((front
->type
== VEH_AIRCRAFT
&& IsCargoInClass(front
->cargo_type
, CC_PASSENGERS
) && front
->cargo_cap
> front
->cargo
.StoredCount()) ||
1852 (cargo_not_full
&& (cargo_full
& ~cargo_not_full
) == 0)) { // There are still non-full cargoes
1853 finished_loading
= false;
1855 } else if (cargo_not_full
!= 0) {
1856 finished_loading
= false;
1859 /* Refresh next hop stats if we're full loading to make the links
1860 * known to the distribution algorithm and allow cargo to be sent
1861 * along them. Otherwise the vehicle could wait for cargo
1862 * indefinitely if it hasn't visited the other links yet, or if the
1863 * links die while it's loading. */
1864 if (!finished_loading
) LinkRefresher::Run(front
, true, true);
1867 SB(front
->vehicle_flags
, VF_LOADING_FINISHED
, 1, finished_loading
);
1870 /* Calculate the loading indicator fill percent and display
1871 * In the Game Menu do not display indicators
1872 * If _settings_client.gui.loading_indicators == 2, show indicators (bool can be promoted to int as 0 or 1 - results in 2 > 0,1 )
1873 * if _settings_client.gui.loading_indicators == 1, _local_company must be the owner or must be a spectator to show ind., so 1 > 0
1874 * if _settings_client.gui.loading_indicators == 0, do not display indicators ... 0 is never greater than anything
1876 if (_game_mode
!= GM_MENU
&& (_settings_client
.gui
.loading_indicators
> (uint
)(front
->owner
!= _local_company
&& _local_company
!= COMPANY_SPECTATOR
))) {
1877 StringID percent_up_down
= STR_NULL
;
1878 int percent
= CalcPercentVehicleFilled(front
, &percent_up_down
);
1879 if (front
->fill_percent_te_id
== INVALID_TE_ID
) {
1880 front
->fill_percent_te_id
= ShowFillingPercent(front
->x_pos
, front
->y_pos
, front
->z_pos
+ 20, percent
, percent_up_down
);
1882 UpdateFillingPercent(front
->fill_percent_te_id
, percent
, percent_up_down
);
1886 if (completely_emptied
) {
1887 /* Make sure the vehicle is marked dirty, since we need to update the NewGRF
1888 * properties such as weight, power and TE whenever the trigger runs. */
1889 dirty_vehicle
= true;
1890 TriggerVehicle(front
, VEHICLE_TRIGGER_EMPTY
);
1893 if (dirty_vehicle
) {
1894 SetWindowDirty(GetWindowClassForVehicleType(front
->type
), front
->owner
);
1895 SetWindowDirty(WC_VEHICLE_DETAILS
, front
->index
);
1898 if (dirty_station
) {
1899 st
->MarkTilesDirty(true);
1900 SetWindowDirty(WC_STATION_VIEW
, last_visited
);
1901 InvalidateWindowData(WC_STATION_LIST
, last_visited
);
1906 * Load/unload the vehicles in this station according to the order
1908 * @param st the station to do the loading/unloading for
1910 void LoadUnloadStation(Station
*st
)
1912 /* No vehicle is here... */
1913 if (st
->loading_vehicles
.empty()) return;
1915 Vehicle
*last_loading
= NULL
;
1916 std::list
<Vehicle
*>::iterator iter
;
1918 /* Check if anything will be loaded at all. Otherwise we don't need to reserve either. */
1919 for (iter
= st
->loading_vehicles
.begin(); iter
!= st
->loading_vehicles
.end(); ++iter
) {
1922 if ((v
->vehstatus
& (VS_STOPPED
| VS_CRASHED
))) continue;
1924 assert(v
->load_unload_ticks
!= 0);
1925 if (--v
->load_unload_ticks
== 0) last_loading
= v
;
1928 /* We only need to reserve and load/unload up to the last loading vehicle.
1929 * Anything else will be forgotten anyway after returning from this function.
1931 * Especially this means we do _not_ need to reserve cargo for a single
1932 * consist in a station which is not allowed to load yet because its
1933 * load_unload_ticks is still not 0.
1935 if (last_loading
== NULL
) return;
1937 for (iter
= st
->loading_vehicles
.begin(); iter
!= st
->loading_vehicles
.end(); ++iter
) {
1939 if (!(v
->vehstatus
& (VS_STOPPED
| VS_CRASHED
))) LoadUnloadVehicle(v
);
1940 if (v
== last_loading
) break;
1943 /* Call the production machinery of industries */
1944 const Industry
* const *isend
= _cargo_delivery_destinations
.End();
1945 for (Industry
**iid
= _cargo_delivery_destinations
.Begin(); iid
!= isend
; iid
++) {
1946 TriggerIndustryProduction(*iid
);
1948 _cargo_delivery_destinations
.Clear();
1952 * Monthly update of the economic data (of the companies as well as economic fluctuations).
1954 void CompaniesMonthlyLoop()
1956 CompaniesGenStatistics();
1957 if (_settings_game
.economy
.inflation
) {
1961 CompaniesPayInterest();
1962 HandleEconomyFluctuations();
1965 static void DoAcquireCompany(Company
*c
)
1967 CompanyID ci
= c
->index
;
1969 AddNewsItem
<MergerNewsItem
> (c
, Company::Get(_current_company
));
1970 AI::BroadcastNewEvent(new ScriptEventCompanyMerger(ci
, _current_company
));
1971 Game::NewEvent(new ScriptEventCompanyMerger(ci
, _current_company
));
1973 ChangeOwnershipOfCompanyItems(ci
, _current_company
);
1975 if (c
->bankrupt_value
== 0) {
1976 Company
*owner
= Company::Get(_current_company
);
1977 owner
->current_loan
+= c
->current_loan
;
1980 if (c
->is_ai
) AI::Stop(c
->index
);
1982 DeleteCompanyWindows(ci
);
1983 InvalidateWindowClassesData(WC_TRAINS_LIST
, 0);
1984 InvalidateWindowClassesData(WC_SHIPS_LIST
, 0);
1985 InvalidateWindowClassesData(WC_ROADVEH_LIST
, 0);
1986 InvalidateWindowClassesData(WC_AIRCRAFT_LIST
, 0);
1991 extern int GetAmountOwnedBy(const Company
*c
, Owner owner
);
1994 * Acquire shares in an opposing company.
1995 * @param tile unused
1996 * @param flags type of operation
1997 * @param p1 company to buy the shares from
1999 * @param text unused
2000 * @return the cost of this operation or an error
2002 CommandCost
CmdBuyShareInCompany(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2004 CommandCost
cost(EXPENSES_OTHER
);
2005 CompanyID target_company
= (CompanyID
)p1
;
2006 Company
*c
= Company::GetIfValid(target_company
);
2008 /* Check if buying shares is allowed (protection against modified clients)
2009 * Cannot buy own shares */
2010 if (c
== NULL
|| !_settings_game
.economy
.allow_shares
|| _current_company
== target_company
) return CMD_ERROR
;
2012 /* Protect new companies from hostile takeovers */
2013 if (_cur_year
- c
->inaugurated_year
< 6) return_cmd_error(STR_ERROR_PROTECTED
);
2015 /* Those lines are here for network-protection (clients can be slow) */
2016 if (GetAmountOwnedBy(c
, COMPANY_SPECTATOR
) == 0) return cost
;
2018 if (GetAmountOwnedBy(c
, COMPANY_SPECTATOR
) == 1) {
2019 if (!c
->is_ai
) return cost
; // We can not buy out a real company (temporarily). TODO: well, enable it obviously.
2021 if (GetAmountOwnedBy(c
, _current_company
) == 3 && !MayCompanyTakeOver(_current_company
, target_company
)) return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME
);
2025 cost
.AddCost(CalculateCompanyValue(c
) >> 2);
2026 if (flags
& DC_EXEC
) {
2027 OwnerByte
*b
= c
->share_owners
;
2029 while (*b
!= COMPANY_SPECTATOR
) b
++; // share owners is guaranteed to contain at least one COMPANY_SPECTATOR
2030 *b
= _current_company
;
2032 for (int i
= 0; c
->share_owners
[i
] == _current_company
;) {
2034 c
->bankrupt_value
= 0;
2035 DoAcquireCompany(c
);
2039 InvalidateWindowData(WC_COMPANY
, target_company
);
2040 CompanyAdminUpdate(c
);
2046 * Sell shares in an opposing company.
2047 * @param tile unused
2048 * @param flags type of operation
2049 * @param p1 company to sell the shares from
2051 * @param text unused
2052 * @return the cost of this operation or an error
2054 CommandCost
CmdSellShareInCompany(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2056 CompanyID target_company
= (CompanyID
)p1
;
2057 Company
*c
= Company::GetIfValid(target_company
);
2059 /* Cannot sell own shares */
2060 if (c
== NULL
|| _current_company
== target_company
) return CMD_ERROR
;
2062 /* Check if selling shares is allowed (protection against modified clients).
2063 * However, we must sell shares of companies being closed down. */
2064 if (!_settings_game
.economy
.allow_shares
&& !(flags
& DC_BANKRUPT
)) return CMD_ERROR
;
2066 /* Those lines are here for network-protection (clients can be slow) */
2067 if (GetAmountOwnedBy(c
, _current_company
) == 0) return CommandCost();
2069 /* adjust it a little to make it less profitable to sell and buy */
2070 Money cost
= CalculateCompanyValue(c
) >> 2;
2071 cost
= -(cost
- (cost
>> 7));
2073 if (flags
& DC_EXEC
) {
2074 OwnerByte
*b
= c
->share_owners
;
2075 while (*b
!= _current_company
) b
++; // share owners is guaranteed to contain company
2076 *b
= COMPANY_SPECTATOR
;
2077 InvalidateWindowData(WC_COMPANY
, target_company
);
2078 CompanyAdminUpdate(c
);
2080 return CommandCost(EXPENSES_OTHER
, cost
);
2084 * Buy up another company.
2085 * When a competing company is gone bankrupt you get the chance to purchase
2087 * @todo currently this only works for AI companies
2088 * @param tile unused
2089 * @param flags type of operation
2090 * @param p1 company to buy up
2092 * @param text unused
2093 * @return the cost of this operation or an error
2095 CommandCost
CmdBuyCompany(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2097 CompanyID target_company
= (CompanyID
)p1
;
2098 Company
*c
= Company::GetIfValid(target_company
);
2099 if (c
== NULL
) return CMD_ERROR
;
2101 /* Disable takeovers when not asked */
2102 if (!HasBit(c
->bankrupt_asked
, _current_company
)) return CMD_ERROR
;
2104 /* Disable taking over the local company in single player */
2105 if (!_networking
&& _local_company
== c
->index
) return CMD_ERROR
;
2107 /* Do not allow companies to take over themselves */
2108 if (target_company
== _current_company
) return CMD_ERROR
;
2110 /* Disable taking over when not allowed. */
2111 if (!MayCompanyTakeOver(_current_company
, target_company
)) return CMD_ERROR
;
2113 /* Get the cost here as the company is deleted in DoAcquireCompany. */
2114 CommandCost
cost(EXPENSES_OTHER
, c
->bankrupt_value
);
2116 if (flags
& DC_EXEC
) {
2117 DoAcquireCompany(c
);