OpenTTD

- Main Page
- Related Pages
- Modules
- Namespaces
- Data Structures
- Files

- File List
- Globals

economy.cpp
Go to the documentation of this file.
1 /* $Id: economy.cpp 26918 2014-09-24 20:56:52Z fonsinchen $ */
2
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 */
9
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 "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"
53
54 #include "table/strings.h"
55 #include "table/pricebase.h"
56
57 #include "safeguards.h"
58
59
60 /* Initialize the cargo payment-pool */
61 CargoPaymentPool _cargo_payment_pool("CargoPayment");
62 INSTANTIATE_POOL_METHODS(CargoPayment)
63
64
75 static inline int32 BigMulS(const int32 a, const int32 b, const uint8 shift)
76 {
77 return (int32)((int64)a * (int64)b >> shift);
78 }
79
80 typedef SmallVector<Industry *, 16> SmallIndustryList;
81
85 const ScoreInfo _score_info[] = {
86 { 120, 100}, // SCORE_VEHICLES
87 { 80, 100}, // SCORE_STATIONS
88 { 10000, 100}, // SCORE_MIN_PROFIT
89 { 50000, 50}, // SCORE_MIN_INCOME
90 { 100000, 100}, // SCORE_MAX_INCOME
91 { 40000, 400}, // SCORE_DELIVERED
92 { 8, 50}, // SCORE_CARGO
93 {10000000, 50}, // SCORE_MONEY
94 { 250000, 50}, // SCORE_LOAN
95 { 0, 0} // SCORE_TOTAL
96 };
97
98 int _score_part[MAX_COMPANIES][SCORE_END];
99 Economy _economy;
100 Prices _price;
101 Money _additional_cash_required;
102 static PriceMultipliers _price_base_multiplier;
103
113 Money CalculateCompanyValue(const Company *c, bool including_loan)
114 {
115 Owner owner = c->index;
116
117 Station *st;
118 uint num = 0;
119
120 FOR_ALL_STATIONS(st) {
121 if (st->owner == owner) num += CountBits((byte)st->facilities);
122 }
123
124 Money value = num * _price[PR_STATION_VALUE] * 25;
125
126 Vehicle *v;
127 FOR_ALL_VEHICLES(v) {
128 if (v->owner != owner) continue;
129
130 if (v->type == VEH_TRAIN ||
131 v->type == VEH_ROAD ||
132 (v->type == VEH_AIRCRAFT && Aircraft::From(v)->IsNormalAircraft()) ||
133 v->type == VEH_SHIP) {
134 value += v->value * 3 >> 1;
135 }
136 }
137
138 /* Add real money value */
139 if (including_loan) value -= c->current_loan;
140 value += c->money;
141
142 return max(value, (Money)1);
143 }
144
153 int UpdateCompanyRatingAndValue(Company *c, bool update)
154 {
155 Owner owner = c->index;
156 int score = 0;
157
158 memset(_score_part[owner], 0, sizeof(_score_part[owner]));
159
160 /* Count vehicles */
161 {
162 Vehicle *v;
163 Money min_profit = 0;
164 bool min_profit_first = true;
165 uint num = 0;
166
167 FOR_ALL_VEHICLES(v) {
168 if (v->owner != owner) continue;
169 if (IsCompanyBuildableVehicleType(v->type) && v->IsPrimaryVehicle()) {
170 if (v->profit_last_year > 0) num++; // For the vehicle score only count profitable vehicles
171 if (v->age > 730) {
172 /* Find the vehicle with the lowest amount of profit */
173 if (min_profit_first || min_profit > v->profit_last_year) {
174 min_profit = v->profit_last_year;
175 min_profit_first = false;
176 }
177 }
178 }
179 }
180
181 min_profit >>= 8; // remove the fract part
182
183 _score_part[owner][SCORE_VEHICLES] = num;
184 /* Don't allow negative min_profit to show */
185 if (min_profit > 0) {
186 _score_part[owner][SCORE_MIN_PROFIT] = ClampToI32(min_profit);
187 }
188 }
189
190 /* Count stations */
191 {
192 uint num = 0;
193 const Station *st;
194
195 FOR_ALL_STATIONS(st) {
196 /* Only count stations that are actually serviced */
197 if (st->owner == owner && (st->time_since_load <= 20 || st->time_since_unload <= 20)) num += CountBits((byte)st->facilities);
198 }
199 _score_part[owner][SCORE_STATIONS] = num;
200 }
201
202 /* Generate statistics depending on recent income statistics */
203 {
204 int numec = min(c->num_valid_stat_ent, 12);
205 if (numec != 0) {
206 const CompanyEconomyEntry *cee = c->old_economy;
207 Money min_income = cee->income + cee->expenses;
208 Money max_income = cee->income + cee->expenses;
209
210 do {
211 min_income = min(min_income, cee->income + cee->expenses);
212 max_income = max(max_income, cee->income + cee->expenses);
213 } while (++cee, --numec);
214
215 if (min_income > 0) {
216 _score_part[owner][SCORE_MIN_INCOME] = ClampToI32(min_income);
217 }
218
219 _score_part[owner][SCORE_MAX_INCOME] = ClampToI32(max_income);
220 }
221 }
222
223 /* Generate score depending on amount of transported cargo */
224 {
225 int numec = min(c->num_valid_stat_ent, 4);
226 if (numec != 0) {
227 const CompanyEconomyEntry *cee = c->old_economy;
228 OverflowSafeInt64 total_delivered = 0;
229 do {
230 total_delivered += cee->delivered_cargo.GetSum<OverflowSafeInt64>();
231 } while (++cee, --numec);
232
233 _score_part[owner][SCORE_DELIVERED] = ClampToI32(total_delivered);
234 }
235 }
236
237 /* Generate score for variety of cargo */
238 {
239 _score_part[owner][SCORE_CARGO] = c->old_economy->delivered_cargo.GetCount();
240 }
241
242 /* Generate score for company's money */
243 {
244 if (c->money > 0) {
245 _score_part[owner][SCORE_MONEY] = ClampToI32(c->money);
246 }
247 }
248
249 /* Generate score for loan */
250 {
251 _score_part[owner][SCORE_LOAN] = ClampToI32(_score_info[SCORE_LOAN].needed - c->current_loan);
252 }
253
254 /* Now we calculate the score for each item.. */
255 {
256 int total_score = 0;
257 int s;
258 score = 0;
259 for (ScoreID i = SCORE_BEGIN; i < SCORE_END; i++) {
260 /* Skip the total */
261 if (i == SCORE_TOTAL) continue;
262 /* Check the score */
263 s = Clamp(_score_part[owner][i], 0, _score_info[i].needed) * _score_info[i].score / _score_info[i].needed;
264 score += s;
265 total_score += _score_info[i].score;
266 }
267
268 _score_part[owner][SCORE_TOTAL] = score;
269
270 /* We always want the score scaled to SCORE_MAX (1000) */
271 if (total_score != SCORE_MAX) score = score * SCORE_MAX / total_score;
272 }
273
274 if (update) {
275 c->old_economy[0].performance_history = score;
276 UpdateCompanyHQ(c->location_of_HQ, score);
277 c->old_economy[0].company_value = CalculateCompanyValue(c);
278 }
279
280 SetWindowDirty(WC_PERFORMANCE_DETAIL, 0);
281 return score;
282 }
283
289 void ChangeOwnershipOfCompanyItems(Owner old_owner, Owner new_owner)
290 {
291 /* We need to set _current_company to old_owner before we try to move
292 * the client. This is needed as it needs to know whether "you" really
293 * are the current local company. */
294 Backup<CompanyByte> cur_company(_current_company, old_owner, FILE_LINE);
295 #ifdef ENABLE_NETWORK
296 /* In all cases, make spectators of clients connected to that company */
297 if (_networking) NetworkClientsToSpectators(old_owner);
298 #endif /* ENABLE_NETWORK */
299 if (old_owner == _local_company) {
300 /* Single player cheated to AI company.
301 * There are no spectators in single player, so we must pick some other company. */
302 assert(!_networking);
303 Backup<CompanyByte> cur_company(_current_company, FILE_LINE);
304 Company *c;
305 FOR_ALL_COMPANIES(c) {
306 if (c->index != old_owner) {
307 SetLocalCompany(c->index);
308 break;
309 }
310 }
311 cur_company.Restore();
312 assert(old_owner != _local_company);
313 }
314
315 Town *t;
316
317 assert(old_owner != new_owner);
318
319 {
320 Company *c;
321 uint i;
322
323 /* See if the old_owner had shares in other companies */
324 FOR_ALL_COMPANIES(c) {
325 for (i = 0; i < 4; i++) {
326 if (c->share_owners[i] == old_owner) {
327 /* Sell his shares */
328 CommandCost res = DoCommand(0, c->index, 0, DC_EXEC | DC_BANKRUPT, CMD_SELL_SHARE_IN_COMPANY);
329 /* Because we are in a DoCommand, we can't just execute another one and
330 * expect the money to be removed. We need to do it ourself! */
331 SubtractMoneyFromCompany(res);
332 }
333 }
334 }
335
336 /* Sell all the shares that people have on this company */
337 Backup<CompanyByte> cur_company2(_current_company, FILE_LINE);
338 c = Company::Get(old_owner);
339 for (i = 0; i < 4; i++) {
340 cur_company2.Change(c->share_owners[i]);
341 if (_current_company != INVALID_OWNER) {
342 /* Sell the shares */
343 CommandCost res = DoCommand(0, old_owner, 0, DC_EXEC | DC_BANKRUPT, CMD_SELL_SHARE_IN_COMPANY);
344 /* Because we are in a DoCommand, we can't just execute another one and
345 * expect the money to be removed. We need to do it ourself! */
346 SubtractMoneyFromCompany(res);
347 }
348 }
349 cur_company2.Restore();
350 }
351
352 /* Temporarily increase the company's money, to be sure that
353 * removing his/her property doesn't fail because of lack of money.
354 * Not too drastically though, because it could overflow */
355 if (new_owner == INVALID_OWNER) {
356 Company::Get(old_owner)->money = UINT64_MAX >> 2; // jackpot ;p
357 }
358
359 Subsidy *s;
360 FOR_ALL_SUBSIDIES(s) {
361 if (s->awarded == old_owner) {
362 if (new_owner == INVALID_OWNER) {
363 delete s;
364 } else {
365 s->awarded = new_owner;
366 }
367 }
368 }
369 if (new_owner == INVALID_OWNER) RebuildSubsidisedSourceAndDestinationCache();
370
371 /* Take care of rating and transport rights in towns */
372 FOR_ALL_TOWNS(t) {
373 /* If a company takes over, give the ratings to that company. */
374 if (new_owner != INVALID_OWNER) {
375 if (HasBit(t->have_ratings, old_owner)) {
376 if (HasBit(t->have_ratings, new_owner)) {
377 /* use max of the two ratings. */
378 t->ratings[new_owner] = max(t->ratings[new_owner], t->ratings[old_owner]);
379 } else {
380 SetBit(t->have_ratings, new_owner);
381 t->ratings[new_owner] = t->ratings[old_owner];
382 }
383 }
384 }
385
386 /* Reset the ratings for the old owner */
387 t->ratings[old_owner] = RATING_INITIAL;
388 ClrBit(t->have_ratings, old_owner);
389
390 /* Transfer exclusive rights */
391 if (t->exclusive_counter > 0 && t->exclusivity == old_owner) {
392 if (new_owner != INVALID_OWNER) {
393 t->exclusivity = new_owner;
394 } else {
395 t->exclusive_counter = 0;
396 t->exclusivity = INVALID_COMPANY;
397 }
398 }
399 }
400
401 {
402 Vehicle *v;
403 FOR_ALL_VEHICLES(v) {
404 if (v->owner == old_owner && IsCompanyBuildableVehicleType(v->type)) {
405 if (new_owner == INVALID_OWNER) {
406 if (v->Previous() == NULL) delete v;
407 } else {
408 if (v->IsEngineCountable()) GroupStatistics::CountEngine(v, -1);
409 if (v->IsPrimaryVehicle()) GroupStatistics::CountVehicle(v, -1);
410 }
411 }
412 }
413 }
414
415 /* In all cases clear replace engine rules.
416 * Even if it was copied, it could interfere with new owner's rules */
417 RemoveAllEngineReplacementForCompany(Company::Get(old_owner));
418
419 if (new_owner == INVALID_OWNER) {
420 RemoveAllGroupsForCompany(old_owner);
421 } else {
422 Group *g;
423 FOR_ALL_GROUPS(g) {
424 if (g->owner == old_owner) g->owner = new_owner;
425 }
426 }
427
428 {
429 FreeUnitIDGenerator unitidgen[] = {
430 FreeUnitIDGenerator(VEH_TRAIN, new_owner), FreeUnitIDGenerator(VEH_ROAD, new_owner),
431 FreeUnitIDGenerator(VEH_SHIP, new_owner), FreeUnitIDGenerator(VEH_AIRCRAFT, new_owner)
432 };
433
434 Vehicle *v;
435 FOR_ALL_VEHICLES(v) {
436 if (v->owner == old_owner && IsCompanyBuildableVehicleType(v->type)) {
437 assert(new_owner != INVALID_OWNER);
438
439 v->owner = new_owner;
440
441 /* Owner changes, clear cache */
442 v->colourmap = PAL_NONE;
443 v->InvalidateNewGRFCache();
444
445 if (v->IsEngineCountable()) {
446 GroupStatistics::CountEngine(v, 1);
447 }
448 if (v->IsPrimaryVehicle()) {
449 GroupStatistics::CountVehicle(v, 1);
450 v->unitnumber = unitidgen[v->type].NextID();
451 }
452
453 /* Invalidate the vehicle's cargo payment "owner cache". */
454 if (v->cargo_payment != NULL) v->cargo_payment->owner = NULL;
455 }
456 }
457
458 if (new_owner != INVALID_OWNER) GroupStatistics::UpdateAutoreplace(new_owner);
459 }
460
461 /* Change ownership of tiles */
462 {
463 TileIndex tile = 0;
464 do {
465 ChangeTileOwner(tile, old_owner, new_owner);
466 } while (++tile != MapSize());
467
468 if (new_owner != INVALID_OWNER) {
469 /* Update all signals because there can be new segment that was owned by two companies
470 * and signals were not propagated
471 * Similar with crossings - it is needed to bar crossings that weren't before
472 * because of different owner of crossing and approaching train */
473 tile = 0;
474
475 do {
476 if (IsTileType(tile, MP_RAILWAY) && IsTileOwner(tile, new_owner) && HasSignals(tile)) {
477 TrackBits tracks = GetTrackBits(tile);
478 do { // there may be two tracks with signals for TRACK_BIT_HORZ and TRACK_BIT_VERT
479 Track track = RemoveFirstTrack(&tracks);
480 if (HasSignalOnTrack(tile, track)) AddTrackToSignalBuffer(tile, track, new_owner);
481 } while (tracks != TRACK_BIT_NONE);
482 } else if (IsLevelCrossingTile(tile) && IsTileOwner(tile, new_owner)) {
483 UpdateLevelCrossing(tile);
484 }
485 } while (++tile != MapSize());
486 }
487
488 /* update signals in buffer */
489 UpdateSignalsInBuffer();
490 }
491
492 /* Add airport infrastructure count of the old company to the new one. */
493 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.airport += Company::Get(old_owner)->infrastructure.airport;
494
495 /* convert owner of stations (including deleted ones, but excluding buoys) */
496 Station *st;
497 FOR_ALL_STATIONS(st) {
498 if (st->owner == old_owner) {
499 /* if a company goes bankrupt, set owner to OWNER_NONE so the sign doesn't disappear immediately
500 * also, drawing station window would cause reading invalid company's colour */
501 st->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner;
502 }
503 }
504
505 /* do the same for waypoints (we need to do this here so deleted waypoints are converted too) */
506 Waypoint *wp;
507 FOR_ALL_WAYPOINTS(wp) {
508 if (wp->owner == old_owner) {
509 wp->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner;
510 }
511 }
512
513 Sign *si;
514 FOR_ALL_SIGNS(si) {
515 if (si->owner == old_owner) si->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner;
516 }
517
518 /* Remove Game Script created Goals, CargoMonitors and Story pages. */
519 Goal *g;
520 FOR_ALL_GOALS(g) {
521 if (g->company == old_owner) delete g;
522 }
523
524 ClearCargoPickupMonitoring(old_owner);
525 ClearCargoDeliveryMonitoring(old_owner);
526
527 StoryPage *sp;
528 FOR_ALL_STORY_PAGES(sp) {
529 if (sp->company == old_owner) delete sp;
530 }
531
532 /* Change colour of existing windows */
533 if (new_owner != INVALID_OWNER) ChangeWindowOwner(old_owner, new_owner);
534
535 cur_company.Restore();
536
537 MarkWholeScreenDirty();
538 }
539
544 static void CompanyCheckBankrupt(Company *c)
545 {
546 /* If the company has money again, it does not go bankrupt */
547 if (c->money - c->current_loan >= -_economy.max_loan) {
548 c->months_of_bankruptcy = 0;
549 c->bankrupt_asked = 0;
550 return;
551 }
552
553 c->months_of_bankruptcy++;
554
555 switch (c->months_of_bankruptcy) {
556 /* All the boring cases (months) with a bad balance where no action is taken */
557 case 0:
558 case 1:
559 case 2:
560 case 3:
561
562 case 5:
563 case 6:
564
565 case 8:
566 case 9:
567 break;
568
569 /* Warn about bankruptcy after 3 months */
570 case 4: {
571 CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
572 cni->FillData(c);
573 SetDParam(0, STR_NEWS_COMPANY_IN_TROUBLE_TITLE);
574 SetDParam(1, STR_NEWS_COMPANY_IN_TROUBLE_DESCRIPTION);
575 SetDParamStr(2, cni->company_name);
576 AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, cni);
577 AI::BroadcastNewEvent(new ScriptEventCompanyInTrouble(c->index));
578 Game::NewEvent(new ScriptEventCompanyInTrouble(c->index));
579 break;
580 }
581
582 /* Offer company for sale after 6 months */
583 case 7: {
584 /* Don't consider the loan */
585 Money val = CalculateCompanyValue(c, false);
586
587 c->bankrupt_value = val;
588 c->bankrupt_asked = 1 << c->index; // Don't ask the owner
589 c->bankrupt_timeout = 0;
590
591 /* The company assets should always have some value */
592 assert(c->bankrupt_value > 0);
593 break;
594 }
595
596 /* Bankrupt company after 6 months (if the company has no value) or latest
597 * after 9 months (if it still had value after 6 months) */
598 default:
599 case 10: {
600 if (!_networking && _local_company == c->index) {
601 /* If we are in offline mode, leave the company playing. Eg. there
602 * is no THE-END, otherwise mark the client as spectator to make sure
603 * he/she is no long in control of this company. However... when you
604 * join another company (cheat) the "unowned" company can bankrupt. */
605 c->bankrupt_asked = MAX_UVALUE(CompanyMask);
606 break;
607 }
608
609 /* Actually remove the company, but not when we're a network client.
610 * In case of network clients we will be getting a command from the
611 * server. It is done in this way as we are called from the
612 * StateGameLoop which can't change the current company, and thus
613 * updating the local company triggers an assert later on. In the
614 * case of a network game the command will be processed at a time
615 * that changing the current company is okay. In case of single
616 * player we are sure (the above check) that we are not the local
617 * company and thus we won't be moved. */
618 if (!_networking || _network_server) DoCommandP(0, 2 | (c->index << 16), CRR_BANKRUPT, CMD_COMPANY_CTRL);
619 break;
620 }
621 }
622 }
623
628 static void CompaniesGenStatistics()
629 {
630 Station *st;
631
632 Backup<CompanyByte> cur_company(_current_company, FILE_LINE);
633 Company *c;
634
635 if (!_settings_game.economy.infrastructure_maintenance) {
636 FOR_ALL_STATIONS(st) {
637 cur_company.Change(st->owner);
638 CommandCost cost(EXPENSES_PROPERTY, _price[PR_STATION_VALUE] >> 1);
639 SubtractMoneyFromCompany(cost);
640 }
641 } else {
642 /* Improved monthly infrastructure costs. */
643 FOR_ALL_COMPANIES(c) {
644 cur_company.Change(c->index);
645
646 CommandCost cost(EXPENSES_PROPERTY);
647 uint32 rail_total = c->infrastructure.GetRailTotal();
648 for (RailType rt = RAILTYPE_BEGIN; rt < RAILTYPE_END; rt++) {
649 if (c->infrastructure.rail[rt] != 0) cost.AddCost(RailMaintenanceCost(rt, c->infrastructure.rail[rt], rail_total));
650 }
651 cost.AddCost(SignalMaintenanceCost(c->infrastructure.signal));
652 for (RoadType rt = ROADTYPE_BEGIN; rt < ROADTYPE_END; rt++) {
653 if (c->infrastructure.road[rt] != 0) cost.AddCost(RoadMaintenanceCost(rt, c->infrastructure.road[rt]));
654 }
655 cost.AddCost(CanalMaintenanceCost(c->infrastructure.water));
656 cost.AddCost(StationMaintenanceCost(c->infrastructure.station));
657 cost.AddCost(AirportMaintenanceCost(c->index));
658
659 SubtractMoneyFromCompany(cost);
660 }
661 }
662 cur_company.Restore();
663
664 /* Check for bankruptcy each month */
665 FOR_ALL_COMPANIES(c) {
666 CompanyCheckBankrupt(c);
667 }
668
669 /* Only run the economic statics and update company stats every 3rd month (1st of quarter). */
670 if (!HasBit(1 << 0 | 1 << 3 | 1 << 6 | 1 << 9, _cur_month)) return;
671
672 FOR_ALL_COMPANIES(c) {
673 memmove(&c->old_economy[1], &c->old_economy[0], sizeof(c->old_economy) - sizeof(c->old_economy[0]));
674 c->old_economy[0] = c->cur_economy;
675 memset(&c->cur_economy, 0, sizeof(c->cur_economy));
676
677 if (c->num_valid_stat_ent != MAX_HISTORY_QUARTERS) c->num_valid_stat_ent++;
678
679 UpdateCompanyRatingAndValue(c, true);
680 if (c->block_preview != 0) c->block_preview--;
681 }
682
683 SetWindowDirty(WC_INCOME_GRAPH, 0);
684 SetWindowDirty(WC_OPERATING_PROFIT, 0);
685 SetWindowDirty(WC_DELIVERED_CARGO, 0);
686 SetWindowDirty(WC_PERFORMANCE_HISTORY, 0);
687 SetWindowDirty(WC_COMPANY_VALUE, 0);
688 SetWindowDirty(WC_COMPANY_LEAGUE, 0);
689 }
690
696 bool AddInflation(bool check_year)
697 {
698 /* The cargo payment inflation differs from the normal inflation, so the
699 * relative amount of money you make with a transport decreases slowly over
700 * the 170 years. After a few hundred years we reach a level in which the
701 * games will become unplayable as the maximum income will be less than
702 * the minimum running cost.
703 *
704 * Furthermore there are a lot of inflation related overflows all over the
705 * place. Solving them is hardly possible because inflation will always
706 * reach the overflow threshold some day. So we'll just perform the
707 * inflation mechanism during the first 170 years (the amount of years that
708 * one had in the original TTD) and stop doing the inflation after that
709 * because it only causes problems that can't be solved nicely and the
710 * inflation doesn't add anything after that either; it even makes playing
711 * it impossible due to the diverging cost and income rates.
712 */
713 if (check_year && (_cur_year - _settings_game.game_creation.starting_year) >= (ORIGINAL_MAX_YEAR - ORIGINAL_BASE_YEAR)) return true;
714
715 if (_economy.inflation_prices == MAX_INFLATION || _economy.inflation_payment == MAX_INFLATION) return true;
716
717 /* Approximation for (100 + infl_amount)% ** (1 / 12) - 100%
718 * scaled by 65536
719 * 12 -> months per year
720 * This is only a good approximation for small values
721 */
722 _economy.inflation_prices += (_economy.inflation_prices * _economy.infl_amount * 54) >> 16;
723 _economy.inflation_payment += (_economy.inflation_payment * _economy.infl_amount_pr * 54) >> 16;
724
725 if (_economy.inflation_prices > MAX_INFLATION) _economy.inflation_prices = MAX_INFLATION;
726 if (_economy.inflation_payment > MAX_INFLATION) _economy.inflation_payment = MAX_INFLATION;
727
728 return false;
729 }
730
734 void RecomputePrices()
735 {
736 /* Setup maximum loan */
737 _economy.max_loan = (_settings_game.difficulty.max_loan * _economy.inflation_prices >> 16) / 50000 * 50000;
738
739 /* Setup price bases */
740 for (Price i = PR_BEGIN; i < PR_END; i++) {
741 Money price = _price_base_specs[i].start_price;
742
743 /* Apply difficulty settings */
744 uint mod = 1;
745 switch (_price_base_specs[i].category) {
746 case PCAT_RUNNING:
747 mod = _settings_game.difficulty.vehicle_costs;
748 break;
749
750 case PCAT_CONSTRUCTION:
751 mod = _settings_game.difficulty.construction_cost;
752 break;
753
754 default: break;
755 }
756 switch (mod) {
757 case 0: price *= 6; break;
758 case 1: price *= 8; break; // normalised to 1 below
759 case 2: price *= 9; break;
760 default: NOT_REACHED();
761 }
762
763 /* Apply inflation */
764 price = (int64)price * _economy.inflation_prices;
765
766 /* Apply newgrf modifiers, remove fractional part of inflation, and normalise on medium difficulty. */
767 int shift = _price_base_multiplier[i] - 16 - 3;
768 if (shift >= 0) {
769 price <<= shift;
770 } else {
771 price >>= -shift;
772 }
773
774 /* Make sure the price does not get reduced to zero.
775 * Zero breaks quite a few commands that use a zero
776 * cost to see whether something got changed or not
777 * and based on that cause an error. When the price
778 * is zero that fails even when things are done. */
779 if (price == 0) {
780 price = Clamp(_price_base_specs[i].start_price, -1, 1);
781 /* No base price should be zero, but be sure. */
782 assert(price != 0);
783 }
784 /* Store value */
785 _price[i] = price;
786 }
787
788 /* Setup cargo payment */
789 CargoSpec *cs;
790 FOR_ALL_CARGOSPECS(cs) {
791 cs->current_payment = ((int64)cs->initial_payment * _economy.inflation_payment) >> 16;
792 }
793
794 SetWindowClassesDirty(WC_BUILD_VEHICLE);
795 SetWindowClassesDirty(WC_REPLACE_VEHICLE);
796 SetWindowClassesDirty(WC_VEHICLE_DETAILS);
797 SetWindowClassesDirty(WC_COMPANY_INFRASTRUCTURE);
798 InvalidateWindowData(WC_PAYMENT_RATES, 0);
799 }
800
802 static void CompaniesPayInterest()
803 {
804 const Company *c;
805
806 Backup<CompanyByte> cur_company(_current_company, FILE_LINE);
807 FOR_ALL_COMPANIES(c) {
808 cur_company.Change(c->index);
809
810 /* Over a year the paid interest should be "loan * interest percentage",
811 * but... as that number is likely not dividable by 12 (pay each month),
812 * one needs to account for that in the monthly fee calculations.
813 * To easily calculate what one should pay "this" month, you calculate
814 * what (total) should have been paid up to this month and you subtract
815 * whatever has been paid in the previous months. This will mean one month
816 * it'll be a bit more and the other it'll be a bit less than the average
817 * monthly fee, but on average it will be exact.
818 * In order to prevent cheating or abuse (just not paying interest by not
819 * taking a loan we make companies pay interest on negative cash as well
820 */
821 Money yearly_fee = c->current_loan * _economy.interest_rate / 100;
822 if (c->money < 0) {
823 yearly_fee += -c->money *_economy.interest_rate / 100;
824 }
825 Money up_to_previous_month = yearly_fee * _cur_month / 12;
826 Money up_to_this_month = yearly_fee * (_cur_month + 1) / 12;
827
828 SubtractMoneyFromCompany(CommandCost(EXPENSES_LOAN_INT, up_to_this_month - up_to_previous_month));
829
830 SubtractMoneyFromCompany(CommandCost(EXPENSES_OTHER, _price[PR_STATION_VALUE] >> 2));
831 }
832 cur_company.Restore();
833 }
834
835 static void HandleEconomyFluctuations()
836 {
837 if (_settings_game.difficulty.economy != 0) {
838 /* When economy is Fluctuating, decrease counter */
839 _economy.fluct--;
840 } else if (EconomyIsInRecession()) {
841 /* When it's Steady and we are in recession, end it now */
842 _economy.fluct = -12;
843 } else {
844 /* No need to do anything else in other cases */
845 return;
846 }
847
848 if (_economy.fluct == 0) {
849 _economy.fluct = -(int)GB(Random(), 0, 2);
850 AddNewsItem(STR_NEWS_BEGIN_OF_RECESSION, NT_ECONOMY, NF_NORMAL);
851 } else if (_economy.fluct == -12) {
852 _economy.fluct = GB(Random(), 0, 8) + 312;
853 AddNewsItem(STR_NEWS_END_OF_RECESSION, NT_ECONOMY, NF_NORMAL);
854 }
855 }
856
857
861 void ResetPriceBaseMultipliers()
862 {
863 memset(_price_base_multiplier, 0, sizeof(_price_base_multiplier));
864 }
865
873 void SetPriceBaseMultiplier(Price price, int factor)
874 {
875 assert(price < PR_END);
876 _price_base_multiplier[price] = Clamp(factor, MIN_PRICE_MODIFIER, MAX_PRICE_MODIFIER);
877 }
878
883 void StartupIndustryDailyChanges(bool init_counter)
884 {
885 uint map_size = MapLogX() + MapLogY();
886 /* After getting map size, it needs to be scaled appropriately and divided by 31,
887 * which stands for the days in a month.
888 * Using just 31 will make it so that a monthly reset (based on the real number of days of that month)
889 * would not be needed.
890 * Since it is based on "fractional parts", the leftover days will not make much of a difference
891 * on the overall total number of changes performed */
892 _economy.industry_daily_increment = (1 << map_size) / 31;
893
894 if (init_counter) {
895 /* A new game or a savegame from an older version will require the counter to be initialized */
896 _economy.industry_daily_change_counter = 0;
897 }
898 }
899
900 void StartupEconomy()
901 {
902 _economy.interest_rate = _settings_game.difficulty.initial_interest;
903 _economy.infl_amount = _settings_game.difficulty.initial_interest;
904 _economy.infl_amount_pr = max(0, _settings_game.difficulty.initial_interest - 1);
905 _economy.fluct = GB(Random(), 0, 8) + 168;
906
907 /* Set up prices */
908 RecomputePrices();
909
910 StartupIndustryDailyChanges(true); // As we are starting a new game, initialize the counter too
911
912 }
913
917 void InitializeEconomy()
918 {
919 _economy.inflation_prices = _economy.inflation_payment = 1 << 16;
920 ClearCargoPickupMonitoring();
921 ClearCargoDeliveryMonitoring();
922 }
923
932 Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift)
933 {
934 if (index >= PR_END) return 0;
935
936 Money cost = _price[index] * cost_factor;
937 if (grf_file != NULL) shift += grf_file->price_base_multipliers[index];
938
939 if (shift >= 0) {
940 cost <<= shift;
941 } else {
942 cost >>= -shift;
943 }
944
945 return cost;
946 }
947
948 Money GetTransportedGoodsIncome(uint num_pieces, uint dist, byte transit_days, CargoID cargo_type)
949 {
950 const CargoSpec *cs = CargoSpec::Get(cargo_type);
951 if (!cs->IsValid()) {
952 /* User changed newgrfs and some vehicle still carries some cargo which is no longer available. */
953 return 0;
954 }
955
956 /* Use callback to calculate cargo profit, if available */
957 if (HasBit(cs->callback_mask, CBM_CARGO_PROFIT_CALC)) {
958 uint32 var18 = min(dist, 0xFFFF) | (min(num_pieces, 0xFF) << 16) | (transit_days << 24);
959 uint16 callback = GetCargoCallback(CBID_CARGO_PROFIT_CALC, 0, var18, cs);
960 if (callback != CALLBACK_FAILED) {
961 int result = GB(callback, 0, 14);
962
963 /* Simulate a 15 bit signed value */
964 if (HasBit(callback, 14)) result -= 0x4000;
965
966 /* "The result should be a signed multiplier that gets multiplied
967 * by the amount of cargo moved and the price factor, then gets
968 * divided by 8192." */
969 return result * num_pieces * cs->current_payment / 8192;
970 }
971 }
972
973 static const int MIN_TIME_FACTOR = 31;
974 static const int MAX_TIME_FACTOR = 255;
975
976 const int days1 = cs->transit_days[0];
977 const int days2 = cs->transit_days[1];
978 const int days_over_days1 = max( transit_days - days1, 0);
979 const int days_over_days2 = max(days_over_days1 - days2, 0);
980
981 /*
982 * The time factor is calculated based on the time it took
983 * (transit_days) compared two cargo-depending values. The
984 * range is divided into three parts:
985 *
986 * - constant for fast transits
987 * - linear decreasing with time with a slope of -1 for medium transports
988 * - linear decreasing with time with a slope of -2 for slow transports
989 *
990 */
991 const int time_factor = max(MAX_TIME_FACTOR - days_over_days1 - days_over_days2, MIN_TIME_FACTOR);
992
993 return BigMulS(dist * time_factor * num_pieces, cs->current_payment, 21);
994 }
995
997 static SmallIndustryList _cargo_delivery_destinations;
998
1008 static uint DeliverGoodsToIndustry(const Station *st, CargoID cargo_type, uint num_pieces, IndustryID source)
1009 {
1010 /* Find the nearest industrytile to the station sign inside the catchment area, whose industry accepts the cargo.
1011 * This fails in three cases:
1012 * 1) The station accepts the cargo because there are enough houses around it accepting the cargo.
1013 * 2) The industries in the catchment area temporarily reject the cargo, and the daily station loop has not yet updated station acceptance.
1014 * 3) The results of callbacks CBID_INDUSTRY_REFUSE_CARGO and CBID_INDTILE_CARGO_ACCEPTANCE are inconsistent. (documented behaviour)
1015 */
1016
1017 uint accepted = 0;
1018
1019 for (uint i = 0; i < st->industries_near.Length() && num_pieces != 0; i++) {
1020 Industry *ind = st->industries_near[i];
1021 if (ind->index == source) continue;
1022
1023 uint cargo_index;
1024 for (cargo_index = 0; cargo_index < lengthof(ind->accepts_cargo); cargo_index++) {
1025 if (cargo_type == ind->accepts_cargo[cargo_index]) break;
1026 }
1027 /* Check if matching cargo has been found */
1028 if (cargo_index >= lengthof(ind->accepts_cargo)) continue;
1029
1030 /* Check if industry temporarily refuses acceptance */
1031 if (IndustryTemporarilyRefusesCargo(ind, cargo_type)) continue;
1032
1033 /* Insert the industry into _cargo_delivery_destinations, if not yet contained */
1034 _cargo_delivery_destinations.Include(ind);
1035
1036 uint amount = min(num_pieces, 0xFFFFU - ind->incoming_cargo_waiting[cargo_index]);
1037 ind->incoming_cargo_waiting[cargo_index] += amount;
1038 num_pieces -= amount;
1039 accepted += amount;
1040 }
1041
1042 return accepted;
1043 }
1044
1058 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)
1059 {
1060 assert(num_pieces > 0);
1061
1062 Station *st = Station::Get(dest);
1063
1064 /* Give the goods to the industry. */
1065 uint accepted = DeliverGoodsToIndustry(st, cargo_type, num_pieces, src_type == ST_INDUSTRY ? src : INVALID_INDUSTRY);
1066
1067 /* If this cargo type is always accepted, accept all */
1068 if (HasBit(st->always_accepted, cargo_type)) accepted = num_pieces;
1069
1070 /* Update station statistics */
1071 if (accepted > 0) {
1072 SetBit(st->goods[cargo_type].status, GoodsEntry::GES_EVER_ACCEPTED);
1073 SetBit(st->goods[cargo_type].status, GoodsEntry::GES_CURRENT_MONTH);
1074 SetBit(st->goods[cargo_type].status, GoodsEntry::GES_ACCEPTED_BIGTICK);
1075 }
1076
1077 /* Update company statistics */
1078 company->cur_economy.delivered_cargo[cargo_type] += accepted;
1079
1080 /* Increase town's counter for town effects */
1081 const CargoSpec *cs = CargoSpec::Get(cargo_type);
1082 st->town->received[cs->town_effect].new_act += accepted;
1083
1084 /* Determine profit */
1085 Money profit = GetTransportedGoodsIncome(accepted, DistanceManhattan(source_tile, st->xy), days_in_transit, cargo_type);
1086
1087 /* Update the cargo monitor. */
1088 AddCargoDelivery(cargo_type, company->index, accepted, src_type, src, st);
1089
1090 /* Modify profit if a subsidy is in effect */
1091 if (CheckSubsidised(cargo_type, company->index, src_type, src, st)) {
1092 switch (_settings_game.difficulty.subsidy_multiplier) {
1093 case 0: profit += profit >> 1; break;
1094 case 1: profit *= 2; break;
1095 case 2: profit *= 3; break;
1096 default: profit *= 4; break;
1097 }
1098 }
1099
1100 return profit;
1101 }
1102
1108 static void TriggerIndustryProduction(Industry *i)
1109 {
1110 const IndustrySpec *indspec = GetIndustrySpec(i->type);
1111 uint16 callback = indspec->callback_mask;
1112
1113 i->was_cargo_delivered = true;
1114 i->last_cargo_accepted_at = _date;
1115
1116 if (HasBit(callback, CBM_IND_PRODUCTION_CARGO_ARRIVAL) || HasBit(callback, CBM_IND_PRODUCTION_256_TICKS)) {
1117 if (HasBit(callback, CBM_IND_PRODUCTION_CARGO_ARRIVAL)) {
1118 IndustryProductionCallback(i, 0);
1119 } else {
1120 SetWindowDirty(WC_INDUSTRY_VIEW, i->index);
1121 }
1122 } else {
1123 for (uint cargo_index = 0; cargo_index < lengthof(i->incoming_cargo_waiting); cargo_index++) {
1124 uint cargo_waiting = i->incoming_cargo_waiting[cargo_index];
1125 if (cargo_waiting == 0) continue;
1126
1127 i->produced_cargo_waiting[0] = min(i->produced_cargo_waiting[0] + (cargo_waiting * indspec->input_cargo_multiplier[cargo_index][0] / 256), 0xFFFF);
1128 i->produced_cargo_waiting[1] = min(i->produced_cargo_waiting[1] + (cargo_waiting * indspec->input_cargo_multiplier[cargo_index][1] / 256), 0xFFFF);
1129
1130 i->incoming_cargo_waiting[cargo_index] = 0;
1131 }
1132 }
1133
1134 TriggerIndustry(i, INDUSTRY_TRIGGER_RECEIVED_CARGO);
1135 StartStopIndustryTileAnimation(i, IAT_INDUSTRY_RECEIVED_CARGO);
1136 }
1137
1142 CargoPayment::CargoPayment(Vehicle *front) :
1143 front(front),
1144 current_station(front->last_station_visited)
1145 {
1146 }
1147
1148 CargoPayment::~CargoPayment()
1149 {
1150 if (this->CleaningPool()) return;
1151
1152 this->front->cargo_payment = NULL;
1153
1154 if (this->visual_profit == 0 && this->visual_transfer == 0) return;
1155
1156 Backup<CompanyByte> cur_company(_current_company, this->front->owner, FILE_LINE);
1157
1158 SubtractMoneyFromCompany(CommandCost(this->front->GetExpenseType(true), -this->route_profit));
1159 this->front->profit_this_year += (this->visual_profit + this->visual_transfer) << 8;
1160
1161 if (this->route_profit != 0 && IsLocalCompany() && !PlayVehicleSound(this->front, VSE_LOAD_UNLOAD)) {
1162 SndPlayVehicleFx(SND_14_CASHTILL, this->front);
1163 }
1164
1165 if (this->visual_transfer != 0) {
1166 ShowFeederIncomeAnimation(this->front->x_pos, this->front->y_pos,
1167 this->front->z_pos, this->visual_transfer, -this->visual_profit);
1168 } else if (this->visual_profit != 0) {
1169 ShowCostOrIncomeAnimation(this->front->x_pos, this->front->y_pos,
1170 this->front->z_pos, -this->visual_profit);
1171 }
1172
1173 cur_company.Restore();
1174 }
1175
1181 void CargoPayment::PayFinalDelivery(const CargoPacket *cp, uint count)
1182 {
1183 if (this->owner == NULL) {
1184 this->owner = Company::Get(this->front->owner);
1185 }
1186
1187 /* Handle end of route payment */
1188 Money profit = DeliverGoods(count, this->ct, this->current_station, cp->SourceStationXY(), cp->DaysInTransit(), this->owner, cp->SourceSubsidyType(), cp->SourceSubsidyID());
1189 this->route_profit += profit;
1190
1191 /* The vehicle's profit is whatever route profit there is minus feeder shares. */
1192 this->visual_profit += profit - cp->FeederShare(count);
1193 }
1194
1201 Money CargoPayment::PayTransfer(const CargoPacket *cp, uint count)
1202 {
1203 Money profit = GetTransportedGoodsIncome(
1204 count,
1205 /* pay transfer vehicle for only the part of transfer it has done: ie. cargo_loaded_at_xy to here */
1206 DistanceManhattan(cp->LoadedAtXY(), Station::Get(this->current_station)->xy),
1207 cp->DaysInTransit(),
1208 this->ct);
1209
1210 profit = profit * _settings_game.economy.feeder_payment_share / 100;
1211
1212 this->visual_transfer += profit; // accumulate transfer profits for whole vehicle
1213 return profit; // account for the (virtual) profit already made for the cargo packet
1214 }
1215
1221 void PrepareUnload(Vehicle *front_v)
1222 {
1223 Station *curr_station = Station::Get(front_v->last_station_visited);
1224 curr_station->loading_vehicles.push_back(front_v);
1225
1226 /* At this moment loading cannot be finished */
1227 ClrBit(front_v->vehicle_flags, VF_LOADING_FINISHED);
1228
1229 /* Start unloading at the first possible moment */
1230 front_v->load_unload_ticks = 1;
1231
1232 assert(front_v->cargo_payment == NULL);
1233 /* One CargoPayment per vehicle and the vehicle limit equals the
1234 * limit in number of CargoPayments. Can't go wrong. */
1235 assert_compile(CargoPaymentPool::MAX_SIZE == VehiclePool::MAX_SIZE);
1236 assert(CargoPayment::CanAllocateItem());
1237 front_v->cargo_payment = new CargoPayment(front_v);
1238
1239 StationIDStack next_station = front_v->GetNextStoppingStation();
1240 if (front_v->orders.list == NULL || (front_v->current_order.GetUnloadType() & OUFB_NO_UNLOAD) == 0) {
1241 Station *st = Station::Get(front_v->last_station_visited);
1242 for (Vehicle *v = front_v; v != NULL; v = v->Next()) {
1243 const GoodsEntry *ge = &st->goods[v->cargo_type];
1244 if (v->cargo_cap > 0 && v->cargo.TotalCount() > 0) {
1245 v->cargo.Stage(
1246 HasBit(ge->status, GoodsEntry::GES_ACCEPTANCE),
1247 front_v->last_station_visited, next_station,
1248 front_v->current_order.GetUnloadType(), ge,
1249 front_v->cargo_payment);
1250 if (v->cargo.UnloadCount() > 0) SetBit(v->vehicle_flags, VF_CARGO_UNLOADING);
1251 }
1252 }
1253 }
1254 }
1255
1262 static uint GetLoadAmount(Vehicle *v)
1263 {
1264 const Engine *e = v->GetEngine();
1265 uint load_amount = e->info.load_amount;
1266
1267 /* The default loadamount for mail is 1/4 of the load amount for passengers */
1268 bool air_mail = v->type == VEH_AIRCRAFT && !Aircraft::From(v)->IsNormalAircraft();
1269 if (air_mail) load_amount = CeilDiv(load_amount, 4);
1270
1271 if (_settings_game.order.gradual_loading) {
1272 uint16 cb_load_amount = CALLBACK_FAILED;
1273 if (e->GetGRF() != NULL && e->GetGRF()->grf_version >= 8) {
1274 /* Use callback 36 */
1275 cb_load_amount = GetVehicleProperty(v, PROP_VEHICLE_LOAD_AMOUNT, CALLBACK_FAILED);
1276 } else if (HasBit(e->info.callback_mask, CBM_VEHICLE_LOAD_AMOUNT)) {
1277 /* Use callback 12 */
1278 cb_load_amount = GetVehicleCallback(CBID_VEHICLE_LOAD_AMOUNT, 0, 0, v->engine_type, v);
1279 }
1280 if (cb_load_amount != CALLBACK_FAILED) {
1281 if (e->GetGRF()->grf_version < 8) cb_load_amount = GB(cb_load_amount, 0, 8);
1282 if (cb_load_amount >= 0x100) {
1283 ErrorUnknownCallbackResult(e->GetGRFID(), CBID_VEHICLE_LOAD_AMOUNT, cb_load_amount);
1284 } else if (cb_load_amount != 0) {
1285 load_amount = cb_load_amount;
1286 }
1287 }
1288 }
1289
1290 /* Scale load amount the same as capacity */
1291 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);
1292
1293 return load_amount;
1294 }
1295
1305 template<class Taction>
1306 bool IterateVehicleParts(Vehicle *v, Taction action)
1307 {
1308 for (Vehicle *w = v; w != NULL;
1309 w = w->HasArticulatedPart() ? w->GetNextArticulatedPart() : NULL) {
1310 if (!action(w)) return false;
1311 if (w->type == VEH_TRAIN) {
1312 Train *train = Train::From(w);
1313 if (train->IsMultiheaded() && !action(train->other_multiheaded_part)) return false;
1314 }
1315 }
1316 if (v->type == VEH_AIRCRAFT && Aircraft::From(v)->IsNormalAircraft()) return action(v->Next());
1317 return true;
1318 }
1319
1323 struct IsEmptyAction
1324 {
1330 bool operator()(const Vehicle *v)
1331 {
1332 return v->cargo.StoredCount() == 0;
1333 }
1334 };
1335
1339 struct PrepareRefitAction
1340 {
1341 CargoArray &consist_capleft;
1342 uint32 &refit_mask;
1343
1349 PrepareRefitAction(CargoArray &consist_capleft, uint32 &refit_mask) :
1350 consist_capleft(consist_capleft), refit_mask(refit_mask) {}
1351
1358 bool operator()(const Vehicle *v)
1359 {
1360 this->consist_capleft[v->cargo_type] -= v->cargo_cap - v->cargo.ReservedCount();
1361 this->refit_mask |= EngInfo(v->engine_type)->refit_mask;
1362 return true;
1363 }
1364 };
1365
1369 struct ReturnCargoAction
1370 {
1371 Station *st;
1372 StationID next_hop;
1373
1379 ReturnCargoAction(Station *st, StationID next_one) : st(st), next_hop(next_one) {}
1380
1386 bool operator()(Vehicle *v)
1387 {
1388 v->cargo.Return(UINT_MAX, &this->st->goods[v->cargo_type].cargo, this->next_hop);
1389 return true;
1390 }
1391 };
1392
1396 struct FinalizeRefitAction
1397 {
1398 CargoArray &consist_capleft;
1399 Station *st;
1400 StationIDStack &next_station;
1401 bool do_reserve;
1402
1410 FinalizeRefitAction(CargoArray &consist_capleft, Station *st, StationIDStack &next_station, bool do_reserve) :
1411 consist_capleft(consist_capleft), st(st), next_station(next_station), do_reserve(do_reserve) {}
1412
1419 bool operator()(Vehicle *v)
1420 {
1421 if (this->do_reserve) {
1422 this->st->goods[v->cargo_type].cargo.Reserve(v->cargo_cap - v->cargo.RemainingCount(),
1423 &v->cargo, st->xy, this->next_station);
1424 }
1425 this->consist_capleft[v->cargo_type] += v->cargo_cap - v->cargo.RemainingCount();
1426 return true;
1427 }
1428 };
1429
1438 static void HandleStationRefit(Vehicle *v, CargoArray &consist_capleft, Station *st, StationIDStack next_station, CargoID new_cid)
1439 {
1440 Vehicle *v_start = v->GetFirstEnginePart();
1441 if (!IterateVehicleParts(v_start, IsEmptyAction())) return;
1442
1443 Backup<CompanyByte> cur_company(_current_company, v->owner, FILE_LINE);
1444
1445 uint32 refit_mask = v->GetEngine()->info.refit_mask;
1446
1447 /* Remove old capacity from consist capacity and collect refit mask. */
1448 IterateVehicleParts(v_start, PrepareRefitAction(consist_capleft, refit_mask));
1449
1450 bool is_auto_refit = new_cid == CT_AUTO_REFIT;
1451 if (is_auto_refit) {
1452 /* Get a refittable cargo type with waiting cargo for next_station or INVALID_STATION. */
1453 CargoID cid;
1454 new_cid = v_start->cargo_type;
1455 FOR_EACH_SET_CARGO_ID(cid, refit_mask) {
1456 if (st->goods[cid].cargo.HasCargoFor(next_station)) {
1457 /* Try to find out if auto-refitting would succeed. In case the refit is allowed,
1458 * the returned refit capacity will be greater than zero. */
1459 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.
1460 /* Try to balance different loadable cargoes between parts of the consist, so that
1461 * all of them can be loaded. Avoid a situation where all vehicles suddenly switch
1462 * to the first loadable cargo for which there is only one packet. If the capacities
1463 * are equal refit to the cargo of which most is available. This is important for
1464 * consists of only a single vehicle as those will generally have a consist_capleft
1465 * of 0 for all cargoes. */
1466 if (_returned_refit_capacity > 0 && (consist_capleft[cid] < consist_capleft[new_cid] ||
1467 (consist_capleft[cid] == consist_capleft[new_cid] &&
1468 st->goods[cid].cargo.AvailableCount() > st->goods[new_cid].cargo.AvailableCount()))) {
1469 new_cid = cid;
1470 }
1471 }
1472 }
1473 }
1474
1475 /* Refit if given a valid cargo. */
1476 if (new_cid < NUM_CARGO && new_cid != v_start->cargo_type) {
1477 /* INVALID_STATION because in the DT_MANUAL case that's correct and in the DT_(A)SYMMETRIC
1478 * cases the next hop of the vehicle doesn't really tell us anything if the cargo had been
1479 * "via any station" before reserving. We rather produce some more "any station" cargo than
1480 * misrouting it. */
1481 IterateVehicleParts(v_start, ReturnCargoAction(st, INVALID_STATION));
1482 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.
1483 if (cost.Succeeded()) v->First()->profit_this_year -= cost.GetCost() << 8;
1484 }
1485
1486 /* Add new capacity to consist capacity and reserve cargo */
1487 IterateVehicleParts(v_start, FinalizeRefitAction(consist_capleft, st, next_station,
1488 is_auto_refit || (v->First()->current_order.GetLoadType() & OLFB_FULL_LOAD) != 0));
1489
1490 cur_company.Restore();
1491 }
1492
1493 struct ReserveCargoAction {
1494 Station *st;
1495 StationIDStack *next_station;
1496
1497 ReserveCargoAction(Station *st, StationIDStack *next_station) :
1498 st(st), next_station(next_station) {}
1499
1500 bool operator()(Vehicle *v)
1501 {
1502 if (v->cargo_cap > v->cargo.RemainingCount()) {
1503 st->goods[v->cargo_type].cargo.Reserve(v->cargo_cap - v->cargo.RemainingCount(),
1504 &v->cargo, st->xy, *next_station);
1505 }
1506
1507 return true;
1508 }
1509
1510 };
1511
1520 static void ReserveConsist(Station *st, Vehicle *u, CargoArray *consist_capleft, StationIDStack *next_station)
1521 {
1522 /* If there is a cargo payment not all vehicles of the consist have tried to do the refit.
1523 * In that case, only reserve if it's a fixed refit and the equivalent of "articulated chain"
1524 * a vehicle belongs to already has the right cargo. */
1525 bool must_reserve = !u->current_order.IsRefit() || u->cargo_payment == NULL;
1526 for (Vehicle *v = u; v != NULL; v = v->Next()) {
1527 assert(v->cargo_cap >= v->cargo.RemainingCount());
1528
1529 /* Exclude various ways in which the vehicle might not be the head of an equivalent of
1530 * "articulated chain". Also don't do the reservation if the vehicle is going to refit
1531 * to a different cargo and hasn't tried to do so, yet. */
1532 if (!v->IsArticulatedPart() &&
1533 (v->type != VEH_TRAIN || !Train::From(v)->IsRearDualheaded()) &&
1534 (v->type != VEH_AIRCRAFT || Aircraft::From(v)->IsNormalAircraft()) &&
1535 (must_reserve || u->current_order.GetRefitCargo() == v->cargo_type)) {
1536 IterateVehicleParts(v, ReserveCargoAction(st, next_station));
1537 }
1538 if (consist_capleft == NULL || v->cargo_cap == 0) continue;
1539 (*consist_capleft)[v->cargo_type] += v->cargo_cap - v->cargo.RemainingCount();
1540 }
1541 }
1542
1550 static void UpdateLoadUnloadTicks(Vehicle *front, const Station *st, int ticks)
1551 {
1552 if (front->type == VEH_TRAIN) {
1553 /* Each platform tile is worth 2 rail vehicles. */
1554 int overhang = front->GetGroundVehicleCache()->cached_total_length - st->GetPlatformLength(front->tile) * TILE_SIZE;
1555 if (overhang > 0) {
1556 ticks <<= 1;
1557 ticks += (overhang * ticks) / 8;
1558 }
1559 }
1560 /* Always wait at least 1, otherwise we'll wait 'infinitively' long. */
1561 front->load_unload_ticks = max(1, ticks);
1562 }
1563
1568 static void LoadUnloadVehicle(Vehicle *front)
1569 {
1570 assert(front->current_order.IsType(OT_LOADING));
1571
1572 StationID last_visited = front->last_station_visited;
1573 Station *st = Station::Get(last_visited);
1574
1575 StationIDStack next_station = front->GetNextStoppingStation();
1576 bool use_autorefit = front->current_order.IsRefit() && front->current_order.GetRefitCargo() == CT_AUTO_REFIT;
1577 CargoArray consist_capleft;
1578 if (_settings_game.order.improved_load && use_autorefit ?
1579 front->cargo_payment == NULL : (front->current_order.GetLoadType() & OLFB_FULL_LOAD) != 0) {
1580 ReserveConsist(st, front,
1581 (use_autorefit && front->load_unload_ticks != 0) ? &consist_capleft : NULL,
1582 &next_station);
1583 }
1584
1585 /* We have not waited enough time till the next round of loading/unloading */
1586 if (front->load_unload_ticks != 0) return;
1587
1588 if (front->type == VEH_TRAIN && (!IsTileType(front->tile, MP_STATION) || GetStationIndex(front->tile) != st->index)) {
1589 /* The train reversed in the station. Take the "easy" way
1590 * out and let the train just leave as it always did. */
1591 SetBit(front->vehicle_flags, VF_LOADING_FINISHED);
1592 front->load_unload_ticks = 1;
1593 return;
1594 }
1595
1596 int new_load_unload_ticks = 0;
1597 bool dirty_vehicle = false;
1598 bool dirty_station = false;
1599
1600 bool completely_emptied = true;
1601 bool anything_unloaded = false;
1602 bool anything_loaded = false;
1603 uint32 full_load_amount = 0;
1604 uint32 cargo_not_full = 0;
1605 uint32 cargo_full = 0;
1606 uint32 reservation_left = 0;
1607
1608 front->cur_speed = 0;
1609
1610 CargoPayment *payment = front->cargo_payment;
1611
1612 uint artic_part = 0; // Articulated part we are currently trying to load. (not counting parts without capacity)
1613 for (Vehicle *v = front; v != NULL; v = v->Next()) {
1614 if (v == front || !v->Previous()->HasArticulatedPart()) artic_part = 0;
1615 if (v->cargo_cap == 0) continue;
1616 artic_part++;
1617
1618 uint load_amount = GetLoadAmount(v);
1619
1620 GoodsEntry *ge = &st->goods[v->cargo_type];
1621
1622 if (HasBit(v->vehicle_flags, VF_CARGO_UNLOADING) && (front->current_order.GetUnloadType() & OUFB_NO_UNLOAD) == 0) {
1623 uint cargo_count = v->cargo.UnloadCount();
1624 uint amount_unloaded = _settings_game.order.gradual_loading ? min(cargo_count, load_amount) : cargo_count;
1625 bool remaining = false; // Are there cargo entities in this vehicle that can still be unloaded here?
1626
1627 payment->SetCargo(v->cargo_type);
1628
1629 if (!HasBit(ge->status, GoodsEntry::GES_ACCEPTANCE) && v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER) > 0) {
1630 /* The station does not accept our goods anymore. */
1631 if (front->current_order.GetUnloadType() & (OUFB_TRANSFER | OUFB_UNLOAD)) {
1632 /* Transfer instead of delivering. */
1633 v->cargo.Reassign<VehicleCargoList::MTA_DELIVER, VehicleCargoList::MTA_TRANSFER>(
1634 v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER), INVALID_STATION);
1635 } else {
1636 uint new_remaining = v->cargo.RemainingCount() + v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER);
1637 if (v->cargo_cap < new_remaining) {
1638 /* Return some of the reserved cargo to not overload the vehicle. */
1639 v->cargo.Return(new_remaining - v->cargo_cap, &ge->cargo, INVALID_STATION);
1640 }
1641
1642 /* Keep instead of delivering. This may lead to no cargo being unloaded, so ...*/
1643 v->cargo.Reassign<VehicleCargoList::MTA_DELIVER, VehicleCargoList::MTA_KEEP>(
1644 v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER));
1645
1646 /* ... say we unloaded something, otherwise we'll think we didn't unload
1647 * something and we didn't load something, so we must be finished
1648 * at this station. Setting the unloaded means that we will get a
1649 * retry for loading in the next cycle. */
1650 anything_unloaded = true;
1651 }
1652 }
1653
1654 if (v->cargo.ActionCount(VehicleCargoList::MTA_TRANSFER) > 0) {
1655 /* Mark the station dirty if we transfer, but not if we only deliver. */
1656 dirty_station = true;
1657
1658 if (!ge->HasRating()) {
1659 /* Upon transfering cargo, make sure the station has a rating. Fake a pickup for the
1660 * first unload to prevent the cargo from quickly decaying after the initial drop. */
1661 ge->time_since_pickup = 0;
1662 SetBit(ge->status, GoodsEntry::GES_RATING);
1663 }
1664 }
1665
1666 amount_unloaded = v->cargo.Unload(amount_unloaded, &ge->cargo, payment);
1667 remaining = v->cargo.UnloadCount() > 0;
1668 if (amount_unloaded > 0) {
1669 dirty_vehicle = true;
1670 anything_unloaded = true;
1671 new_load_unload_ticks += amount_unloaded;
1672
1673 /* Deliver goods to the station */
1674 st->time_since_unload = 0;
1675 }
1676
1677 if (_settings_game.order.gradual_loading && remaining) {
1678 completely_emptied = false;
1679 } else {
1680 /* We have finished unloading (cargo count == 0) */
1681 ClrBit(v->vehicle_flags, VF_CARGO_UNLOADING);
1682 }
1683
1684 continue;
1685 }
1686
1687 /* Do not pick up goods when we have no-load set or loading is stopped. */
1688 if (front->current_order.GetLoadType() & OLFB_NO_LOAD || HasBit(front->vehicle_flags, VF_STOP_LOADING)) continue;
1689
1690 /* This order has a refit, if this is the first vehicle part carrying cargo and the whole vehicle is empty, try refitting. */
1691 if (front->current_order.IsRefit() && artic_part == 1) {
1692 HandleStationRefit(v, consist_capleft, st, next_station, front->current_order.GetRefitCargo());
1693 ge = &st->goods[v->cargo_type];
1694 }
1695
1696 /* As we're loading here the following link can carry the full capacity of the vehicle. */
1697 v->refit_cap = v->cargo_cap;
1698
1699 /* update stats */
1700 int t;
1701 switch (front->type) {
1702 case VEH_TRAIN: /* FALL THROUGH */
1703 case VEH_SHIP:
1704 t = front->vcache.cached_max_speed;
1705 break;
1706
1707 case VEH_ROAD:
1708 t = front->vcache.cached_max_speed / 2;
1709 break;
1710
1711 case VEH_AIRCRAFT:
1712 t = Aircraft::From(front)->GetSpeedOldUnits(); // Convert to old units.
1713 break;
1714
1715 default: NOT_REACHED();
1716 }
1717
1718 /* if last speed is 0, we treat that as if no vehicle has ever visited the station. */
1719 ge->last_speed = min(t, 255);
1720 ge->last_age = min(_cur_year - front->build_year, 255);
1721 ge->time_since_pickup = 0;
1722
1723 assert(v->cargo_cap >= v->cargo.StoredCount());
1724 /* If there's goods waiting at the station, and the vehicle
1725 * has capacity for it, load it on the vehicle. */
1726 uint cap_left = v->cargo_cap - v->cargo.StoredCount();
1727 if (cap_left > 0 && (v->cargo.ActionCount(VehicleCargoList::MTA_LOAD) > 0 || ge->cargo.AvailableCount() > 0)) {
1728 if (_settings_game.order.gradual_loading) cap_left = min(cap_left, load_amount);
1729 if (v->cargo.StoredCount() == 0) TriggerVehicle(v, VEHICLE_TRIGGER_NEW_CARGO);
1730
1731 uint loaded = ge->cargo.Load(cap_left, &v->cargo, st->xy, next_station);
1732 if (v->cargo.ActionCount(VehicleCargoList::MTA_LOAD) > 0) {
1733 /* Remember if there are reservations left so that we don't stop
1734 * loading before they're loaded. */
1735 SetBit(reservation_left, v->cargo_type);
1736 }
1737
1738 /* Store whether the maximum possible load amount was loaded or not.*/
1739 if (loaded == cap_left) {
1740 SetBit(full_load_amount, v->cargo_type);
1741 } else {
1742 ClrBit(full_load_amount, v->cargo_type);
1743 }
1744
1745 /* TODO: Regarding this, when we do gradual loading, we
1746 * should first unload all vehicles and then start
1747 * loading them. Since this will cause
1748 * VEHICLE_TRIGGER_EMPTY to be called at the time when
1749 * the whole vehicle chain is really totally empty, the
1750 * completely_emptied assignment can then be safely
1751 * removed; that's how TTDPatch behaves too. --pasky */
1752 if (loaded > 0) {
1753 completely_emptied = false;
1754 anything_loaded = true;
1755
1756 st->time_since_load = 0;
1757 st->last_vehicle_type = v->type;
1758
1759 if (ge->cargo.TotalCount() == 0) {
1760 TriggerStationRandomisation(st, st->xy, SRT_CARGO_TAKEN, v->cargo_type);
1761 TriggerStationAnimation(st, st->xy, SAT_CARGO_TAKEN, v->cargo_type);
1762 AirportAnimationTrigger(st, AAT_STATION_CARGO_TAKEN, v->cargo_type);
1763 }
1764
1765 new_load_unload_ticks += loaded;
1766
1767 dirty_vehicle = dirty_station = true;
1768 }
1769 }
1770
1771 if (v->cargo.StoredCount() >= v->cargo_cap) {
1772 SetBit(cargo_full, v->cargo_type);
1773 } else {
1774 SetBit(cargo_not_full, v->cargo_type);
1775 }
1776 }
1777
1778 if (anything_loaded || anything_unloaded) {
1779 if (front->type == VEH_TRAIN) {
1780 TriggerStationRandomisation(st, front->tile, SRT_TRAIN_LOADS);
1781 TriggerStationAnimation(st, front->tile, SAT_TRAIN_LOADS);
1782 }
1783 }
1784
1785 /* Only set completely_emptied, if we just unloaded all remaining cargo */
1786 completely_emptied &= anything_unloaded;
1787
1788 if (!anything_unloaded) delete payment;
1789
1790 ClrBit(front->vehicle_flags, VF_STOP_LOADING);
1791 if (anything_loaded || anything_unloaded) {
1792 if (_settings_game.order.gradual_loading) {
1793 /* The time it takes to load one 'slice' of cargo or passengers depends
1794 * on the vehicle type - the values here are those found in TTDPatch */
1795 const uint gradual_loading_wait_time[] = { 40, 20, 10, 20 };
1796
1797 new_load_unload_ticks = gradual_loading_wait_time[front->type];
1798 }
1799 /* We loaded less cargo than possible for all cargo types and it's not full
1800 * load and we're not supposed to wait any longer: stop loading. */
1801 if (!anything_unloaded && full_load_amount == 0 && reservation_left == 0 && !(front->current_order.GetLoadType() & OLFB_FULL_LOAD) &&
1802 front->current_order_time >= (uint)max(front->current_order.GetTimetabledWait() - front->lateness_counter, 0)) {
1803 SetBit(front->vehicle_flags, VF_STOP_LOADING);
1804 }
1805
1806 UpdateLoadUnloadTicks(front, st, new_load_unload_ticks);
1807 } else {
1808 UpdateLoadUnloadTicks(front, st, 20); // We need the ticks for link refreshing.
1809 bool finished_loading = true;
1810 if (front->current_order.GetLoadType() & OLFB_FULL_LOAD) {
1811 if (front->current_order.GetLoadType() == OLF_FULL_LOAD_ANY) {
1812 /* if the aircraft carries passengers and is NOT full, then
1813 * continue loading, no matter how much mail is in */
1814 if ((front->type == VEH_AIRCRAFT && IsCargoInClass(front->cargo_type, CC_PASSENGERS) && front->cargo_cap > front->cargo.StoredCount()) ||
1815 (cargo_not_full && (cargo_full & ~cargo_not_full) == 0)) { // There are still non-full cargoes
1816 finished_loading = false;
1817 }
1818 } else if (cargo_not_full != 0) {
1819 finished_loading = false;
1820 }
1821
1822 /* Refresh next hop stats if we're full loading to make the links
1823 * known to the distribution algorithm and allow cargo to be sent
1824 * along them. Otherwise the vehicle could wait for cargo
1825 * indefinitely if it hasn't visited the other links yet, or if the
1826 * links die while it's loading. */
1827 if (!finished_loading) LinkRefresher::Run(front, true, true);
1828 }
1829
1830 SB(front->vehicle_flags, VF_LOADING_FINISHED, 1, finished_loading);
1831 }
1832
1833 /* Calculate the loading indicator fill percent and display
1834 * In the Game Menu do not display indicators
1835 * If _settings_client.gui.loading_indicators == 2, show indicators (bool can be promoted to int as 0 or 1 - results in 2 > 0,1 )
1836 * if _settings_client.gui.loading_indicators == 1, _local_company must be the owner or must be a spectator to show ind., so 1 > 0
1837 * if _settings_client.gui.loading_indicators == 0, do not display indicators ... 0 is never greater than anything
1838 */
1839 if (_game_mode != GM_MENU && (_settings_client.gui.loading_indicators > (uint)(front->owner != _local_company && _local_company != COMPANY_SPECTATOR))) {
1840 StringID percent_up_down = STR_NULL;
1841 int percent = CalcPercentVehicleFilled(front, &percent_up_down);
1842 if (front->fill_percent_te_id == INVALID_TE_ID) {
1843 front->fill_percent_te_id = ShowFillingPercent(front->x_pos, front->y_pos, front->z_pos + 20, percent, percent_up_down);
1844 } else {
1845 UpdateFillingPercent(front->fill_percent_te_id, percent, percent_up_down);
1846 }
1847 }
1848
1849 if (completely_emptied) {
1850 /* Make sure the vehicle is marked dirty, since we need to update the NewGRF
1851 * properties such as weight, power and TE whenever the trigger runs. */
1852 dirty_vehicle = true;
1853 TriggerVehicle(front, VEHICLE_TRIGGER_EMPTY);
1854 }
1855
1856 if (dirty_vehicle) {
1857 SetWindowDirty(GetWindowClassForVehicleType(front->type), front->owner);
1858 SetWindowDirty(WC_VEHICLE_DETAILS, front->index);
1859 front->MarkDirty();
1860 }
1861 if (dirty_station) {
1862 st->MarkTilesDirty(true);
1863 SetWindowDirty(WC_STATION_VIEW, last_visited);
1864 InvalidateWindowData(WC_STATION_LIST, last_visited);
1865 }
1866 }
1867
1873 void LoadUnloadStation(Station *st)
1874 {
1875 /* No vehicle is here... */
1876 if (st->loading_vehicles.empty()) return;
1877
1878 Vehicle *last_loading = NULL;
1879 std::list<Vehicle *>::iterator iter;
1880
1881 /* Check if anything will be loaded at all. Otherwise we don't need to reserve either. */
1882 for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end(); ++iter) {
1883 Vehicle *v = *iter;
1884
1885 if ((v->vehstatus & (VS_STOPPED | VS_CRASHED))) continue;
1886
1887 assert(v->load_unload_ticks != 0);
1888 if (--v->load_unload_ticks == 0) last_loading = v;
1889 }
1890
1891 /* We only need to reserve and load/unload up to the last loading vehicle.
1892 * Anything else will be forgotten anyway after returning from this function.
1893 *
1894 * Especially this means we do _not_ need to reserve cargo for a single
1895 * consist in a station which is not allowed to load yet because its
1896 * load_unload_ticks is still not 0.
1897 */
1898 if (last_loading == NULL) return;
1899
1900 for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end(); ++iter) {
1901 Vehicle *v = *iter;
1902 if (!(v->vehstatus & (VS_STOPPED | VS_CRASHED))) LoadUnloadVehicle(v);
1903 if (v == last_loading) break;
1904 }
1905
1906 /* Call the production machinery of industries */
1907 const Industry * const *isend = _cargo_delivery_destinations.End();
1908 for (Industry **iid = _cargo_delivery_destinations.Begin(); iid != isend; iid++) {
1909 TriggerIndustryProduction(*iid);
1910 }
1911 _cargo_delivery_destinations.Clear();
1912 }
1913
1917 void CompaniesMonthlyLoop()
1918 {
1919 CompaniesGenStatistics();
1920 if (_settings_game.economy.inflation) {
1921 AddInflation();
1922 RecomputePrices();
1923 }
1924 CompaniesPayInterest();
1925 HandleEconomyFluctuations();
1926 }
1927
1928 static void DoAcquireCompany(Company *c)
1929 {
1930 CompanyID ci = c->index;
1931
1932 CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
1933 cni->FillData(c, Company::Get(_current_company));
1934
1935 SetDParam(0, STR_NEWS_COMPANY_MERGER_TITLE);
1936 SetDParam(1, c->bankrupt_value == 0 ? STR_NEWS_MERGER_TAKEOVER_TITLE : STR_NEWS_COMPANY_MERGER_DESCRIPTION);
1937 SetDParamStr(2, cni->company_name);
1938 SetDParamStr(3, cni->other_company_name);
1939 SetDParam(4, c->bankrupt_value);
1940 AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, cni);
1941 AI::BroadcastNewEvent(new ScriptEventCompanyMerger(ci, _current_company));
1942 Game::NewEvent(new ScriptEventCompanyMerger(ci, _current_company));
1943
1944 ChangeOwnershipOfCompanyItems(ci, _current_company);
1945
1946 if (c->bankrupt_value == 0) {
1947 Company *owner = Company::Get(_current_company);
1948 owner->current_loan += c->current_loan;
1949 }
1950
1951 if (c->is_ai) AI::Stop(c->index);
1952
1953 DeleteCompanyWindows(ci);
1954 InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
1955 InvalidateWindowClassesData(WC_SHIPS_LIST, 0);
1956 InvalidateWindowClassesData(WC_ROADVEH_LIST, 0);
1957 InvalidateWindowClassesData(WC_AIRCRAFT_LIST, 0);
1958
1959 delete c;
1960 }
1961
1962 extern int GetAmountOwnedBy(const Company *c, Owner owner);
1963
1973 CommandCost CmdBuyShareInCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1974 {
1975 CommandCost cost(EXPENSES_OTHER);
1976 CompanyID target_company = (CompanyID)p1;
1977 Company *c = Company::GetIfValid(target_company);
1978
1979 /* Check if buying shares is allowed (protection against modified clients)
1980 * Cannot buy own shares */
1981 if (c == NULL || !_settings_game.economy.allow_shares || _current_company == target_company) return CMD_ERROR;
1982
1983 /* Protect new companies from hostile takeovers */
1984 if (_cur_year - c->inaugurated_year < 6) return_cmd_error(STR_ERROR_PROTECTED);
1985
1986 /* Those lines are here for network-protection (clients can be slow) */
1987 if (GetAmountOwnedBy(c, COMPANY_SPECTATOR) == 0) return cost;
1988
1989 if (GetAmountOwnedBy(c, COMPANY_SPECTATOR) == 1) {
1990 if (!c->is_ai) return cost; // We can not buy out a real company (temporarily). TODO: well, enable it obviously.
1991
1992 if (GetAmountOwnedBy(c, _current_company) == 3 && !MayCompanyTakeOver(_current_company, target_company)) return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
1993 }
1994
1995
1996 cost.AddCost(CalculateCompanyValue(c) >> 2);
1997 if (flags & DC_EXEC) {
1998 OwnerByte *b = c->share_owners;
1999
2000 while (*b != COMPANY_SPECTATOR) b++; // share owners is guaranteed to contain at least one COMPANY_SPECTATOR
2001 *b = _current_company;
2002
2003 for (int i = 0; c->share_owners[i] == _current_company;) {
2004 if (++i == 4) {
2005 c->bankrupt_value = 0;
2006 DoAcquireCompany(c);
2007 break;
2008 }
2009 }
2010 InvalidateWindowData(WC_COMPANY, target_company);
2011 CompanyAdminUpdate(c);
2012 }
2013 return cost;
2014 }
2015
2025 CommandCost CmdSellShareInCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2026 {
2027 CompanyID target_company = (CompanyID)p1;
2028 Company *c = Company::GetIfValid(target_company);
2029
2030 /* Cannot sell own shares */
2031 if (c == NULL || _current_company == target_company) return CMD_ERROR;
2032
2033 /* Check if selling shares is allowed (protection against modified clients).
2034 * However, we must sell shares of companies being closed down. */
2035 if (!_settings_game.economy.allow_shares && !(flags & DC_BANKRUPT)) return CMD_ERROR;
2036
2037 /* Those lines are here for network-protection (clients can be slow) */
2038 if (GetAmountOwnedBy(c, _current_company) == 0) return CommandCost();
2039
2040 /* adjust it a little to make it less profitable to sell and buy */
2041 Money cost = CalculateCompanyValue(c) >> 2;
2042 cost = -(cost - (cost >> 7));
2043
2044 if (flags & DC_EXEC) {
2045 OwnerByte *b = c->share_owners;
2046 while (*b != _current_company) b++; // share owners is guaranteed to contain company
2047 *b = COMPANY_SPECTATOR;
2048 InvalidateWindowData(WC_COMPANY, target_company);
2049 CompanyAdminUpdate(c);
2050 }
2051 return CommandCost(EXPENSES_OTHER, cost);
2052 }
2053
2066 CommandCost CmdBuyCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2067 {
2068 CompanyID target_company = (CompanyID)p1;
2069 Company *c = Company::GetIfValid(target_company);
2070 if (c == NULL) return CMD_ERROR;
2071
2072 /* Disable takeovers when not asked */
2073 if (!HasBit(c->bankrupt_asked, _current_company)) return CMD_ERROR;
2074
2075 /* Disable taking over the local company in single player */
2076 if (!_networking && _local_company == c->index) return CMD_ERROR;
2077
2078 /* Do not allow companies to take over themselves */
2079 if (target_company == _current_company) return CMD_ERROR;
2080
2081 /* Disable taking over when not allowed. */
2082 if (!MayCompanyTakeOver(_current_company, target_company)) return CMD_ERROR;
2083
2084 /* Get the cost here as the company is deleted in DoAcquireCompany. */
2085 CommandCost cost(EXPENSES_OTHER, c->bankrupt_value);
2086
2087 if (flags & DC_EXEC) {
2088 DoAcquireCompany(c);
2089 }
2090 return cost;
2091 }