Codechange: Un-bitstuff commands taking a ClientID (i.e. CMD_CLIENT_ID).
[openttd-github.git] / src / economy.cpp
blob8bf608a86459aad8b6dd080209879af78bf112f8
1 /*
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/>.
6 */
8 /** @file economy.cpp Handling of the economy. */
10 #include "stdafx.h"
11 #include "company_func.h"
12 #include "command_func.h"
13 #include "industry.h"
14 #include "town.h"
15 #include "news_func.h"
16 #include "network/network.h"
17 #include "network/network_func.h"
18 #include "ai/ai.hpp"
19 #include "aircraft.h"
20 #include "train.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 "object.h"
30 #include "strings_func.h"
31 #include "date_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 "cargo_type.h"
45 #include "water.h"
46 #include "game/game.hpp"
47 #include "cargomonitor.h"
48 #include "goal_base.h"
49 #include "story_base.h"
50 #include "linkgraph/refresh.h"
51 #include "company_cmd.h"
52 #include "economy_cmd.h"
53 #include "vehicle_cmd.h"
55 #include "table/strings.h"
56 #include "table/pricebase.h"
58 #include "safeguards.h"
61 /* Initialize the cargo payment-pool */
62 CargoPaymentPool _cargo_payment_pool("CargoPayment");
63 INSTANTIATE_POOL_METHODS(CargoPayment)
65 /**
66 * Multiply two integer values and shift the results to right.
68 * This function multiplies two integer values. The result is
69 * shifted by the amount of shift to right.
71 * @param a The first integer
72 * @param b The second integer
73 * @param shift The amount to shift the value to right.
74 * @return The shifted result
76 static inline int32 BigMulS(const int32 a, const int32 b, const uint8 shift)
78 return (int32)((int64)a * (int64)b >> shift);
81 typedef std::vector<Industry *> SmallIndustryList;
83 /**
84 * Score info, values used for computing the detailed performance rating.
86 const ScoreInfo _score_info[] = {
87 { 120, 100}, // SCORE_VEHICLES
88 { 80, 100}, // SCORE_STATIONS
89 { 10000, 100}, // SCORE_MIN_PROFIT
90 { 50000, 50}, // SCORE_MIN_INCOME
91 { 100000, 100}, // SCORE_MAX_INCOME
92 { 40000, 400}, // SCORE_DELIVERED
93 { 8, 50}, // SCORE_CARGO
94 {10000000, 50}, // SCORE_MONEY
95 { 250000, 50}, // SCORE_LOAN
96 { 0, 0} // SCORE_TOTAL
99 int64 _score_part[MAX_COMPANIES][SCORE_END];
100 Economy _economy;
101 Prices _price;
102 Money _additional_cash_required;
103 static PriceMultipliers _price_base_multiplier;
106 * Calculate the value of the company. That is the value of all
107 * assets (vehicles, stations, etc) and money minus the loan,
108 * except when including_loan is \c false which is useful when
109 * we want to calculate the value for bankruptcy.
110 * @param c the company to get the value of.
111 * @param including_loan include the loan in the company value.
112 * @return the value of the company.
114 Money CalculateCompanyValue(const Company *c, bool including_loan)
116 Owner owner = c->index;
118 uint num = 0;
120 for (const Station *st : Station::Iterate()) {
121 if (st->owner == owner) num += CountBits((byte)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;
137 /* Add real money value */
138 if (including_loan) value -= c->current_loan;
139 value += c->money;
141 return std::max<Money>(value, 1);
145 * if update is set to true, the economy is updated with this score
146 * (also the house is updated, should only be true in the on-tick event)
147 * @param update the economy with calculated score
148 * @param c company been evaluated
149 * @return actual score of this company
152 int UpdateCompanyRatingAndValue(Company *c, bool update)
154 Owner owner = c->index;
155 int score = 0;
157 memset(_score_part[owner], 0, sizeof(_score_part[owner]));
159 /* Count vehicles */
161 Money min_profit = 0;
162 bool min_profit_first = true;
163 uint num = 0;
165 for (const Vehicle *v : Vehicle::Iterate()) {
166 if (v->owner != owner) continue;
167 if (IsCompanyBuildableVehicleType(v->type) && v->IsPrimaryVehicle()) {
168 if (v->profit_last_year > 0) num++; // For the vehicle score only count profitable vehicles
169 if (v->age > 730) {
170 /* Find the vehicle with the lowest amount of profit */
171 if (min_profit_first || min_profit > v->profit_last_year) {
172 min_profit = v->profit_last_year;
173 min_profit_first = false;
179 min_profit >>= 8; // remove the fract part
181 _score_part[owner][SCORE_VEHICLES] = num;
182 /* Don't allow negative min_profit to show */
183 if (min_profit > 0) {
184 _score_part[owner][SCORE_MIN_PROFIT] = min_profit;
188 /* Count stations */
190 uint num = 0;
191 for (const Station *st : Station::Iterate()) {
192 /* Only count stations that are actually serviced */
193 if (st->owner == owner && (st->time_since_load <= 20 || st->time_since_unload <= 20)) num += CountBits((byte)st->facilities);
195 _score_part[owner][SCORE_STATIONS] = num;
198 /* Generate statistics depending on recent income statistics */
200 int numec = std::min<uint>(c->num_valid_stat_ent, 12u);
201 if (numec != 0) {
202 const CompanyEconomyEntry *cee = c->old_economy;
203 Money min_income = cee->income + cee->expenses;
204 Money max_income = cee->income + cee->expenses;
206 do {
207 min_income = std::min(min_income, cee->income + cee->expenses);
208 max_income = std::max(max_income, cee->income + cee->expenses);
209 } while (++cee, --numec);
211 if (min_income > 0) {
212 _score_part[owner][SCORE_MIN_INCOME] = min_income;
215 _score_part[owner][SCORE_MAX_INCOME] = max_income;
219 /* Generate score depending on amount of transported cargo */
221 int numec = std::min<uint>(c->num_valid_stat_ent, 4u);
222 if (numec != 0) {
223 const CompanyEconomyEntry *cee = c->old_economy;
224 OverflowSafeInt64 total_delivered = 0;
225 do {
226 total_delivered += cee->delivered_cargo.GetSum<OverflowSafeInt64>();
227 } while (++cee, --numec);
229 _score_part[owner][SCORE_DELIVERED] = total_delivered;
233 /* Generate score for variety of cargo */
235 _score_part[owner][SCORE_CARGO] = c->old_economy->delivered_cargo.GetCount();
238 /* Generate score for company's money */
240 if (c->money > 0) {
241 _score_part[owner][SCORE_MONEY] = c->money;
245 /* Generate score for loan */
247 _score_part[owner][SCORE_LOAN] = _score_info[SCORE_LOAN].needed - c->current_loan;
250 /* Now we calculate the score for each item.. */
252 int total_score = 0;
253 int s;
254 score = 0;
255 for (ScoreID i = SCORE_BEGIN; i < SCORE_END; i++) {
256 /* Skip the total */
257 if (i == SCORE_TOTAL) continue;
258 /* Check the score */
259 s = Clamp<int64>(_score_part[owner][i], 0, _score_info[i].needed) * _score_info[i].score / _score_info[i].needed;
260 score += s;
261 total_score += _score_info[i].score;
264 _score_part[owner][SCORE_TOTAL] = score;
266 /* We always want the score scaled to SCORE_MAX (1000) */
267 if (total_score != SCORE_MAX) score = score * SCORE_MAX / total_score;
270 if (update) {
271 c->old_economy[0].performance_history = score;
272 UpdateCompanyHQ(c->location_of_HQ, score);
273 c->old_economy[0].company_value = CalculateCompanyValue(c);
276 SetWindowDirty(WC_PERFORMANCE_DETAIL, 0);
277 return score;
281 * Change the ownership of all the items of a company.
282 * @param old_owner The company that gets removed.
283 * @param new_owner The company to merge to, or INVALID_OWNER to remove the company.
285 void ChangeOwnershipOfCompanyItems(Owner old_owner, Owner new_owner)
287 /* We need to set _current_company to old_owner before we try to move
288 * the client. This is needed as it needs to know whether "you" really
289 * are the current local company. */
290 Backup<CompanyID> cur_company(_current_company, old_owner, FILE_LINE);
291 /* In all cases, make spectators of clients connected to that company */
292 if (_networking) NetworkClientsToSpectators(old_owner);
293 if (old_owner == _local_company) {
294 /* Single player cheated to AI company.
295 * There are no spectators in singleplayer mode, so we must pick some other company. */
296 assert(!_networking);
297 Backup<CompanyID> cur_company2(_current_company, FILE_LINE);
298 for (const Company *c : Company::Iterate()) {
299 if (c->index != old_owner) {
300 SetLocalCompany(c->index);
301 break;
304 cur_company2.Restore();
305 assert(old_owner != _local_company);
308 assert(old_owner != new_owner);
311 uint i;
313 /* See if the old_owner had shares in other companies */
314 for (const Company *c : Company::Iterate()) {
315 for (i = 0; i < 4; i++) {
316 if (c->share_owners[i] == old_owner) {
317 /* Sell its shares */
318 CommandCost res = Command<CMD_SELL_SHARE_IN_COMPANY>::Do(DC_EXEC | DC_BANKRUPT, 0, c->index, 0, {});
319 /* Because we are in a DoCommand, we can't just execute another one and
320 * expect the money to be removed. We need to do it ourself! */
321 SubtractMoneyFromCompany(res);
326 /* Sell all the shares that people have on this company */
327 Backup<CompanyID> cur_company2(_current_company, FILE_LINE);
328 const Company *c = Company::Get(old_owner);
329 for (i = 0; i < 4; i++) {
330 if (c->share_owners[i] == INVALID_OWNER) continue;
332 if (c->bankrupt_value == 0 && c->share_owners[i] == new_owner) {
333 /* You are the one buying the company; so don't sell the shares back to you. */
334 Company::Get(new_owner)->share_owners[i] = INVALID_OWNER;
335 } else {
336 cur_company2.Change(c->share_owners[i]);
337 /* Sell the shares */
338 CommandCost res = Command<CMD_SELL_SHARE_IN_COMPANY>::Do(DC_EXEC | DC_BANKRUPT, 0, old_owner, 0, {});
339 /* Because we are in a DoCommand, we can't just execute another one and
340 * expect the money to be removed. We need to do it ourself! */
341 SubtractMoneyFromCompany(res);
344 cur_company2.Restore();
347 /* Temporarily increase the company's money, to be sure that
348 * removing their property doesn't fail because of lack of money.
349 * Not too drastically though, because it could overflow */
350 if (new_owner == INVALID_OWNER) {
351 Company::Get(old_owner)->money = UINT64_MAX >> 2; // jackpot ;p
354 for (Subsidy *s : Subsidy::Iterate()) {
355 if (s->awarded == old_owner) {
356 if (new_owner == INVALID_OWNER) {
357 delete s;
358 } else {
359 s->awarded = new_owner;
363 if (new_owner == INVALID_OWNER) RebuildSubsidisedSourceAndDestinationCache();
365 /* Take care of rating and transport rights in towns */
366 for (Town *t : Town::Iterate()) {
367 /* If a company takes over, give the ratings to that company. */
368 if (new_owner != INVALID_OWNER) {
369 if (HasBit(t->have_ratings, old_owner)) {
370 if (HasBit(t->have_ratings, new_owner)) {
371 /* use max of the two ratings. */
372 t->ratings[new_owner] = std::max(t->ratings[new_owner], t->ratings[old_owner]);
373 } else {
374 SetBit(t->have_ratings, new_owner);
375 t->ratings[new_owner] = t->ratings[old_owner];
380 /* Reset the ratings for the old owner */
381 t->ratings[old_owner] = RATING_INITIAL;
382 ClrBit(t->have_ratings, old_owner);
384 /* Transfer exclusive rights */
385 if (t->exclusive_counter > 0 && t->exclusivity == old_owner) {
386 if (new_owner != INVALID_OWNER) {
387 t->exclusivity = new_owner;
388 } else {
389 t->exclusive_counter = 0;
390 t->exclusivity = INVALID_COMPANY;
396 for (Vehicle *v : Vehicle::Iterate()) {
397 if (v->owner == old_owner && IsCompanyBuildableVehicleType(v->type)) {
398 if (new_owner == INVALID_OWNER) {
399 if (v->Previous() == nullptr) delete v;
400 } else {
401 if (v->IsEngineCountable()) GroupStatistics::CountEngine(v, -1);
402 if (v->IsPrimaryVehicle()) GroupStatistics::CountVehicle(v, -1);
408 /* In all cases clear replace engine rules.
409 * Even if it was copied, it could interfere with new owner's rules */
410 RemoveAllEngineReplacementForCompany(Company::Get(old_owner));
412 if (new_owner == INVALID_OWNER) {
413 RemoveAllGroupsForCompany(old_owner);
414 } else {
415 for (Group *g : Group::Iterate()) {
416 if (g->owner == old_owner) g->owner = new_owner;
421 FreeUnitIDGenerator unitidgen[] = {
422 FreeUnitIDGenerator(VEH_TRAIN, new_owner), FreeUnitIDGenerator(VEH_ROAD, new_owner),
423 FreeUnitIDGenerator(VEH_SHIP, new_owner), FreeUnitIDGenerator(VEH_AIRCRAFT, new_owner)
426 /* Override company settings to new company defaults in case we need to convert them.
427 * This is required as the CmdChangeServiceInt doesn't copy the supplied value when it is non-custom
429 if (new_owner != INVALID_OWNER) {
430 Company *old_company = Company::Get(old_owner);
431 Company *new_company = Company::Get(new_owner);
433 old_company->settings.vehicle.servint_aircraft = new_company->settings.vehicle.servint_aircraft;
434 old_company->settings.vehicle.servint_trains = new_company->settings.vehicle.servint_trains;
435 old_company->settings.vehicle.servint_roadveh = new_company->settings.vehicle.servint_roadveh;
436 old_company->settings.vehicle.servint_ships = new_company->settings.vehicle.servint_ships;
437 old_company->settings.vehicle.servint_ispercent = new_company->settings.vehicle.servint_ispercent;
440 for (Vehicle *v : Vehicle::Iterate()) {
441 if (v->owner == old_owner && IsCompanyBuildableVehicleType(v->type)) {
442 assert(new_owner != INVALID_OWNER);
444 /* Correct default values of interval settings while maintaining custom set ones.
445 * This prevents invalid values on mismatching company defaults being accepted.
447 if (!v->ServiceIntervalIsCustom()) {
448 Company *new_company = Company::Get(new_owner);
450 /* Technically, passing the interval is not needed as the command will query the default value itself.
451 * However, do not rely on that behaviour.
453 int interval = CompanyServiceInterval(new_company, v->type);
454 Command<CMD_CHANGE_SERVICE_INT>::Do(DC_EXEC | DC_BANKRUPT, v->tile, v->index, interval | (new_company->settings.vehicle.servint_ispercent << 17), {});
457 v->owner = new_owner;
459 /* Owner changes, clear cache */
460 v->colourmap = PAL_NONE;
461 v->InvalidateNewGRFCache();
463 if (v->IsEngineCountable()) {
464 GroupStatistics::CountEngine(v, 1);
466 if (v->IsPrimaryVehicle()) {
467 GroupStatistics::CountVehicle(v, 1);
468 v->unitnumber = unitidgen[v->type].NextID();
471 /* Invalidate the vehicle's cargo payment "owner cache". */
472 if (v->cargo_payment != nullptr) v->cargo_payment->owner = nullptr;
476 if (new_owner != INVALID_OWNER) GroupStatistics::UpdateAutoreplace(new_owner);
479 /* Change ownership of tiles */
481 TileIndex tile = 0;
482 do {
483 ChangeTileOwner(tile, old_owner, new_owner);
484 } while (++tile != MapSize());
486 if (new_owner != INVALID_OWNER) {
487 /* Update all signals because there can be new segment that was owned by two companies
488 * and signals were not propagated
489 * Similar with crossings - it is needed to bar crossings that weren't before
490 * because of different owner of crossing and approaching train */
491 tile = 0;
493 do {
494 if (IsTileType(tile, MP_RAILWAY) && IsTileOwner(tile, new_owner) && HasSignals(tile)) {
495 TrackBits tracks = GetTrackBits(tile);
496 do { // there may be two tracks with signals for TRACK_BIT_HORZ and TRACK_BIT_VERT
497 Track track = RemoveFirstTrack(&tracks);
498 if (HasSignalOnTrack(tile, track)) AddTrackToSignalBuffer(tile, track, new_owner);
499 } while (tracks != TRACK_BIT_NONE);
500 } else if (IsLevelCrossingTile(tile) && IsTileOwner(tile, new_owner)) {
501 UpdateLevelCrossing(tile);
503 } while (++tile != MapSize());
506 /* update signals in buffer */
507 UpdateSignalsInBuffer();
510 /* Add airport infrastructure count of the old company to the new one. */
511 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.airport += Company::Get(old_owner)->infrastructure.airport;
513 /* convert owner of stations (including deleted ones, but excluding buoys) */
514 for (Station *st : Station::Iterate()) {
515 if (st->owner == old_owner) {
516 /* if a company goes bankrupt, set owner to OWNER_NONE so the sign doesn't disappear immediately
517 * also, drawing station window would cause reading invalid company's colour */
518 st->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner;
522 /* do the same for waypoints (we need to do this here so deleted waypoints are converted too) */
523 for (Waypoint *wp : Waypoint::Iterate()) {
524 if (wp->owner == old_owner) {
525 wp->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner;
529 for (Sign *si : Sign::Iterate()) {
530 if (si->owner == old_owner) si->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner;
533 /* Remove Game Script created Goals, CargoMonitors and Story pages. */
534 for (Goal *g : Goal::Iterate()) {
535 if (g->company == old_owner) delete g;
538 ClearCargoPickupMonitoring(old_owner);
539 ClearCargoDeliveryMonitoring(old_owner);
541 for (StoryPage *sp : StoryPage::Iterate()) {
542 if (sp->company == old_owner) delete sp;
545 /* Change colour of existing windows */
546 if (new_owner != INVALID_OWNER) ChangeWindowOwner(old_owner, new_owner);
548 cur_company.Restore();
550 MarkWholeScreenDirty();
554 * Check for bankruptcy of a company. Called every three months.
555 * @param c Company to check.
557 static void CompanyCheckBankrupt(Company *c)
559 /* If the company has money again, it does not go bankrupt */
560 if (c->money - c->current_loan >= -_economy.max_loan) {
561 int previous_months_of_bankruptcy = CeilDiv(c->months_of_bankruptcy, 3);
562 c->months_of_bankruptcy = 0;
563 c->bankrupt_asked = 0;
564 if (previous_months_of_bankruptcy != 0) CompanyAdminUpdate(c);
565 return;
568 c->months_of_bankruptcy++;
570 switch (c->months_of_bankruptcy) {
571 /* All the boring cases (months) with a bad balance where no action is taken */
572 case 0:
573 case 1:
574 case 2:
575 case 3:
577 case 5:
578 case 6:
580 case 8:
581 case 9:
582 break;
584 /* Warn about bankruptcy after 3 months */
585 case 4: {
586 CompanyNewsInformation *cni = new CompanyNewsInformation(c);
587 SetDParam(0, STR_NEWS_COMPANY_IN_TROUBLE_TITLE);
588 SetDParam(1, STR_NEWS_COMPANY_IN_TROUBLE_DESCRIPTION);
589 SetDParamStr(2, cni->company_name);
590 AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, cni);
591 AI::BroadcastNewEvent(new ScriptEventCompanyInTrouble(c->index));
592 Game::NewEvent(new ScriptEventCompanyInTrouble(c->index));
593 break;
596 /* Offer company for sale after 6 months */
597 case 7: {
598 /* Don't consider the loan */
599 Money val = CalculateCompanyValue(c, false);
601 c->bankrupt_value = val;
602 c->bankrupt_asked = 1 << c->index; // Don't ask the owner
603 c->bankrupt_timeout = 0;
605 /* The company assets should always have some value */
606 assert(c->bankrupt_value > 0);
607 break;
610 /* Bankrupt company after 6 months (if the company has no value) or latest
611 * after 9 months (if it still had value after 6 months) */
612 default:
613 case 10: {
614 if (!_networking && _local_company == c->index) {
615 /* If we are in singleplayer mode, leave the company playing. Eg. there
616 * is no THE-END, otherwise mark the client as spectator to make sure
617 * they are no longer in control of this company. However... when you
618 * join another company (cheat) the "unowned" company can bankrupt. */
619 c->bankrupt_asked = MAX_UVALUE(CompanyMask);
620 break;
623 /* Actually remove the company, but not when we're a network client.
624 * In case of network clients we will be getting a command from the
625 * server. It is done in this way as we are called from the
626 * StateGameLoop which can't change the current company, and thus
627 * updating the local company triggers an assert later on. In the
628 * case of a network game the command will be processed at a time
629 * that changing the current company is okay. In case of single
630 * player we are sure (the above check) that we are not the local
631 * company and thus we won't be moved. */
632 if (!_networking || _network_server) {
633 Command<CMD_COMPANY_CTRL>::Post(CCA_DELETE, c->index, CRR_BANKRUPT, INVALID_CLIENT_ID);
634 return;
636 break;
640 if (CeilDiv(c->months_of_bankruptcy, 3) != CeilDiv(c->months_of_bankruptcy - 1, 3)) CompanyAdminUpdate(c);
644 * Update the finances of all companies.
645 * Pay for the stations, update the history graph, update ratings and company values, and deal with bankruptcy.
647 static void CompaniesGenStatistics()
649 /* Check for bankruptcy each month */
650 for (Company *c : Company::Iterate()) {
651 CompanyCheckBankrupt(c);
654 Backup<CompanyID> cur_company(_current_company, FILE_LINE);
656 if (!_settings_game.economy.infrastructure_maintenance) {
657 for (const Station *st : Station::Iterate()) {
658 cur_company.Change(st->owner);
659 CommandCost cost(EXPENSES_PROPERTY, _price[PR_STATION_VALUE] >> 1);
660 SubtractMoneyFromCompany(cost);
662 } else {
663 /* Improved monthly infrastructure costs. */
664 for (const Company *c : Company::Iterate()) {
665 cur_company.Change(c->index);
667 CommandCost cost(EXPENSES_PROPERTY);
668 uint32 rail_total = c->infrastructure.GetRailTotal();
669 for (RailType rt = RAILTYPE_BEGIN; rt < RAILTYPE_END; rt++) {
670 if (c->infrastructure.rail[rt] != 0) cost.AddCost(RailMaintenanceCost(rt, c->infrastructure.rail[rt], rail_total));
672 cost.AddCost(SignalMaintenanceCost(c->infrastructure.signal));
673 uint32 road_total = c->infrastructure.GetRoadTotal();
674 uint32 tram_total = c->infrastructure.GetTramTotal();
675 for (RoadType rt = ROADTYPE_BEGIN; rt < ROADTYPE_END; rt++) {
676 if (c->infrastructure.road[rt] != 0) cost.AddCost(RoadMaintenanceCost(rt, c->infrastructure.road[rt], RoadTypeIsRoad(rt) ? road_total : tram_total));
678 cost.AddCost(CanalMaintenanceCost(c->infrastructure.water));
679 cost.AddCost(StationMaintenanceCost(c->infrastructure.station));
680 cost.AddCost(AirportMaintenanceCost(c->index));
682 SubtractMoneyFromCompany(cost);
685 cur_company.Restore();
687 /* Only run the economic statics and update company stats every 3rd month (1st of quarter). */
688 if (!HasBit(1 << 0 | 1 << 3 | 1 << 6 | 1 << 9, _cur_month)) return;
690 for (Company *c : Company::Iterate()) {
691 /* Drop the oldest history off the end */
692 std::copy_backward(c->old_economy, c->old_economy + MAX_HISTORY_QUARTERS - 1, c->old_economy + MAX_HISTORY_QUARTERS);
693 c->old_economy[0] = c->cur_economy;
694 c->cur_economy = {};
696 if (c->num_valid_stat_ent != MAX_HISTORY_QUARTERS) c->num_valid_stat_ent++;
698 UpdateCompanyRatingAndValue(c, true);
699 if (c->block_preview != 0) c->block_preview--;
702 SetWindowDirty(WC_INCOME_GRAPH, 0);
703 SetWindowDirty(WC_OPERATING_PROFIT, 0);
704 SetWindowDirty(WC_DELIVERED_CARGO, 0);
705 SetWindowDirty(WC_PERFORMANCE_HISTORY, 0);
706 SetWindowDirty(WC_COMPANY_VALUE, 0);
707 SetWindowDirty(WC_COMPANY_LEAGUE, 0);
711 * Add monthly inflation
712 * @param check_year Shall the inflation get stopped after 170 years?
713 * @return true if inflation is maxed and nothing was changed
715 bool AddInflation(bool check_year)
717 /* The cargo payment inflation differs from the normal inflation, so the
718 * relative amount of money you make with a transport decreases slowly over
719 * the 170 years. After a few hundred years we reach a level in which the
720 * games will become unplayable as the maximum income will be less than
721 * the minimum running cost.
723 * Furthermore there are a lot of inflation related overflows all over the
724 * place. Solving them is hardly possible because inflation will always
725 * reach the overflow threshold some day. So we'll just perform the
726 * inflation mechanism during the first 170 years (the amount of years that
727 * one had in the original TTD) and stop doing the inflation after that
728 * because it only causes problems that can't be solved nicely and the
729 * inflation doesn't add anything after that either; it even makes playing
730 * it impossible due to the diverging cost and income rates.
732 if (check_year && (_cur_year < ORIGINAL_BASE_YEAR || _cur_year >= ORIGINAL_MAX_YEAR)) return true;
734 if (_economy.inflation_prices == MAX_INFLATION || _economy.inflation_payment == MAX_INFLATION) return true;
736 /* Approximation for (100 + infl_amount)% ** (1 / 12) - 100%
737 * scaled by 65536
738 * 12 -> months per year
739 * This is only a good approximation for small values
741 _economy.inflation_prices += (_economy.inflation_prices * _economy.infl_amount * 54) >> 16;
742 _economy.inflation_payment += (_economy.inflation_payment * _economy.infl_amount_pr * 54) >> 16;
744 if (_economy.inflation_prices > MAX_INFLATION) _economy.inflation_prices = MAX_INFLATION;
745 if (_economy.inflation_payment > MAX_INFLATION) _economy.inflation_payment = MAX_INFLATION;
747 return false;
751 * Computes all prices, payments and maximum loan.
753 void RecomputePrices()
755 /* Setup maximum loan */
756 _economy.max_loan = ((uint64)_settings_game.difficulty.max_loan * _economy.inflation_prices >> 16) / 50000 * 50000;
758 /* Setup price bases */
759 for (Price i = PR_BEGIN; i < PR_END; i++) {
760 Money price = _price_base_specs[i].start_price;
762 /* Apply difficulty settings */
763 uint mod = 1;
764 switch (_price_base_specs[i].category) {
765 case PCAT_RUNNING:
766 mod = _settings_game.difficulty.vehicle_costs;
767 break;
769 case PCAT_CONSTRUCTION:
770 mod = _settings_game.difficulty.construction_cost;
771 break;
773 default: break;
775 switch (mod) {
776 case 0: price *= 6; break;
777 case 1: price *= 8; break; // normalised to 1 below
778 case 2: price *= 9; break;
779 default: NOT_REACHED();
782 /* Apply inflation */
783 price = (int64)price * _economy.inflation_prices;
785 /* Apply newgrf modifiers, remove fractional part of inflation, and normalise on medium difficulty. */
786 int shift = _price_base_multiplier[i] - 16 - 3;
787 if (shift >= 0) {
788 price <<= shift;
789 } else {
790 price >>= -shift;
793 /* Make sure the price does not get reduced to zero.
794 * Zero breaks quite a few commands that use a zero
795 * cost to see whether something got changed or not
796 * and based on that cause an error. When the price
797 * is zero that fails even when things are done. */
798 if (price == 0) {
799 price = Clamp(_price_base_specs[i].start_price, -1, 1);
800 /* No base price should be zero, but be sure. */
801 assert(price != 0);
803 /* Store value */
804 _price[i] = price;
807 /* Setup cargo payment */
808 for (CargoSpec *cs : CargoSpec::Iterate()) {
809 cs->current_payment = (cs->initial_payment * (int64)_economy.inflation_payment) >> 16;
812 SetWindowClassesDirty(WC_BUILD_VEHICLE);
813 SetWindowClassesDirty(WC_REPLACE_VEHICLE);
814 SetWindowClassesDirty(WC_VEHICLE_DETAILS);
815 SetWindowClassesDirty(WC_COMPANY_INFRASTRUCTURE);
816 InvalidateWindowData(WC_PAYMENT_RATES, 0);
819 /** Let all companies pay the monthly interest on their loan. */
820 static void CompaniesPayInterest()
822 Backup<CompanyID> cur_company(_current_company, FILE_LINE);
823 for (const Company *c : Company::Iterate()) {
824 cur_company.Change(c->index);
826 /* Over a year the paid interest should be "loan * interest percentage",
827 * but... as that number is likely not dividable by 12 (pay each month),
828 * one needs to account for that in the monthly fee calculations.
829 * To easily calculate what one should pay "this" month, you calculate
830 * what (total) should have been paid up to this month and you subtract
831 * whatever has been paid in the previous months. This will mean one month
832 * it'll be a bit more and the other it'll be a bit less than the average
833 * monthly fee, but on average it will be exact.
834 * In order to prevent cheating or abuse (just not paying interest by not
835 * taking a loan we make companies pay interest on negative cash as well
837 Money yearly_fee = c->current_loan * _economy.interest_rate / 100;
838 if (c->money < 0) {
839 yearly_fee += -c->money *_economy.interest_rate / 100;
841 Money up_to_previous_month = yearly_fee * _cur_month / 12;
842 Money up_to_this_month = yearly_fee * (_cur_month + 1) / 12;
844 SubtractMoneyFromCompany(CommandCost(EXPENSES_LOAN_INT, up_to_this_month - up_to_previous_month));
846 SubtractMoneyFromCompany(CommandCost(EXPENSES_OTHER, _price[PR_STATION_VALUE] >> 2));
848 cur_company.Restore();
851 static void HandleEconomyFluctuations()
853 if (_settings_game.difficulty.economy != 0) {
854 /* When economy is Fluctuating, decrease counter */
855 _economy.fluct--;
856 } else if (EconomyIsInRecession()) {
857 /* When it's Steady and we are in recession, end it now */
858 _economy.fluct = -12;
859 } else {
860 /* No need to do anything else in other cases */
861 return;
864 if (_economy.fluct == 0) {
865 _economy.fluct = -(int)GB(Random(), 0, 2);
866 AddNewsItem(STR_NEWS_BEGIN_OF_RECESSION, NT_ECONOMY, NF_NORMAL);
867 } else if (_economy.fluct == -12) {
868 _economy.fluct = GB(Random(), 0, 8) + 312;
869 AddNewsItem(STR_NEWS_END_OF_RECESSION, NT_ECONOMY, NF_NORMAL);
875 * Reset changes to the price base multipliers.
877 void ResetPriceBaseMultipliers()
879 memset(_price_base_multiplier, 0, sizeof(_price_base_multiplier));
883 * Change a price base by the given factor.
884 * The price base is altered by factors of two.
885 * NewBaseCost = OldBaseCost * 2^n
886 * @param price Index of price base to change.
887 * @param factor Amount to change by.
889 void SetPriceBaseMultiplier(Price price, int factor)
891 assert(price < PR_END);
892 _price_base_multiplier[price] = Clamp(factor, MIN_PRICE_MODIFIER, MAX_PRICE_MODIFIER);
896 * Initialize the variables that will maintain the daily industry change system.
897 * @param init_counter specifies if the counter is required to be initialized
899 void StartupIndustryDailyChanges(bool init_counter)
901 uint map_size = MapLogX() + MapLogY();
902 /* After getting map size, it needs to be scaled appropriately and divided by 31,
903 * which stands for the days in a month.
904 * Using just 31 will make it so that a monthly reset (based on the real number of days of that month)
905 * would not be needed.
906 * Since it is based on "fractional parts", the leftover days will not make much of a difference
907 * on the overall total number of changes performed */
908 _economy.industry_daily_increment = (1 << map_size) / 31;
910 if (init_counter) {
911 /* A new game or a savegame from an older version will require the counter to be initialized */
912 _economy.industry_daily_change_counter = 0;
916 void StartupEconomy()
918 _economy.interest_rate = _settings_game.difficulty.initial_interest;
919 _economy.infl_amount = _settings_game.difficulty.initial_interest;
920 _economy.infl_amount_pr = std::max(0, _settings_game.difficulty.initial_interest - 1);
921 _economy.fluct = GB(Random(), 0, 8) + 168;
923 if (_settings_game.economy.inflation) {
924 /* Apply inflation that happened before our game start year. */
925 int months = (std::min(_cur_year, ORIGINAL_MAX_YEAR) - ORIGINAL_BASE_YEAR) * 12;
926 for (int i = 0; i < months; i++) {
927 AddInflation(false);
931 /* Set up prices */
932 RecomputePrices();
934 StartupIndustryDailyChanges(true); // As we are starting a new game, initialize the counter too
939 * Resets economy to initial values
941 void InitializeEconomy()
943 _economy.inflation_prices = _economy.inflation_payment = 1 << 16;
944 ClearCargoPickupMonitoring();
945 ClearCargoDeliveryMonitoring();
949 * Determine a certain price
950 * @param index Price base
951 * @param cost_factor Price factor
952 * @param grf_file NewGRF to use local price multipliers from.
953 * @param shift Extra bit shifting after the computation
954 * @return Price
956 Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift)
958 if (index >= PR_END) return 0;
960 Money cost = _price[index] * cost_factor;
961 if (grf_file != nullptr) shift += grf_file->price_base_multipliers[index];
963 if (shift >= 0) {
964 cost <<= shift;
965 } else {
966 cost >>= -shift;
969 return cost;
972 Money GetTransportedGoodsIncome(uint num_pieces, uint dist, byte transit_days, CargoID cargo_type)
974 const CargoSpec *cs = CargoSpec::Get(cargo_type);
975 if (!cs->IsValid()) {
976 /* User changed newgrfs and some vehicle still carries some cargo which is no longer available. */
977 return 0;
980 /* Use callback to calculate cargo profit, if available */
981 if (HasBit(cs->callback_mask, CBM_CARGO_PROFIT_CALC)) {
982 uint32 var18 = std::min(dist, 0xFFFFu) | (std::min(num_pieces, 0xFFu) << 16) | (transit_days << 24);
983 uint16 callback = GetCargoCallback(CBID_CARGO_PROFIT_CALC, 0, var18, cs);
984 if (callback != CALLBACK_FAILED) {
985 int result = GB(callback, 0, 14);
987 /* Simulate a 15 bit signed value */
988 if (HasBit(callback, 14)) result -= 0x4000;
990 /* "The result should be a signed multiplier that gets multiplied
991 * by the amount of cargo moved and the price factor, then gets
992 * divided by 8192." */
993 return result * num_pieces * cs->current_payment / 8192;
997 static const int MIN_TIME_FACTOR = 31;
998 static const int MAX_TIME_FACTOR = 255;
1000 const int days1 = cs->transit_days[0];
1001 const int days2 = cs->transit_days[1];
1002 const int days_over_days1 = std::max( transit_days - days1, 0);
1003 const int days_over_days2 = std::max(days_over_days1 - days2, 0);
1006 * The time factor is calculated based on the time it took
1007 * (transit_days) compared two cargo-depending values. The
1008 * range is divided into three parts:
1010 * - constant for fast transits
1011 * - linear decreasing with time with a slope of -1 for medium transports
1012 * - linear decreasing with time with a slope of -2 for slow transports
1015 const int time_factor = std::max(MAX_TIME_FACTOR - days_over_days1 - days_over_days2, MIN_TIME_FACTOR);
1017 return BigMulS(dist * time_factor * num_pieces, cs->current_payment, 21);
1020 /** The industries we've currently brought cargo to. */
1021 static SmallIndustryList _cargo_delivery_destinations;
1024 * Transfer goods from station to industry.
1025 * All cargo is delivered to the nearest (Manhattan) industry to the station sign, which is inside the acceptance rectangle and actually accepts the cargo.
1026 * @param st The station that accepted the cargo
1027 * @param cargo_type Type of cargo delivered
1028 * @param num_pieces Amount of cargo delivered
1029 * @param source The source of the cargo
1030 * @param company The company delivering the cargo
1031 * @return actually accepted pieces of cargo
1033 static uint DeliverGoodsToIndustry(const Station *st, CargoID cargo_type, uint num_pieces, IndustryID source, CompanyID company)
1035 /* Find the nearest industrytile to the station sign inside the catchment area, whose industry accepts the cargo.
1036 * This fails in three cases:
1037 * 1) The station accepts the cargo because there are enough houses around it accepting the cargo.
1038 * 2) The industries in the catchment area temporarily reject the cargo, and the daily station loop has not yet updated station acceptance.
1039 * 3) The results of callbacks CBID_INDUSTRY_REFUSE_CARGO and CBID_INDTILE_CARGO_ACCEPTANCE are inconsistent. (documented behaviour)
1042 uint accepted = 0;
1044 for (Industry *ind : st->industries_near) {
1045 if (num_pieces == 0) break;
1047 if (ind->index == source) continue;
1049 uint cargo_index;
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 if (ind->exclusive_supplier != INVALID_OWNER && ind->exclusive_supplier != st->owner) continue;
1061 /* Insert the industry into _cargo_delivery_destinations, if not yet contained */
1062 include(_cargo_delivery_destinations, ind);
1064 uint amount = std::min(num_pieces, 0xFFFFu - ind->incoming_cargo_waiting[cargo_index]);
1065 ind->incoming_cargo_waiting[cargo_index] += amount;
1066 ind->last_cargo_accepted_at[cargo_index] = _date;
1067 num_pieces -= amount;
1068 accepted += amount;
1070 /* Update the cargo monitor. */
1071 AddCargoDelivery(cargo_type, company, amount, ST_INDUSTRY, source, st, ind->index);
1074 return accepted;
1078 * Delivers goods to industries/towns and calculates the payment
1079 * @param num_pieces amount of cargo delivered
1080 * @param cargo_type the type of cargo that is delivered
1081 * @param dest Station the cargo has been unloaded
1082 * @param source_tile The origin of the cargo for distance calculation
1083 * @param days_in_transit Travel time
1084 * @param company The company delivering the cargo
1085 * @param src_type Type of source of cargo (industry, town, headquarters)
1086 * @param src Index of source of cargo
1087 * @return Revenue for delivering cargo
1088 * @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
1090 static Money DeliverGoods(int num_pieces, CargoID cargo_type, StationID dest, TileIndex source_tile, byte days_in_transit, Company *company, SourceType src_type, SourceID src)
1092 assert(num_pieces > 0);
1094 Station *st = Station::Get(dest);
1096 /* Give the goods to the industry. */
1097 uint accepted_ind = DeliverGoodsToIndustry(st, cargo_type, num_pieces, src_type == ST_INDUSTRY ? src : INVALID_INDUSTRY, company->index);
1099 /* If this cargo type is always accepted, accept all */
1100 uint accepted_total = HasBit(st->always_accepted, cargo_type) ? num_pieces : accepted_ind;
1102 /* Update station statistics */
1103 if (accepted_total > 0) {
1104 SetBit(st->goods[cargo_type].status, GoodsEntry::GES_EVER_ACCEPTED);
1105 SetBit(st->goods[cargo_type].status, GoodsEntry::GES_CURRENT_MONTH);
1106 SetBit(st->goods[cargo_type].status, GoodsEntry::GES_ACCEPTED_BIGTICK);
1109 /* Update company statistics */
1110 company->cur_economy.delivered_cargo[cargo_type] += accepted_total;
1112 /* Increase town's counter for town effects */
1113 const CargoSpec *cs = CargoSpec::Get(cargo_type);
1114 st->town->received[cs->town_effect].new_act += accepted_total;
1116 /* Determine profit */
1117 Money profit = GetTransportedGoodsIncome(accepted_total, DistanceManhattan(source_tile, st->xy), days_in_transit, cargo_type);
1119 /* Update the cargo monitor. */
1120 AddCargoDelivery(cargo_type, company->index, accepted_total - accepted_ind, src_type, src, st);
1122 /* Modify profit if a subsidy is in effect */
1123 if (CheckSubsidised(cargo_type, company->index, src_type, src, st)) {
1124 switch (_settings_game.difficulty.subsidy_multiplier) {
1125 case 0: profit += profit >> 1; break;
1126 case 1: profit *= 2; break;
1127 case 2: profit *= 3; break;
1128 default: profit *= 4; break;
1132 return profit;
1136 * Inform the industry about just delivered cargo
1137 * DeliverGoodsToIndustry() silently incremented incoming_cargo_waiting, now it is time to do something with the new cargo.
1138 * @param i The industry to process
1140 static void TriggerIndustryProduction(Industry *i)
1142 const IndustrySpec *indspec = GetIndustrySpec(i->type);
1143 uint16 callback = indspec->callback_mask;
1145 i->was_cargo_delivered = true;
1147 if (HasBit(callback, CBM_IND_PRODUCTION_CARGO_ARRIVAL) || HasBit(callback, CBM_IND_PRODUCTION_256_TICKS)) {
1148 if (HasBit(callback, CBM_IND_PRODUCTION_CARGO_ARRIVAL)) {
1149 IndustryProductionCallback(i, 0);
1150 } else {
1151 SetWindowDirty(WC_INDUSTRY_VIEW, i->index);
1153 } else {
1154 for (uint ci_in = 0; ci_in < lengthof(i->incoming_cargo_waiting); ci_in++) {
1155 uint cargo_waiting = i->incoming_cargo_waiting[ci_in];
1156 if (cargo_waiting == 0) continue;
1158 for (uint ci_out = 0; ci_out < lengthof(i->produced_cargo_waiting); ci_out++) {
1159 i->produced_cargo_waiting[ci_out] = std::min(i->produced_cargo_waiting[ci_out] + (cargo_waiting * indspec->input_cargo_multiplier[ci_in][ci_out] / 256), 0xFFFFu);
1162 i->incoming_cargo_waiting[ci_in] = 0;
1166 TriggerIndustry(i, INDUSTRY_TRIGGER_RECEIVED_CARGO);
1167 StartStopIndustryTileAnimation(i, IAT_INDUSTRY_RECEIVED_CARGO);
1171 * Makes us a new cargo payment helper.
1172 * @param front The front of the train
1174 CargoPayment::CargoPayment(Vehicle *front) :
1175 front(front),
1176 current_station(front->last_station_visited)
1180 CargoPayment::~CargoPayment()
1182 if (this->CleaningPool()) return;
1184 this->front->cargo_payment = nullptr;
1186 if (this->visual_profit == 0 && this->visual_transfer == 0) return;
1188 Backup<CompanyID> cur_company(_current_company, this->front->owner, FILE_LINE);
1190 SubtractMoneyFromCompany(CommandCost(this->front->GetExpenseType(true), -this->route_profit));
1191 this->front->profit_this_year += (this->visual_profit + this->visual_transfer) << 8;
1193 if (this->route_profit != 0 && IsLocalCompany() && !PlayVehicleSound(this->front, VSE_LOAD_UNLOAD)) {
1194 SndPlayVehicleFx(SND_14_CASHTILL, this->front);
1197 if (this->visual_transfer != 0) {
1198 ShowFeederIncomeAnimation(this->front->x_pos, this->front->y_pos,
1199 this->front->z_pos, this->visual_transfer, -this->visual_profit);
1200 } else if (this->visual_profit != 0) {
1201 ShowCostOrIncomeAnimation(this->front->x_pos, this->front->y_pos,
1202 this->front->z_pos, -this->visual_profit);
1205 cur_company.Restore();
1209 * Handle payment for final delivery of the given cargo packet.
1210 * @param cp The cargo packet to pay for.
1211 * @param count The number of packets to pay for.
1213 void CargoPayment::PayFinalDelivery(const CargoPacket *cp, uint count)
1215 if (this->owner == nullptr) {
1216 this->owner = Company::Get(this->front->owner);
1219 /* Handle end of route payment */
1220 Money profit = DeliverGoods(count, this->ct, this->current_station, cp->SourceStationXY(), cp->DaysInTransit(), this->owner, cp->SourceSubsidyType(), cp->SourceSubsidyID());
1221 this->route_profit += profit;
1223 /* The vehicle's profit is whatever route profit there is minus feeder shares. */
1224 this->visual_profit += profit - cp->FeederShare(count);
1228 * Handle payment for transfer of the given cargo packet.
1229 * @param cp The cargo packet to pay for; actual payment won't be made!.
1230 * @param count The number of packets to pay for.
1231 * @return The amount of money paid for the transfer.
1233 Money CargoPayment::PayTransfer(const CargoPacket *cp, uint count)
1235 Money profit = -cp->FeederShare(count) + GetTransportedGoodsIncome(
1236 count,
1237 /* pay transfer vehicle the difference between the payment for the journey from
1238 * the source to the current point, and the sum of the previous transfer payments */
1239 DistanceManhattan(cp->SourceStationXY(), Station::Get(this->current_station)->xy),
1240 cp->DaysInTransit(),
1241 this->ct);
1243 profit = profit * _settings_game.economy.feeder_payment_share / 100;
1245 this->visual_transfer += profit; // accumulate transfer profits for whole vehicle
1246 return profit; // account for the (virtual) profit already made for the cargo packet
1250 * Prepare the vehicle to be unloaded.
1251 * @param front_v the vehicle to be unloaded
1253 void PrepareUnload(Vehicle *front_v)
1255 Station *curr_station = Station::Get(front_v->last_station_visited);
1256 curr_station->loading_vehicles.push_back(front_v);
1258 /* At this moment loading cannot be finished */
1259 ClrBit(front_v->vehicle_flags, VF_LOADING_FINISHED);
1261 /* Start unloading at the first possible moment */
1262 front_v->load_unload_ticks = 1;
1264 assert(front_v->cargo_payment == nullptr);
1265 /* One CargoPayment per vehicle and the vehicle limit equals the
1266 * limit in number of CargoPayments. Can't go wrong. */
1267 static_assert(CargoPaymentPool::MAX_SIZE == VehiclePool::MAX_SIZE);
1268 assert(CargoPayment::CanAllocateItem());
1269 front_v->cargo_payment = new CargoPayment(front_v);
1271 StationIDStack next_station = front_v->GetNextStoppingStation();
1272 if (front_v->orders.list == nullptr || (front_v->current_order.GetUnloadType() & OUFB_NO_UNLOAD) == 0) {
1273 Station *st = Station::Get(front_v->last_station_visited);
1274 for (Vehicle *v = front_v; v != nullptr; v = v->Next()) {
1275 const GoodsEntry *ge = &st->goods[v->cargo_type];
1276 if (v->cargo_cap > 0 && v->cargo.TotalCount() > 0) {
1277 v->cargo.Stage(
1278 HasBit(ge->status, GoodsEntry::GES_ACCEPTANCE),
1279 front_v->last_station_visited, next_station,
1280 front_v->current_order.GetUnloadType(), ge,
1281 front_v->cargo_payment);
1282 if (v->cargo.UnloadCount() > 0) SetBit(v->vehicle_flags, VF_CARGO_UNLOADING);
1289 * Gets the amount of cargo the given vehicle can load in the current tick.
1290 * This is only about loading speed. The free capacity is ignored.
1291 * @param v Vehicle to be queried.
1292 * @return Amount of cargo the vehicle can load at once.
1294 static uint GetLoadAmount(Vehicle *v)
1296 const Engine *e = v->GetEngine();
1297 uint load_amount = e->info.load_amount;
1299 /* The default loadamount for mail is 1/4 of the load amount for passengers */
1300 bool air_mail = v->type == VEH_AIRCRAFT && !Aircraft::From(v)->IsNormalAircraft();
1301 if (air_mail) load_amount = CeilDiv(load_amount, 4);
1303 if (_settings_game.order.gradual_loading) {
1304 uint16 cb_load_amount = CALLBACK_FAILED;
1305 if (e->GetGRF() != nullptr && e->GetGRF()->grf_version >= 8) {
1306 /* Use callback 36 */
1307 cb_load_amount = GetVehicleProperty(v, PROP_VEHICLE_LOAD_AMOUNT, CALLBACK_FAILED);
1308 } else if (HasBit(e->info.callback_mask, CBM_VEHICLE_LOAD_AMOUNT)) {
1309 /* Use callback 12 */
1310 cb_load_amount = GetVehicleCallback(CBID_VEHICLE_LOAD_AMOUNT, 0, 0, v->engine_type, v);
1312 if (cb_load_amount != CALLBACK_FAILED) {
1313 if (e->GetGRF()->grf_version < 8) cb_load_amount = GB(cb_load_amount, 0, 8);
1314 if (cb_load_amount >= 0x100) {
1315 ErrorUnknownCallbackResult(e->GetGRFID(), CBID_VEHICLE_LOAD_AMOUNT, cb_load_amount);
1316 } else if (cb_load_amount != 0) {
1317 load_amount = cb_load_amount;
1322 /* Scale load amount the same as capacity */
1323 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);
1325 /* Zero load amount breaks a lot of things. */
1326 return std::max(1u, load_amount);
1330 * Iterate the articulated parts of a vehicle, also considering the special cases of "normal"
1331 * aircraft and double headed trains. Apply an action to each vehicle and immediately return false
1332 * if that action does so. Otherwise return true.
1333 * @tparam Taction Class of action to be applied. Must implement bool operator()([const] Vehicle *).
1334 * @param v First articulated part.
1335 * @param action Instance of Taction.
1336 * @return false if any of the action invocations returned false, true otherwise.
1338 template<class Taction>
1339 bool IterateVehicleParts(Vehicle *v, Taction action)
1341 for (Vehicle *w = v; w != nullptr;
1342 w = w->HasArticulatedPart() ? w->GetNextArticulatedPart() : nullptr) {
1343 if (!action(w)) return false;
1344 if (w->type == VEH_TRAIN) {
1345 Train *train = Train::From(w);
1346 if (train->IsMultiheaded() && !action(train->other_multiheaded_part)) return false;
1349 if (v->type == VEH_AIRCRAFT && Aircraft::From(v)->IsNormalAircraft()) return action(v->Next());
1350 return true;
1354 * Action to check if a vehicle has no stored cargo.
1356 struct IsEmptyAction
1359 * Checks if the vehicle has stored cargo.
1360 * @param v Vehicle to be checked.
1361 * @return true if v is either empty or has only reserved cargo, false otherwise.
1363 bool operator()(const Vehicle *v)
1365 return v->cargo.StoredCount() == 0;
1370 * Refit preparation action.
1372 struct PrepareRefitAction
1374 CargoArray &consist_capleft; ///< Capacities left in the consist.
1375 CargoTypes &refit_mask; ///< Bitmask of possible refit cargoes.
1378 * Create a refit preparation action.
1379 * @param consist_capleft Capacities left in consist, to be updated here.
1380 * @param refit_mask Refit mask to be constructed from refit information of vehicles.
1382 PrepareRefitAction(CargoArray &consist_capleft, CargoTypes &refit_mask) :
1383 consist_capleft(consist_capleft), refit_mask(refit_mask) {}
1386 * Prepares for refitting of a vehicle, subtracting its free capacity from consist_capleft and
1387 * adding the cargoes it can refit to to the refit mask.
1388 * @param v The vehicle to be refitted.
1389 * @return true.
1391 bool operator()(const Vehicle *v)
1393 this->consist_capleft[v->cargo_type] -= v->cargo_cap - v->cargo.ReservedCount();
1394 this->refit_mask |= EngInfo(v->engine_type)->refit_mask;
1395 return true;
1400 * Action for returning reserved cargo.
1402 struct ReturnCargoAction
1404 Station *st; ///< Station to give the returned cargo to.
1405 StationID next_hop; ///< Next hop the cargo should be assigned to.
1408 * Construct a cargo return action.
1409 * @param st Station to give the returned cargo to.
1410 * @param next_one Next hop the cargo should be assigned to.
1412 ReturnCargoAction(Station *st, StationID next_one) : st(st), next_hop(next_one) {}
1415 * Return all reserved cargo from a vehicle.
1416 * @param v Vehicle to return cargo from.
1417 * @return true.
1419 bool operator()(Vehicle *v)
1421 v->cargo.Return(UINT_MAX, &this->st->goods[v->cargo_type].cargo, this->next_hop);
1422 return true;
1427 * Action for finalizing a refit.
1429 struct FinalizeRefitAction
1431 CargoArray &consist_capleft; ///< Capacities left in the consist.
1432 Station *st; ///< Station to reserve cargo from.
1433 StationIDStack &next_station; ///< Next hops to reserve cargo for.
1434 bool do_reserve; ///< If the vehicle should reserve.
1437 * Create a finalizing action.
1438 * @param consist_capleft Capacities left in the consist.
1439 * @param st Station to reserve cargo from.
1440 * @param next_station Next hops to reserve cargo for.
1441 * @param do_reserve If we should reserve cargo or just add up the capacities.
1443 FinalizeRefitAction(CargoArray &consist_capleft, Station *st, StationIDStack &next_station, bool do_reserve) :
1444 consist_capleft(consist_capleft), st(st), next_station(next_station), do_reserve(do_reserve) {}
1447 * Reserve cargo from the station and update the remaining consist capacities with the
1448 * vehicle's remaining free capacity.
1449 * @param v Vehicle to be finalized.
1450 * @return true.
1452 bool operator()(Vehicle *v)
1454 if (this->do_reserve) {
1455 this->st->goods[v->cargo_type].cargo.Reserve(v->cargo_cap - v->cargo.RemainingCount(),
1456 &v->cargo, st->xy, this->next_station);
1458 this->consist_capleft[v->cargo_type] += v->cargo_cap - v->cargo.RemainingCount();
1459 return true;
1464 * Refit a vehicle in a station.
1465 * @param v Vehicle to be refitted.
1466 * @param consist_capleft Added cargo capacities in the consist.
1467 * @param st Station the vehicle is loading at.
1468 * @param next_station Possible next stations the vehicle can travel to.
1469 * @param new_cid Target cargo for refit.
1471 static void HandleStationRefit(Vehicle *v, CargoArray &consist_capleft, Station *st, StationIDStack next_station, CargoID new_cid)
1473 Vehicle *v_start = v->GetFirstEnginePart();
1474 if (!IterateVehicleParts(v_start, IsEmptyAction())) return;
1476 Backup<CompanyID> cur_company(_current_company, v->owner, FILE_LINE);
1478 CargoTypes refit_mask = v->GetEngine()->info.refit_mask;
1480 /* Remove old capacity from consist capacity and collect refit mask. */
1481 IterateVehicleParts(v_start, PrepareRefitAction(consist_capleft, refit_mask));
1483 bool is_auto_refit = new_cid == CT_AUTO_REFIT;
1484 if (is_auto_refit) {
1485 /* Get a refittable cargo type with waiting cargo for next_station or INVALID_STATION. */
1486 new_cid = v_start->cargo_type;
1487 for (CargoID cid : SetCargoBitIterator(refit_mask)) {
1488 if (st->goods[cid].cargo.HasCargoFor(next_station)) {
1489 /* Try to find out if auto-refitting would succeed. In case the refit is allowed,
1490 * the returned refit capacity will be greater than zero. */
1491 Command<CMD_REFIT_VEHICLE>::Do(DC_QUERY_COST, v_start->tile, v_start->index, cid | 1U << 24 | 0xFF << 8 | 1U << 16, {}); // Auto-refit and only this vehicle including artic parts.
1492 /* Try to balance different loadable cargoes between parts of the consist, so that
1493 * all of them can be loaded. Avoid a situation where all vehicles suddenly switch
1494 * to the first loadable cargo for which there is only one packet. If the capacities
1495 * are equal refit to the cargo of which most is available. This is important for
1496 * consists of only a single vehicle as those will generally have a consist_capleft
1497 * of 0 for all cargoes. */
1498 if (_returned_refit_capacity > 0 && (consist_capleft[cid] < consist_capleft[new_cid] ||
1499 (consist_capleft[cid] == consist_capleft[new_cid] &&
1500 st->goods[cid].cargo.AvailableCount() > st->goods[new_cid].cargo.AvailableCount()))) {
1501 new_cid = cid;
1507 /* Refit if given a valid cargo. */
1508 if (new_cid < NUM_CARGO && new_cid != v_start->cargo_type) {
1509 /* INVALID_STATION because in the DT_MANUAL case that's correct and in the DT_(A)SYMMETRIC
1510 * cases the next hop of the vehicle doesn't really tell us anything if the cargo had been
1511 * "via any station" before reserving. We rather produce some more "any station" cargo than
1512 * misrouting it. */
1513 IterateVehicleParts(v_start, ReturnCargoAction(st, INVALID_STATION));
1514 CommandCost cost = Command<CMD_REFIT_VEHICLE>::Do(DC_EXEC, v_start->tile, v_start->index, new_cid | 1U << 24 | 0xFF << 8 | 1U << 16, {}); // Auto-refit and only this vehicle including artic parts.
1515 if (cost.Succeeded()) v->First()->profit_this_year -= cost.GetCost() << 8;
1518 /* Add new capacity to consist capacity and reserve cargo */
1519 IterateVehicleParts(v_start, FinalizeRefitAction(consist_capleft, st, next_station,
1520 is_auto_refit || (v->First()->current_order.GetLoadType() & OLFB_FULL_LOAD) != 0));
1522 cur_company.Restore();
1526 * Test whether a vehicle can load cargo at a station even if exclusive transport rights are present.
1527 * @param st Station with cargo waiting to be loaded.
1528 * @param v Vehicle loading the cargo.
1529 * @return true when a vehicle can load the cargo.
1531 static bool MayLoadUnderExclusiveRights(const Station *st, const Vehicle *v)
1533 return st->owner != OWNER_NONE || st->town->exclusive_counter == 0 || st->town->exclusivity == v->owner;
1536 struct ReserveCargoAction {
1537 Station *st;
1538 StationIDStack *next_station;
1540 ReserveCargoAction(Station *st, StationIDStack *next_station) :
1541 st(st), next_station(next_station) {}
1543 bool operator()(Vehicle *v)
1545 if (v->cargo_cap > v->cargo.RemainingCount() && MayLoadUnderExclusiveRights(st, v)) {
1546 st->goods[v->cargo_type].cargo.Reserve(v->cargo_cap - v->cargo.RemainingCount(),
1547 &v->cargo, st->xy, *next_station);
1550 return true;
1556 * Reserves cargo if the full load order and improved_load is set or if the
1557 * current order allows autorefit.
1558 * @param st Station where the consist is loading at the moment.
1559 * @param u Front of the loading vehicle consist.
1560 * @param consist_capleft If given, save free capacities after reserving there.
1561 * @param next_station Station(s) the vehicle will stop at next.
1563 static void ReserveConsist(Station *st, Vehicle *u, CargoArray *consist_capleft, StationIDStack *next_station)
1565 /* If there is a cargo payment not all vehicles of the consist have tried to do the refit.
1566 * In that case, only reserve if it's a fixed refit and the equivalent of "articulated chain"
1567 * a vehicle belongs to already has the right cargo. */
1568 bool must_reserve = !u->current_order.IsRefit() || u->cargo_payment == nullptr;
1569 for (Vehicle *v = u; v != nullptr; v = v->Next()) {
1570 assert(v->cargo_cap >= v->cargo.RemainingCount());
1572 /* Exclude various ways in which the vehicle might not be the head of an equivalent of
1573 * "articulated chain". Also don't do the reservation if the vehicle is going to refit
1574 * to a different cargo and hasn't tried to do so, yet. */
1575 if (!v->IsArticulatedPart() &&
1576 (v->type != VEH_TRAIN || !Train::From(v)->IsRearDualheaded()) &&
1577 (v->type != VEH_AIRCRAFT || Aircraft::From(v)->IsNormalAircraft()) &&
1578 (must_reserve || u->current_order.GetRefitCargo() == v->cargo_type)) {
1579 IterateVehicleParts(v, ReserveCargoAction(st, next_station));
1581 if (consist_capleft == nullptr || v->cargo_cap == 0) continue;
1582 (*consist_capleft)[v->cargo_type] += v->cargo_cap - v->cargo.RemainingCount();
1587 * Update the vehicle's load_unload_ticks, the time it will wait until it tries to load or unload
1588 * again. Adjust for overhang of trains and set it at least to 1.
1589 * @param front The vehicle to be updated.
1590 * @param st The station the vehicle is loading at.
1591 * @param ticks The time it would normally wait, based on cargo loaded and unloaded.
1593 static void UpdateLoadUnloadTicks(Vehicle *front, const Station *st, int ticks)
1595 if (front->type == VEH_TRAIN) {
1596 /* Each platform tile is worth 2 rail vehicles. */
1597 int overhang = front->GetGroundVehicleCache()->cached_total_length - st->GetPlatformLength(front->tile) * TILE_SIZE;
1598 if (overhang > 0) {
1599 ticks <<= 1;
1600 ticks += (overhang * ticks) / 8;
1603 /* Always wait at least 1, otherwise we'll wait 'infinitively' long. */
1604 front->load_unload_ticks = std::max(1, ticks);
1608 * Loads/unload the vehicle if possible.
1609 * @param front the vehicle to be (un)loaded
1611 static void LoadUnloadVehicle(Vehicle *front)
1613 assert(front->current_order.IsType(OT_LOADING));
1615 StationID last_visited = front->last_station_visited;
1616 Station *st = Station::Get(last_visited);
1618 StationIDStack next_station = front->GetNextStoppingStation();
1619 bool use_autorefit = front->current_order.IsRefit() && front->current_order.GetRefitCargo() == CT_AUTO_REFIT;
1620 CargoArray consist_capleft;
1621 if (_settings_game.order.improved_load && use_autorefit ?
1622 front->cargo_payment == nullptr : (front->current_order.GetLoadType() & OLFB_FULL_LOAD) != 0) {
1623 ReserveConsist(st, front,
1624 (use_autorefit && front->load_unload_ticks != 0) ? &consist_capleft : nullptr,
1625 &next_station);
1628 /* We have not waited enough time till the next round of loading/unloading */
1629 if (front->load_unload_ticks != 0) return;
1631 if (front->type == VEH_TRAIN && (!IsTileType(front->tile, MP_STATION) || GetStationIndex(front->tile) != st->index)) {
1632 /* The train reversed in the station. Take the "easy" way
1633 * out and let the train just leave as it always did. */
1634 SetBit(front->vehicle_flags, VF_LOADING_FINISHED);
1635 front->load_unload_ticks = 1;
1636 return;
1639 int new_load_unload_ticks = 0;
1640 bool dirty_vehicle = false;
1641 bool dirty_station = false;
1643 bool completely_emptied = true;
1644 bool anything_unloaded = false;
1645 bool anything_loaded = false;
1646 CargoTypes full_load_amount = 0;
1647 CargoTypes cargo_not_full = 0;
1648 CargoTypes cargo_full = 0;
1649 CargoTypes reservation_left = 0;
1651 front->cur_speed = 0;
1653 CargoPayment *payment = front->cargo_payment;
1655 uint artic_part = 0; // Articulated part we are currently trying to load. (not counting parts without capacity)
1656 for (Vehicle *v = front; v != nullptr; v = v->Next()) {
1657 if (v == front || !v->Previous()->HasArticulatedPart()) artic_part = 0;
1658 if (v->cargo_cap == 0) continue;
1659 artic_part++;
1661 GoodsEntry *ge = &st->goods[v->cargo_type];
1663 if (HasBit(v->vehicle_flags, VF_CARGO_UNLOADING) && (front->current_order.GetUnloadType() & OUFB_NO_UNLOAD) == 0) {
1664 uint cargo_count = v->cargo.UnloadCount();
1665 uint amount_unloaded = _settings_game.order.gradual_loading ? std::min(cargo_count, GetLoadAmount(v)) : cargo_count;
1666 bool remaining = false; // Are there cargo entities in this vehicle that can still be unloaded here?
1668 assert(payment != nullptr);
1669 payment->SetCargo(v->cargo_type);
1671 if (!HasBit(ge->status, GoodsEntry::GES_ACCEPTANCE) && v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER) > 0) {
1672 /* The station does not accept our goods anymore. */
1673 if (front->current_order.GetUnloadType() & (OUFB_TRANSFER | OUFB_UNLOAD)) {
1674 /* Transfer instead of delivering. */
1675 v->cargo.Reassign<VehicleCargoList::MTA_DELIVER, VehicleCargoList::MTA_TRANSFER>(
1676 v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER), INVALID_STATION);
1677 } else {
1678 uint new_remaining = v->cargo.RemainingCount() + v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER);
1679 if (v->cargo_cap < new_remaining) {
1680 /* Return some of the reserved cargo to not overload the vehicle. */
1681 v->cargo.Return(new_remaining - v->cargo_cap, &ge->cargo, INVALID_STATION);
1684 /* Keep instead of delivering. This may lead to no cargo being unloaded, so ...*/
1685 v->cargo.Reassign<VehicleCargoList::MTA_DELIVER, VehicleCargoList::MTA_KEEP>(
1686 v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER));
1688 /* ... say we unloaded something, otherwise we'll think we didn't unload
1689 * something and we didn't load something, so we must be finished
1690 * at this station. Setting the unloaded means that we will get a
1691 * retry for loading in the next cycle. */
1692 anything_unloaded = true;
1696 if (v->cargo.ActionCount(VehicleCargoList::MTA_TRANSFER) > 0) {
1697 /* Mark the station dirty if we transfer, but not if we only deliver. */
1698 dirty_station = true;
1700 if (!ge->HasRating()) {
1701 /* Upon transferring cargo, make sure the station has a rating. Fake a pickup for the
1702 * first unload to prevent the cargo from quickly decaying after the initial drop. */
1703 ge->time_since_pickup = 0;
1704 SetBit(ge->status, GoodsEntry::GES_RATING);
1708 amount_unloaded = v->cargo.Unload(amount_unloaded, &ge->cargo, payment);
1709 remaining = v->cargo.UnloadCount() > 0;
1710 if (amount_unloaded > 0) {
1711 dirty_vehicle = true;
1712 anything_unloaded = true;
1713 new_load_unload_ticks += amount_unloaded;
1715 /* Deliver goods to the station */
1716 st->time_since_unload = 0;
1719 if (_settings_game.order.gradual_loading && remaining) {
1720 completely_emptied = false;
1721 } else {
1722 /* We have finished unloading (cargo count == 0) */
1723 ClrBit(v->vehicle_flags, VF_CARGO_UNLOADING);
1726 continue;
1729 /* Do not pick up goods when we have no-load set or loading is stopped. */
1730 if (front->current_order.GetLoadType() & OLFB_NO_LOAD || HasBit(front->vehicle_flags, VF_STOP_LOADING)) continue;
1732 /* This order has a refit, if this is the first vehicle part carrying cargo and the whole vehicle is empty, try refitting. */
1733 if (front->current_order.IsRefit() && artic_part == 1) {
1734 HandleStationRefit(v, consist_capleft, st, next_station, front->current_order.GetRefitCargo());
1735 ge = &st->goods[v->cargo_type];
1738 /* As we're loading here the following link can carry the full capacity of the vehicle. */
1739 v->refit_cap = v->cargo_cap;
1741 /* update stats */
1742 int t;
1743 switch (front->type) {
1744 case VEH_TRAIN:
1745 case VEH_SHIP:
1746 t = front->vcache.cached_max_speed;
1747 break;
1749 case VEH_ROAD:
1750 t = front->vcache.cached_max_speed / 2;
1751 break;
1753 case VEH_AIRCRAFT:
1754 t = Aircraft::From(front)->GetSpeedOldUnits(); // Convert to old units.
1755 break;
1757 default: NOT_REACHED();
1760 /* if last speed is 0, we treat that as if no vehicle has ever visited the station. */
1761 ge->last_speed = std::min(t, 255);
1762 ge->last_age = std::min(_cur_year - front->build_year, 255);
1764 assert(v->cargo_cap >= v->cargo.StoredCount());
1765 /* Capacity available for loading more cargo. */
1766 uint cap_left = v->cargo_cap - v->cargo.StoredCount();
1768 if (cap_left > 0) {
1769 /* If vehicle can load cargo, reset time_since_pickup. */
1770 ge->time_since_pickup = 0;
1772 /* If there's goods waiting at the station, and the vehicle
1773 * has capacity for it, load it on the vehicle. */
1774 if ((v->cargo.ActionCount(VehicleCargoList::MTA_LOAD) > 0 || ge->cargo.AvailableCount() > 0) && MayLoadUnderExclusiveRights(st, v)) {
1775 if (v->cargo.StoredCount() == 0) TriggerVehicle(v, VEHICLE_TRIGGER_NEW_CARGO);
1776 if (_settings_game.order.gradual_loading) cap_left = std::min(cap_left, GetLoadAmount(v));
1778 uint loaded = ge->cargo.Load(cap_left, &v->cargo, st->xy, next_station);
1779 if (v->cargo.ActionCount(VehicleCargoList::MTA_LOAD) > 0) {
1780 /* Remember if there are reservations left so that we don't stop
1781 * loading before they're loaded. */
1782 SetBit(reservation_left, v->cargo_type);
1785 /* Store whether the maximum possible load amount was loaded or not.*/
1786 if (loaded == cap_left) {
1787 SetBit(full_load_amount, v->cargo_type);
1788 } else {
1789 ClrBit(full_load_amount, v->cargo_type);
1792 /* TODO: Regarding this, when we do gradual loading, we
1793 * should first unload all vehicles and then start
1794 * loading them. Since this will cause
1795 * VEHICLE_TRIGGER_EMPTY to be called at the time when
1796 * the whole vehicle chain is really totally empty, the
1797 * completely_emptied assignment can then be safely
1798 * removed; that's how TTDPatch behaves too. --pasky */
1799 if (loaded > 0) {
1800 completely_emptied = false;
1801 anything_loaded = true;
1803 st->time_since_load = 0;
1804 st->last_vehicle_type = v->type;
1806 if (ge->cargo.TotalCount() == 0) {
1807 TriggerStationRandomisation(st, st->xy, SRT_CARGO_TAKEN, v->cargo_type);
1808 TriggerStationAnimation(st, st->xy, SAT_CARGO_TAKEN, v->cargo_type);
1809 AirportAnimationTrigger(st, AAT_STATION_CARGO_TAKEN, v->cargo_type);
1812 new_load_unload_ticks += loaded;
1814 dirty_vehicle = dirty_station = true;
1819 if (v->cargo.StoredCount() >= v->cargo_cap) {
1820 SetBit(cargo_full, v->cargo_type);
1821 } else {
1822 SetBit(cargo_not_full, v->cargo_type);
1826 if (anything_loaded || anything_unloaded) {
1827 if (front->type == VEH_TRAIN) {
1828 TriggerStationRandomisation(st, front->tile, SRT_TRAIN_LOADS);
1829 TriggerStationAnimation(st, front->tile, SAT_TRAIN_LOADS);
1833 /* Only set completely_emptied, if we just unloaded all remaining cargo */
1834 completely_emptied &= anything_unloaded;
1836 if (!anything_unloaded) delete payment;
1838 ClrBit(front->vehicle_flags, VF_STOP_LOADING);
1839 if (anything_loaded || anything_unloaded) {
1840 if (_settings_game.order.gradual_loading) {
1841 /* The time it takes to load one 'slice' of cargo or passengers depends
1842 * on the vehicle type - the values here are those found in TTDPatch */
1843 const uint gradual_loading_wait_time[] = { 40, 20, 10, 20 };
1845 new_load_unload_ticks = gradual_loading_wait_time[front->type];
1847 /* We loaded less cargo than possible for all cargo types and it's not full
1848 * load and we're not supposed to wait any longer: stop loading. */
1849 if (!anything_unloaded && full_load_amount == 0 && reservation_left == 0 && !(front->current_order.GetLoadType() & OLFB_FULL_LOAD) &&
1850 front->current_order_time >= (uint)std::max(front->current_order.GetTimetabledWait() - front->lateness_counter, 0)) {
1851 SetBit(front->vehicle_flags, VF_STOP_LOADING);
1854 UpdateLoadUnloadTicks(front, st, new_load_unload_ticks);
1855 } else {
1856 UpdateLoadUnloadTicks(front, st, 20); // We need the ticks for link refreshing.
1857 bool finished_loading = true;
1858 if (front->current_order.GetLoadType() & OLFB_FULL_LOAD) {
1859 if (front->current_order.GetLoadType() == OLF_FULL_LOAD_ANY) {
1860 /* if the aircraft carries passengers and is NOT full, then
1861 * continue loading, no matter how much mail is in */
1862 if ((front->type == VEH_AIRCRAFT && IsCargoInClass(front->cargo_type, CC_PASSENGERS) && front->cargo_cap > front->cargo.StoredCount()) ||
1863 (cargo_not_full != 0 && (cargo_full & ~cargo_not_full) == 0)) { // There are still non-full cargoes
1864 finished_loading = false;
1866 } else if (cargo_not_full != 0) {
1867 finished_loading = false;
1870 /* Refresh next hop stats if we're full loading to make the links
1871 * known to the distribution algorithm and allow cargo to be sent
1872 * along them. Otherwise the vehicle could wait for cargo
1873 * indefinitely if it hasn't visited the other links yet, or if the
1874 * links die while it's loading. */
1875 if (!finished_loading) LinkRefresher::Run(front, true, true);
1878 SB(front->vehicle_flags, VF_LOADING_FINISHED, 1, finished_loading);
1881 /* Calculate the loading indicator fill percent and display
1882 * In the Game Menu do not display indicators
1883 * If _settings_client.gui.loading_indicators == 2, show indicators (bool can be promoted to int as 0 or 1 - results in 2 > 0,1 )
1884 * if _settings_client.gui.loading_indicators == 1, _local_company must be the owner or must be a spectator to show ind., so 1 > 0
1885 * if _settings_client.gui.loading_indicators == 0, do not display indicators ... 0 is never greater than anything
1887 if (_game_mode != GM_MENU && (_settings_client.gui.loading_indicators > (uint)(front->owner != _local_company && _local_company != COMPANY_SPECTATOR))) {
1888 StringID percent_up_down = STR_NULL;
1889 int percent = CalcPercentVehicleFilled(front, &percent_up_down);
1890 if (front->fill_percent_te_id == INVALID_TE_ID) {
1891 front->fill_percent_te_id = ShowFillingPercent(front->x_pos, front->y_pos, front->z_pos + 20, percent, percent_up_down);
1892 } else {
1893 UpdateFillingPercent(front->fill_percent_te_id, percent, percent_up_down);
1897 if (completely_emptied) {
1898 /* Make sure the vehicle is marked dirty, since we need to update the NewGRF
1899 * properties such as weight, power and TE whenever the trigger runs. */
1900 dirty_vehicle = true;
1901 TriggerVehicle(front, VEHICLE_TRIGGER_EMPTY);
1904 if (dirty_vehicle) {
1905 SetWindowDirty(GetWindowClassForVehicleType(front->type), front->owner);
1906 SetWindowDirty(WC_VEHICLE_DETAILS, front->index);
1907 front->MarkDirty();
1909 if (dirty_station) {
1910 st->MarkTilesDirty(true);
1911 SetWindowDirty(WC_STATION_VIEW, last_visited);
1912 InvalidateWindowData(WC_STATION_LIST, last_visited);
1917 * Load/unload the vehicles in this station according to the order
1918 * they entered.
1919 * @param st the station to do the loading/unloading for
1921 void LoadUnloadStation(Station *st)
1923 /* No vehicle is here... */
1924 if (st->loading_vehicles.empty()) return;
1926 Vehicle *last_loading = nullptr;
1927 std::list<Vehicle *>::iterator iter;
1929 /* Check if anything will be loaded at all. Otherwise we don't need to reserve either. */
1930 for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end(); ++iter) {
1931 Vehicle *v = *iter;
1933 if ((v->vehstatus & (VS_STOPPED | VS_CRASHED))) continue;
1935 assert(v->load_unload_ticks != 0);
1936 if (--v->load_unload_ticks == 0) last_loading = v;
1939 /* We only need to reserve and load/unload up to the last loading vehicle.
1940 * Anything else will be forgotten anyway after returning from this function.
1942 * Especially this means we do _not_ need to reserve cargo for a single
1943 * consist in a station which is not allowed to load yet because its
1944 * load_unload_ticks is still not 0.
1946 if (last_loading == nullptr) return;
1948 for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end(); ++iter) {
1949 Vehicle *v = *iter;
1950 if (!(v->vehstatus & (VS_STOPPED | VS_CRASHED))) LoadUnloadVehicle(v);
1951 if (v == last_loading) break;
1954 /* Call the production machinery of industries */
1955 for (Industry *iid : _cargo_delivery_destinations) {
1956 TriggerIndustryProduction(iid);
1958 _cargo_delivery_destinations.clear();
1962 * Monthly update of the economic data (of the companies as well as economic fluctuations).
1964 void CompaniesMonthlyLoop()
1966 CompaniesGenStatistics();
1967 if (_settings_game.economy.inflation) {
1968 AddInflation();
1969 RecomputePrices();
1971 CompaniesPayInterest();
1972 HandleEconomyFluctuations();
1975 static void DoAcquireCompany(Company *c)
1977 CompanyID ci = c->index;
1979 CompanyNewsInformation *cni = new CompanyNewsInformation(c, Company::Get(_current_company));
1981 SetDParam(0, STR_NEWS_COMPANY_MERGER_TITLE);
1982 SetDParam(1, c->bankrupt_value == 0 ? STR_NEWS_MERGER_TAKEOVER_TITLE : STR_NEWS_COMPANY_MERGER_DESCRIPTION);
1983 SetDParamStr(2, cni->company_name);
1984 SetDParamStr(3, cni->other_company_name);
1985 SetDParam(4, c->bankrupt_value);
1986 AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, cni);
1987 AI::BroadcastNewEvent(new ScriptEventCompanyMerger(ci, _current_company));
1988 Game::NewEvent(new ScriptEventCompanyMerger(ci, _current_company));
1990 ChangeOwnershipOfCompanyItems(ci, _current_company);
1992 if (c->bankrupt_value == 0) {
1993 Company *owner = Company::Get(_current_company);
1995 /* Get both the balance and the loan of the company you just bought. */
1996 SubtractMoneyFromCompany(CommandCost(EXPENSES_OTHER, -c->money));
1997 owner->current_loan += c->current_loan;
2000 if (c->is_ai) AI::Stop(c->index);
2002 CloseCompanyWindows(ci);
2003 InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
2004 InvalidateWindowClassesData(WC_SHIPS_LIST, 0);
2005 InvalidateWindowClassesData(WC_ROADVEH_LIST, 0);
2006 InvalidateWindowClassesData(WC_AIRCRAFT_LIST, 0);
2008 delete c;
2011 extern int GetAmountOwnedBy(const Company *c, Owner owner);
2014 * Acquire shares in an opposing company.
2015 * @param flags type of operation
2016 * @param tile unused
2017 * @param p1 company to buy the shares from
2018 * @param p2 unused
2019 * @param text unused
2020 * @return the cost of this operation or an error
2022 CommandCost CmdBuyShareInCompany(DoCommandFlag flags, TileIndex tile, uint32 p1, uint32 p2, const std::string &text)
2024 CommandCost cost(EXPENSES_OTHER);
2025 CompanyID target_company = (CompanyID)p1;
2026 Company *c = Company::GetIfValid(target_company);
2028 /* Check if buying shares is allowed (protection against modified clients)
2029 * Cannot buy own shares */
2030 if (c == nullptr || !_settings_game.economy.allow_shares || _current_company == target_company) return CMD_ERROR;
2032 /* Protect new companies from hostile takeovers */
2033 if (_cur_year - c->inaugurated_year < _settings_game.economy.min_years_for_shares) return_cmd_error(STR_ERROR_PROTECTED);
2035 /* Those lines are here for network-protection (clients can be slow) */
2036 if (GetAmountOwnedBy(c, COMPANY_SPECTATOR) == 0) return cost;
2038 if (GetAmountOwnedBy(c, COMPANY_SPECTATOR) == 1) {
2039 if (!c->is_ai) return cost; // We can not buy out a real company (temporarily). TODO: well, enable it obviously.
2041 if (GetAmountOwnedBy(c, _current_company) == 3 && !MayCompanyTakeOver(_current_company, target_company)) return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
2045 cost.AddCost(CalculateCompanyValue(c) >> 2);
2046 if (flags & DC_EXEC) {
2047 Owner *b = c->share_owners;
2049 while (*b != COMPANY_SPECTATOR) b++; // share owners is guaranteed to contain at least one COMPANY_SPECTATOR
2050 *b = _current_company;
2052 for (int i = 0; c->share_owners[i] == _current_company;) {
2053 if (++i == 4) {
2054 c->bankrupt_value = 0;
2055 DoAcquireCompany(c);
2056 break;
2059 InvalidateWindowData(WC_COMPANY, target_company);
2060 CompanyAdminUpdate(c);
2062 return cost;
2066 * Sell shares in an opposing company.
2067 * @param flags type of operation
2068 * @param tile unused
2069 * @param p1 company to sell the shares from
2070 * @param p2 unused
2071 * @param text unused
2072 * @return the cost of this operation or an error
2074 CommandCost CmdSellShareInCompany(DoCommandFlag flags, TileIndex tile, uint32 p1, uint32 p2, const std::string &text)
2076 CompanyID target_company = (CompanyID)p1;
2077 Company *c = Company::GetIfValid(target_company);
2079 /* Cannot sell own shares */
2080 if (c == nullptr || _current_company == target_company) return CMD_ERROR;
2082 /* Check if selling shares is allowed (protection against modified clients).
2083 * However, we must sell shares of companies being closed down. */
2084 if (!_settings_game.economy.allow_shares && !(flags & DC_BANKRUPT)) return CMD_ERROR;
2086 /* Those lines are here for network-protection (clients can be slow) */
2087 if (GetAmountOwnedBy(c, _current_company) == 0) return CommandCost();
2089 /* adjust it a little to make it less profitable to sell and buy */
2090 Money cost = CalculateCompanyValue(c) >> 2;
2091 cost = -(cost - (cost >> 7));
2093 if (flags & DC_EXEC) {
2094 Owner *b = c->share_owners;
2095 while (*b != _current_company) b++; // share owners is guaranteed to contain company
2096 *b = COMPANY_SPECTATOR;
2097 InvalidateWindowData(WC_COMPANY, target_company);
2098 CompanyAdminUpdate(c);
2100 return CommandCost(EXPENSES_OTHER, cost);
2104 * Buy up another company.
2105 * When a competing company is gone bankrupt you get the chance to purchase
2106 * that company.
2107 * @todo currently this only works for AI companies
2108 * @param flags type of operation
2109 * @param tile unused
2110 * @param p1 company to buy up
2111 * @param p2 unused
2112 * @param text unused
2113 * @return the cost of this operation or an error
2115 CommandCost CmdBuyCompany(DoCommandFlag flags, TileIndex tile, uint32 p1, uint32 p2, const std::string &text)
2117 CompanyID target_company = (CompanyID)p1;
2118 Company *c = Company::GetIfValid(target_company);
2119 if (c == nullptr) return CMD_ERROR;
2121 /* Disable takeovers when not asked */
2122 if (!HasBit(c->bankrupt_asked, _current_company)) return CMD_ERROR;
2124 /* Disable taking over the local company in singleplayer mode */
2125 if (!_networking && _local_company == c->index) return CMD_ERROR;
2127 /* Do not allow companies to take over themselves */
2128 if (target_company == _current_company) return CMD_ERROR;
2130 /* Disable taking over when not allowed. */
2131 if (!MayCompanyTakeOver(_current_company, target_company)) return CMD_ERROR;
2133 /* Get the cost here as the company is deleted in DoAcquireCompany. */
2134 CommandCost cost(EXPENSES_OTHER, c->bankrupt_value);
2136 if (flags & DC_EXEC) {
2137 DoAcquireCompany(c);
2139 return cost;