Change the way trip history works. It now records ticks and displays time and time...
[openttd-joker.git] / src / economy.cpp
blob5b2f8b1a71ed9c241a2b1cc67261d29876552c80
1 /* $Id$ */
3 /*
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/>.
8 */
10 /** @file economy.cpp Handling of the economy. */
12 #include "stdafx.h"
13 #include "company_func.h"
14 #include "command_func.h"
15 #include "industry.h"
16 #include "town.h"
17 #include "news_func.h"
18 #include "network/network.h"
19 #include "network/network_func.h"
20 #include "ai/ai.hpp"
21 #include "aircraft.h"
22 #include "train.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"
31 #include "object.h"
32 #include "strings_func.h"
33 #include "date_func.h"
34 #include "vehicle_func.h"
35 #include "sound_func.h"
36 #include "autoreplace_func.h"
37 #include "company_gui.h"
38 #include "signs_base.h"
39 #include "subsidy_base.h"
40 #include "subsidy_func.h"
41 #include "station_base.h"
42 #include "waypoint_base.h"
43 #include "triphistory.h"
44 #include "economy_base.h"
45 #include "core/pool_func.hpp"
46 #include "core/backup_type.hpp"
47 #include "cargo_type.h"
48 #include "water.h"
49 #include "game/game.hpp"
50 #include "cargomonitor.h"
51 #include "goal_base.h"
52 #include "story_base.h"
53 #include "linkgraph/refresh.h"
54 #include "tbtr_template_vehicle.h"
56 #include "table/strings.h"
57 #include "table/pricebase.h"
59 #include "safeguards.h"
62 /* Initialize the cargo payment-pool */
63 CargoPaymentPool _cargo_payment_pool("CargoPayment");
64 INSTANTIATE_POOL_METHODS(CargoPayment)
66 /**
67 * Multiply two integer values and shift the results to right.
69 * This function multiplies two integer values. The result is
70 * shifted by the amount of shift to right.
72 * @param a The first integer
73 * @param b The second integer
74 * @param shift The amount to shift the value to right.
75 * @return The shifted result
77 static inline int32 BigMulS(const int32 a, const int32 b, const uint8 shift)
79 return (int32)((int64)a * (int64)b >> shift);
82 typedef SmallVector<Industry *, 16> SmallIndustryList;
84 /**
85 * Score info, values used for computing the detailed performance rating.
87 const ScoreInfo _score_info[] = {
88 { 120, 100}, // SCORE_VEHICLES
89 { 80, 100}, // SCORE_STATIONS
90 { 10000, 100}, // SCORE_MIN_PROFIT
91 { 50000, 50}, // SCORE_MIN_INCOME
92 { 100000, 100}, // SCORE_MAX_INCOME
93 { 40000, 400}, // SCORE_DELIVERED
94 { 8, 50}, // SCORE_CARGO
95 {10000000, 50}, // SCORE_MONEY
96 { 250000, 50}, // SCORE_LOAN
97 { 0, 0} // SCORE_TOTAL
100 int _score_part[MAX_COMPANIES][SCORE_END];
101 Economy _economy;
102 Prices _price;
103 Money _additional_cash_required;
104 static PriceMultipliers _price_base_multiplier;
107 * Calculate the value of the company. That is the value of all
108 * assets (vehicles, stations, etc) and money minus the loan,
109 * except when including_loan is \c false which is useful when
110 * we want to calculate the value for bankruptcy.
111 * @param c the company to get the value of.
112 * @param including_loan include the loan in the company value.
113 * @return the value of the company.
115 Money CalculateCompanyValue(const Company *c, bool including_loan)
117 Owner owner = c->index;
119 Station *st;
120 uint num = 0;
122 FOR_ALL_STATIONS(st) {
123 if (st->owner == owner) num += CountBits((byte)st->facilities);
126 Money value = num * _price[PR_STATION_VALUE] * 25;
128 Vehicle *v;
129 FOR_ALL_VEHICLES(v) {
130 if (v->owner != owner) continue;
132 if (v->type == VEH_TRAIN ||
133 v->type == VEH_ROAD ||
134 (v->type == VEH_AIRCRAFT && Aircraft::From(v)->IsNormalAircraft()) ||
135 v->type == VEH_SHIP) {
136 value += v->value * 3 >> 1;
140 /* Add real money value */
141 if (including_loan) value -= c->current_loan;
142 value += c->money;
144 return max(value, (Money)1);
148 * if update is set to true, the economy is updated with this score
149 * (also the house is updated, should only be true in the on-tick event)
150 * @param update the economy with calculated score
151 * @param c company been evaluated
152 * @return actual score of this company
155 int UpdateCompanyRatingAndValue(Company *c, bool update)
157 Owner owner = c->index;
158 int score = 0;
160 memset(_score_part[owner], 0, sizeof(_score_part[owner]));
162 /* Count vehicles */
164 Vehicle *v;
165 Money min_profit = 0;
166 bool min_profit_first = true;
167 uint num = 0;
169 FOR_ALL_VEHICLES(v) {
170 if (v->owner != owner) continue;
171 if (IsCompanyBuildableVehicleType(v->type) && v->IsPrimaryVehicle()) {
172 if (v->profit_last_year > 0) num++; // For the vehicle score only count profitable vehicles
173 if (v->age > 730) {
174 /* Find the vehicle with the lowest amount of profit */
175 if (min_profit_first || min_profit > v->profit_last_year) {
176 min_profit = v->profit_last_year;
177 min_profit_first = false;
183 min_profit >>= 8; // remove the fract part
185 _score_part[owner][SCORE_VEHICLES] = num;
186 /* Don't allow negative min_profit to show */
187 if (min_profit > 0) {
188 _score_part[owner][SCORE_MIN_PROFIT] = ClampToI32(min_profit);
192 /* Count stations */
194 uint num = 0;
195 const Station *st;
197 FOR_ALL_STATIONS(st) {
198 /* Only count stations that are actually serviced */
199 if (st->owner == owner && (st->time_since_load <= 20 || st->time_since_unload <= 20)) num += CountBits((byte)st->facilities);
201 _score_part[owner][SCORE_STATIONS] = num;
204 /* Generate statistics depending on recent income statistics */
206 int numec = min(c->num_valid_stat_ent, 12);
207 if (numec != 0) {
208 const CompanyEconomyEntry *cee = c->old_economy;
209 Money min_income = cee->income + cee->expenses;
210 Money max_income = cee->income + cee->expenses;
212 do {
213 min_income = min(min_income, cee->income + cee->expenses);
214 max_income = max(max_income, cee->income + cee->expenses);
215 } while (++cee, --numec);
217 if (min_income > 0) {
218 _score_part[owner][SCORE_MIN_INCOME] = ClampToI32(min_income);
221 _score_part[owner][SCORE_MAX_INCOME] = ClampToI32(max_income);
225 /* Generate score depending on amount of transported cargo */
227 int numec = min(c->num_valid_stat_ent, 4);
228 if (numec != 0) {
229 const CompanyEconomyEntry *cee = c->old_economy;
230 OverflowSafeInt64 total_delivered = 0;
231 do {
232 total_delivered += cee->delivered_cargo.GetSum<OverflowSafeInt64>();
233 } while (++cee, --numec);
235 _score_part[owner][SCORE_DELIVERED] = ClampToI32(total_delivered);
239 /* Generate score for variety of cargo */
241 _score_part[owner][SCORE_CARGO] = c->old_economy->delivered_cargo.GetCount();
244 /* Generate score for company's money */
246 if (c->money > 0) {
247 _score_part[owner][SCORE_MONEY] = ClampToI32(c->money);
251 /* Generate score for loan */
253 _score_part[owner][SCORE_LOAN] = ClampToI32(_score_info[SCORE_LOAN].needed - c->current_loan);
256 /* Now we calculate the score for each item.. */
258 int total_score = 0;
259 int s;
260 score = 0;
261 for (ScoreID i = SCORE_BEGIN; i < SCORE_END; i++) {
262 /* Skip the total */
263 if (i == SCORE_TOTAL) continue;
264 /* Check the score */
265 s = Clamp(_score_part[owner][i], 0, _score_info[i].needed) * _score_info[i].score / _score_info[i].needed;
266 score += s;
267 total_score += _score_info[i].score;
270 _score_part[owner][SCORE_TOTAL] = score;
272 /* We always want the score scaled to SCORE_MAX (1000) */
273 if (total_score != SCORE_MAX) score = score * SCORE_MAX / total_score;
276 if (update) {
277 c->old_economy[0].performance_history = score;
278 UpdateCompanyHQ(c->location_of_HQ, score);
279 c->old_economy[0].company_value = CalculateCompanyValue(c);
282 SetWindowDirty(WC_PERFORMANCE_DETAIL, 0);
283 return score;
287 * Change the ownership of all the items of a company.
288 * @param old_owner The company that gets removed.
289 * @param new_owner The company to merge to, or INVALID_OWNER to remove the company.
291 void ChangeOwnershipOfCompanyItems(Owner old_owner, Owner new_owner)
293 /* We need to set _current_company to old_owner before we try to move
294 * the client. This is needed as it needs to know whether "you" really
295 * are the current local company. */
296 Backup<CompanyByte> cur_company(_current_company, old_owner, FILE_LINE);
297 #ifdef ENABLE_NETWORK
298 /* In all cases, make spectators of clients connected to that company */
299 if (_networking) NetworkClientsToSpectators(old_owner);
300 #endif /* ENABLE_NETWORK */
301 if (old_owner == _local_company) {
302 /* Single player cheated to AI company.
303 * There are no spectators in single player, so we must pick some other company. */
304 assert(!_networking);
305 Backup<CompanyByte> cur_company2(_current_company, FILE_LINE);
306 Company *c;
307 FOR_ALL_COMPANIES(c) {
308 if (c->index != old_owner) {
309 SetLocalCompany(c->index);
310 break;
313 cur_company2.Restore();
314 assert(old_owner != _local_company);
317 Town *t;
319 assert(old_owner != new_owner);
322 Company *c;
323 uint i;
325 /* See if the old_owner had shares in other companies */
326 FOR_ALL_COMPANIES(c) {
327 for (i = 0; i < 4; i++) {
328 if (c->share_owners[i] == old_owner) {
329 /* Sell his shares */
330 CommandCost res = DoCommand(0, c->index, 0, DC_EXEC | DC_BANKRUPT, CMD_SELL_SHARE_IN_COMPANY);
331 /* Because we are in a DoCommand, we can't just execute another one and
332 * expect the money to be removed. We need to do it ourself! */
333 SubtractMoneyFromCompany(res);
338 /* Sell all the shares that people have on this company */
339 Backup<CompanyByte> cur_company2(_current_company, FILE_LINE);
340 c = Company::Get(old_owner);
341 for (i = 0; i < 4; i++) {
342 cur_company2.Change(c->share_owners[i]);
343 if (_current_company != INVALID_OWNER) {
344 /* Sell the shares */
345 CommandCost res = DoCommand(0, old_owner, 0, DC_EXEC | DC_BANKRUPT, CMD_SELL_SHARE_IN_COMPANY);
346 /* Because we are in a DoCommand, we can't just execute another one and
347 * expect the money to be removed. We need to do it ourself! */
348 SubtractMoneyFromCompany(res);
351 cur_company2.Restore();
354 /* Temporarily increase the company's money, to be sure that
355 * removing his/her property doesn't fail because of lack of money.
356 * Not too drastically though, because it could overflow */
357 if (new_owner == INVALID_OWNER) {
358 Company::Get(old_owner)->money = UINT64_MAX >> 2; // jackpot ;p
361 Subsidy *s;
362 FOR_ALL_SUBSIDIES(s) {
363 if (s->awarded == old_owner) {
364 if (new_owner == INVALID_OWNER) {
365 delete s;
366 } else {
367 s->awarded = new_owner;
371 if (new_owner == INVALID_OWNER) RebuildSubsidisedSourceAndDestinationCache();
373 /* Take care of rating and transport rights in towns */
374 FOR_ALL_TOWNS(t) {
375 /* If a company takes over, give the ratings to that company. */
376 if (new_owner != INVALID_OWNER) {
377 if (HasBit(t->have_ratings, old_owner)) {
378 if (HasBit(t->have_ratings, new_owner)) {
379 /* use max of the two ratings. */
380 t->ratings[new_owner] = max(t->ratings[new_owner], t->ratings[old_owner]);
381 } else {
382 SetBit(t->have_ratings, new_owner);
383 t->ratings[new_owner] = t->ratings[old_owner];
388 /* Reset the ratings for the old owner */
389 t->ratings[old_owner] = RATING_INITIAL;
390 ClrBit(t->have_ratings, old_owner);
392 /* Transfer exclusive rights */
393 if (t->exclusive_counter > 0 && t->exclusivity == old_owner) {
394 if (new_owner != INVALID_OWNER) {
395 t->exclusivity = new_owner;
396 } else {
397 t->exclusive_counter = 0;
398 t->exclusivity = INVALID_COMPANY;
404 Vehicle *v;
405 FOR_ALL_VEHICLES(v) {
406 if (v->owner == old_owner && IsCompanyBuildableVehicleType(v->type)) {
407 if (new_owner == INVALID_OWNER) {
408 if (v->Previous() == NULL) delete v;
409 } else {
410 if (v->IsEngineCountable()) GroupStatistics::CountEngine(v, -1);
411 if (v->IsPrimaryVehicle()) GroupStatistics::CountVehicle(v, -1);
417 /* In all cases clear replace engine rules.
418 * Even if it was copied, it could interfere with new owner's rules */
419 RemoveAllEngineReplacementForCompany(Company::Get(old_owner));
421 if (new_owner == INVALID_OWNER) {
422 RemoveAllGroupsForCompany(old_owner);
423 } else {
424 Group *g;
425 FOR_ALL_GROUPS(g) {
426 if (g->owner == old_owner) g->owner = new_owner;
431 FreeUnitIDGenerator unitidgen[] = {
432 FreeUnitIDGenerator(VEH_TRAIN, new_owner), FreeUnitIDGenerator(VEH_ROAD, new_owner),
433 FreeUnitIDGenerator(VEH_SHIP, new_owner), FreeUnitIDGenerator(VEH_AIRCRAFT, new_owner)
436 /* Override company settings to new company defaults in case we need to convert them.
437 * This is required as the CmdChangeServiceInt doesn't copy the supplied value when it is non-custom
439 if (new_owner != INVALID_OWNER) {
440 Company *old_company = Company::Get(old_owner);
441 Company *new_company = Company::Get(new_owner);
443 old_company->settings.vehicle.servint_aircraft = new_company->settings.vehicle.servint_aircraft;
444 old_company->settings.vehicle.servint_trains = new_company->settings.vehicle.servint_trains;
445 old_company->settings.vehicle.servint_roadveh = new_company->settings.vehicle.servint_roadveh;
446 old_company->settings.vehicle.servint_ships = new_company->settings.vehicle.servint_ships;
447 old_company->settings.vehicle.servint_ispercent = new_company->settings.vehicle.servint_ispercent;
450 Vehicle *v;
451 FOR_ALL_VEHICLES(v) {
452 if (v->owner == old_owner && IsCompanyBuildableVehicleType(v->type)) {
453 assert(new_owner != INVALID_OWNER);
455 /* Correct default values of interval settings while maintaining custom set ones.
456 * This prevents invalid values on mismatching company defaults being accepted.
458 if (!v->ServiceIntervalIsCustom()) {
459 Company *new_company = Company::Get(new_owner);
461 /* Technically, passing the interval is not needed as the command will query the default value itself.
462 * However, do not rely on that behaviour.
464 int interval = CompanyServiceInterval(new_company, v->type);
465 DoCommand(v->tile, v->index, interval | (new_company->settings.vehicle.servint_ispercent << 17), DC_EXEC | DC_BANKRUPT, CMD_CHANGE_SERVICE_INT);
468 v->owner = new_owner;
470 /* Owner changes, clear cache */
471 v->colourmap = PAL_NONE;
472 v->InvalidateNewGRFCache();
474 if (v->IsEngineCountable()) {
475 GroupStatistics::CountEngine(v, 1);
477 if (v->IsPrimaryVehicle()) {
478 GroupStatistics::CountVehicle(v, 1);
479 v->unitnumber = unitidgen[v->type].NextID();
482 /* Invalidate the vehicle's cargo payment "owner cache". */
483 if (v->cargo_payment != NULL) v->cargo_payment->owner = NULL;
487 if (new_owner != INVALID_OWNER) GroupStatistics::UpdateAutoreplace(new_owner);
490 /* Change ownership of template vehicles */
491 if (new_owner == INVALID_OWNER) {
492 TemplateVehicle *tv;
493 FOR_ALL_TEMPLATES(tv) {
494 if (tv->owner == old_owner) {
495 TemplateReplacement *tr;
496 FOR_ALL_TEMPLATE_REPLACEMENTS(tr) {
497 if (tr->Template() == tv->index) {
498 delete tr;
501 delete tv;
504 } else {
505 TemplateVehicle *tv;
506 FOR_ALL_TEMPLATES(tv) {
507 if (tv->owner == old_owner) tv->owner = new_owner;
511 /* Change ownership of tiles */
513 TileIndex tile = 0;
514 do {
515 ChangeTileOwner(tile, old_owner, new_owner);
516 } while (++tile != MapSize());
518 if (new_owner != INVALID_OWNER) {
519 /* Update all signals because there can be new segment that was owned by two companies
520 * and signals were not propagated
521 * Similar with crossings - it is needed to bar crossings that weren't before
522 * because of different owner of crossing and approaching train */
523 tile = 0;
525 do {
526 if (IsTileType(tile, MP_RAILWAY) && IsTileOwner(tile, new_owner) && HasSignals(tile)) {
527 TrackBits tracks = GetTrackBits(tile);
528 do { // there may be two tracks with signals for TRACK_BIT_HORZ and TRACK_BIT_VERT
529 Track track = RemoveFirstTrack(&tracks);
530 if (HasSignalOnTrack(tile, track)) AddTrackToSignalBuffer(tile, track, new_owner);
531 } while (tracks != TRACK_BIT_NONE);
532 } else if (IsLevelCrossingTile(tile) && IsTileOwner(tile, new_owner)) {
533 UpdateLevelCrossing(tile);
535 } while (++tile != MapSize());
538 /* update signals in buffer */
539 UpdateSignalsInBuffer();
542 /* Add airport infrastructure count of the old company to the new one. */
543 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.airport += Company::Get(old_owner)->infrastructure.airport;
545 /* convert owner of stations (including deleted ones, but excluding buoys) */
546 Station *st;
547 FOR_ALL_STATIONS(st) {
548 if (st->owner == old_owner) {
549 /* if a company goes bankrupt, set owner to OWNER_NONE so the sign doesn't disappear immediately
550 * also, drawing station window would cause reading invalid company's colour */
551 st->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner;
555 /* do the same for waypoints (we need to do this here so deleted waypoints are converted too) */
556 Waypoint *wp;
557 FOR_ALL_WAYPOINTS(wp) {
558 if (wp->owner == old_owner) {
559 wp->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner;
563 Sign *si;
564 FOR_ALL_SIGNS(si) {
565 if (si->owner == old_owner) si->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner;
568 /* Remove Game Script created Goals, CargoMonitors and Story pages. */
569 Goal *g;
570 FOR_ALL_GOALS(g) {
571 if (g->company == old_owner) delete g;
574 ClearCargoPickupMonitoring(old_owner);
575 ClearCargoDeliveryMonitoring(old_owner);
577 StoryPage *sp;
578 FOR_ALL_STORY_PAGES(sp) {
579 if (sp->company == old_owner) delete sp;
582 /* Change colour of existing windows */
583 if (new_owner != INVALID_OWNER) ChangeWindowOwner(old_owner, new_owner);
585 cur_company.Restore();
587 MarkWholeScreenDirty();
591 * Check for bankruptcy of a company. Called every three months.
592 * @param c Company to check.
594 static void CompanyCheckBankrupt(Company *c)
596 /* If the company has money again, it does not go bankrupt */
597 if (c->money - c->current_loan >= -_economy.max_loan) {
598 c->months_of_bankruptcy = 0;
599 c->bankrupt_asked = 0;
600 return;
603 c->months_of_bankruptcy++;
605 switch (c->months_of_bankruptcy) {
606 /* All the boring cases (months) with a bad balance where no action is taken */
607 case 0:
608 case 1:
609 case 2:
610 case 3:
612 case 5:
613 case 6:
615 case 8:
616 case 9:
617 break;
619 /* Warn about bankruptcy after 3 months */
620 case 4: {
621 CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
622 cni->FillData(c);
623 SetDParam(0, STR_NEWS_COMPANY_IN_TROUBLE_TITLE);
624 SetDParam(1, STR_NEWS_COMPANY_IN_TROUBLE_DESCRIPTION);
625 SetDParamStr(2, cni->company_name);
626 AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, cni);
627 AI::BroadcastNewEvent(new ScriptEventCompanyInTrouble(c->index));
628 Game::NewEvent(new ScriptEventCompanyInTrouble(c->index));
629 break;
632 /* Offer company for sale after 6 months */
633 case 7: {
634 /* Don't consider the loan */
635 Money val = CalculateCompanyValue(c, false);
637 c->bankrupt_value = val;
638 c->bankrupt_asked = 1 << c->index; // Don't ask the owner
639 c->bankrupt_timeout = 0;
641 /* The company assets should always have some value */
642 assert(c->bankrupt_value > 0);
643 break;
646 /* Bankrupt company after 6 months (if the company has no value) or latest
647 * after 9 months (if it still had value after 6 months) */
648 default:
649 case 10: {
650 if (!_networking && _local_company == c->index) {
651 /* If we are in offline mode, leave the company playing. Eg. there
652 * is no THE-END, otherwise mark the client as spectator to make sure
653 * he/she is no long in control of this company. However... when you
654 * join another company (cheat) the "unowned" company can bankrupt. */
655 c->bankrupt_asked = MAX_UVALUE(CompanyMask);
656 break;
659 /* Actually remove the company, but not when we're a network client.
660 * In case of network clients we will be getting a command from the
661 * server. It is done in this way as we are called from the
662 * StateGameLoop which can't change the current company, and thus
663 * updating the local company triggers an assert later on. In the
664 * case of a network game the command will be processed at a time
665 * that changing the current company is okay. In case of single
666 * player we are sure (the above check) that we are not the local
667 * company and thus we won't be moved. */
668 if (!_networking || _network_server) DoCommandP(0, 2 | (c->index << 16), CRR_BANKRUPT, CMD_COMPANY_CTRL);
669 break;
675 * Update the finances of all companies.
676 * Pay for the stations, update the history graph, update ratings and company values, and deal with bankruptcy.
678 static void CompaniesGenStatistics()
680 /* Check for bankruptcy each month */
681 Company *c;
682 FOR_ALL_COMPANIES(c) {
683 CompanyCheckBankrupt(c);
686 Backup<CompanyByte> cur_company(_current_company, FILE_LINE);
688 if (!_settings_game.economy.infrastructure_maintenance) {
689 Station *st;
690 FOR_ALL_STATIONS(st) {
691 cur_company.Change(st->owner);
692 CommandCost cost(EXPENSES_PROPERTY, _price[PR_STATION_VALUE] >> 1);
693 SubtractMoneyFromCompany(cost);
695 } else {
696 /* Improved monthly infrastructure costs. */
697 FOR_ALL_COMPANIES(c) {
698 cur_company.Change(c->index);
700 CommandCost cost(EXPENSES_PROPERTY);
701 uint32 rail_total = c->infrastructure.GetRailTotal();
702 for (RailType rt = RAILTYPE_BEGIN; rt < RAILTYPE_END; rt++) {
703 if (c->infrastructure.rail[rt] != 0) cost.AddCost(RailMaintenanceCost(rt, c->infrastructure.rail[rt], rail_total));
705 cost.AddCost(SignalMaintenanceCost(c->infrastructure.signal));
706 for (RoadType rt = ROADTYPE_BEGIN; rt < ROADTYPE_END; rt++) {
707 if (c->infrastructure.road[rt] != 0) cost.AddCost(RoadMaintenanceCost(rt, c->infrastructure.road[rt]));
709 cost.AddCost(CanalMaintenanceCost(c->infrastructure.water));
710 cost.AddCost(StationMaintenanceCost(c->infrastructure.station));
711 cost.AddCost(AirportMaintenanceCost(c->index));
713 SubtractMoneyFromCompany(cost);
716 cur_company.Restore();
718 Backup<CompanyByte> cur_company_2(_current_company, FILE_LINE);
720 FOR_ALL_COMPANIES(c) {
721 cur_company_2.Change(c->index);
723 if (c->inaugurated_year + 2 > _cur_year) continue;
725 CommandCost cost(EXPENSES_OTHER, 0);
727 if (c->old_economy[0].company_value > 1500000) {
728 cost.AddCost(c->old_economy[0].company_value >> 6); //~20% company value tax per year
729 }else if (c->old_economy[0].company_value > 200000 ) {
730 cost.AddCost(c->old_economy[0].company_value >> 7); //~10% company value tax per year
733 if (cost.GetCost() > 0) {
734 _economy.industry_helper += cost.GetCost();
735 SubtractMoneyFromCompany(cost);
738 cur_company_2.Restore();
740 /* Only run the economic statics and update company stats every 3rd month (1st of quarter). */
741 if (!HasBit(1 << 0 | 1 << 3 | 1 << 6 | 1 << 9, _cur_month)) return;
743 FOR_ALL_COMPANIES(c) {
744 memmove(&c->old_economy[1], &c->old_economy[0], sizeof(c->old_economy) - sizeof(c->old_economy[0]));
745 c->old_economy[0] = c->cur_economy;
746 memset(&c->cur_economy, 0, sizeof(c->cur_economy));
748 if (c->num_valid_stat_ent != MAX_HISTORY_QUARTERS) c->num_valid_stat_ent++;
750 UpdateCompanyRatingAndValue(c, true);
751 if (c->block_preview != 0) c->block_preview--;
754 SetWindowDirty(WC_INCOME_GRAPH, 0);
755 SetWindowDirty(WC_OPERATING_PROFIT, 0);
756 SetWindowDirty(WC_DELIVERED_CARGO, 0);
757 SetWindowDirty(WC_PERFORMANCE_HISTORY, 0);
758 SetWindowDirty(WC_COMPANY_VALUE, 0);
759 SetWindowDirty(WC_COMPANY_LEAGUE, 0);
763 * Add monthly inflation
764 * @param check_year Shall the inflation get stopped after 170 years?
765 * @return true if inflation is maxed and nothing was changed
767 bool AddInflation(bool check_year)
769 /* The cargo payment inflation differs from the normal inflation, so the
770 * relative amount of money you make with a transport decreases slowly over
771 * the 170 years. After a few hundred years we reach a level in which the
772 * games will become unplayable as the maximum income will be less than
773 * the minimum running cost.
775 * Furthermore there are a lot of inflation related overflows all over the
776 * place. Solving them is hardly possible because inflation will always
777 * reach the overflow threshold some day. So we'll just perform the
778 * inflation mechanism during the first 170 years (the amount of years that
779 * one had in the original TTD) and stop doing the inflation after that
780 * because it only causes problems that can't be solved nicely and the
781 * inflation doesn't add anything after that either; it even makes playing
782 * it impossible due to the diverging cost and income rates.
784 if (check_year && (_cur_year - _settings_game.game_creation.starting_year) >= (ORIGINAL_MAX_YEAR - ORIGINAL_BASE_YEAR)) return true;
786 if (_economy.inflation_prices == MAX_INFLATION || _economy.inflation_payment == MAX_INFLATION) return true;
788 /* Approximation for (100 + infl_amount)% ** (1 / 12) - 100%
789 * scaled by 65536
790 * 12 -> months per year
791 * This is only a good approximation for small values
793 _economy.inflation_prices += (_economy.inflation_prices * _economy.infl_amount * 54) >> 16;
794 _economy.inflation_payment += (_economy.inflation_payment * _economy.infl_amount_pr * 54) >> 16;
796 if (_economy.inflation_prices > MAX_INFLATION) _economy.inflation_prices = MAX_INFLATION;
797 if (_economy.inflation_payment > MAX_INFLATION) _economy.inflation_payment = MAX_INFLATION;
799 return false;
803 * Computes all prices, payments and maximum loan.
805 void RecomputePrices()
807 /* Setup maximum loan */
808 _economy.max_loan = (_settings_game.difficulty.max_loan * _economy.inflation_prices >> 16) / 50000 * 50000;
810 /* Setup price bases */
811 for (Price i = PR_BEGIN; i < PR_END; i++) {
812 Money price = _price_base_specs[i].start_price;
814 /* Apply difficulty settings */
815 uint mod = 1;
816 switch (_price_base_specs[i].category) {
817 case PCAT_RUNNING:
818 mod = _settings_game.difficulty.vehicle_costs;
819 break;
821 case PCAT_CONSTRUCTION:
822 mod = _settings_game.difficulty.construction_cost;
823 break;
825 default: break;
827 switch (mod) {
828 case 0: price *= 6; break;
829 case 1: price *= 8; break; // normalised to 1 below
830 case 2: price *= 9; break;
831 default: NOT_REACHED();
834 /* Apply inflation */
835 price = (int64)price * _economy.inflation_prices;
837 /* Apply newgrf modifiers, remove fractional part of inflation, and normalise on medium difficulty. */
838 int shift = _price_base_multiplier[i] - 16 - 3;
839 if (shift >= 0) {
840 price <<= shift;
841 } else {
842 price >>= -shift;
845 /* Make sure the price does not get reduced to zero.
846 * Zero breaks quite a few commands that use a zero
847 * cost to see whether something got changed or not
848 * and based on that cause an error. When the price
849 * is zero that fails even when things are done. */
850 if (price == 0) {
851 price = Clamp(_price_base_specs[i].start_price, -1, 1);
852 /* No base price should be zero, but be sure. */
853 assert(price != 0);
855 /* Store value */
856 _price[i] = price;
859 /* Setup cargo payment */
860 CargoSpec *cs;
861 FOR_ALL_CARGOSPECS(cs) {
862 cs->current_payment = ((int64)cs->initial_payment * _economy.inflation_payment) >> 16;
865 SetWindowClassesDirty(WC_BUILD_VEHICLE);
866 SetWindowClassesDirty(WC_REPLACE_VEHICLE);
867 SetWindowClassesDirty(WC_VEHICLE_DETAILS);
868 SetWindowClassesDirty(WC_COMPANY_INFRASTRUCTURE);
869 InvalidateWindowData(WC_PAYMENT_RATES, 0);
872 /** Let all companies pay the monthly interest on their loan. */
873 static void CompaniesPayInterest()
875 const Company *c;
877 Backup<CompanyByte> cur_company(_current_company, FILE_LINE);
878 FOR_ALL_COMPANIES(c) {
879 cur_company.Change(c->index);
881 /* Over a year the paid interest should be "loan * interest percentage",
882 * but... as that number is likely not dividable by 12 (pay each month),
883 * one needs to account for that in the monthly fee calculations.
884 * To easily calculate what one should pay "this" month, you calculate
885 * what (total) should have been paid up to this month and you subtract
886 * whatever has been paid in the previous months. This will mean one month
887 * it'll be a bit more and the other it'll be a bit less than the average
888 * monthly fee, but on average it will be exact.
889 * In order to prevent cheating or abuse (just not paying interest by not
890 * taking a loan we make companies pay interest on negative cash as well
892 Money yearly_fee = c->current_loan * _economy.interest_rate / 100;
893 if (c->money < 0) {
894 yearly_fee += -c->money *_economy.interest_rate / 100;
896 Money up_to_previous_month = yearly_fee * _cur_month / 12;
897 Money up_to_this_month = yearly_fee * (_cur_month + 1) / 12;
899 SubtractMoneyFromCompany(CommandCost(EXPENSES_LOAN_INT, up_to_this_month - up_to_previous_month));
901 SubtractMoneyFromCompany(CommandCost(EXPENSES_OTHER, _price[PR_STATION_VALUE] >> 2));
903 cur_company.Restore();
906 static void HandleEconomyFluctuations()
908 if (_settings_game.difficulty.economy != 0) {
909 /* When economy is Fluctuating, decrease counter */
910 _economy.fluct--;
911 } else if (EconomyIsInRecession()) {
912 /* When it's Steady and we are in recession, end it now */
913 _economy.fluct = -12;
914 } else {
915 /* No need to do anything else in other cases */
916 return;
919 if (_economy.fluct == 0) {
920 _economy.fluct = -(int)GB(Random(), 0, 2);
921 AddNewsItem(STR_NEWS_BEGIN_OF_RECESSION, NT_ECONOMY, NF_NORMAL);
922 } else if (_economy.fluct == -12) {
923 _economy.fluct = GB(Random(), 0, 8) + 312;
924 AddNewsItem(STR_NEWS_END_OF_RECESSION, NT_ECONOMY, NF_NORMAL);
930 * Reset changes to the price base multipliers.
932 void ResetPriceBaseMultipliers()
934 memset(_price_base_multiplier, 0, sizeof(_price_base_multiplier));
938 * Change a price base by the given factor.
939 * The price base is altered by factors of two.
940 * NewBaseCost = OldBaseCost * 2^n
941 * @param price Index of price base to change.
942 * @param factor Amount to change by.
944 void SetPriceBaseMultiplier(Price price, int factor)
946 assert(price < PR_END);
947 _price_base_multiplier[price] = Clamp(factor, MIN_PRICE_MODIFIER, MAX_PRICE_MODIFIER);
951 * Initialize the variables that will maintain the daily industry change system.
952 * @param init_counter specifies if the counter is required to be initialized
954 void StartupIndustryDailyChanges(bool init_counter)
956 uint map_size = MapLogX() + MapLogY();
957 /* After getting map size, it needs to be scaled appropriately and divided by 31,
958 * which stands for the days in a month.
959 * Using just 31 will make it so that a monthly reset (based on the real number of days of that month)
960 * would not be needed.
961 * Since it is based on "fractional parts", the leftover days will not make much of a difference
962 * on the overall total number of changes performed */
963 _economy.industry_daily_increment = (1 << map_size) / 31;
965 if (init_counter) {
966 /* A new game or a savegame from an older version will require the counter to be initialized */
967 _economy.industry_daily_change_counter = 0;
971 void StartupEconomy()
973 _economy.interest_rate = _settings_game.difficulty.initial_interest;
974 _economy.infl_amount = _settings_game.difficulty.initial_interest;
975 _economy.infl_amount_pr = max(0, _settings_game.difficulty.initial_interest - 1);
976 _economy.fluct = GB(Random(), 0, 8) + 168;
978 /* Set up prices */
979 RecomputePrices();
981 StartupIndustryDailyChanges(true); // As we are starting a new game, initialize the counter too
986 * Resets economy to initial values
988 void InitializeEconomy()
990 _economy.inflation_prices = _economy.inflation_payment = 1 << 16;
991 ClearCargoPickupMonitoring();
992 ClearCargoDeliveryMonitoring();
996 * Determine a certain price
997 * @param index Price base
998 * @param cost_factor Price factor
999 * @param grf_file NewGRF to use local price multipliers from.
1000 * @param shift Extra bit shifting after the computation
1001 * @return Price
1003 Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift)
1005 if (index >= PR_END) return 0;
1007 Money cost = _price[index] * cost_factor;
1008 if (grf_file != NULL) shift += grf_file->price_base_multipliers[index];
1010 if (shift >= 0) {
1011 cost <<= shift;
1012 } else {
1013 cost >>= -shift;
1016 return cost;
1019 Money GetTransportedGoodsIncome(uint num_pieces, uint dist, byte transit_days, CargoID cargo_type)
1021 const CargoSpec *cs = CargoSpec::Get(cargo_type);
1022 if (!cs->IsValid()) {
1023 /* User changed newgrfs and some vehicle still carries some cargo which is no longer available. */
1024 return 0;
1027 /* Use callback to calculate cargo profit, if available */
1028 if (HasBit(cs->callback_mask, CBM_CARGO_PROFIT_CALC)) {
1029 uint32 var18 = min(dist, 0xFFFF) | (min(num_pieces, 0xFF) << 16) | (transit_days << 24);
1030 uint16 callback = GetCargoCallback(CBID_CARGO_PROFIT_CALC, 0, var18, cs);
1031 if (callback != CALLBACK_FAILED) {
1032 int result = GB(callback, 0, 14);
1034 /* Simulate a 15 bit signed value */
1035 if (HasBit(callback, 14)) result -= 0x4000;
1037 /* "The result should be a signed multiplier that gets multiplied
1038 * by the amount of cargo moved and the price factor, then gets
1039 * divided by 8192." */
1040 return result * num_pieces * cs->current_payment / 8192;
1044 static const float DECAY1 = 40.0f;
1045 static const float DECAY2 = 5.0f;
1046 static const float TILE2KM = 28.66f;
1047 static const float INCOME_DIVISOR = 5000.0f;
1048 const float d = dist;
1049 float transitdays = transit_days;
1050 transitdays = 2.5f * max<float>(transitdays, 1.0f);
1051 const int cargo_payment = cs->current_payment;
1053 const int days1 = cs->transit_days[0];
1054 const int days2 = cs->transit_days[1];
1056 const float inv_vt1 =days1/(200*TILE2KM); // reciprocal of first threshold velocity
1057 const float inv_vt2 = (days1 + days2) / (200 * TILE2KM); // reciprocal of second threshold velocity
1058 const float vt1 = inv_vt1 > 0.0f ? (1.0f / inv_vt1) : 1.0f;
1059 const float vt2 = inv_vt2 > 0.0f ? (1.0f / inv_vt2) : 1.0f;
1060 const float v_avg = d*TILE2KM/(transitdays); //average transit velocity
1063 * The income factor is calculated based on the average velocity
1064 * compared to two cargo-depending threshold velocities.
1065 * Formula is divided into three parts:
1067 * - fast exponential growth limited by 1st threshold velocity
1068 * - slow exponential growth depending on 2nd threshold
1071 const float exp1 = (1.0f - exp((-v_avg) / (vt1 / DECAY1)));
1072 const float exp2 = (1.0f - exp((-v_avg) / (vt2 / DECAY2)));
1074 const Money income = static_cast<Money>(dist * cargo_payment * num_pieces * exp1 * exp2 / INCOME_DIVISOR);
1076 return income;
1079 /** The industries we've currently brought cargo to. */
1080 static SmallIndustryList _cargo_delivery_destinations;
1083 * Transfer goods from station to industry.
1084 * The cargo is delivered to all accepting industries in a round-robin way.
1085 * @param st The station that accepted the cargo
1086 * @param cargo_type Type of cargo delivered
1087 * @param num_pieces Amount of cargo delivered
1088 * @param source The source of the cargo
1089 * @return actually accepted pieces of cargo
1091 static uint DeliverGoodsToIndustry(const Station *st, CargoID cargo_type, uint num_pieces, IndustryID source)
1093 /* Find any industry tile inside the catchment area, whose industry accepts the cargo.
1094 * This fails in three cases:
1095 * 1) The station accepts the cargo because there are enough houses around it accepting the cargo.
1096 * 2) The industries in the catchment area temporarily reject the cargo, and the daily station loop has not yet updated station acceptance.
1097 * 3) The results of callbacks CBID_INDUSTRY_REFUSE_CARGO and CBID_INDTILE_CARGO_ACCEPTANCE are inconsistent. (documented behavior)
1100 uint accepted = 0;
1102 std::vector<std::tuple<Industry*, uint, bool> > accepting_industries;
1104 for (uint i = 0; i < st->industries_near.Length(); i++) {
1105 Industry *ind = st->industries_near[i];
1106 if (ind->index == source) continue;
1108 uint cargo_index;
1109 for (cargo_index = 0; cargo_index < lengthof(ind->accepts_cargo); cargo_index++) {
1110 if (cargo_type == ind->accepts_cargo[cargo_index]) break;
1112 /* Check if matching cargo has been found */
1113 if (cargo_index >= lengthof(ind->accepts_cargo)) continue;
1115 /* Check if industry temporarily refuses acceptance */
1116 if (IndustryTemporarilyRefusesCargo(ind, cargo_type)) continue;
1118 /* Insert the industry into _cargo_delivery_destinations, if not yet contained */
1119 _cargo_delivery_destinations.Include(ind);
1121 accepting_industries.push_back(std::tuple<Industry*, uint, bool>(ind, cargo_index, true));
1124 int num_accepting_industries = (int)accepting_industries.size();
1125 int ind_index = 0;
1127 // Do a round-robin for all industries and mark all industries that are no longer accepting because their maximum stockpile is full.
1128 while (num_accepting_industries > 0 && num_pieces > 0) {
1129 // Check if the current industry still accepts cargo
1130 if (std::get<2>(accepting_industries[ind_index])) {
1131 Industry* ind = std::get<0>(accepting_industries[ind_index]);
1132 uint cargo_index = std::get<1>(accepting_industries[ind_index]);
1134 if ((0xFFFFU - ind->incoming_cargo_waiting[cargo_index]) == 0) {
1135 // The maximum stockpile limit is reached. Mark the industry as no longer accepting.
1136 std::get<2>(accepting_industries[ind_index]) = false;
1137 --num_accepting_industries;
1139 else {
1140 // The industry still accepts cargo.
1141 ++ind->incoming_cargo_waiting[cargo_index];
1142 --num_pieces;
1143 ++accepted;
1147 ind_index = (++ind_index) % accepting_industries.size();
1150 return accepted;
1154 * Delivers goods to industries/towns and calculates the payment
1155 * @param num_pieces amount of cargo delivered
1156 * @param cargo_type the type of cargo that is delivered
1157 * @param dest Station the cargo has been unloaded
1158 * @param source_tile The origin of the cargo for distance calculation
1159 * @param days_in_transit Travel time
1160 * @param company The company delivering the cargo
1161 * @param src_type Type of source of cargo (industry, town, headquarters)
1162 * @param src Index of source of cargo
1163 * @return Revenue for delivering cargo
1164 * @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
1166 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)
1168 assert(num_pieces > 0);
1170 Station *st = Station::Get(dest);
1172 /* Give the goods to the industry. */
1173 uint accepted = DeliverGoodsToIndustry(st, cargo_type, num_pieces, src_type == ST_INDUSTRY ? src : INVALID_INDUSTRY);
1175 /* If this cargo type is always accepted, accept all */
1176 if (HasBit(st->always_accepted, cargo_type)) accepted = num_pieces;
1178 /* Update station statistics */
1179 if (accepted > 0) {
1180 SetBit(st->goods[cargo_type].status, GoodsEntry::GES_EVER_ACCEPTED);
1181 SetBit(st->goods[cargo_type].status, GoodsEntry::GES_CURRENT_MONTH);
1182 SetBit(st->goods[cargo_type].status, GoodsEntry::GES_ACCEPTED_BIGTICK);
1185 /* Update company statistics */
1186 company->cur_economy.delivered_cargo[cargo_type] += accepted;
1188 /* Increase town's counter for town effects */
1189 const CargoSpec *cs = CargoSpec::Get(cargo_type);
1190 st->town->received[cs->town_effect].new_act += accepted;
1192 /* Determine profit */
1193 Money profit = GetTransportedGoodsIncome(accepted, DistanceOpenTTD(source_tile, st->xy), days_in_transit, cargo_type);
1195 /* Update the cargo monitor. */
1196 AddCargoDelivery(cargo_type, company->index, accepted, src_type, src, st);
1198 /* Modify profit if a subsidy is in effect */
1199 if (CheckSubsidised(cargo_type, company->index, src_type, src, st)) {
1200 switch (_settings_game.difficulty.subsidy_multiplier) {
1201 case 0: profit += profit >> 1; break;
1202 case 1: profit *= 2; break;
1203 case 2: profit *= 3; break;
1204 default: profit *= 4; break;
1208 return profit;
1212 * Inform the industry about just delivered cargo
1213 * DeliverGoodsToIndustry() silently incremented incoming_cargo_waiting, now it is time to do something with the new cargo.
1214 * @param i The industry to process
1216 static void TriggerIndustryProduction(Industry *i)
1218 const IndustrySpec *indspec = GetIndustrySpec(i->type);
1219 uint16 callback = indspec->callback_mask;
1221 i->was_cargo_delivered = true;
1222 i->last_cargo_accepted_at = _date;
1224 if (HasBit(callback, CBM_IND_PRODUCTION_CARGO_ARRIVAL) || HasBit(callback, CBM_IND_PRODUCTION_256_TICKS)) {
1225 if (HasBit(callback, CBM_IND_PRODUCTION_CARGO_ARRIVAL)) {
1226 IndustryProductionCallback(i, 0);
1227 } else {
1228 SetWindowDirty(WC_INDUSTRY_VIEW, i->index);
1230 } else {
1231 for (uint cargo_index = 0; cargo_index < lengthof(i->incoming_cargo_waiting); cargo_index++) {
1232 uint cargo_waiting = i->incoming_cargo_waiting[cargo_index];
1233 if (cargo_waiting == 0) continue;
1235 i->produced_cargo_waiting[0] = min(i->produced_cargo_waiting[0] + (cargo_waiting * indspec->input_cargo_multiplier[cargo_index][0] / 256), 0xFFFF);
1236 i->produced_cargo_waiting[1] = min(i->produced_cargo_waiting[1] + (cargo_waiting * indspec->input_cargo_multiplier[cargo_index][1] / 256), 0xFFFF);
1238 i->incoming_cargo_waiting[cargo_index] = 0;
1242 TriggerIndustry(i, INDUSTRY_TRIGGER_RECEIVED_CARGO);
1243 StartStopIndustryTileAnimation(i, IAT_INDUSTRY_RECEIVED_CARGO);
1247 * Makes us a new cargo payment helper.
1248 * @param front The front of the train
1250 CargoPayment::CargoPayment(Vehicle *front) :
1251 front(front),
1252 current_station(front->last_station_visited)
1256 CargoPayment::~CargoPayment()
1258 if (this->CleaningPool()) return;
1260 this->front->cargo_payment = NULL;
1262 if (this->visual_profit == 0 && this->visual_transfer == 0) return;
1264 Backup<CompanyByte> cur_company(_current_company, this->front->owner, FILE_LINE);
1266 SubtractMoneyFromCompany(CommandCost(this->front->GetExpenseType(true), -this->route_profit));
1267 this->front->profit_this_year += (this->visual_profit + this->visual_transfer) << 8;
1269 if (this->route_profit != 0 && IsLocalCompany() && !PlayVehicleSound(this->front, VSE_LOAD_UNLOAD)) {
1270 SndPlayVehicleFx(SND_14_CASHTILL, this->front);
1273 if (this->visual_transfer != 0) {
1274 ShowFeederIncomeAnimation(this->front->x_pos, this->front->y_pos,
1275 this->front->z_pos, this->visual_transfer, -this->visual_profit);
1276 } else if (this->visual_profit != 0) {
1277 ShowCostOrIncomeAnimation(this->front->x_pos, this->front->y_pos,
1278 this->front->z_pos, -this->visual_profit);
1281 this->front->trip_history.AddValue((this->visual_profit + this->visual_transfer), GetCurrentTickCount());
1282 InvalidateWindowData(WC_VEHICLE_TRIP_HISTORY, this->front->index);
1283 cur_company.Restore();
1287 * Handle payment for final delivery of the given cargo packet.
1288 * @param cp The cargo packet to pay for.
1289 * @param count The number of packets to pay for.
1291 void CargoPayment::PayFinalDelivery(const CargoPacket *cp, uint count)
1293 if (this->owner == NULL) {
1294 this->owner = Company::Get(this->front->owner);
1297 DeliverGoods(count, this->ct, this->current_station, cp->SourceStationXY(), cp->DaysInTransit(), this->owner, cp->SourceSubsidyType(), cp->SourceSubsidyID());
1299 // Pay vehicle for only the part of total route it has done: ie. cargo_loaded_at_xy to here
1300 uint distance;
1302 if ((this->front != nullptr) && (this->front->type == VEH_ROAD)) {
1303 distance = DistanceManhattan(cp->LoadedAtXY(), Station::Get(this->current_station)->xy);
1304 } else {
1305 distance = DistanceOpenTTD(cp->LoadedAtXY(), Station::Get(this->current_station)->xy);
1308 // Allows the actual profits for only the last part of the trip to be calculated and, consequently, paid.
1309 Money profit = GetTransportedGoodsIncome(count, distance, cp->DaysInTransit(), this->ct);
1311 this->route_profit += profit + cp->FeederShare();
1312 this->visual_profit += profit;
1316 * Handle payment for transfer of the given cargo packet.
1317 * @param cp The cargo packet to pay for; actual payment won't be made!.
1318 * @param count The number of packets to pay for.
1319 * @return The amount of money paid for the transfer.
1321 Money CargoPayment::PayTransfer(CargoPacket *cp, uint count)
1323 // Pay vehicle for only the part of total route it has done: ie. cargo_loaded_at_xy to here
1324 uint distance;
1326 if ((this->front != nullptr) && (this->front->type == VEH_ROAD)) {
1327 distance = DistanceManhattan(cp->LoadedAtXY(), Station::Get(this->current_station)->xy);
1328 } else {
1329 distance = DistanceOpenTTD(cp->LoadedAtXY(), Station::Get(this->current_station)->xy);
1332 Money profit = GetTransportedGoodsIncome(count, distance, cp->DaysInTransit(), this->ct);
1334 // Reset the amount of days this package has been in transit, important for the next leg
1335 cp->ResetTransitDays();
1337 this->visual_transfer += profit;
1339 return profit;
1343 * Returns the load type of a vehicle.
1344 * In case of cargo type order, the load type returned depends on the cargo carriable by the vehicle.
1345 * @pre v != NULL
1346 * @param v A pointer to a vehicle.
1347 * @return the load type of this vehicle.
1349 static OrderLoadFlags GetLoadType(const Vehicle *v)
1351 return v->First()->current_order.GetCargoLoadType(v->cargo_type);
1355 * Returns the unload type of a vehicle.
1356 * In case of cargo type order, the unload type returned depends on the cargo carriable by the vehicle.
1357 * @pre v != NULL
1358 * @param v A pointer to a vehicle.
1359 * @return The unload type of this vehicle.
1361 static OrderUnloadFlags GetUnloadType(const Vehicle *v)
1363 return v->First()->current_order.GetCargoUnloadType(v->cargo_type);
1367 * Prepare the vehicle to be unloaded.
1368 * @param curr_station the station where the consist is at the moment
1369 * @param front_v the vehicle to be unloaded
1371 void PrepareUnload(Vehicle *front_v)
1373 Station *curr_station = Station::Get(front_v->last_station_visited);
1374 curr_station->loading_vehicles.push_back(front_v);
1376 /* At this moment loading cannot be finished */
1377 ClrBit(front_v->vehicle_flags, VF_LOADING_FINISHED);
1379 /* Start unloading at the first possible moment */
1380 front_v->load_unload_ticks = 1;
1382 assert(front_v->cargo_payment == NULL);
1383 /* One CargoPayment per vehicle and the vehicle limit equals the
1384 * limit in number of CargoPayments. Can't go wrong. */
1385 assert_compile(CargoPaymentPool::MAX_SIZE == VehiclePool::MAX_SIZE);
1386 assert(CargoPayment::CanAllocateItem());
1387 front_v->cargo_payment = new CargoPayment(front_v);
1389 CargoStationIDStackSet next_station = front_v->GetNextStoppingStation();
1390 if (!front_v->HasOrdersList() || (front_v->current_order.GetUnloadType() & OUFB_NO_UNLOAD) == 0) {
1391 Station *st = Station::Get(front_v->last_station_visited);
1392 for (Vehicle *v = front_v; v != NULL; v = v->Next()) {
1393 if (GetUnloadType(v) & OUFB_NO_UNLOAD) continue;
1394 const GoodsEntry *ge = &st->goods[v->cargo_type];
1395 if (v->cargo_cap > 0 && v->cargo.TotalCount() > 0) {
1396 v->cargo.Stage(
1397 HasBit(ge->status, GoodsEntry::GES_ACCEPTANCE),
1398 front_v->last_station_visited, next_station.Get(v->cargo_type),
1399 GetUnloadType(v), ge,
1400 front_v->cargo_payment);
1401 if (v->cargo.UnloadCount() > 0) SetBit(v->vehicle_flags, VF_CARGO_UNLOADING);
1408 * Gets the amount of cargo the given vehicle can load in the current tick.
1409 * This is only about loading speed. The free capacity is ignored.
1410 * @param v Vehicle to be queried.
1411 * @return Amount of cargo the vehicle can load at once.
1413 static uint GetLoadAmount(Vehicle *v)
1415 const Engine *e = v->GetEngine();
1416 uint load_amount = e->info.load_amount;
1418 /* The default loadamount for mail is 1/4 of the load amount for passengers */
1419 bool air_mail = v->type == VEH_AIRCRAFT && !Aircraft::From(v)->IsNormalAircraft();
1420 if (air_mail) load_amount = CeilDiv(load_amount, 4);
1422 if (_settings_game.order.gradual_loading) {
1423 uint16 cb_load_amount = CALLBACK_FAILED;
1424 if (e->GetGRF() != NULL && e->GetGRF()->grf_version >= 8) {
1425 /* Use callback 36 */
1426 cb_load_amount = GetVehicleProperty(v, PROP_VEHICLE_LOAD_AMOUNT, CALLBACK_FAILED);
1427 } else if (HasBit(e->info.callback_mask, CBM_VEHICLE_LOAD_AMOUNT)) {
1428 /* Use callback 12 */
1429 cb_load_amount = GetVehicleCallback(CBID_VEHICLE_LOAD_AMOUNT, 0, 0, v->engine_type, v);
1431 if (cb_load_amount != CALLBACK_FAILED) {
1432 if (e->GetGRF()->grf_version < 8) cb_load_amount = GB(cb_load_amount, 0, 8);
1433 if (cb_load_amount >= 0x100) {
1434 ErrorUnknownCallbackResult(e->GetGRFID(), CBID_VEHICLE_LOAD_AMOUNT, cb_load_amount);
1435 } else if (cb_load_amount != 0) {
1436 load_amount = cb_load_amount;
1441 /* Scale load amount the same as capacity */
1442 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);
1444 /* Zero load amount breaks a lot of things. */
1445 return max(1u, load_amount);
1449 * Iterate the articulated parts of a vehicle, also considering the special cases of "normal"
1450 * aircraft and double headed trains. Apply an action to each vehicle and immediately return false
1451 * if that action does so. Otherwise return true.
1452 * @tparam Taction Class of action to be applied. Must implement bool operator()([const] Vehicle *).
1453 * @param v First articulated part.
1454 * @param action Instance of Taction.
1455 * @return false if any of the action invocations returned false, true otherwise.
1457 template<class Taction>
1458 bool IterateVehicleParts(Vehicle *v, Taction action)
1460 for (Vehicle *w = v; w != NULL;
1461 w = w->HasArticulatedPart() ? w->GetNextArticulatedPart() : NULL) {
1462 if (!action(w)) return false;
1463 if (w->type == VEH_TRAIN) {
1464 Train *train = Train::From(w);
1465 if (train->IsMultiheaded() && !action(train->other_multiheaded_part)) return false;
1468 if (v->type == VEH_AIRCRAFT && Aircraft::From(v)->IsNormalAircraft()) return action(v->Next());
1469 return true;
1473 * Action to check if a vehicle has no stored cargo.
1475 struct IsEmptyAction
1478 * Checks if the vehicle has stored cargo.
1479 * @param v Vehicle to be checked.
1480 * @return true if v is either empty or has only reserved cargo, false otherwise.
1482 bool operator()(const Vehicle *v)
1484 return v->cargo.StoredCount() == 0;
1489 * Refit preparation action.
1491 struct PrepareRefitAction
1493 CargoArray &consist_capleft; ///< Capacities left in the consist.
1494 uint32 &refit_mask; ///< Bitmask of possible refit cargoes.
1497 * Create a refit preparation action.
1498 * @param consist_capleft Capacities left in consist, to be updated here.
1499 * @param refit_mask Refit mask to be constructed from refit information of vehicles.
1501 PrepareRefitAction(CargoArray &consist_capleft, uint32 &refit_mask) :
1502 consist_capleft(consist_capleft), refit_mask(refit_mask) {}
1505 * Prepares for refitting of a vehicle, subtracting its free capacity from consist_capleft and
1506 * adding the cargoes it can refit to to the refit mask.
1507 * @param v The vehicle to be refitted.
1508 * @return true.
1510 bool operator()(const Vehicle *v)
1512 this->consist_capleft[v->cargo_type] -= v->cargo_cap - v->cargo.ReservedCount();
1513 this->refit_mask |= EngInfo(v->engine_type)->refit_mask;
1514 return true;
1519 * Action for returning reserved cargo.
1521 struct ReturnCargoAction
1523 Station *st; ///< Station to give the returned cargo to.
1524 StationID next_hop; ///< Next hop the cargo should be assigned to.
1527 * Construct a cargo return action.
1528 * @param st Station to give the returned cargo to.
1529 * @param next_one Next hop the cargo should be assigned to.
1531 ReturnCargoAction(Station *st, StationID next_one) : st(st), next_hop(next_one) {}
1534 * Return all reserved cargo from a vehicle.
1535 * @param v Vehicle to return cargo from.
1536 * @return true.
1538 bool operator()(Vehicle *v)
1540 v->cargo.Return(UINT_MAX, &this->st->goods[v->cargo_type].cargo, this->next_hop);
1541 return true;
1546 * Action for finalizing a refit.
1548 struct FinalizeRefitAction
1550 CargoArray &consist_capleft; ///< Capacities left in the consist.
1551 Station *st; ///< Station to reserve cargo from.
1552 const CargoStationIDStackSet &next_station; ///< Next hops to reserve cargo for.
1553 bool do_reserve; ///< If the vehicle should reserve.
1554 Vehicle *cargo_type_loading; ///< Non-null if vehicle should reserve if the cargo type of the vehicle is a cargo-specific full-load order using this pointer
1557 * Create a finalizing action.
1558 * @param consist_capleft Capacities left in the consist.
1559 * @param st Station to reserve cargo from.
1560 * @param next_station Next hops to reserve cargo for.
1561 * @param do_reserve If we should reserve cargo or just add up the capacities.
1562 * @param cargo_type_loading Non-null if vehicle should reserve if the cargo type of the vehicle is a cargo-specific full-load order using this pointer
1564 FinalizeRefitAction(CargoArray &consist_capleft, Station *st, const CargoStationIDStackSet &next_station, bool do_reserve, Vehicle *cargo_type_loading) :
1565 consist_capleft(consist_capleft), st(st), next_station(next_station), do_reserve(do_reserve), cargo_type_loading(cargo_type_loading) {}
1569 * Reserve cargo from the station and update the remaining consist capacities with the
1570 * vehicle's remaining free capacity.
1571 * @param v Vehicle to be finalized.
1572 * @return true.
1574 bool operator()(Vehicle *v)
1576 if (this->do_reserve || (cargo_type_loading == NULL || (cargo_type_loading->current_order.GetCargoLoadTypeRaw(v->cargo_type) & OLFB_FULL_LOAD))) {
1577 this->st->goods[v->cargo_type].cargo.Reserve(v->cargo_cap - v->cargo.RemainingCount(),
1578 &v->cargo, st->xy, this->next_station.Get(v->cargo_type));
1580 this->consist_capleft[v->cargo_type] += v->cargo_cap - v->cargo.RemainingCount();
1581 return true;
1586 * Refit a vehicle in a station.
1587 * @param v Vehicle to be refitted.
1588 * @param consist_capleft Added cargo capacities in the consist.
1589 * @param st Station the vehicle is loading at.
1590 * @param next_station Possible next stations the vehicle can travel to.
1591 * @param new_cid Target cargo for refit.
1593 static void HandleStationRefit(Vehicle *v, CargoArray &consist_capleft, Station *st, CargoStationIDStackSet next_station, CargoID new_cid)
1595 Vehicle *v_start = v->GetFirstEnginePart();
1596 if (!IterateVehicleParts(v_start, IsEmptyAction())) return;
1598 Backup<CompanyByte> cur_company(_current_company, v->owner, FILE_LINE);
1600 uint32 refit_mask = v->GetEngine()->info.refit_mask;
1602 /* Remove old capacity from consist capacity and collect refit mask. */
1603 IterateVehicleParts(v_start, PrepareRefitAction(consist_capleft, refit_mask));
1605 bool is_auto_refit = new_cid == CT_AUTO_REFIT;
1606 bool check_order = (v->First()->current_order.GetLoadType() == OLFB_CARGO_TYPE_LOAD);
1607 if (is_auto_refit) {
1608 /* Get a refittable cargo type with waiting cargo for next_station or INVALID_STATION. */
1609 CargoID cid;
1610 new_cid = v_start->cargo_type;
1611 FOR_EACH_SET_CARGO_ID(cid, refit_mask) {
1612 if (check_order && v->First()->current_order.GetCargoLoadType(cid) == OLFB_NO_LOAD) continue;
1613 if (st->goods[cid].cargo.HasCargoFor(next_station.Get(cid))) {
1614 /* Try to find out if auto-refitting would succeed. In case the refit is allowed,
1615 * the returned refit capacity will be greater than zero. */
1616 DoCommand(v_start->tile, v_start->index, cid | 1U << 6 | 0xFF << 8 | 1U << 16, DC_QUERY_COST, GetCmdRefitVeh(v_start)); // Auto-refit and only this vehicle including artic parts.
1617 /* Try to balance different loadable cargoes between parts of the consist, so that
1618 * all of them can be loaded. Avoid a situation where all vehicles suddenly switch
1619 * to the first loadable cargo for which there is only one packet. If the capacities
1620 * are equal refit to the cargo of which most is available. This is important for
1621 * consists of only a single vehicle as those will generally have a consist_capleft
1622 * of 0 for all cargoes. */
1623 if (_returned_refit_capacity > 0 && (consist_capleft[cid] < consist_capleft[new_cid] ||
1624 (consist_capleft[cid] == consist_capleft[new_cid] &&
1625 st->goods[cid].cargo.AvailableCount() > st->goods[new_cid].cargo.AvailableCount()))) {
1626 new_cid = cid;
1632 /* Refit if given a valid cargo. */
1633 if (new_cid < NUM_CARGO && new_cid != v_start->cargo_type) {
1634 /* INVALID_STATION because in the DT_MANUAL case that's correct and in the DT_(A)SYMMETRIC
1635 * cases the next hop of the vehicle doesn't really tell us anything if the cargo had been
1636 * "via any station" before reserving. We rather produce some more "any station" cargo than
1637 * misrouting it. */
1638 IterateVehicleParts(v_start, ReturnCargoAction(st, INVALID_STATION));
1639 CommandCost cost = DoCommand(v_start->tile, v_start->index, new_cid | 1U << 6 | 0xFF << 8 | 1U << 16, DC_EXEC, GetCmdRefitVeh(v_start)); // Auto-refit and only this vehicle including artic parts.
1640 if (cost.Succeeded()) v->First()->profit_this_year -= cost.GetCost() << 8;
1643 /* Add new capacity to consist capacity and reserve cargo */
1644 IterateVehicleParts(v_start, FinalizeRefitAction(consist_capleft, st, next_station,
1645 is_auto_refit || (v->First()->current_order.GetLoadType() & OLFB_FULL_LOAD) != 0,
1646 (v->First()->current_order.GetLoadType() == OLFB_CARGO_TYPE_LOAD) ? v->First() : NULL));
1648 cur_company.Restore();
1651 struct ReserveCargoAction {
1652 Station *st;
1653 const CargoStationIDStackSet &next_station;
1654 Vehicle *cargo_type_loading;
1656 ReserveCargoAction(Station *st, const CargoStationIDStackSet &next_station, Vehicle *cargo_type_loading) :
1657 st(st), next_station(next_station), cargo_type_loading(cargo_type_loading) {}
1659 bool operator()(Vehicle *v)
1661 if (cargo_type_loading != NULL && !(cargo_type_loading->current_order.GetCargoLoadTypeRaw(v->cargo_type) & OLFB_FULL_LOAD)) return true;
1662 if (v->cargo_cap > v->cargo.RemainingCount()) {
1663 st->goods[v->cargo_type].cargo.Reserve(v->cargo_cap - v->cargo.RemainingCount(),
1664 &v->cargo, st->xy, next_station.Get(v->cargo_type));
1667 return true;
1673 * Reserves cargo if the full load order and improved_load is set or if the
1674 * current order allows autorefit.
1675 * @param st Station where the consist is loading at the moment.
1676 * @param u Front of the loading vehicle consist.
1677 * @param consist_capleft If given, save free capacities after reserving there.
1678 * @param next_station Station(s) the vehicle will stop at next.
1679 * @param cargo_type_loading check cargo-specific loading type
1681 static void ReserveConsist(Station *st, Vehicle *u, CargoArray *consist_capleft, const CargoStationIDStackSet &next_station, bool cargo_type_loading)
1683 /* If there is a cargo payment not all vehicles of the consist have tried to do the refit.
1684 * In that case, only reserve if it's a fixed refit and the equivalent of "articulated chain"
1685 * a vehicle belongs to already has the right cargo. */
1686 bool must_reserve = !u->current_order.IsRefit() || u->cargo_payment == NULL;
1687 for (Vehicle *v = u; v != NULL; v = v->Next()) {
1688 assert(v->cargo_cap >= v->cargo.RemainingCount());
1690 /* Exclude various ways in which the vehicle might not be the head of an equivalent of
1691 * "articulated chain". Also don't do the reservation if the vehicle is going to refit
1692 * to a different cargo and hasn't tried to do so, yet. */
1693 if (!v->IsArticulatedPart() &&
1694 (v->type != VEH_TRAIN || !Train::From(v)->IsRearDualheaded()) &&
1695 (v->type != VEH_AIRCRAFT || Aircraft::From(v)->IsNormalAircraft()) &&
1696 (must_reserve || u->current_order.GetRefitCargo() == v->cargo_type)) {
1697 IterateVehicleParts(v, ReserveCargoAction(st, next_station, cargo_type_loading ? u : NULL));
1699 if (consist_capleft == NULL || v->cargo_cap == 0) continue;
1700 if (cargo_type_loading && !(u->current_order.GetCargoLoadTypeRaw(v->cargo_type) & OLFB_FULL_LOAD)) continue;
1701 (*consist_capleft)[v->cargo_type] += v->cargo_cap - v->cargo.RemainingCount();
1706 * Update the vehicle's load_unload_ticks, the time it will wait until it tries to load or unload
1707 * again. Adjust for overhang of trains and set it at least to 1.
1708 * @param front The vehicle to be updated.
1709 * @param st The station the vehicle is loading at.
1710 * @param ticks The time it would normally wait, based on cargo loaded and unloaded.
1712 static void UpdateLoadUnloadTicks(Vehicle *front, const Station *st, int ticks)
1714 if (front->type == VEH_TRAIN) {
1715 /* Each platform tile is worth 2 rail vehicles. */
1716 int overhang = front->GetGroundVehicleCache()->cached_total_length - st->GetPlatformLength(front->tile) * TILE_SIZE;
1717 if (overhang > 0) {
1718 ticks <<= 1;
1719 ticks += (overhang * ticks) / 8;
1722 /* Always wait at least 1, otherwise we'll wait 'infinitively' long. */
1723 front->load_unload_ticks = max(1, ticks);
1727 * Loads/unload the vehicle if possible.
1728 * @param front the vehicle to be (un)loaded
1730 static void LoadUnloadVehicle(Vehicle *front)
1732 assert(front->current_order.IsType(OT_LOADING));
1734 StationID last_visited = front->last_station_visited;
1735 Station *st = Station::Get(last_visited);
1737 CargoStationIDStackSet next_station = front->GetNextStoppingStation();
1738 bool use_autorefit = front->current_order.IsRefit() && front->current_order.GetRefitCargo() == CT_AUTO_REFIT;
1739 CargoArray consist_capleft;
1740 bool should_reserve_consist = false;
1741 bool reserve_consist_cargo_type_loading = false;
1742 if (_settings_game.order.improved_load && use_autorefit) {
1743 if (front->cargo_payment == NULL) should_reserve_consist = true;
1744 } else {
1745 if ((front->current_order.GetLoadType() & OLFB_FULL_LOAD) || (front->current_order.GetLoadType() == OLFB_CARGO_TYPE_LOAD)) {
1746 should_reserve_consist = true;
1747 reserve_consist_cargo_type_loading = (front->current_order.GetLoadType() == OLFB_CARGO_TYPE_LOAD);
1751 if (should_reserve_consist) {
1752 ReserveConsist(st, front,
1753 (use_autorefit && front->load_unload_ticks != 0) ? &consist_capleft : NULL,
1754 next_station,
1755 reserve_consist_cargo_type_loading);
1758 /* We have not waited enough time till the next round of loading/unloading */
1759 if (front->load_unload_ticks != 0) return;
1761 if (front->type == VEH_TRAIN && (!IsTileType(front->tile, MP_STATION) || GetStationIndex(front->tile) != st->index)) {
1762 /* The train reversed in the station. Take the "easy" way
1763 * out and let the train just leave as it always did. */
1764 SetBit(front->vehicle_flags, VF_LOADING_FINISHED);
1765 front->load_unload_ticks = 1;
1766 return;
1769 int new_load_unload_ticks = 0;
1770 bool dirty_vehicle = false;
1771 bool dirty_station = false;
1773 bool completely_emptied = true;
1774 bool anything_unloaded = false;
1775 bool anything_loaded = false;
1776 uint32 full_load_amount = 0;
1777 uint32 cargo_not_full = 0;
1778 uint32 cargo_full = 0;
1779 uint32 reservation_left = 0;
1781 front->cur_speed = 0;
1783 CargoPayment *payment = front->cargo_payment;
1785 uint artic_part = 0; // Articulated part we are currently trying to load. (not counting parts without capacity)
1786 for (Vehicle *v = front; v != NULL; v = v->Next()) {
1787 if (v == front || !v->Previous()->HasArticulatedPart()) artic_part = 0;
1788 if (v->cargo_cap == 0) continue;
1789 artic_part++;
1791 GoodsEntry *ge = &st->goods[v->cargo_type];
1793 if (HasBit(v->vehicle_flags, VF_CARGO_UNLOADING) && (GetUnloadType(v) & OUFB_NO_UNLOAD) == 0) {
1794 uint cargo_count = v->cargo.UnloadCount();
1795 uint amount_unloaded = _settings_game.order.gradual_loading ? min(cargo_count, GetLoadAmount(v)) : cargo_count;
1796 bool remaining = false; // Are there cargo entities in this vehicle that can still be unloaded here?
1798 assert(payment != NULL);
1799 payment->SetCargo(v->cargo_type);
1801 if (!HasBit(ge->status, GoodsEntry::GES_ACCEPTANCE) && v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER) > 0) {
1802 /* The station does not accept our goods anymore. */
1803 if (GetUnloadType(v) & (OUFB_TRANSFER | OUFB_UNLOAD)) {
1804 /* Transfer instead of delivering. */
1805 v->cargo.Reassign<VehicleCargoList::MTA_DELIVER, VehicleCargoList::MTA_TRANSFER>(
1806 v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER), INVALID_STATION);
1807 } else {
1808 uint new_remaining = v->cargo.RemainingCount() + v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER);
1809 if (v->cargo_cap < new_remaining) {
1810 /* Return some of the reserved cargo to not overload the vehicle. */
1811 v->cargo.Return(new_remaining - v->cargo_cap, &ge->cargo, INVALID_STATION);
1814 /* Keep instead of delivering. This may lead to no cargo being unloaded, so ...*/
1815 v->cargo.Reassign<VehicleCargoList::MTA_DELIVER, VehicleCargoList::MTA_KEEP>(
1816 v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER));
1818 /* ... say we unloaded something, otherwise we'll think we didn't unload
1819 * something and we didn't load something, so we must be finished
1820 * at this station. Setting the unloaded means that we will get a
1821 * retry for loading in the next cycle. *////
1822 anything_unloaded = true;
1826 if (v->cargo.ActionCount(VehicleCargoList::MTA_TRANSFER) > 0) {
1827 /* Mark the station dirty if we transfer, but not if we only deliver. */
1828 dirty_station = true;
1830 if (!ge->HasRating()) {
1831 /* Upon transfering cargo, make sure the station has a rating. Fake a pickup for the
1832 * first unload to prevent the cargo from quickly decaying after the initial drop. */
1833 ge->time_since_pickup = 0;
1834 SetBit(ge->status, GoodsEntry::GES_RATING);
1838 amount_unloaded = v->cargo.Unload(amount_unloaded, &ge->cargo, payment);
1839 remaining = v->cargo.UnloadCount() > 0;
1840 if (amount_unloaded > 0) {
1841 dirty_vehicle = true;
1842 anything_unloaded = true;
1843 new_load_unload_ticks += amount_unloaded;
1845 /* Deliver goods to the station */
1846 st->time_since_unload = 0;
1849 if (_settings_game.order.gradual_loading && remaining) {
1850 completely_emptied = false;
1851 } else {
1852 /* We have finished unloading (cargo count == 0) */
1853 ClrBit(v->vehicle_flags, VF_CARGO_UNLOADING);
1856 continue;
1859 /* Do not pick up goods when we have no-load set or loading is stopped. */
1860 if (GetLoadType(v) & OLFB_NO_LOAD || HasBit(front->vehicle_flags, VF_STOP_LOADING)) continue;
1862 /* This order has a refit, if this is the first vehicle part carrying cargo and the whole vehicle is empty, try refitting. */
1863 if (front->current_order.IsRefit() && artic_part == 1) {
1864 HandleStationRefit(v, consist_capleft, st, next_station, front->current_order.GetRefitCargo());
1865 ge = &st->goods[v->cargo_type];
1868 /* As we're loading here the following link can carry the full capacity of the vehicle. */
1869 v->refit_cap = v->cargo_cap;
1871 /* update stats */
1872 int t;
1873 switch (front->type) {
1874 case VEH_TRAIN:
1875 t = front->GetDisplayMaxSpeed();
1876 break;
1878 case VEH_SHIP:
1879 t = front->GetDisplayMaxSpeed() * 4;
1880 break;
1882 case VEH_ROAD:
1883 t = front->GetDisplayMaxSpeed() * 2;
1884 break;
1886 case VEH_AIRCRAFT:
1887 t = Aircraft::From(front)->GetSpeedOldUnits() * 2; // Convert to old units.
1888 break;
1890 default: NOT_REACHED();
1893 /* if last speed is 0, we treat that as if no vehicle has ever visited the station. */
1894 ge->last_speed = min(t, 255);
1895 ge->last_unprocessed_speed = front->GetDisplayMaxSpeed();
1896 ge->last_vehicle_type = front->type;
1897 ge->last_age = min(_cur_year - front->build_year, 255);
1898 ge->time_since_pickup = 0;
1900 assert(v->cargo_cap >= v->cargo.StoredCount());
1901 /* If there's goods waiting at the station, and the vehicle
1902 * has capacity for it, load it on the vehicle. */
1903 uint cap_left = v->cargo_cap - v->cargo.StoredCount();
1904 if (cap_left > 0 && (v->cargo.ActionCount(VehicleCargoList::MTA_LOAD) > 0 || ge->cargo.AvailableCount() > 0)) {
1905 if (v->cargo.StoredCount() == 0) TriggerVehicle(v, VEHICLE_TRIGGER_NEW_CARGO);
1906 if (_settings_game.order.gradual_loading) cap_left = min(cap_left, GetLoadAmount(v));
1908 uint loaded = ge->cargo.Load(cap_left, &v->cargo, st->xy, next_station.Get(v->cargo_type));
1909 if (v->cargo.ActionCount(VehicleCargoList::MTA_LOAD) > 0) {
1910 /* Remember if there are reservations left so that we don't stop
1911 * loading before they're loaded. */
1912 SetBit(reservation_left, v->cargo_type);
1915 /* Store whether the maximum possible load amount was loaded or not.*/
1916 if (loaded == cap_left) {
1917 SetBit(full_load_amount, v->cargo_type);
1918 } else {
1919 ClrBit(full_load_amount, v->cargo_type);
1922 /* TODO: Regarding this, when we do gradual loading, we
1923 * should first unload all vehicles and then start
1924 * loading them. Since this will cause
1925 * VEHICLE_TRIGGER_EMPTY to be called at the time when
1926 * the whole vehicle chain is really totally empty, the
1927 * completely_emptied assignment can then be safely
1928 * removed; that's how TTDPatch behaves too. --pasky */
1929 if (loaded > 0) {
1930 completely_emptied = false;
1931 anything_loaded = true;
1933 st->time_since_load = 0;
1934 st->last_vehicle_type = v->type;
1936 if (ge->cargo.TotalCount() == 0) {
1937 TriggerStationRandomisation(st, st->xy, SRT_CARGO_TAKEN, v->cargo_type);
1938 TriggerStationAnimation(st, st->xy, SAT_CARGO_TAKEN, v->cargo_type);
1939 AirportAnimationTrigger(st, AAT_STATION_CARGO_TAKEN, v->cargo_type);
1942 new_load_unload_ticks += loaded;
1944 dirty_vehicle = dirty_station = true;
1948 if (v->cargo.StoredCount() >= v->cargo_cap) {
1949 SetBit(cargo_full, v->cargo_type);
1950 } else {
1951 SetBit(cargo_not_full, v->cargo_type);
1955 if (anything_loaded || anything_unloaded) {
1956 if (front->type == VEH_TRAIN) {
1957 TriggerStationRandomisation(st, front->tile, SRT_TRAIN_LOADS);
1958 TriggerStationAnimation(st, front->tile, SAT_TRAIN_LOADS);
1962 /* Only set completely_emptied, if we just unloaded all remaining cargo */
1963 completely_emptied &= anything_unloaded;
1965 if (!anything_unloaded) delete payment;
1967 ClrBit(front->vehicle_flags, VF_STOP_LOADING);
1969 bool has_full_load_order = front->current_order.GetLoadType() & OLFB_FULL_LOAD;
1971 if (front->current_order.GetLoadType() == OLFB_CARGO_TYPE_LOAD) {
1972 for (Vehicle *v = front; v != NULL; v = v->Next()) {
1973 if (front->current_order.GetCargoLoadTypeRaw(v->cargo_type) & OLFB_FULL_LOAD) {
1974 has_full_load_order = true;
1975 break;
1980 if (anything_loaded || anything_unloaded) {
1981 if (_settings_game.order.gradual_loading) {
1982 /* The time it takes to load one 'slice' of cargo or passengers depends
1983 * on the vehicle type - the values here are those found in TTDPatch */
1984 const uint gradual_loading_wait_time[] = { 40, 20, 10, 20 };
1986 new_load_unload_ticks = gradual_loading_wait_time[front->type];
1988 /* We loaded less cargo than possible for all cargo types and it's not full
1989 * load and we're not supposed to wait any longer: stop loading. */
1990 if (!anything_unloaded && full_load_amount == 0 && reservation_left == 0 && !has_full_load_order &&
1991 front->current_order_time >= (uint)max(front->current_order.GetTimetabledWait() - front->lateness_counter, 0)) {
1992 SetBit(front->vehicle_flags, VF_STOP_LOADING);
1995 UpdateLoadUnloadTicks(front, st, new_load_unload_ticks);
1996 } else {
1997 UpdateLoadUnloadTicks(front, st, 20); // We need the ticks for link refreshing.
1998 bool finished_loading = true;
1999 if (has_full_load_order) {
2000 if (front->current_order.GetLoadType() == OLF_FULL_LOAD_ANY) {
2001 /* if the aircraft carries passengers and is NOT full, then
2002 * continue loading, no matter how much mail is in */
2003 if ((front->type == VEH_AIRCRAFT && IsCargoInClass(front->cargo_type, CC_PASSENGERS) && front->cargo_cap > front->cargo.StoredCount()) ||
2004 (cargo_not_full && (cargo_full & ~cargo_not_full) == 0)) { // There are still non-full cargoes
2005 finished_loading = false;
2007 } else if (front->current_order.GetLoadType() == OLFB_CARGO_TYPE_LOAD) {
2008 for (Vehicle *v = front; v != NULL; v = v->Next()) {
2009 if ((front->current_order.GetCargoLoadTypeRaw(v->cargo_type) & OLFB_FULL_LOAD) && HasBit(cargo_not_full, v->cargo_type)) {
2010 finished_loading = false;
2011 break;
2014 } else if (cargo_not_full != 0) {
2015 finished_loading = false;
2018 /* Refresh next hop stats if we're full loading to make the links
2019 * known to the distribution algorithm and allow cargo to be sent
2020 * along them. Otherwise the vehicle could wait for cargo
2021 * indefinitely if it hasn't visited the other links yet, or if the
2022 * links die while it's loading. */
2023 if (!finished_loading) LinkRefresher::Run(front, true, true);
2026 SB(front->vehicle_flags, VF_LOADING_FINISHED, 1, finished_loading);
2029 /* Calculate the loading indicator fill percent and display
2030 * In the Game Menu do not display indicators
2031 * If _settings_client.gui.loading_indicators == 2, show indicators (bool can be promoted to int as 0 or 1 - results in 2 > 0,1 )
2032 * if _settings_client.gui.loading_indicators == 1, _local_company must be the owner or must be a spectator to show ind., so 1 > 0
2033 * if _settings_client.gui.loading_indicators == 0, do not display indicators ... 0 is never greater than anything
2035 if (_game_mode != GM_MENU && (_settings_client.gui.loading_indicators > (uint)(front->owner != _local_company && _local_company != COMPANY_SPECTATOR))) {
2036 StringID percent_up_down = STR_NULL;
2037 int percent = CalcPercentVehicleFilled(front, &percent_up_down);
2038 if (front->fill_percent_te_id == INVALID_TE_ID) {
2039 front->fill_percent_te_id = ShowFillingPercent(front->x_pos, front->y_pos, front->z_pos + 20, percent, percent_up_down);
2040 } else {
2041 UpdateFillingPercent(front->fill_percent_te_id, percent, percent_up_down);
2045 if (completely_emptied) {
2046 /* Make sure the vehicle is marked dirty, since we need to update the NewGRF
2047 * properties such as weight, power and TE whenever the trigger runs. */
2048 dirty_vehicle = true;
2049 TriggerVehicle(front, VEHICLE_TRIGGER_EMPTY);
2052 if (dirty_vehicle) {
2053 SetWindowDirty(GetWindowClassForVehicleType(front->type), front->owner);
2054 SetWindowDirty(WC_VEHICLE_DETAILS, front->index);
2055 front->MarkDirty();
2057 if (dirty_station) {
2058 st->MarkTilesDirty(true);
2059 SetWindowDirty(WC_STATION_VIEW, last_visited);
2060 InvalidateWindowData(WC_STATION_LIST, last_visited);
2065 * Load/unload the vehicles in this station according to the order
2066 * they entered.
2067 * @param st the station to do the loading/unloading for
2069 void LoadUnloadStation(Station *st)
2071 /* No vehicle is here... */
2072 if (st->loading_vehicles.empty()) return;
2074 Vehicle *last_loading = NULL;
2076 /* Check if anything will be loaded at all. Otherwise we don't need to reserve either. */
2077 for (Vehicle *v : st->loading_vehicles) {
2078 if ((v->vehstatus & (VS_STOPPED | VS_CRASHED))) continue;
2080 assert(v->load_unload_ticks != 0);
2081 if (--v->load_unload_ticks == 0) last_loading = v;
2084 /* We only need to reserve and load/unload up to the last loading vehicle.
2085 * Anything else will be forgotten anyway after returning from this function.
2087 * Especially this means we do _not_ need to reserve cargo for a single
2088 * consist in a station which is not allowed to load yet because its
2089 * load_unload_ticks is still not 0.
2091 if (last_loading == NULL) return;
2093 for (Vehicle *v : st->loading_vehicles) {
2094 if (!(v->vehstatus & (VS_STOPPED | VS_CRASHED))) LoadUnloadVehicle(v);
2095 if (v == last_loading) break;
2098 /* Call the production machinery of industries */
2099 const Industry * const *isend = _cargo_delivery_destinations.End();
2100 for (Industry **iid = _cargo_delivery_destinations.Begin(); iid != isend; iid++) {
2101 TriggerIndustryProduction(*iid);
2103 _cargo_delivery_destinations.Clear();
2107 * Monthly update of the economic data (of the companies as well as economic fluctuations).
2109 void CompaniesMonthlyLoop()
2111 CompaniesGenStatistics();
2112 if (_settings_game.economy.inflation) {
2113 AddInflation();
2114 RecomputePrices();
2116 CompaniesPayInterest();
2117 HandleEconomyFluctuations();
2120 static void DoAcquireCompany(Company *c)
2122 CompanyID ci = c->index;
2124 CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
2125 cni->FillData(c, Company::Get(_current_company));
2127 SetDParam(0, STR_NEWS_COMPANY_MERGER_TITLE);
2128 SetDParam(1, c->bankrupt_value == 0 ? STR_NEWS_MERGER_TAKEOVER_TITLE : STR_NEWS_COMPANY_MERGER_DESCRIPTION);
2129 SetDParamStr(2, cni->company_name);
2130 SetDParamStr(3, cni->other_company_name);
2131 SetDParam(4, c->bankrupt_value);
2132 AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, cni);
2133 AI::BroadcastNewEvent(new ScriptEventCompanyMerger(ci, _current_company));
2134 Game::NewEvent(new ScriptEventCompanyMerger(ci, _current_company));
2136 ChangeOwnershipOfCompanyItems(ci, _current_company);
2138 if (c->bankrupt_value == 0) {
2139 Company *owner = Company::Get(_current_company);
2140 owner->current_loan += c->current_loan;
2143 if (c->is_ai) AI::Stop(c->index);
2145 DeleteCompanyWindows(ci);
2146 InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
2147 InvalidateWindowClassesData(WC_SHIPS_LIST, 0);
2148 InvalidateWindowClassesData(WC_ROADVEH_LIST, 0);
2149 InvalidateWindowClassesData(WC_AIRCRAFT_LIST, 0);
2151 delete c;
2154 extern int GetAmountOwnedBy(const Company *c, Owner owner);
2157 * Acquire shares in an opposing company.
2158 * @param tile unused
2159 * @param flags type of operation
2160 * @param p1 company to buy the shares from
2161 * @param p2 unused
2162 * @param text unused
2163 * @return the cost of this operation or an error
2165 CommandCost CmdBuyShareInCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2167 CommandCost cost(EXPENSES_OTHER);
2168 CompanyID target_company = (CompanyID)p1;
2169 Company *c = Company::GetIfValid(target_company);
2171 /* Check if buying shares is allowed (protection against modified clients)
2172 * Cannot buy own shares */
2173 if (c == NULL || !_settings_game.economy.allow_shares || _current_company == target_company) return CMD_ERROR;
2175 /* Protect new companies from hostile takeovers */
2176 if (_cur_year - c->inaugurated_year < 6) return_cmd_error(STR_ERROR_PROTECTED);
2178 /* Those lines are here for network-protection (clients can be slow) */
2179 if (GetAmountOwnedBy(c, COMPANY_SPECTATOR) == 0) return cost;
2181 if (GetAmountOwnedBy(c, COMPANY_SPECTATOR) == 1) {
2182 if (!c->is_ai) return cost; // We can not buy out a real company (temporarily). TODO: well, enable it obviously.
2184 if (GetAmountOwnedBy(c, _current_company) == 3 && !MayCompanyTakeOver(_current_company, target_company)) return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
2188 cost.AddCost(CalculateCompanyValue(c) >> 2);
2189 if (flags & DC_EXEC) {
2190 OwnerByte *b = c->share_owners;
2192 while (*b != COMPANY_SPECTATOR) b++; // share owners is guaranteed to contain at least one COMPANY_SPECTATOR
2193 *b = _current_company;
2195 for (int i = 0; c->share_owners[i] == _current_company;) {
2196 if (++i == 4) {
2197 c->bankrupt_value = 0;
2198 DoAcquireCompany(c);
2199 break;
2202 InvalidateWindowData(WC_COMPANY, target_company);
2203 CompanyAdminUpdate(c);
2205 return cost;
2209 * Sell shares in an opposing company.
2210 * @param tile unused
2211 * @param flags type of operation
2212 * @param p1 company to sell the shares from
2213 * @param p2 unused
2214 * @param text unused
2215 * @return the cost of this operation or an error
2217 CommandCost CmdSellShareInCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2219 CompanyID target_company = (CompanyID)p1;
2220 Company *c = Company::GetIfValid(target_company);
2222 /* Cannot sell own shares */
2223 if (c == NULL || _current_company == target_company) return CMD_ERROR;
2225 /* Check if selling shares is allowed (protection against modified clients).
2226 * However, we must sell shares of companies being closed down. */
2227 if (!_settings_game.economy.allow_shares && !(flags & DC_BANKRUPT)) return CMD_ERROR;
2229 /* Those lines are here for network-protection (clients can be slow) */
2230 if (GetAmountOwnedBy(c, _current_company) == 0) return CommandCost();
2232 /* adjust it a little to make it less profitable to sell and buy */
2233 Money cost = CalculateCompanyValue(c) >> 2;
2234 cost = -(cost - (cost >> 7));
2236 if (flags & DC_EXEC) {
2237 OwnerByte *b = c->share_owners;
2238 while (*b != _current_company) b++; // share owners is guaranteed to contain company
2239 *b = COMPANY_SPECTATOR;
2240 InvalidateWindowData(WC_COMPANY, target_company);
2241 CompanyAdminUpdate(c);
2243 return CommandCost(EXPENSES_OTHER, cost);
2247 * Buy up another company.
2248 * When a competing company is gone bankrupt you get the chance to purchase
2249 * that company.
2250 * @todo currently this only works for AI companies
2251 * @param tile unused
2252 * @param flags type of operation
2253 * @param p1 company to buy up
2254 * @param p2 unused
2255 * @param text unused
2256 * @return the cost of this operation or an error
2258 CommandCost CmdBuyCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2260 CompanyID target_company = (CompanyID)p1;
2261 Company *c = Company::GetIfValid(target_company);
2262 if (c == NULL) return CMD_ERROR;
2264 /* Disable takeovers when not asked */
2265 if (!HasBit(c->bankrupt_asked, _current_company)) return CMD_ERROR;
2267 /* Disable taking over the local company in single player */
2268 if (!_networking && _local_company == c->index) return CMD_ERROR;
2270 /* Do not allow companies to take over themselves */
2271 if (target_company == _current_company) return CMD_ERROR;
2273 /* Disable taking over when not allowed. */
2274 if (!MayCompanyTakeOver(_current_company, target_company)) return CMD_ERROR;
2276 /* Get the cost here as the company is deleted in DoAcquireCompany. */
2277 CommandCost cost(EXPENSES_OTHER, c->bankrupt_value);
2279 if (flags & DC_EXEC) {
2280 DoAcquireCompany(c);
2282 return cost;