Add support for deleted functions
[openttd/fttd.git] / src / economy.cpp
blob7d10d42b7f86d8546af4452775f1a48bf73a5a52
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 "newgrf_engine.h"
23 #include "engine_base.h"
24 #include "ground_vehicle.hpp"
25 #include "newgrf_cargo.h"
26 #include "newgrf_sound.h"
27 #include "newgrf_industrytiles.h"
28 #include "newgrf_station.h"
29 #include "newgrf_airporttiles.h"
30 #include "object.h"
31 #include "strings_func.h"
32 #include "date_func.h"
33 #include "vehicle_func.h"
34 #include "signal_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 "economy_base.h"
44 #include "core/pool_func.hpp"
45 #include "core/backup_type.hpp"
46 #include "cargo_type.h"
47 #include "water.h"
48 #include "game/game.hpp"
49 #include "cargomonitor.h"
50 #include "goal_base.h"
51 #include "story_base.h"
52 #include "linkgraph/refresh.h"
54 #include "table/strings.h"
55 #include "table/pricebase.h"
58 /* Initialize the cargo payment-pool */
59 CargoPaymentPool _cargo_payment_pool("CargoPayment");
60 INSTANTIATE_POOL_METHODS(CargoPayment)
62 /**
63 * Multiply two integer values and shift the results to right.
65 * This function multiplies two integer values. The result is
66 * shifted by the amount of shift to right.
68 * @param a The first integer
69 * @param b The second integer
70 * @param shift The amount to shift the value to right.
71 * @return The shifted result
73 static inline int32 BigMulS(const int32 a, const int32 b, const uint8 shift)
75 return (int32)((int64)a * (int64)b >> shift);
78 typedef SmallVector<Industry *, 16> SmallIndustryList;
80 /**
81 * Score info, values used for computing the detailed performance rating.
83 const ScoreInfo _score_info[] = {
84 { 120, 100}, // SCORE_VEHICLES
85 { 80, 100}, // SCORE_STATIONS
86 { 10000, 100}, // SCORE_MIN_PROFIT
87 { 50000, 50}, // SCORE_MIN_INCOME
88 { 100000, 100}, // SCORE_MAX_INCOME
89 { 40000, 400}, // SCORE_DELIVERED
90 { 8, 50}, // SCORE_CARGO
91 {10000000, 50}, // SCORE_MONEY
92 { 250000, 50}, // SCORE_LOAN
93 { 0, 0} // SCORE_TOTAL
96 int _score_part[MAX_COMPANIES][SCORE_END];
97 Economy _economy;
98 Prices _price;
99 Money _additional_cash_required;
100 static PriceMultipliers _price_base_multiplier;
103 * Calculate the value of the company. That is the value of all
104 * assets (vehicles, stations, etc) and money minus the loan,
105 * except when including_loan is \c false which is useful when
106 * we want to calculate the value for bankruptcy.
107 * @param c the company to get the value of.
108 * @param including_loan include the loan in the company value.
109 * @return the value of the company.
111 Money CalculateCompanyValue(const Company *c, bool including_loan)
113 Owner owner = c->index;
115 Station *st;
116 uint num = 0;
118 FOR_ALL_STATIONS(st) {
119 if (st->owner == owner) num += CountBits((byte)st->facilities);
122 Money value = num * _price[PR_STATION_VALUE] * 25;
124 Vehicle *v;
125 FOR_ALL_VEHICLES(v) {
126 if (v->owner != owner) continue;
128 if (v->type == VEH_TRAIN ||
129 v->type == VEH_ROAD ||
130 (v->type == VEH_AIRCRAFT && Aircraft::From(v)->IsNormalAircraft()) ||
131 v->type == VEH_SHIP) {
132 value += v->value * 3 >> 1;
136 /* Add real money value */
137 if (including_loan) value -= c->current_loan;
138 value += c->money;
140 return max(value, (Money)1);
144 * if update is set to true, the economy is updated with this score
145 * (also the house is updated, should only be true in the on-tick event)
146 * @param update the economy with calculated score
147 * @param c company been evaluated
148 * @return actual score of this company
151 int UpdateCompanyRatingAndValue(Company *c, bool update)
153 Owner owner = c->index;
154 int score = 0;
156 memset(_score_part[owner], 0, sizeof(_score_part[owner]));
158 /* Count vehicles */
160 Vehicle *v;
161 Money min_profit = 0;
162 bool min_profit_first = true;
163 uint num = 0;
165 FOR_ALL_VEHICLES(v) {
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] = ClampToI32(min_profit);
188 /* Count stations */
190 uint num = 0;
191 const Station *st;
193 FOR_ALL_STATIONS(st) {
194 /* Only count stations that are actually serviced */
195 if (st->owner == owner && (st->time_since_load <= 20 || st->time_since_unload <= 20)) num += CountBits((byte)st->facilities);
197 _score_part[owner][SCORE_STATIONS] = num;
200 /* Generate statistics depending on recent income statistics */
202 int numec = min(c->num_valid_stat_ent, 12);
203 if (numec != 0) {
204 const CompanyEconomyEntry *cee = c->old_economy;
205 Money min_income = cee->income + cee->expenses;
206 Money max_income = cee->income + cee->expenses;
208 do {
209 min_income = min(min_income, cee->income + cee->expenses);
210 max_income = max(max_income, cee->income + cee->expenses);
211 } while (++cee, --numec);
213 if (min_income > 0) {
214 _score_part[owner][SCORE_MIN_INCOME] = ClampToI32(min_income);
217 _score_part[owner][SCORE_MAX_INCOME] = ClampToI32(max_income);
221 /* Generate score depending on amount of transported cargo */
223 int numec = min(c->num_valid_stat_ent, 4);
224 if (numec != 0) {
225 const CompanyEconomyEntry *cee = c->old_economy;
226 OverflowSafeInt64 total_delivered = 0;
227 do {
228 total_delivered += cee->delivered_cargo.GetSum<OverflowSafeInt64>();
229 } while (++cee, --numec);
231 _score_part[owner][SCORE_DELIVERED] = ClampToI32(total_delivered);
235 /* Generate score for variety of cargo */
237 _score_part[owner][SCORE_CARGO] = c->old_economy->delivered_cargo.GetCount();
240 /* Generate score for company's money */
242 if (c->money > 0) {
243 _score_part[owner][SCORE_MONEY] = ClampToI32(c->money);
247 /* Generate score for loan */
249 _score_part[owner][SCORE_LOAN] = ClampToI32(_score_info[SCORE_LOAN].needed - c->current_loan);
252 /* Now we calculate the score for each item.. */
254 int total_score = 0;
255 int s;
256 score = 0;
257 for (ScoreID i = SCORE_BEGIN; i < SCORE_END; i++) {
258 /* Skip the total */
259 if (i == SCORE_TOTAL) continue;
260 /* Check the score */
261 s = Clamp(_score_part[owner][i], 0, _score_info[i].needed) * _score_info[i].score / _score_info[i].needed;
262 score += s;
263 total_score += _score_info[i].score;
266 _score_part[owner][SCORE_TOTAL] = score;
268 /* We always want the score scaled to SCORE_MAX (1000) */
269 if (total_score != SCORE_MAX) score = score * SCORE_MAX / total_score;
272 if (update) {
273 c->old_economy[0].performance_history = score;
274 UpdateCompanyHQ(c->location_of_HQ, score);
275 c->old_economy[0].company_value = CalculateCompanyValue(c);
278 SetWindowDirty(WC_PERFORMANCE_DETAIL, 0);
279 return score;
283 * Change the ownership of all the items of a company.
284 * @param old_owner The company that gets removed.
285 * @param new_owner The company to merge to, or INVALID_OWNER to remove the company.
287 void ChangeOwnershipOfCompanyItems(Owner old_owner, Owner new_owner)
289 /* We need to set _current_company to old_owner before we try to move
290 * the client. This is needed as it needs to know whether "you" really
291 * are the current local company. */
292 Backup<CompanyByte> cur_company(_current_company, old_owner, FILE_LINE);
293 #ifdef ENABLE_NETWORK
294 /* In all cases, make spectators of clients connected to that company */
295 if (_networking) NetworkClientsToSpectators(old_owner);
296 #endif /* ENABLE_NETWORK */
297 if (old_owner == _local_company) {
298 /* Single player cheated to AI company.
299 * There are no spectators in single player, so we must pick some other company. */
300 assert(!_networking);
301 Backup<CompanyByte> cur_company(_current_company, FILE_LINE);
302 Company *c;
303 FOR_ALL_COMPANIES(c) {
304 if (c->index != old_owner) {
305 SetLocalCompany(c->index);
306 break;
309 cur_company.Restore();
310 assert(old_owner != _local_company);
313 Town *t;
315 assert(old_owner != new_owner);
318 Company *c;
319 uint i;
321 /* See if the old_owner had shares in other companies */
322 FOR_ALL_COMPANIES(c) {
323 for (i = 0; i < 4; i++) {
324 if (c->share_owners[i] == old_owner) {
325 /* Sell his shares */
326 CommandCost res = DoCommand(0, c->index, 0, DC_EXEC | DC_BANKRUPT, CMD_SELL_SHARE_IN_COMPANY);
327 /* Because we are in a DoCommand, we can't just execute another one and
328 * expect the money to be removed. We need to do it ourself! */
329 SubtractMoneyFromCompany(res);
334 /* Sell all the shares that people have on this company */
335 Backup<CompanyByte> cur_company2(_current_company, FILE_LINE);
336 c = Company::Get(old_owner);
337 for (i = 0; i < 4; i++) {
338 cur_company2.Change(c->share_owners[i]);
339 if (_current_company != INVALID_OWNER) {
340 /* Sell the shares */
341 CommandCost res = DoCommand(0, old_owner, 0, DC_EXEC | DC_BANKRUPT, CMD_SELL_SHARE_IN_COMPANY);
342 /* Because we are in a DoCommand, we can't just execute another one and
343 * expect the money to be removed. We need to do it ourself! */
344 SubtractMoneyFromCompany(res);
347 cur_company2.Restore();
350 /* Temporarily increase the company's money, to be sure that
351 * removing his/her property doesn't fail because of lack of money.
352 * Not too drastically though, because it could overflow */
353 if (new_owner == INVALID_OWNER) {
354 Company::Get(old_owner)->money = UINT64_MAX >> 2; // jackpot ;p
357 Subsidy *s;
358 FOR_ALL_SUBSIDIES(s) {
359 if (s->awarded == old_owner) {
360 if (new_owner == INVALID_OWNER) {
361 delete s;
362 } else {
363 s->awarded = new_owner;
367 if (new_owner == INVALID_OWNER) RebuildSubsidisedSourceAndDestinationCache();
369 /* Take care of rating and transport rights in towns */
370 FOR_ALL_TOWNS(t) {
371 /* If a company takes over, give the ratings to that company. */
372 if (new_owner != INVALID_OWNER) {
373 if (HasBit(t->have_ratings, old_owner)) {
374 if (HasBit(t->have_ratings, new_owner)) {
375 /* use max of the two ratings. */
376 t->ratings[new_owner] = max(t->ratings[new_owner], t->ratings[old_owner]);
377 } else {
378 SetBit(t->have_ratings, new_owner);
379 t->ratings[new_owner] = t->ratings[old_owner];
384 /* Reset the ratings for the old owner */
385 t->ratings[old_owner] = RATING_INITIAL;
386 ClrBit(t->have_ratings, old_owner);
388 /* Transfer exclusive rights */
389 if (t->exclusive_counter > 0 && t->exclusivity == old_owner) {
390 if (new_owner != INVALID_OWNER) {
391 t->exclusivity = new_owner;
392 } else {
393 t->exclusive_counter = 0;
394 t->exclusivity = INVALID_COMPANY;
400 Vehicle *v;
401 FOR_ALL_VEHICLES(v) {
402 if (v->owner == old_owner && IsCompanyBuildableVehicleType(v->type)) {
403 if (new_owner == INVALID_OWNER) {
404 if (v->Previous() == NULL) delete v;
405 } else {
406 if (v->IsEngineCountable()) GroupStatistics::CountEngine(v, -1);
407 if (v->IsPrimaryVehicle()) GroupStatistics::CountVehicle(v, -1);
413 /* In all cases clear replace engine rules.
414 * Even if it was copied, it could interfere with new owner's rules */
415 RemoveAllEngineReplacementForCompany(Company::Get(old_owner));
417 if (new_owner == INVALID_OWNER) {
418 RemoveAllGroupsForCompany(old_owner);
419 } else {
420 Group *g;
421 FOR_ALL_GROUPS(g) {
422 if (g->owner == old_owner) g->owner = new_owner;
427 FreeUnitIDGenerator unitidgen[] = {
428 FreeUnitIDGenerator(VEH_TRAIN, new_owner), FreeUnitIDGenerator(VEH_ROAD, new_owner),
429 FreeUnitIDGenerator(VEH_SHIP, new_owner), FreeUnitIDGenerator(VEH_AIRCRAFT, new_owner)
432 Vehicle *v;
433 FOR_ALL_VEHICLES(v) {
434 if (v->owner == old_owner && IsCompanyBuildableVehicleType(v->type)) {
435 assert(new_owner != INVALID_OWNER);
437 v->owner = new_owner;
439 /* Owner changes, clear cache */
440 v->colourmap = PAL_NONE;
441 v->InvalidateNewGRFCache();
443 if (v->IsEngineCountable()) {
444 GroupStatistics::CountEngine(v, 1);
446 if (v->IsPrimaryVehicle()) {
447 GroupStatistics::CountVehicle(v, 1);
448 v->unitnumber = unitidgen[v->type].NextID();
451 /* Invalidate the vehicle's cargo payment "owner cache". */
452 if (v->cargo_payment != NULL) v->cargo_payment->owner = NULL;
456 if (new_owner != INVALID_OWNER) GroupStatistics::UpdateAutoreplace(new_owner);
459 /* Change ownership of tiles */
461 TileIndex tile = 0;
462 do {
463 ChangeTileOwner(tile, old_owner, new_owner);
464 } while (++tile != MapSize());
466 if (new_owner != INVALID_OWNER) {
467 /* Update all signals because there can be new segment that was owned by two companies
468 * and signals were not propagated
469 * Similar with crossings - it is needed to bar crossings that weren't before
470 * because of different owner of crossing and approaching train */
471 tile = 0;
473 do {
474 if (IsRailwayTile(tile) && IsTileOwner(tile, new_owner)) {
475 TrackBits tracks = GetTrackBits(tile);
476 do { // there may be two tracks with signals for TRACK_BIT_HORZ and TRACK_BIT_VERT
477 Track track = RemoveFirstTrack(&tracks);
478 if (HasSignalOnTrack(tile, track)) AddTrackToSignalBuffer(tile, track, new_owner);
479 } while (tracks != TRACK_BIT_NONE);
480 } else if (IsLevelCrossingTile(tile) && IsTileOwner(tile, new_owner)) {
481 UpdateLevelCrossing(tile);
483 } while (++tile != MapSize());
486 /* update signals in buffer */
487 UpdateSignalsInBuffer();
490 /* Add airport infrastructure count of the old company to the new one. */
491 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.airport += Company::Get(old_owner)->infrastructure.airport;
493 /* convert owner of stations (including deleted ones, but excluding buoys) */
494 Station *st;
495 FOR_ALL_STATIONS(st) {
496 if (st->owner == old_owner) {
497 /* if a company goes bankrupt, set owner to OWNER_NONE so the sign doesn't disappear immediately
498 * also, drawing station window would cause reading invalid company's colour */
499 st->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner;
503 /* do the same for waypoints (we need to do this here so deleted waypoints are converted too) */
504 Waypoint *wp;
505 FOR_ALL_WAYPOINTS(wp) {
506 if (wp->owner == old_owner) {
507 wp->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner;
511 Sign *si;
512 FOR_ALL_SIGNS(si) {
513 if (si->owner == old_owner) si->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner;
516 /* Remove Game Script created Goals, CargoMonitors and Story pages. */
517 Goal *g;
518 FOR_ALL_GOALS(g) {
519 if (g->company == old_owner) delete g;
522 ClearCargoPickupMonitoring(old_owner);
523 ClearCargoDeliveryMonitoring(old_owner);
525 StoryPage *sp;
526 FOR_ALL_STORY_PAGES(sp) {
527 if (sp->company == old_owner) delete sp;
530 /* Change colour of existing windows */
531 if (new_owner != INVALID_OWNER) ChangeWindowOwner(old_owner, new_owner);
533 cur_company.Restore();
535 MarkWholeScreenDirty();
539 * Check for bankruptcy of a company. Called every three months.
540 * @param c Company to check.
542 static void CompanyCheckBankrupt(Company *c)
544 /* If the company has money again, it does not go bankrupt */
545 if (c->money - c->current_loan >= -_economy.max_loan) {
546 c->months_of_bankruptcy = 0;
547 c->bankrupt_asked = 0;
548 return;
551 c->months_of_bankruptcy++;
553 switch (c->months_of_bankruptcy) {
554 /* All the boring cases (months) with a bad balance where no action is taken */
555 case 0:
556 case 1:
557 case 2:
558 case 3:
560 case 5:
561 case 6:
563 case 8:
564 case 9:
565 break;
567 /* Warn about bankruptcy after 3 months */
568 case 4: {
569 CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
570 cni->FillData(c);
571 SetDParam(0, STR_NEWS_COMPANY_IN_TROUBLE_TITLE);
572 SetDParam(1, STR_NEWS_COMPANY_IN_TROUBLE_DESCRIPTION);
573 SetDParamStr(2, cni->company_name);
574 AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, cni);
575 AI::BroadcastNewEvent(new ScriptEventCompanyInTrouble(c->index));
576 Game::NewEvent(new ScriptEventCompanyInTrouble(c->index));
577 break;
580 /* Offer company for sale after 6 months */
581 case 7: {
582 /* Don't consider the loan */
583 Money val = CalculateCompanyValue(c, false);
585 c->bankrupt_value = val;
586 c->bankrupt_asked = 1 << c->index; // Don't ask the owner
587 c->bankrupt_timeout = 0;
589 /* The company assets should always have some value */
590 assert(c->bankrupt_value > 0);
591 break;
594 /* Bankrupt company after 6 months (if the company has no value) or latest
595 * after 9 months (if it still had value after 6 months) */
596 default:
597 case 10: {
598 if (!_networking && _local_company == c->index) {
599 /* If we are in offline mode, leave the company playing. Eg. there
600 * is no THE-END, otherwise mark the client as spectator to make sure
601 * he/she is no long in control of this company. However... when you
602 * join another company (cheat) the "unowned" company can bankrupt. */
603 c->bankrupt_asked = MAX_UVALUE(CompanyMask);
604 break;
607 /* Actually remove the company, but not when we're a network client.
608 * In case of network clients we will be getting a command from the
609 * server. It is done in this way as we are called from the
610 * StateGameLoop which can't change the current company, and thus
611 * updating the local company triggers an assert later on. In the
612 * case of a network game the command will be processed at a time
613 * that changing the current company is okay. In case of single
614 * player we are sure (the above check) that we are not the local
615 * company and thus we won't be moved. */
616 if (!_networking || _network_server) DoCommandP(0, 2 | (c->index << 16), CRR_BANKRUPT, CMD_COMPANY_CTRL);
617 break;
623 * Update the finances of all companies.
624 * Pay for the stations, update the history graph, update ratings and company values, and deal with bankruptcy.
626 static void CompaniesGenStatistics()
628 Station *st;
630 Backup<CompanyByte> cur_company(_current_company, FILE_LINE);
631 Company *c;
633 if (!_settings_game.economy.infrastructure_maintenance) {
634 FOR_ALL_STATIONS(st) {
635 cur_company.Change(st->owner);
636 CommandCost cost(EXPENSES_PROPERTY, _price[PR_STATION_VALUE] >> 1);
637 SubtractMoneyFromCompany(cost);
639 } else {
640 /* Improved monthly infrastructure costs. */
641 FOR_ALL_COMPANIES(c) {
642 cur_company.Change(c->index);
644 CommandCost cost(EXPENSES_PROPERTY);
645 uint32 rail_total = c->infrastructure.GetRailTotal();
646 for (RailType rt = RAILTYPE_BEGIN; rt < RAILTYPE_END; rt++) {
647 if (c->infrastructure.rail[rt] != 0) cost.AddCost(RailMaintenanceCost(rt, c->infrastructure.rail[rt], rail_total));
649 cost.AddCost(SignalMaintenanceCost(c->infrastructure.signal));
650 for (RoadType rt = ROADTYPE_BEGIN; rt < ROADTYPE_END; rt++) {
651 if (c->infrastructure.road[rt] != 0) cost.AddCost(RoadMaintenanceCost(rt, c->infrastructure.road[rt]));
653 cost.AddCost(CanalMaintenanceCost(c->infrastructure.water));
654 cost.AddCost(StationMaintenanceCost(c->infrastructure.station));
655 cost.AddCost(AirportMaintenanceCost(c->index));
657 SubtractMoneyFromCompany(cost);
660 cur_company.Restore();
662 /* Check for bankruptcy each month */
663 FOR_ALL_COMPANIES(c) {
664 CompanyCheckBankrupt(c);
667 /* Only run the economic statics and update company stats every 3rd month (1st of quarter). */
668 if (!HasBit(1 << 0 | 1 << 3 | 1 << 6 | 1 << 9, _cur_month)) return;
670 FOR_ALL_COMPANIES(c) {
671 memmove(&c->old_economy[1], &c->old_economy[0], sizeof(c->old_economy) - sizeof(c->old_economy[0]));
672 c->old_economy[0] = c->cur_economy;
673 memset(&c->cur_economy, 0, sizeof(c->cur_economy));
675 if (c->num_valid_stat_ent != MAX_HISTORY_QUARTERS) c->num_valid_stat_ent++;
677 UpdateCompanyRatingAndValue(c, true);
678 if (c->block_preview != 0) c->block_preview--;
681 SetWindowDirty(WC_INCOME_GRAPH, 0);
682 SetWindowDirty(WC_OPERATING_PROFIT, 0);
683 SetWindowDirty(WC_DELIVERED_CARGO, 0);
684 SetWindowDirty(WC_PERFORMANCE_HISTORY, 0);
685 SetWindowDirty(WC_COMPANY_VALUE, 0);
686 SetWindowDirty(WC_COMPANY_LEAGUE, 0);
690 * Add monthly inflation
691 * @param check_year Shall the inflation get stopped after 170 years?
692 * @return true if inflation is maxed and nothing was changed
694 bool AddInflation(bool check_year)
696 /* The cargo payment inflation differs from the normal inflation, so the
697 * relative amount of money you make with a transport decreases slowly over
698 * the 170 years. After a few hundred years we reach a level in which the
699 * games will become unplayable as the maximum income will be less than
700 * the minimum running cost.
702 * Furthermore there are a lot of inflation related overflows all over the
703 * place. Solving them is hardly possible because inflation will always
704 * reach the overflow threshold some day. So we'll just perform the
705 * inflation mechanism during the first 170 years (the amount of years that
706 * one had in the original TTD) and stop doing the inflation after that
707 * because it only causes problems that can't be solved nicely and the
708 * inflation doesn't add anything after that either; it even makes playing
709 * it impossible due to the diverging cost and income rates.
711 if (check_year && (_cur_year - _settings_game.game_creation.starting_year) >= (ORIGINAL_MAX_YEAR - ORIGINAL_BASE_YEAR)) return true;
713 if (_economy.inflation_prices == MAX_INFLATION || _economy.inflation_payment == MAX_INFLATION) return true;
715 /* Approximation for (100 + infl_amount)% ** (1 / 12) - 100%
716 * scaled by 65536
717 * 12 -> months per year
718 * This is only a good approximation for small values
720 _economy.inflation_prices += (_economy.inflation_prices * _economy.infl_amount * 54) >> 16;
721 _economy.inflation_payment += (_economy.inflation_payment * _economy.infl_amount_pr * 54) >> 16;
723 if (_economy.inflation_prices > MAX_INFLATION) _economy.inflation_prices = MAX_INFLATION;
724 if (_economy.inflation_payment > MAX_INFLATION) _economy.inflation_payment = MAX_INFLATION;
726 return false;
730 * Computes all prices, payments and maximum loan.
732 void RecomputePrices()
734 /* Setup maximum loan */
735 _economy.max_loan = (_settings_game.difficulty.max_loan * _economy.inflation_prices >> 16) / 50000 * 50000;
737 /* Setup price bases */
738 for (Price i = PR_BEGIN; i < PR_END; i++) {
739 Money price = _price_base_specs[i].start_price;
741 /* Apply difficulty settings */
742 uint mod = 1;
743 switch (_price_base_specs[i].category) {
744 case PCAT_RUNNING:
745 mod = _settings_game.difficulty.vehicle_costs;
746 break;
748 case PCAT_CONSTRUCTION:
749 mod = _settings_game.difficulty.construction_cost;
750 break;
752 default: break;
754 switch (mod) {
755 case 0: price *= 6; break;
756 case 1: price *= 8; break; // normalised to 1 below
757 case 2: price *= 9; break;
758 default: NOT_REACHED();
761 /* Apply inflation */
762 price = (int64)price * _economy.inflation_prices;
764 /* Apply newgrf modifiers, remove fractional part of inflation, and normalise on medium difficulty. */
765 int shift = _price_base_multiplier[i] - 16 - 3;
766 if (shift >= 0) {
767 price <<= shift;
768 } else {
769 price >>= -shift;
772 /* Make sure the price does not get reduced to zero.
773 * Zero breaks quite a few commands that use a zero
774 * cost to see whether something got changed or not
775 * and based on that cause an error. When the price
776 * is zero that fails even when things are done. */
777 if (price == 0) {
778 price = Clamp(_price_base_specs[i].start_price, -1, 1);
779 /* No base price should be zero, but be sure. */
780 assert(price != 0);
782 /* Store value */
783 _price[i] = price;
786 /* Setup cargo payment */
787 CargoSpec *cs;
788 FOR_ALL_CARGOSPECS(cs) {
789 cs->current_payment = ((int64)cs->initial_payment * _economy.inflation_payment) >> 16;
792 SetWindowClassesDirty(WC_BUILD_VEHICLE);
793 SetWindowClassesDirty(WC_REPLACE_VEHICLE);
794 SetWindowClassesDirty(WC_VEHICLE_DETAILS);
795 SetWindowClassesDirty(WC_COMPANY_INFRASTRUCTURE);
796 InvalidateWindowData(WC_PAYMENT_RATES, 0);
799 /** Let all companies pay the monthly interest on their loan. */
800 static void CompaniesPayInterest()
802 const Company *c;
804 Backup<CompanyByte> cur_company(_current_company, FILE_LINE);
805 FOR_ALL_COMPANIES(c) {
806 cur_company.Change(c->index);
808 /* Over a year the paid interest should be "loan * interest percentage",
809 * but... as that number is likely not dividable by 12 (pay each month),
810 * one needs to account for that in the monthly fee calculations.
811 * To easily calculate what one should pay "this" month, you calculate
812 * what (total) should have been paid up to this month and you subtract
813 * whatever has been paid in the previous months. This will mean one month
814 * it'll be a bit more and the other it'll be a bit less than the average
815 * monthly fee, but on average it will be exact.
816 * In order to prevent cheating or abuse (just not paying interest by not
817 * taking a loan we make companies pay interest on negative cash as well
819 Money yearly_fee = c->current_loan * _economy.interest_rate / 100;
820 if (c->money < 0) {
821 yearly_fee += -c->money *_economy.interest_rate / 100;
823 Money up_to_previous_month = yearly_fee * _cur_month / 12;
824 Money up_to_this_month = yearly_fee * (_cur_month + 1) / 12;
826 SubtractMoneyFromCompany(CommandCost(EXPENSES_LOAN_INT, up_to_this_month - up_to_previous_month));
828 SubtractMoneyFromCompany(CommandCost(EXPENSES_OTHER, _price[PR_STATION_VALUE] >> 2));
830 cur_company.Restore();
833 static void HandleEconomyFluctuations()
835 if (_settings_game.difficulty.economy != 0) {
836 /* When economy is Fluctuating, decrease counter */
837 _economy.fluct--;
838 } else if (EconomyIsInRecession()) {
839 /* When it's Steady and we are in recession, end it now */
840 _economy.fluct = -12;
841 } else {
842 /* No need to do anything else in other cases */
843 return;
846 if (_economy.fluct == 0) {
847 _economy.fluct = -(int)GB(Random(), 0, 2);
848 AddNewsItem(STR_NEWS_BEGIN_OF_RECESSION, NT_ECONOMY, NF_NORMAL);
849 } else if (_economy.fluct == -12) {
850 _economy.fluct = GB(Random(), 0, 8) + 312;
851 AddNewsItem(STR_NEWS_END_OF_RECESSION, NT_ECONOMY, NF_NORMAL);
857 * Reset changes to the price base multipliers.
859 void ResetPriceBaseMultipliers()
861 memset(_price_base_multiplier, 0, sizeof(_price_base_multiplier));
865 * Change a price base by the given factor.
866 * The price base is altered by factors of two.
867 * NewBaseCost = OldBaseCost * 2^n
868 * @param price Index of price base to change.
869 * @param factor Amount to change by.
871 void SetPriceBaseMultiplier(Price price, int factor)
873 assert(price < PR_END);
874 _price_base_multiplier[price] = Clamp(factor, MIN_PRICE_MODIFIER, MAX_PRICE_MODIFIER);
878 * Initialize the variables that will maintain the daily industry change system.
879 * @param init_counter specifies if the counter is required to be initialized
881 void StartupIndustryDailyChanges(bool init_counter)
883 uint map_size = MapLogX() + MapLogY();
884 /* After getting map size, it needs to be scaled appropriately and divided by 31,
885 * which stands for the days in a month.
886 * Using just 31 will make it so that a monthly reset (based on the real number of days of that month)
887 * would not be needed.
888 * Since it is based on "fractional parts", the leftover days will not make much of a difference
889 * on the overall total number of changes performed */
890 _economy.industry_daily_increment = (1 << map_size) / 31;
892 if (init_counter) {
893 /* A new game or a savegame from an older version will require the counter to be initialized */
894 _economy.industry_daily_change_counter = 0;
898 void StartupEconomy()
900 _economy.interest_rate = _settings_game.difficulty.initial_interest;
901 _economy.infl_amount = _settings_game.difficulty.initial_interest;
902 _economy.infl_amount_pr = max(0, _settings_game.difficulty.initial_interest - 1);
903 _economy.fluct = GB(Random(), 0, 8) + 168;
905 /* Set up prices */
906 RecomputePrices();
908 StartupIndustryDailyChanges(true); // As we are starting a new game, initialize the counter too
913 * Resets economy to initial values
915 void InitializeEconomy()
917 _economy.inflation_prices = _economy.inflation_payment = 1 << 16;
918 ClearCargoPickupMonitoring();
919 ClearCargoDeliveryMonitoring();
923 * Determine a certain price
924 * @param index Price base
925 * @param cost_factor Price factor
926 * @param grf_file NewGRF to use local price multipliers from.
927 * @param shift Extra bit shifting after the computation
928 * @return Price
930 Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift)
932 if (index >= PR_END) return 0;
934 Money cost = _price[index] * cost_factor;
935 if (grf_file != NULL) shift += grf_file->price_base_multipliers[index];
937 if (shift >= 0) {
938 cost <<= shift;
939 } else {
940 cost >>= -shift;
943 return cost;
946 Money GetTransportedGoodsIncome(uint num_pieces, uint dist, byte transit_days, CargoID cargo_type)
948 const CargoSpec *cs = CargoSpec::Get(cargo_type);
949 if (!cs->IsValid()) {
950 /* User changed newgrfs and some vehicle still carries some cargo which is no longer available. */
951 return 0;
954 /* Use callback to calculate cargo profit, if available */
955 if (HasBit(cs->callback_mask, CBM_CARGO_PROFIT_CALC)) {
956 uint32 var18 = min(dist, 0xFFFF) | (min(num_pieces, 0xFF) << 16) | (transit_days << 24);
957 uint16 callback = GetCargoCallback(CBID_CARGO_PROFIT_CALC, 0, var18, cs);
958 if (callback != CALLBACK_FAILED) {
959 int result = GB(callback, 0, 14);
961 /* Simulate a 15 bit signed value */
962 if (HasBit(callback, 14)) result -= 0x4000;
964 /* "The result should be a signed multiplier that gets multiplied
965 * by the amount of cargo moved and the price factor, then gets
966 * divided by 8192." */
967 return result * num_pieces * cs->current_payment / 8192;
971 static const int MIN_TIME_FACTOR = 31;
972 static const int MAX_TIME_FACTOR = 255;
974 const int days1 = cs->transit_days[0];
975 const int days2 = cs->transit_days[1];
976 const int days_over_days1 = max( transit_days - days1, 0);
977 const int days_over_days2 = max(days_over_days1 - days2, 0);
980 * The time factor is calculated based on the time it took
981 * (transit_days) compared two cargo-depending values. The
982 * range is divided into three parts:
984 * - constant for fast transits
985 * - linear decreasing with time with a slope of -1 for medium transports
986 * - linear decreasing with time with a slope of -2 for slow transports
989 const int time_factor = max(MAX_TIME_FACTOR - days_over_days1 - days_over_days2, MIN_TIME_FACTOR);
991 return BigMulS(dist * time_factor * num_pieces, cs->current_payment, 21);
994 /** The industries we've currently brought cargo to. */
995 static SmallIndustryList _cargo_delivery_destinations;
998 * Transfer goods from station to industry.
999 * All cargo is delivered to the nearest (Manhattan) industry to the station sign, which is inside the acceptance rectangle and actually accepts the cargo.
1000 * @param st The station that accepted the cargo
1001 * @param cargo_type Type of cargo delivered
1002 * @param num_pieces Amount of cargo delivered
1003 * @param source The source of the cargo
1004 * @return actually accepted pieces of cargo
1006 static uint DeliverGoodsToIndustry(const Station *st, CargoID cargo_type, uint num_pieces, IndustryID source)
1008 /* Find the nearest industrytile to the station sign inside the catchment area, whose industry accepts the cargo.
1009 * This fails in three cases:
1010 * 1) The station accepts the cargo because there are enough houses around it accepting the cargo.
1011 * 2) The industries in the catchment area temporarily reject the cargo, and the daily station loop has not yet updated station acceptance.
1012 * 3) The results of callbacks CBID_INDUSTRY_REFUSE_CARGO and CBID_INDTILE_CARGO_ACCEPTANCE are inconsistent. (documented behaviour)
1015 uint accepted = 0;
1017 for (uint i = 0; i < st->industries_near.Length() && num_pieces != 0; i++) {
1018 Industry *ind = st->industries_near[i];
1019 if (ind->index == source) continue;
1021 uint cargo_index;
1022 for (cargo_index = 0; cargo_index < lengthof(ind->accepts_cargo); cargo_index++) {
1023 if (cargo_type == ind->accepts_cargo[cargo_index]) break;
1025 /* Check if matching cargo has been found */
1026 if (cargo_index >= lengthof(ind->accepts_cargo)) continue;
1028 /* Check if industry temporarily refuses acceptance */
1029 if (IndustryTemporarilyRefusesCargo(ind, cargo_type)) continue;
1031 /* Insert the industry into _cargo_delivery_destinations, if not yet contained */
1032 _cargo_delivery_destinations.Include(ind);
1034 uint amount = min(num_pieces, 0xFFFFU - ind->incoming_cargo_waiting[cargo_index]);
1035 ind->incoming_cargo_waiting[cargo_index] += amount;
1036 num_pieces -= amount;
1037 accepted += amount;
1040 return accepted;
1044 * Delivers goods to industries/towns and calculates the payment
1045 * @param num_pieces amount of cargo delivered
1046 * @param cargo_type the type of cargo that is delivered
1047 * @param dest Station the cargo has been unloaded
1048 * @param source_tile The origin of the cargo for distance calculation
1049 * @param days_in_transit Travel time
1050 * @param company The company delivering the cargo
1051 * @param src_type Type of source of cargo (industry, town, headquarters)
1052 * @param src Index of source of cargo
1053 * @return Revenue for delivering cargo
1054 * @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
1056 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)
1058 assert(num_pieces > 0);
1060 Station *st = Station::Get(dest);
1062 /* Give the goods to the industry. */
1063 uint accepted = DeliverGoodsToIndustry(st, cargo_type, num_pieces, src_type == ST_INDUSTRY ? src : INVALID_INDUSTRY);
1065 /* If this cargo type is always accepted, accept all */
1066 if (HasBit(st->always_accepted, cargo_type)) accepted = num_pieces;
1068 /* Update station statistics */
1069 if (accepted > 0) {
1070 SetBit(st->goods[cargo_type].acceptance_pickup, GoodsEntry::GES_EVER_ACCEPTED);
1071 SetBit(st->goods[cargo_type].acceptance_pickup, GoodsEntry::GES_CURRENT_MONTH);
1072 SetBit(st->goods[cargo_type].acceptance_pickup, GoodsEntry::GES_ACCEPTED_BIGTICK);
1075 /* Update company statistics */
1076 company->cur_economy.delivered_cargo[cargo_type] += accepted;
1078 /* Increase town's counter for town effects */
1079 const CargoSpec *cs = CargoSpec::Get(cargo_type);
1080 st->town->received[cs->town_effect].new_act += accepted;
1082 /* Determine profit */
1083 Money profit = GetTransportedGoodsIncome(accepted, DistanceManhattan(source_tile, st->xy), days_in_transit, cargo_type);
1085 /* Update the cargo monitor. */
1086 AddCargoDelivery(cargo_type, company->index, accepted, src_type, src, st);
1088 /* Modify profit if a subsidy is in effect */
1089 if (CheckSubsidised(cargo_type, company->index, src_type, src, st)) {
1090 switch (_settings_game.difficulty.subsidy_multiplier) {
1091 case 0: profit += profit >> 1; break;
1092 case 1: profit *= 2; break;
1093 case 2: profit *= 3; break;
1094 default: profit *= 4; break;
1098 return profit;
1102 * Inform the industry about just delivered cargo
1103 * DeliverGoodsToIndustry() silently incremented incoming_cargo_waiting, now it is time to do something with the new cargo.
1104 * @param i The industry to process
1106 static void TriggerIndustryProduction(Industry *i)
1108 const IndustrySpec *indspec = GetIndustrySpec(i->type);
1109 uint16 callback = indspec->callback_mask;
1111 i->was_cargo_delivered = true;
1112 i->last_cargo_accepted_at = _date;
1114 if (HasBit(callback, CBM_IND_PRODUCTION_CARGO_ARRIVAL) || HasBit(callback, CBM_IND_PRODUCTION_256_TICKS)) {
1115 if (HasBit(callback, CBM_IND_PRODUCTION_CARGO_ARRIVAL)) {
1116 IndustryProductionCallback(i, 0);
1117 } else {
1118 SetWindowDirty(WC_INDUSTRY_VIEW, i->index);
1120 } else {
1121 for (uint cargo_index = 0; cargo_index < lengthof(i->incoming_cargo_waiting); cargo_index++) {
1122 uint cargo_waiting = i->incoming_cargo_waiting[cargo_index];
1123 if (cargo_waiting == 0) continue;
1125 i->produced_cargo_waiting[0] = min(i->produced_cargo_waiting[0] + (cargo_waiting * indspec->input_cargo_multiplier[cargo_index][0] / 256), 0xFFFF);
1126 i->produced_cargo_waiting[1] = min(i->produced_cargo_waiting[1] + (cargo_waiting * indspec->input_cargo_multiplier[cargo_index][1] / 256), 0xFFFF);
1128 i->incoming_cargo_waiting[cargo_index] = 0;
1132 TriggerIndustry(i, INDUSTRY_TRIGGER_RECEIVED_CARGO);
1133 StartStopIndustryTileAnimation(i, IAT_INDUSTRY_RECEIVED_CARGO);
1137 * Makes us a new cargo payment helper.
1138 * @param front The front of the train
1140 CargoPayment::CargoPayment(Vehicle *front) :
1141 front(front),
1142 current_station(front->last_station_visited)
1146 CargoPayment::~CargoPayment()
1148 if (this->CleaningPool()) return;
1150 this->front->cargo_payment = NULL;
1152 if (this->visual_profit == 0 && this->visual_transfer == 0) return;
1154 Backup<CompanyByte> cur_company(_current_company, this->front->owner, FILE_LINE);
1156 SubtractMoneyFromCompany(CommandCost(this->front->GetExpenseType(true), -this->route_profit));
1157 this->front->profit_this_year += (this->visual_profit + this->visual_transfer) << 8;
1159 if (this->route_profit != 0 && IsLocalCompany() && !PlayVehicleSound(this->front, VSE_LOAD_UNLOAD)) {
1160 SndPlayVehicleFx(SND_14_CASHTILL, this->front);
1163 if (this->visual_transfer != 0) {
1164 ShowFeederIncomeAnimation(this->front->x_pos, this->front->y_pos,
1165 this->front->z_pos, this->visual_transfer, -this->visual_profit);
1166 } else if (this->visual_profit != 0) {
1167 ShowCostOrIncomeAnimation(this->front->x_pos, this->front->y_pos,
1168 this->front->z_pos, -this->visual_profit);
1171 cur_company.Restore();
1175 * Handle payment for final delivery of the given cargo packet.
1176 * @param cp The cargo packet to pay for.
1177 * @param count The number of packets to pay for.
1179 void CargoPayment::PayFinalDelivery(const CargoPacket *cp, uint count)
1181 if (this->owner == NULL) {
1182 this->owner = Company::Get(this->front->owner);
1185 /* Handle end of route payment */
1186 Money profit = DeliverGoods(count, this->ct, this->current_station, cp->SourceStationXY(), cp->DaysInTransit(), this->owner, cp->SourceSubsidyType(), cp->SourceSubsidyID());
1187 this->route_profit += profit;
1189 /* The vehicle's profit is whatever route profit there is minus feeder shares. */
1190 this->visual_profit += profit - cp->FeederShare(count);
1194 * Handle payment for transfer of the given cargo packet.
1195 * @param cp The cargo packet to pay for; actual payment won't be made!.
1196 * @param count The number of packets to pay for.
1197 * @return The amount of money paid for the transfer.
1199 Money CargoPayment::PayTransfer(const CargoPacket *cp, uint count)
1201 Money profit = GetTransportedGoodsIncome(
1202 count,
1203 /* pay transfer vehicle for only the part of transfer it has done: ie. cargo_loaded_at_xy to here */
1204 DistanceManhattan(cp->LoadedAtXY(), Station::Get(this->current_station)->xy),
1205 cp->DaysInTransit(),
1206 this->ct);
1208 profit = profit * _settings_game.economy.feeder_payment_share / 100;
1210 this->visual_transfer += profit; // accumulate transfer profits for whole vehicle
1211 return profit; // account for the (virtual) profit already made for the cargo packet
1215 * Prepare the vehicle to be unloaded.
1216 * @param curr_station the station where the consist is at the moment
1217 * @param front_v the vehicle to be unloaded
1219 void PrepareUnload(Vehicle *front_v)
1221 Station *curr_station = Station::Get(front_v->last_station_visited);
1222 curr_station->loading_vehicles.push_back(front_v);
1224 /* At this moment loading cannot be finished */
1225 ClrBit(front_v->vehicle_flags, VF_LOADING_FINISHED);
1227 /* Start unloading at the first possible moment */
1228 front_v->load_unload_ticks = 1;
1230 assert(front_v->cargo_payment == NULL);
1231 /* One CargoPayment per vehicle and the vehicle limit equals the
1232 * limit in number of CargoPayments. Can't go wrong. */
1233 assert_compile(CargoPaymentPool::MAX_SIZE == VehiclePool::MAX_SIZE);
1234 assert(CargoPayment::CanAllocateItem());
1235 front_v->cargo_payment = new CargoPayment(front_v);
1237 StationIDStack next_station = front_v->GetNextStoppingStation();
1238 if (front_v->orders.list == NULL || (front_v->current_order.GetUnloadType() & OUFB_NO_UNLOAD) == 0) {
1239 Station *st = Station::Get(front_v->last_station_visited);
1240 for (Vehicle *v = front_v; v != NULL; v = v->Next()) {
1241 const GoodsEntry *ge = &st->goods[v->cargo_type];
1242 if (v->cargo_cap > 0 && v->cargo.TotalCount() > 0) {
1243 v->cargo.Stage(
1244 HasBit(ge->acceptance_pickup, GoodsEntry::GES_ACCEPTANCE),
1245 front_v->last_station_visited, next_station,
1246 front_v->current_order.GetUnloadType(), ge,
1247 front_v->cargo_payment);
1248 if (v->cargo.UnloadCount() > 0) SetBit(v->vehicle_flags, VF_CARGO_UNLOADING);
1255 * Gets the amount of cargo the given vehicle can load in the current tick.
1256 * This is only about loading speed. The free capacity is ignored.
1257 * @param v Vehicle to be queried.
1258 * @return Amount of cargo the vehicle can load at once.
1260 static uint GetLoadAmount(Vehicle *v)
1262 const Engine *e = v->GetEngine();
1263 uint load_amount = e->info.load_amount;
1265 /* The default loadamount for mail is 1/4 of the load amount for passengers */
1266 bool air_mail = v->type == VEH_AIRCRAFT && !Aircraft::From(v)->IsNormalAircraft();
1267 if (air_mail) load_amount = CeilDiv(load_amount, 4);
1269 if (_settings_game.order.gradual_loading) {
1270 uint16 cb_load_amount = CALLBACK_FAILED;
1271 if (e->GetGRF() != NULL && e->GetGRF()->grf_version >= 8) {
1272 /* Use callback 36 */
1273 cb_load_amount = GetVehicleProperty(v, PROP_VEHICLE_LOAD_AMOUNT, CALLBACK_FAILED);
1274 } else if (HasBit(e->info.callback_mask, CBM_VEHICLE_LOAD_AMOUNT)) {
1275 /* Use callback 12 */
1276 cb_load_amount = GetVehicleCallback(CBID_VEHICLE_LOAD_AMOUNT, 0, 0, v->engine_type, v);
1278 if (cb_load_amount != CALLBACK_FAILED) {
1279 if (e->GetGRF()->grf_version < 8) cb_load_amount = GB(cb_load_amount, 0, 8);
1280 if (cb_load_amount >= 0x100) {
1281 ErrorUnknownCallbackResult(e->GetGRFID(), CBID_VEHICLE_LOAD_AMOUNT, cb_load_amount);
1282 } else if (cb_load_amount != 0) {
1283 load_amount = cb_load_amount;
1288 /* Scale load amount the same as capacity */
1289 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);
1291 return load_amount;
1295 * Reserves cargo if the full load order and improved_load is set or if the
1296 * current order allows autorefit.
1297 * @param st Station where the consist is loading at the moment.
1298 * @param u Front of the loading vehicle consist.
1299 * @param consist_capleft If given, save free capacities after reserving there.
1300 * @param next_station Station(s) the vehicle will stop at next.
1302 static void ReserveConsist(Station *st, Vehicle *u, CargoArray *consist_capleft, StationIDStack next_station)
1304 Vehicle *next_cargo = u;
1305 uint32 seen_cargos = 0;
1307 while (next_cargo != NULL) {
1308 if (next_cargo->cargo_cap == 0) {
1309 /* No need to reserve for vehicles without capacity. */
1310 next_cargo = next_cargo->Next();
1311 continue;
1314 CargoID current_cargo = next_cargo->cargo_type;
1316 Vehicle *v = next_cargo;
1317 SetBit(seen_cargos, current_cargo);
1318 next_cargo = NULL;
1319 for (; v != NULL; v = v->Next()) {
1320 if (v->cargo_type != current_cargo) {
1321 /* Save start point for next cargo type. */
1322 if (next_cargo == NULL && !HasBit(seen_cargos, v->cargo_type)) next_cargo = v;
1323 continue;
1326 assert(v->cargo_cap >= v->cargo.RemainingCount());
1327 uint cap = v->cargo_cap - v->cargo.RemainingCount();
1329 /* Nothing to do if the vehicle is full */
1330 if (cap > 0) {
1331 cap -= st->goods[v->cargo_type].cargo.Reserve(cap, &v->cargo, st->xy, next_station);
1334 if (consist_capleft != NULL) {
1335 (*consist_capleft)[current_cargo] += cap;
1342 * Checks whether an articulated vehicle is empty.
1343 * @param v Vehicle
1344 * @return true if all parts are empty.
1346 static bool IsArticulatedVehicleEmpty(Vehicle *v)
1348 v = v->GetFirstEnginePart();
1350 for (; v != NULL; v = v->HasArticulatedPart() ? v->GetNextArticulatedPart() : NULL) {
1351 if (v->cargo.StoredCount() != 0) return false;
1354 return true;
1358 * Refit a vehicle in a station.
1359 * @param v Vehicle to be refitted.
1360 * @param consist_capleft Added cargo capacities in the consist.
1361 * @param st Station the vehicle is loading at.
1362 * @param next_station Possible next stations the vehicle can travel to.
1363 * @param new_cid Target cargo for refit.
1365 static void HandleStationRefit(Vehicle *v, CargoArray &consist_capleft, Station *st, StationIDStack next_station, CargoID new_cid)
1367 if (v->type == VEH_AIRCRAFT && (!Aircraft::From(v)->IsNormalAircraft() || v->Next()->cargo.StoredCount() > 0)) {
1368 return;
1371 bool is_normal_aircraft = (v->type == VEH_AIRCRAFT && Aircraft::From(v)->IsNormalAircraft());
1372 Vehicle *v_start = v->GetFirstEnginePart();
1374 /* Remove old capacity from consist capacity */
1375 consist_capleft[v_start->cargo_type] -= (v_start->cargo_cap - v_start->cargo.ReservedCount());
1376 for (Vehicle *w = v_start; w->HasArticulatedPart(); ) {
1377 w = w->GetNextArticulatedPart();
1378 consist_capleft[w->cargo_type] -= (w->cargo_cap - w->cargo.ReservedCount());
1380 if (is_normal_aircraft) {
1381 consist_capleft[v->Next()->cargo_type] -= (v->Next()->cargo_cap - v->Next()->cargo.ReservedCount());
1384 Backup<CompanyByte> cur_company(_current_company, v->owner, FILE_LINE);
1386 /* Check if all articulated parts are empty and collect refit mask. */
1387 uint32 refit_mask = v->GetEngine()->info.refit_mask;
1388 Vehicle *w = v_start;
1389 while (w->HasArticulatedPart()) {
1390 w = w->GetNextArticulatedPart();
1391 refit_mask |= EngInfo(w->engine_type)->refit_mask;
1394 if (new_cid == CT_AUTO_REFIT) {
1395 /* Get a refittable cargo type with waiting cargo for next_station or INVALID_STATION. */
1396 CargoID cid;
1397 new_cid = v_start->cargo_type;
1398 FOR_EACH_SET_CARGO_ID(cid, refit_mask) {
1399 if (st->goods[cid].cargo.HasCargoFor(next_station)) {
1400 /* Try to find out if auto-refitting would succeed. In case the refit is allowed,
1401 * the returned refit capacity will be greater than zero. */
1402 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.
1403 /* Try to balance different loadable cargoes between parts of the consist, so that
1404 * all of them can be loaded. Avoid a situation where all vehicles suddenly switch
1405 * to the first loadable cargo for which there is only one packet. */
1406 if (_returned_refit_capacity > 0 && consist_capleft[cid] < consist_capleft[new_cid]) {
1407 new_cid = cid;
1413 /* Refit if given a valid cargo. */
1414 if (new_cid < NUM_CARGO && new_cid != v_start->cargo_type) {
1415 StationID next_one = StationIDStack(next_station).Pop();
1416 v_start->cargo.Return(UINT_MAX, &st->goods[v_start->cargo_type].cargo, next_one);
1417 for (w = v_start; w->HasArticulatedPart();) {
1418 w = w->GetNextArticulatedPart();
1419 w->cargo.Return(UINT_MAX, &st->goods[w->cargo_type].cargo, next_one);
1421 if (is_normal_aircraft) {
1422 v->Next()->cargo.Return(UINT_MAX, &st->goods[v->Next()->cargo_type].cargo, next_one);
1424 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.
1425 if (cost.Succeeded()) v->First()->profit_this_year -= cost.GetCost() << 8;
1428 /* Add new capacity to consist capacity and reserve cargo */
1429 w = v_start;
1430 do {
1431 st->goods[w->cargo_type].cargo.Reserve(w->cargo_cap - w->cargo.RemainingCount(), &w->cargo, st->xy, next_station);
1432 consist_capleft[w->cargo_type] += w->cargo_cap - w->cargo.RemainingCount();
1433 w = w->HasArticulatedPart() ? w->GetNextArticulatedPart() : NULL;
1434 } while (w != NULL);
1435 if (is_normal_aircraft) {
1436 w = v->Next();
1437 st->goods[w->cargo_type].cargo.Reserve(w->cargo_cap - w->cargo.RemainingCount(), &w->cargo, st->xy, next_station);
1438 consist_capleft[w->cargo_type] += w->cargo_cap - w->cargo.RemainingCount();
1441 cur_company.Restore();
1445 * Loads/unload the vehicle if possible.
1446 * @param front the vehicle to be (un)loaded
1448 static void LoadUnloadVehicle(Vehicle *front)
1450 assert(front->current_order.IsType(OT_LOADING));
1452 StationID last_visited = front->last_station_visited;
1453 Station *st = Station::Get(last_visited);
1455 StationIDStack next_station = front->GetNextStoppingStation();
1456 bool use_autorefit = front->current_order.IsRefit() && front->current_order.GetRefitCargo() == CT_AUTO_REFIT;
1457 CargoArray consist_capleft;
1458 if (_settings_game.order.improved_load &&
1459 ((front->current_order.GetLoadType() & OLFB_FULL_LOAD) != 0 || use_autorefit)) {
1460 ReserveConsist(st, front,
1461 (use_autorefit && front->load_unload_ticks != 0) ? &consist_capleft : NULL,
1462 next_station);
1465 /* We have not waited enough time till the next round of loading/unloading */
1466 if (front->load_unload_ticks != 0) return;
1468 if (front->type == VEH_TRAIN && (!IsStationTile(front->tile) || GetStationIndex(front->tile) != st->index)) {
1469 /* The train reversed in the station. Take the "easy" way
1470 * out and let the train just leave as it always did. */
1471 SetBit(front->vehicle_flags, VF_LOADING_FINISHED);
1472 front->load_unload_ticks = 1;
1473 return;
1476 int unloading_time = 0;
1477 bool dirty_vehicle = false;
1478 bool dirty_station = false;
1480 bool completely_emptied = true;
1481 bool anything_unloaded = false;
1482 bool anything_loaded = false;
1483 uint32 full_load_amount = 0;
1484 uint32 cargo_not_full = 0;
1485 uint32 cargo_full = 0;
1486 uint32 reservation_left = 0;
1488 front->cur_speed = 0;
1490 CargoPayment *payment = front->cargo_payment;
1492 uint artic_part = 0; // Articulated part we are currently trying to load. (not counting parts without capacity)
1493 for (Vehicle *v = front; v != NULL; v = v->Next()) {
1494 if (v == front || !v->Previous()->HasArticulatedPart()) artic_part = 0;
1495 if (v->cargo_cap == 0) continue;
1496 artic_part++;
1498 uint load_amount = GetLoadAmount(v);
1500 GoodsEntry *ge = &st->goods[v->cargo_type];
1502 if (HasBit(v->vehicle_flags, VF_CARGO_UNLOADING) && (front->current_order.GetUnloadType() & OUFB_NO_UNLOAD) == 0) {
1503 uint cargo_count = v->cargo.UnloadCount();
1504 uint amount_unloaded = _settings_game.order.gradual_loading ? min(cargo_count, load_amount) : cargo_count;
1505 bool remaining = false; // Are there cargo entities in this vehicle that can still be unloaded here?
1507 payment->SetCargo(v->cargo_type);
1509 if (!HasBit(ge->acceptance_pickup, GoodsEntry::GES_ACCEPTANCE) && v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER) > 0) {
1510 /* The station does not accept our goods anymore. */
1511 if (front->current_order.GetUnloadType() & (OUFB_TRANSFER | OUFB_UNLOAD)) {
1512 /* Transfer instead of delivering. */
1513 v->cargo.Reassign<VehicleCargoList::MTA_DELIVER, VehicleCargoList::MTA_TRANSFER>(
1514 v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER), INVALID_STATION);
1515 } else {
1516 uint new_remaining = v->cargo.RemainingCount() + v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER);
1517 if (v->cargo_cap < new_remaining) {
1518 /* Return some of the reserved cargo to not overload the vehicle. */
1519 v->cargo.Return(new_remaining - v->cargo_cap, &ge->cargo, INVALID_STATION);
1522 /* Keep instead of delivering. This may lead to no cargo being unloaded, so ...*/
1523 v->cargo.Reassign<VehicleCargoList::MTA_DELIVER, VehicleCargoList::MTA_KEEP>(
1524 v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER));
1526 /* ... say we unloaded something, otherwise we'll think we didn't unload
1527 * something and we didn't load something, so we must be finished
1528 * at this station. Setting the unloaded means that we will get a
1529 * retry for loading in the next cycle. */
1530 anything_unloaded = true;
1534 /* Mark the station dirty if we transfer, but not if we only deliver. */
1535 dirty_station = v->cargo.ActionCount(VehicleCargoList::MTA_TRANSFER) > 0;
1536 amount_unloaded = v->cargo.Unload(amount_unloaded, &ge->cargo, payment);
1537 remaining = v->cargo.UnloadCount() > 0;
1538 if (amount_unloaded > 0) {
1539 dirty_vehicle = true;
1540 anything_unloaded = true;
1541 unloading_time += amount_unloaded;
1543 /* Deliver goods to the station */
1544 st->time_since_unload = 0;
1547 if (_settings_game.order.gradual_loading && remaining) {
1548 completely_emptied = false;
1549 } else {
1550 /* We have finished unloading (cargo count == 0) */
1551 ClrBit(v->vehicle_flags, VF_CARGO_UNLOADING);
1554 continue;
1557 /* Do not pick up goods when we have no-load set or loading is stopped. */
1558 if (front->current_order.GetLoadType() & OLFB_NO_LOAD || HasBit(front->vehicle_flags, VF_STOP_LOADING)) continue;
1560 /* This order has a refit, if this is the first vehicle part carrying cargo and the whole vehicle is empty, try refitting. */
1561 if (front->current_order.IsRefit() && artic_part == 1 && IsArticulatedVehicleEmpty(v)) {
1562 HandleStationRefit(v, consist_capleft, st, next_station, front->current_order.GetRefitCargo());
1563 ge = &st->goods[v->cargo_type];
1566 /* As we're loading here the following link can carry the full capacity of the vehicle. */
1567 v->refit_cap = v->cargo_cap;
1569 /* update stats */
1570 int t;
1571 switch (front->type) {
1572 case VEH_TRAIN: /* FALL THROUGH */
1573 case VEH_SHIP:
1574 t = front->vcache.cached_max_speed;
1575 break;
1577 case VEH_ROAD:
1578 t = front->vcache.cached_max_speed / 2;
1579 break;
1581 case VEH_AIRCRAFT:
1582 t = Aircraft::From(front)->GetSpeedOldUnits(); // Convert to old units.
1583 break;
1585 default: NOT_REACHED();
1588 /* if last speed is 0, we treat that as if no vehicle has ever visited the station. */
1589 ge->last_speed = min(t, 255);
1590 ge->last_age = min(_cur_year - front->build_year, 255);
1591 ge->time_since_pickup = 0;
1593 assert(v->cargo_cap >= v->cargo.StoredCount());
1594 /* If there's goods waiting at the station, and the vehicle
1595 * has capacity for it, load it on the vehicle. */
1596 uint cap_left = v->cargo_cap - v->cargo.StoredCount();
1597 if (cap_left > 0 && (v->cargo.ActionCount(VehicleCargoList::MTA_LOAD) > 0 || ge->cargo.AvailableCount() > 0)) {
1598 if (_settings_game.order.gradual_loading) cap_left = min(cap_left, load_amount);
1599 if (v->cargo.StoredCount() == 0) TriggerVehicle(v, VEHICLE_TRIGGER_NEW_CARGO);
1601 uint loaded = ge->cargo.Load(cap_left, &v->cargo, st->xy, next_station);
1602 if (v->cargo.ActionCount(VehicleCargoList::MTA_LOAD) > 0) {
1603 /* Remember if there are reservations left so that we don't stop
1604 * loading before they're loaded. */
1605 SetBit(reservation_left, v->cargo_type);
1608 /* Store whether the maximum possible load amount was loaded or not.*/
1609 if (loaded == cap_left) {
1610 SetBit(full_load_amount, v->cargo_type);
1611 } else {
1612 ClrBit(full_load_amount, v->cargo_type);
1615 /* TODO: Regarding this, when we do gradual loading, we
1616 * should first unload all vehicles and then start
1617 * loading them. Since this will cause
1618 * VEHICLE_TRIGGER_EMPTY to be called at the time when
1619 * the whole vehicle chain is really totally empty, the
1620 * completely_emptied assignment can then be safely
1621 * removed; that's how TTDPatch behaves too. --pasky */
1622 if (loaded > 0) {
1623 completely_emptied = false;
1624 anything_loaded = true;
1626 st->time_since_load = 0;
1627 st->last_vehicle_type = v->type;
1629 if (ge->cargo.TotalCount() == 0) {
1630 TriggerStationRandomisation(st, st->xy, SRT_CARGO_TAKEN, v->cargo_type);
1631 TriggerStationAnimation(st, st->xy, SAT_CARGO_TAKEN, v->cargo_type);
1632 AirportAnimationTrigger(st, AAT_STATION_CARGO_TAKEN, v->cargo_type);
1635 unloading_time += loaded;
1637 dirty_vehicle = dirty_station = true;
1641 if (v->cargo.StoredCount() >= v->cargo_cap) {
1642 SetBit(cargo_full, v->cargo_type);
1643 } else {
1644 SetBit(cargo_not_full, v->cargo_type);
1648 if (anything_loaded || anything_unloaded) {
1649 if (front->type == VEH_TRAIN) {
1650 TriggerStationRandomisation(st, front->tile, SRT_TRAIN_LOADS);
1651 TriggerStationAnimation(st, front->tile, SAT_TRAIN_LOADS);
1655 /* Only set completely_emptied, if we just unloaded all remaining cargo */
1656 completely_emptied &= anything_unloaded;
1658 if (!anything_unloaded) delete payment;
1660 ClrBit(front->vehicle_flags, VF_STOP_LOADING);
1661 if (anything_loaded || anything_unloaded) {
1662 if (_settings_game.order.gradual_loading) {
1663 /* The time it takes to load one 'slice' of cargo or passengers depends
1664 * on the vehicle type - the values here are those found in TTDPatch */
1665 const uint gradual_loading_wait_time[] = { 40, 20, 10, 20 };
1667 unloading_time = gradual_loading_wait_time[front->type];
1669 /* We loaded less cargo than possible for all cargo types and it's not full
1670 * load and we're not supposed to wait any longer: stop loading. */
1671 if (!anything_unloaded && full_load_amount == 0 && reservation_left == 0 && !(front->current_order.GetLoadType() & OLFB_FULL_LOAD) &&
1672 front->current_order_time >= (uint)max(front->current_order.wait_time - front->lateness_counter, 0)) {
1673 SetBit(front->vehicle_flags, VF_STOP_LOADING);
1675 } else {
1676 bool finished_loading = true;
1677 if (front->current_order.GetLoadType() & OLFB_FULL_LOAD) {
1678 if (front->current_order.GetLoadType() == OLF_FULL_LOAD_ANY) {
1679 /* if the aircraft carries passengers and is NOT full, then
1680 * continue loading, no matter how much mail is in */
1681 if ((front->type == VEH_AIRCRAFT && IsCargoInClass(front->cargo_type, CC_PASSENGERS) && front->cargo_cap > front->cargo.StoredCount()) ||
1682 (cargo_not_full && (cargo_full & ~cargo_not_full) == 0)) { // There are still non-full cargoes
1683 finished_loading = false;
1685 } else if (cargo_not_full != 0) {
1686 finished_loading = false;
1689 /* Refresh next hop stats if we're full loading to make the links
1690 * known to the distribution algorithm and allow cargo to be sent
1691 * along them. Otherwise the vehicle could wait for cargo
1692 * indefinitely if it hasn't visited the other links yet, or if the
1693 * links die while it's loading. */
1694 if (!finished_loading) LinkRefresher::Run(front);
1696 unloading_time = 20;
1698 SB(front->vehicle_flags, VF_LOADING_FINISHED, 1, finished_loading);
1701 if (front->type == VEH_TRAIN) {
1702 /* Each platform tile is worth 2 rail vehicles. */
1703 int overhang = front->GetGroundVehicleCache()->cached_total_length - st->GetPlatformLength(front->tile) * TILE_SIZE;
1704 if (overhang > 0) {
1705 unloading_time <<= 1;
1706 unloading_time += (overhang * unloading_time) / 8;
1710 /* Calculate the loading indicator fill percent and display
1711 * In the Game Menu do not display indicators
1712 * If _settings_client.gui.loading_indicators == 2, show indicators (bool can be promoted to int as 0 or 1 - results in 2 > 0,1 )
1713 * if _settings_client.gui.loading_indicators == 1, _local_company must be the owner or must be a spectator to show ind., so 1 > 0
1714 * if _settings_client.gui.loading_indicators == 0, do not display indicators ... 0 is never greater than anything
1716 if (_game_mode != GM_MENU && (_settings_client.gui.loading_indicators > (uint)(front->owner != _local_company && _local_company != COMPANY_SPECTATOR))) {
1717 StringID percent_up_down = STR_NULL;
1718 int percent = CalcPercentVehicleFilled(front, &percent_up_down);
1719 if (front->fill_percent_te_id == INVALID_TE_ID) {
1720 front->fill_percent_te_id = ShowFillingPercent(front->x_pos, front->y_pos, front->z_pos + 20, percent, percent_up_down);
1721 } else {
1722 UpdateFillingPercent(front->fill_percent_te_id, percent, percent_up_down);
1726 /* Always wait at least 1, otherwise we'll wait 'infinitively' long. */
1727 front->load_unload_ticks = max(1, unloading_time);
1729 if (completely_emptied) {
1730 /* Make sure the vehicle is marked dirty, since we need to update the NewGRF
1731 * properties such as weight, power and TE whenever the trigger runs. */
1732 dirty_vehicle = true;
1733 TriggerVehicle(front, VEHICLE_TRIGGER_EMPTY);
1736 if (dirty_vehicle) {
1737 SetWindowDirty(GetWindowClassForVehicleType(front->type), front->owner);
1738 SetWindowDirty(WC_VEHICLE_DETAILS, front->index);
1739 front->MarkDirty();
1741 if (dirty_station) {
1742 st->MarkTilesDirty(true);
1743 SetWindowDirty(WC_STATION_VIEW, last_visited);
1748 * Load/unload the vehicles in this station according to the order
1749 * they entered.
1750 * @param st the station to do the loading/unloading for
1752 void LoadUnloadStation(Station *st)
1754 /* No vehicle is here... */
1755 if (st->loading_vehicles.empty()) return;
1757 Vehicle *last_loading = NULL;
1758 std::list<Vehicle *>::iterator iter;
1760 /* Check if anything will be loaded at all. Otherwise we don't need to reserve either. */
1761 for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end(); ++iter) {
1762 Vehicle *v = *iter;
1764 if ((v->vehstatus & (VS_STOPPED | VS_CRASHED))) continue;
1766 assert(v->load_unload_ticks != 0);
1767 if (--v->load_unload_ticks == 0) last_loading = v;
1770 /* We only need to reserve and load/unload up to the last loading vehicle.
1771 * Anything else will be forgotten anyway after returning from this function.
1773 * Especially this means we do _not_ need to reserve cargo for a single
1774 * consist in a station which is not allowed to load yet because its
1775 * load_unload_ticks is still not 0.
1777 if (last_loading == NULL) return;
1779 for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end(); ++iter) {
1780 Vehicle *v = *iter;
1781 if (!(v->vehstatus & (VS_STOPPED | VS_CRASHED))) LoadUnloadVehicle(v);
1782 if (v == last_loading) break;
1785 /* Call the production machinery of industries */
1786 const Industry * const *isend = _cargo_delivery_destinations.End();
1787 for (Industry **iid = _cargo_delivery_destinations.Begin(); iid != isend; iid++) {
1788 TriggerIndustryProduction(*iid);
1790 _cargo_delivery_destinations.Clear();
1794 * Monthly update of the economic data (of the companies as well as economic fluctuations).
1796 void CompaniesMonthlyLoop()
1798 CompaniesGenStatistics();
1799 if (_settings_game.economy.inflation) {
1800 AddInflation();
1801 RecomputePrices();
1803 CompaniesPayInterest();
1804 HandleEconomyFluctuations();
1807 static void DoAcquireCompany(Company *c)
1809 CompanyID ci = c->index;
1811 CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
1812 cni->FillData(c, Company::Get(_current_company));
1814 SetDParam(0, STR_NEWS_COMPANY_MERGER_TITLE);
1815 SetDParam(1, c->bankrupt_value == 0 ? STR_NEWS_MERGER_TAKEOVER_TITLE : STR_NEWS_COMPANY_MERGER_DESCRIPTION);
1816 SetDParamStr(2, cni->company_name);
1817 SetDParamStr(3, cni->other_company_name);
1818 SetDParam(4, c->bankrupt_value);
1819 AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, cni);
1820 AI::BroadcastNewEvent(new ScriptEventCompanyMerger(ci, _current_company));
1821 Game::NewEvent(new ScriptEventCompanyMerger(ci, _current_company));
1823 ChangeOwnershipOfCompanyItems(ci, _current_company);
1825 if (c->bankrupt_value == 0) {
1826 Company *owner = Company::Get(_current_company);
1827 owner->current_loan += c->current_loan;
1830 if (c->is_ai) AI::Stop(c->index);
1832 DeleteCompanyWindows(ci);
1833 InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
1834 InvalidateWindowClassesData(WC_SHIPS_LIST, 0);
1835 InvalidateWindowClassesData(WC_ROADVEH_LIST, 0);
1836 InvalidateWindowClassesData(WC_AIRCRAFT_LIST, 0);
1838 delete c;
1841 extern int GetAmountOwnedBy(const Company *c, Owner owner);
1844 * Acquire shares in an opposing company.
1845 * @param tile unused
1846 * @param flags type of operation
1847 * @param p1 company to buy the shares from
1848 * @param p2 unused
1849 * @param text unused
1850 * @return the cost of this operation or an error
1852 CommandCost CmdBuyShareInCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1854 CommandCost cost(EXPENSES_OTHER);
1855 CompanyID target_company = (CompanyID)p1;
1856 Company *c = Company::GetIfValid(target_company);
1858 /* Check if buying shares is allowed (protection against modified clients)
1859 * Cannot buy own shares */
1860 if (c == NULL || !_settings_game.economy.allow_shares || _current_company == target_company) return CMD_ERROR;
1862 /* Protect new companies from hostile takeovers */
1863 if (_cur_year - c->inaugurated_year < 6) return_cmd_error(STR_ERROR_PROTECTED);
1865 /* Those lines are here for network-protection (clients can be slow) */
1866 if (GetAmountOwnedBy(c, COMPANY_SPECTATOR) == 0) return cost;
1868 if (GetAmountOwnedBy(c, COMPANY_SPECTATOR) == 1) {
1869 if (!c->is_ai) return cost; // We can not buy out a real company (temporarily). TODO: well, enable it obviously.
1871 if (GetAmountOwnedBy(c, _current_company) == 3 && !MayCompanyTakeOver(_current_company, target_company)) return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
1875 cost.AddCost(CalculateCompanyValue(c) >> 2);
1876 if (flags & DC_EXEC) {
1877 OwnerByte *b = c->share_owners;
1879 while (*b != COMPANY_SPECTATOR) b++; // share owners is guaranteed to contain at least one COMPANY_SPECTATOR
1880 *b = _current_company;
1882 for (int i = 0; c->share_owners[i] == _current_company;) {
1883 if (++i == 4) {
1884 c->bankrupt_value = 0;
1885 DoAcquireCompany(c);
1886 break;
1889 InvalidateWindowData(WC_COMPANY, target_company);
1890 CompanyAdminUpdate(c);
1892 return cost;
1896 * Sell shares in an opposing company.
1897 * @param tile unused
1898 * @param flags type of operation
1899 * @param p1 company to sell the shares from
1900 * @param p2 unused
1901 * @param text unused
1902 * @return the cost of this operation or an error
1904 CommandCost CmdSellShareInCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1906 CompanyID target_company = (CompanyID)p1;
1907 Company *c = Company::GetIfValid(target_company);
1909 /* Cannot sell own shares */
1910 if (c == NULL || _current_company == target_company) return CMD_ERROR;
1912 /* Check if selling shares is allowed (protection against modified clients).
1913 * However, we must sell shares of companies being closed down. */
1914 if (!_settings_game.economy.allow_shares && !(flags & DC_BANKRUPT)) return CMD_ERROR;
1916 /* Those lines are here for network-protection (clients can be slow) */
1917 if (GetAmountOwnedBy(c, _current_company) == 0) return CommandCost();
1919 /* adjust it a little to make it less profitable to sell and buy */
1920 Money cost = CalculateCompanyValue(c) >> 2;
1921 cost = -(cost - (cost >> 7));
1923 if (flags & DC_EXEC) {
1924 OwnerByte *b = c->share_owners;
1925 while (*b != _current_company) b++; // share owners is guaranteed to contain company
1926 *b = COMPANY_SPECTATOR;
1927 InvalidateWindowData(WC_COMPANY, target_company);
1928 CompanyAdminUpdate(c);
1930 return CommandCost(EXPENSES_OTHER, cost);
1934 * Buy up another company.
1935 * When a competing company is gone bankrupt you get the chance to purchase
1936 * that company.
1937 * @todo currently this only works for AI companies
1938 * @param tile unused
1939 * @param flags type of operation
1940 * @param p1 company to buy up
1941 * @param p2 unused
1942 * @param text unused
1943 * @return the cost of this operation or an error
1945 CommandCost CmdBuyCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1947 CompanyID target_company = (CompanyID)p1;
1948 Company *c = Company::GetIfValid(target_company);
1949 if (c == NULL) return CMD_ERROR;
1951 /* Disable takeovers when not asked */
1952 if (!HasBit(c->bankrupt_asked, _current_company)) return CMD_ERROR;
1954 /* Disable taking over the local company in single player */
1955 if (!_networking && _local_company == c->index) return CMD_ERROR;
1957 /* Do not allow companies to take over themselves */
1958 if (target_company == _current_company) return CMD_ERROR;
1960 /* Disable taking over when not allowed. */
1961 if (!MayCompanyTakeOver(_current_company, target_company)) return CMD_ERROR;
1963 /* Get the cost here as the company is deleted in DoAcquireCompany. */
1964 CommandCost cost(EXPENSES_OTHER, c->bankrupt_value);
1966 if (flags & DC_EXEC) {
1967 DoAcquireCompany(c);
1969 return cost;