OpenTTD
economy.cpp
Go to the documentation of this file.
1 /*
2  * This file is part of OpenTTD.
3  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6  */
7 
10 #include "stdafx.h"
11 #include "company_func.h"
12 #include "command_func.h"
13 #include "industry.h"
14 #include "town.h"
15 #include "news_func.h"
16 #include "network/network.h"
17 #include "network/network_func.h"
18 #include "ai/ai.hpp"
19 #include "aircraft.h"
20 #include "train.h"
21 #include "newgrf_engine.h"
22 #include "engine_base.h"
23 #include "ground_vehicle.hpp"
24 #include "newgrf_cargo.h"
25 #include "newgrf_sound.h"
26 #include "newgrf_industrytiles.h"
27 #include "newgrf_station.h"
28 #include "newgrf_airporttiles.h"
29 #include "object.h"
30 #include "strings_func.h"
31 #include "date_func.h"
32 #include "vehicle_func.h"
33 #include "sound_func.h"
34 #include "autoreplace_func.h"
35 #include "company_gui.h"
36 #include "signs_base.h"
37 #include "subsidy_base.h"
38 #include "subsidy_func.h"
39 #include "station_base.h"
40 #include "waypoint_base.h"
41 #include "economy_base.h"
42 #include "core/pool_func.hpp"
43 #include "core/backup_type.hpp"
44 #include "cargo_type.h"
45 #include "water.h"
46 #include "game/game.hpp"
47 #include "cargomonitor.h"
48 #include "goal_base.h"
49 #include "story_base.h"
50 #include "linkgraph/refresh.h"
51 
52 #include "table/strings.h"
53 #include "table/pricebase.h"
54 
55 #include "safeguards.h"
56 
57 
58 /* Initialize the cargo payment-pool */
61 
62 
73 static inline int32 BigMulS(const int32 a, const int32 b, const uint8 shift)
74 {
75  return (int32)((int64)a * (int64)b >> shift);
76 }
77 
78 typedef std::vector<Industry *> SmallIndustryList;
79 
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
94 };
95 
96 int64 _score_part[MAX_COMPANIES][SCORE_END];
97 Economy _economy;
98 Prices _price;
99 Money _additional_cash_required;
100 static PriceMultipliers _price_base_multiplier;
101 
111 Money CalculateCompanyValue(const Company *c, bool including_loan)
112 {
113  Owner owner = c->index;
114 
115  uint num = 0;
116 
117  for (const Station *st : Station::Iterate()) {
118  if (st->owner == owner) num += CountBits((byte)st->facilities);
119  }
120 
121  Money value = num * _price[PR_STATION_VALUE] * 25;
122 
123  for (const Vehicle *v : Vehicle::Iterate()) {
124  if (v->owner != owner) continue;
125 
126  if (v->type == VEH_TRAIN ||
127  v->type == VEH_ROAD ||
128  (v->type == VEH_AIRCRAFT && Aircraft::From(v)->IsNormalAircraft()) ||
129  v->type == VEH_SHIP) {
130  value += v->value * 3 >> 1;
131  }
132  }
133 
134  /* Add real money value */
135  if (including_loan) value -= c->current_loan;
136  value += c->money;
137 
138  return max(value, (Money)1);
139 }
140 
150 {
151  Owner owner = c->index;
152  int score = 0;
153 
154  memset(_score_part[owner], 0, sizeof(_score_part[owner]));
155 
156  /* Count vehicles */
157  {
158  Money min_profit = 0;
159  bool min_profit_first = true;
160  uint num = 0;
161 
162  for (const Vehicle *v : Vehicle::Iterate()) {
163  if (v->owner != owner) continue;
164  if (IsCompanyBuildableVehicleType(v->type) && v->IsPrimaryVehicle()) {
165  if (v->profit_last_year > 0) num++; // For the vehicle score only count profitable vehicles
166  if (v->age > 730) {
167  /* Find the vehicle with the lowest amount of profit */
168  if (min_profit_first || min_profit > v->profit_last_year) {
169  min_profit = v->profit_last_year;
170  min_profit_first = false;
171  }
172  }
173  }
174  }
175 
176  min_profit >>= 8; // remove the fract part
177 
178  _score_part[owner][SCORE_VEHICLES] = num;
179  /* Don't allow negative min_profit to show */
180  if (min_profit > 0) {
181  _score_part[owner][SCORE_MIN_PROFIT] = min_profit;
182  }
183  }
184 
185  /* Count stations */
186  {
187  uint num = 0;
188  for (const Station *st : Station::Iterate()) {
189  /* Only count stations that are actually serviced */
190  if (st->owner == owner && (st->time_since_load <= 20 || st->time_since_unload <= 20)) num += CountBits((byte)st->facilities);
191  }
192  _score_part[owner][SCORE_STATIONS] = num;
193  }
194 
195  /* Generate statistics depending on recent income statistics */
196  {
197  int numec = min(c->num_valid_stat_ent, 12);
198  if (numec != 0) {
199  const CompanyEconomyEntry *cee = c->old_economy;
200  Money min_income = cee->income + cee->expenses;
201  Money max_income = cee->income + cee->expenses;
202 
203  do {
204  min_income = min(min_income, cee->income + cee->expenses);
205  max_income = max(max_income, cee->income + cee->expenses);
206  } while (++cee, --numec);
207 
208  if (min_income > 0) {
209  _score_part[owner][SCORE_MIN_INCOME] = min_income;
210  }
211 
212  _score_part[owner][SCORE_MAX_INCOME] = max_income;
213  }
214  }
215 
216  /* Generate score depending on amount of transported cargo */
217  {
218  int numec = min(c->num_valid_stat_ent, 4);
219  if (numec != 0) {
220  const CompanyEconomyEntry *cee = c->old_economy;
221  OverflowSafeInt64 total_delivered = 0;
222  do {
223  total_delivered += cee->delivered_cargo.GetSum<OverflowSafeInt64>();
224  } while (++cee, --numec);
225 
226  _score_part[owner][SCORE_DELIVERED] = total_delivered;
227  }
228  }
229 
230  /* Generate score for variety of cargo */
231  {
232  _score_part[owner][SCORE_CARGO] = c->old_economy->delivered_cargo.GetCount();
233  }
234 
235  /* Generate score for company's money */
236  {
237  if (c->money > 0) {
238  _score_part[owner][SCORE_MONEY] = c->money;
239  }
240  }
241 
242  /* Generate score for loan */
243  {
244  _score_part[owner][SCORE_LOAN] = _score_info[SCORE_LOAN].needed - c->current_loan;
245  }
246 
247  /* Now we calculate the score for each item.. */
248  {
249  int total_score = 0;
250  int s;
251  score = 0;
252  for (ScoreID i = SCORE_BEGIN; i < SCORE_END; i++) {
253  /* Skip the total */
254  if (i == SCORE_TOTAL) continue;
255  /* Check the score */
256  s = Clamp<int64>(_score_part[owner][i], 0, _score_info[i].needed) * _score_info[i].score / _score_info[i].needed;
257  score += s;
258  total_score += _score_info[i].score;
259  }
260 
261  _score_part[owner][SCORE_TOTAL] = score;
262 
263  /* We always want the score scaled to SCORE_MAX (1000) */
264  if (total_score != SCORE_MAX) score = score * SCORE_MAX / total_score;
265  }
266 
267  if (update) {
268  c->old_economy[0].performance_history = score;
269  UpdateCompanyHQ(c->location_of_HQ, score);
271  }
272 
274  return score;
275 }
276 
282 void ChangeOwnershipOfCompanyItems(Owner old_owner, Owner new_owner)
283 {
284  /* We need to set _current_company to old_owner before we try to move
285  * the client. This is needed as it needs to know whether "you" really
286  * are the current local company. */
287  Backup<CompanyID> cur_company(_current_company, old_owner, FILE_LINE);
288  /* In all cases, make spectators of clients connected to that company */
289  if (_networking) NetworkClientsToSpectators(old_owner);
290  if (old_owner == _local_company) {
291  /* Single player cheated to AI company.
292  * There are no spectators in single player, so we must pick some other company. */
293  assert(!_networking);
294  Backup<CompanyID> cur_company2(_current_company, FILE_LINE);
295  for (const Company *c : Company::Iterate()) {
296  if (c->index != old_owner) {
297  SetLocalCompany(c->index);
298  break;
299  }
300  }
301  cur_company2.Restore();
302  assert(old_owner != _local_company);
303  }
304 
305  assert(old_owner != new_owner);
306 
307  {
308  uint i;
309 
310  /* See if the old_owner had shares in other companies */
311  for (const Company *c : Company::Iterate()) {
312  for (i = 0; i < 4; i++) {
313  if (c->share_owners[i] == old_owner) {
314  /* Sell his shares */
316  /* Because we are in a DoCommand, we can't just execute another one and
317  * expect the money to be removed. We need to do it ourself! */
319  }
320  }
321  }
322 
323  /* Sell all the shares that people have on this company */
324  Backup<CompanyID> cur_company2(_current_company, FILE_LINE);
325  const Company *c = Company::Get(old_owner);
326  for (i = 0; i < 4; i++) {
327  cur_company2.Change(c->share_owners[i]);
329  /* Sell the shares */
331  /* Because we are in a DoCommand, we can't just execute another one and
332  * expect the money to be removed. We need to do it ourself! */
334  }
335  }
336  cur_company2.Restore();
337  }
338 
339  /* Temporarily increase the company's money, to be sure that
340  * removing his/her property doesn't fail because of lack of money.
341  * Not too drastically though, because it could overflow */
342  if (new_owner == INVALID_OWNER) {
343  Company::Get(old_owner)->money = UINT64_MAX >> 2; // jackpot ;p
344  }
345 
346  for (Subsidy *s : Subsidy::Iterate()) {
347  if (s->awarded == old_owner) {
348  if (new_owner == INVALID_OWNER) {
349  delete s;
350  } else {
351  s->awarded = new_owner;
352  }
353  }
354  }
356 
357  /* Take care of rating and transport rights in towns */
358  for (Town *t : Town::Iterate()) {
359  /* If a company takes over, give the ratings to that company. */
360  if (new_owner != INVALID_OWNER) {
361  if (HasBit(t->have_ratings, old_owner)) {
362  if (HasBit(t->have_ratings, new_owner)) {
363  /* use max of the two ratings. */
364  t->ratings[new_owner] = max(t->ratings[new_owner], t->ratings[old_owner]);
365  } else {
366  SetBit(t->have_ratings, new_owner);
367  t->ratings[new_owner] = t->ratings[old_owner];
368  }
369  }
370  }
371 
372  /* Reset the ratings for the old owner */
373  t->ratings[old_owner] = RATING_INITIAL;
374  ClrBit(t->have_ratings, old_owner);
375 
376  /* Transfer exclusive rights */
377  if (t->exclusive_counter > 0 && t->exclusivity == old_owner) {
378  if (new_owner != INVALID_OWNER) {
379  t->exclusivity = new_owner;
380  } else {
381  t->exclusive_counter = 0;
382  t->exclusivity = INVALID_COMPANY;
383  }
384  }
385  }
386 
387  {
388  for (Vehicle *v : Vehicle::Iterate()) {
389  if (v->owner == old_owner && IsCompanyBuildableVehicleType(v->type)) {
390  if (new_owner == INVALID_OWNER) {
391  if (v->Previous() == nullptr) delete v;
392  } else {
393  if (v->IsEngineCountable()) GroupStatistics::CountEngine(v, -1);
394  if (v->IsPrimaryVehicle()) GroupStatistics::CountVehicle(v, -1);
395  }
396  }
397  }
398  }
399 
400  /* In all cases clear replace engine rules.
401  * Even if it was copied, it could interfere with new owner's rules */
403 
404  if (new_owner == INVALID_OWNER) {
405  RemoveAllGroupsForCompany(old_owner);
406  } else {
407  for (Group *g : Group::Iterate()) {
408  if (g->owner == old_owner) g->owner = new_owner;
409  }
410  }
411 
412  {
413  FreeUnitIDGenerator unitidgen[] = {
416  };
417 
418  /* Override company settings to new company defaults in case we need to convert them.
419  * This is required as the CmdChangeServiceInt doesn't copy the supplied value when it is non-custom
420  */
421  if (new_owner != INVALID_OWNER) {
422  Company *old_company = Company::Get(old_owner);
423  Company *new_company = Company::Get(new_owner);
424 
426  old_company->settings.vehicle.servint_trains = new_company->settings.vehicle.servint_trains;
427  old_company->settings.vehicle.servint_roadveh = new_company->settings.vehicle.servint_roadveh;
428  old_company->settings.vehicle.servint_ships = new_company->settings.vehicle.servint_ships;
430  }
431 
432  for (Vehicle *v : Vehicle::Iterate()) {
433  if (v->owner == old_owner && IsCompanyBuildableVehicleType(v->type)) {
434  assert(new_owner != INVALID_OWNER);
435 
436  /* Correct default values of interval settings while maintaining custom set ones.
437  * This prevents invalid values on mismatching company defaults being accepted.
438  */
439  if (!v->ServiceIntervalIsCustom()) {
440  Company *new_company = Company::Get(new_owner);
441 
442  /* Technically, passing the interval is not needed as the command will query the default value itself.
443  * However, do not rely on that behaviour.
444  */
445  int interval = CompanyServiceInterval(new_company, v->type);
446  DoCommand(v->tile, v->index, interval | (new_company->settings.vehicle.servint_ispercent << 17), DC_EXEC | DC_BANKRUPT, CMD_CHANGE_SERVICE_INT);
447  }
448 
449  v->owner = new_owner;
450 
451  /* Owner changes, clear cache */
452  v->colourmap = PAL_NONE;
453  v->InvalidateNewGRFCache();
454 
455  if (v->IsEngineCountable()) {
457  }
458  if (v->IsPrimaryVehicle()) {
460  v->unitnumber = unitidgen[v->type].NextID();
461  }
462 
463  /* Invalidate the vehicle's cargo payment "owner cache". */
464  if (v->cargo_payment != nullptr) v->cargo_payment->owner = nullptr;
465  }
466  }
467 
468  if (new_owner != INVALID_OWNER) GroupStatistics::UpdateAutoreplace(new_owner);
469  }
470 
471  /* Change ownership of tiles */
472  {
473  TileIndex tile = 0;
474  do {
475  ChangeTileOwner(tile, old_owner, new_owner);
476  } while (++tile != MapSize());
477 
478  if (new_owner != INVALID_OWNER) {
479  /* Update all signals because there can be new segment that was owned by two companies
480  * and signals were not propagated
481  * Similar with crossings - it is needed to bar crossings that weren't before
482  * because of different owner of crossing and approaching train */
483  tile = 0;
484 
485  do {
486  if (IsTileType(tile, MP_RAILWAY) && IsTileOwner(tile, new_owner) && HasSignals(tile)) {
487  TrackBits tracks = GetTrackBits(tile);
488  do { // there may be two tracks with signals for TRACK_BIT_HORZ and TRACK_BIT_VERT
489  Track track = RemoveFirstTrack(&tracks);
490  if (HasSignalOnTrack(tile, track)) AddTrackToSignalBuffer(tile, track, new_owner);
491  } while (tracks != TRACK_BIT_NONE);
492  } else if (IsLevelCrossingTile(tile) && IsTileOwner(tile, new_owner)) {
493  UpdateLevelCrossing(tile);
494  }
495  } while (++tile != MapSize());
496  }
497 
498  /* update signals in buffer */
500  }
501 
502  /* Add airport infrastructure count of the old company to the new one. */
503  if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.airport += Company::Get(old_owner)->infrastructure.airport;
504 
505  /* convert owner of stations (including deleted ones, but excluding buoys) */
506  for (Station *st : Station::Iterate()) {
507  if (st->owner == old_owner) {
508  /* if a company goes bankrupt, set owner to OWNER_NONE so the sign doesn't disappear immediately
509  * also, drawing station window would cause reading invalid company's colour */
510  st->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner;
511  }
512  }
513 
514  /* do the same for waypoints (we need to do this here so deleted waypoints are converted too) */
515  for (Waypoint *wp : Waypoint::Iterate()) {
516  if (wp->owner == old_owner) {
517  wp->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner;
518  }
519  }
520 
521  for (Sign *si : Sign::Iterate()) {
522  if (si->owner == old_owner) si->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner;
523  }
524 
525  /* Remove Game Script created Goals, CargoMonitors and Story pages. */
526  for (Goal *g : Goal::Iterate()) {
527  if (g->company == old_owner) delete g;
528  }
529 
530  ClearCargoPickupMonitoring(old_owner);
531  ClearCargoDeliveryMonitoring(old_owner);
532 
533  for (StoryPage *sp : StoryPage::Iterate()) {
534  if (sp->company == old_owner) delete sp;
535  }
536 
537  /* Change colour of existing windows */
538  if (new_owner != INVALID_OWNER) ChangeWindowOwner(old_owner, new_owner);
539 
540  cur_company.Restore();
541 
543 }
544 
550 {
551  /* If the company has money again, it does not go bankrupt */
552  if (c->money - c->current_loan >= -_economy.max_loan) {
553  int previous_months_of_bankruptcy = CeilDiv(c->months_of_bankruptcy, 3);
554  c->months_of_bankruptcy = 0;
555  c->bankrupt_asked = 0;
556  if (previous_months_of_bankruptcy != 0) CompanyAdminUpdate(c);
557  return;
558  }
559 
561 
562  switch (c->months_of_bankruptcy) {
563  /* All the boring cases (months) with a bad balance where no action is taken */
564  case 0:
565  case 1:
566  case 2:
567  case 3:
568 
569  case 5:
570  case 6:
571 
572  case 8:
573  case 9:
574  break;
575 
576  /* Warn about bankruptcy after 3 months */
577  case 4: {
578  CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
579  cni->FillData(c);
580  SetDParam(0, STR_NEWS_COMPANY_IN_TROUBLE_TITLE);
581  SetDParam(1, STR_NEWS_COMPANY_IN_TROUBLE_DESCRIPTION);
582  SetDParamStr(2, cni->company_name);
583  AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, cni);
584  AI::BroadcastNewEvent(new ScriptEventCompanyInTrouble(c->index));
585  Game::NewEvent(new ScriptEventCompanyInTrouble(c->index));
586  break;
587  }
588 
589  /* Offer company for sale after 6 months */
590  case 7: {
591  /* Don't consider the loan */
592  Money val = CalculateCompanyValue(c, false);
593 
594  c->bankrupt_value = val;
595  c->bankrupt_asked = 1 << c->index; // Don't ask the owner
596  c->bankrupt_timeout = 0;
597 
598  /* The company assets should always have some value */
599  assert(c->bankrupt_value > 0);
600  break;
601  }
602 
603  /* Bankrupt company after 6 months (if the company has no value) or latest
604  * after 9 months (if it still had value after 6 months) */
605  default:
606  case 10: {
607  if (!_networking && _local_company == c->index) {
608  /* If we are in offline mode, leave the company playing. Eg. there
609  * is no THE-END, otherwise mark the client as spectator to make sure
610  * he/she is no long in control of this company. However... when you
611  * join another company (cheat) the "unowned" company can bankrupt. */
612  c->bankrupt_asked = MAX_UVALUE(CompanyMask);
613  break;
614  }
615 
616  /* Actually remove the company, but not when we're a network client.
617  * In case of network clients we will be getting a command from the
618  * server. It is done in this way as we are called from the
619  * StateGameLoop which can't change the current company, and thus
620  * updating the local company triggers an assert later on. In the
621  * case of a network game the command will be processed at a time
622  * that changing the current company is okay. In case of single
623  * player we are sure (the above check) that we are not the local
624  * company and thus we won't be moved. */
625  if (!_networking || _network_server) {
626  DoCommandP(0, CCA_DELETE | (c->index << 16) | (CRR_BANKRUPT << 24), 0, CMD_COMPANY_CTRL);
627  return;
628  }
629  break;
630  }
631  }
632 
634 }
635 
641 {
642  /* Check for bankruptcy each month */
643  for (Company *c : Company::Iterate()) {
645  }
646 
647  Backup<CompanyID> cur_company(_current_company, FILE_LINE);
648 
650  for (const Station *st : Station::Iterate()) {
651  cur_company.Change(st->owner);
652  CommandCost cost(EXPENSES_PROPERTY, _price[PR_STATION_VALUE] >> 1);
654  }
655  } else {
656  /* Improved monthly infrastructure costs. */
657  for (const Company *c : Company::Iterate()) {
658  cur_company.Change(c->index);
659 
661  uint32 rail_total = c->infrastructure.GetRailTotal();
662  for (RailType rt = RAILTYPE_BEGIN; rt < RAILTYPE_END; rt++) {
663  if (c->infrastructure.rail[rt] != 0) cost.AddCost(RailMaintenanceCost(rt, c->infrastructure.rail[rt], rail_total));
664  }
665  cost.AddCost(SignalMaintenanceCost(c->infrastructure.signal));
666  uint32 road_total = c->infrastructure.GetRoadTotal();
667  uint32 tram_total = c->infrastructure.GetTramTotal();
668  for (RoadType rt = ROADTYPE_BEGIN; rt < ROADTYPE_END; rt++) {
669  if (c->infrastructure.road[rt] != 0) cost.AddCost(RoadMaintenanceCost(rt, c->infrastructure.road[rt], RoadTypeIsRoad(rt) ? road_total : tram_total));
670  }
671  cost.AddCost(CanalMaintenanceCost(c->infrastructure.water));
672  cost.AddCost(StationMaintenanceCost(c->infrastructure.station));
673  cost.AddCost(AirportMaintenanceCost(c->index));
674 
676  }
677  }
678  cur_company.Restore();
679 
680  /* Only run the economic statics and update company stats every 3rd month (1st of quarter). */
681  if (!HasBit(1 << 0 | 1 << 3 | 1 << 6 | 1 << 9, _cur_month)) return;
682 
683  for (Company *c : Company::Iterate()) {
684  /* Drop the oldest history off the end */
685  std::copy_backward(c->old_economy, c->old_economy + MAX_HISTORY_QUARTERS - 1, c->old_economy + MAX_HISTORY_QUARTERS);
686  c->old_economy[0] = c->cur_economy;
687  c->cur_economy = {};
688 
689  if (c->num_valid_stat_ent != MAX_HISTORY_QUARTERS) c->num_valid_stat_ent++;
690 
692  if (c->block_preview != 0) c->block_preview--;
693  }
694 
701 }
702 
708 bool AddInflation(bool check_year)
709 {
710  /* The cargo payment inflation differs from the normal inflation, so the
711  * relative amount of money you make with a transport decreases slowly over
712  * the 170 years. After a few hundred years we reach a level in which the
713  * games will become unplayable as the maximum income will be less than
714  * the minimum running cost.
715  *
716  * Furthermore there are a lot of inflation related overflows all over the
717  * place. Solving them is hardly possible because inflation will always
718  * reach the overflow threshold some day. So we'll just perform the
719  * inflation mechanism during the first 170 years (the amount of years that
720  * one had in the original TTD) and stop doing the inflation after that
721  * because it only causes problems that can't be solved nicely and the
722  * inflation doesn't add anything after that either; it even makes playing
723  * it impossible due to the diverging cost and income rates.
724  */
726 
727  if (_economy.inflation_prices == MAX_INFLATION || _economy.inflation_payment == MAX_INFLATION) return true;
728 
729  /* Approximation for (100 + infl_amount)% ** (1 / 12) - 100%
730  * scaled by 65536
731  * 12 -> months per year
732  * This is only a good approximation for small values
733  */
734  _economy.inflation_prices += (_economy.inflation_prices * _economy.infl_amount * 54) >> 16;
735  _economy.inflation_payment += (_economy.inflation_payment * _economy.infl_amount_pr * 54) >> 16;
736 
739 
740  return false;
741 }
742 
747 {
748  /* Setup maximum loan */
749  _economy.max_loan = (_settings_game.difficulty.max_loan * _economy.inflation_prices >> 16) / 50000 * 50000;
750 
751  /* Setup price bases */
752  for (Price i = PR_BEGIN; i < PR_END; i++) {
753  Money price = _price_base_specs[i].start_price;
754 
755  /* Apply difficulty settings */
756  uint mod = 1;
757  switch (_price_base_specs[i].category) {
758  case PCAT_RUNNING:
760  break;
761 
762  case PCAT_CONSTRUCTION:
764  break;
765 
766  default: break;
767  }
768  switch (mod) {
769  case 0: price *= 6; break;
770  case 1: price *= 8; break; // normalised to 1 below
771  case 2: price *= 9; break;
772  default: NOT_REACHED();
773  }
774 
775  /* Apply inflation */
776  price = (int64)price * _economy.inflation_prices;
777 
778  /* Apply newgrf modifiers, remove fractional part of inflation, and normalise on medium difficulty. */
779  int shift = _price_base_multiplier[i] - 16 - 3;
780  if (shift >= 0) {
781  price <<= shift;
782  } else {
783  price >>= -shift;
784  }
785 
786  /* Make sure the price does not get reduced to zero.
787  * Zero breaks quite a few commands that use a zero
788  * cost to see whether something got changed or not
789  * and based on that cause an error. When the price
790  * is zero that fails even when things are done. */
791  if (price == 0) {
792  price = Clamp(_price_base_specs[i].start_price, -1, 1);
793  /* No base price should be zero, but be sure. */
794  assert(price != 0);
795  }
796  /* Store value */
797  _price[i] = price;
798  }
799 
800  /* Setup cargo payment */
801  CargoSpec *cs;
802  FOR_ALL_CARGOSPECS(cs) {
803  cs->current_payment = ((int64)cs->initial_payment * _economy.inflation_payment) >> 16;
804  }
805 
811 }
812 
814 static void CompaniesPayInterest()
815 {
816  Backup<CompanyID> cur_company(_current_company, FILE_LINE);
817  for (const Company *c : Company::Iterate()) {
818  cur_company.Change(c->index);
819 
820  /* Over a year the paid interest should be "loan * interest percentage",
821  * but... as that number is likely not dividable by 12 (pay each month),
822  * one needs to account for that in the monthly fee calculations.
823  * To easily calculate what one should pay "this" month, you calculate
824  * what (total) should have been paid up to this month and you subtract
825  * whatever has been paid in the previous months. This will mean one month
826  * it'll be a bit more and the other it'll be a bit less than the average
827  * monthly fee, but on average it will be exact.
828  * In order to prevent cheating or abuse (just not paying interest by not
829  * taking a loan we make companies pay interest on negative cash as well
830  */
831  Money yearly_fee = c->current_loan * _economy.interest_rate / 100;
832  if (c->money < 0) {
833  yearly_fee += -c->money *_economy.interest_rate / 100;
834  }
835  Money up_to_previous_month = yearly_fee * _cur_month / 12;
836  Money up_to_this_month = yearly_fee * (_cur_month + 1) / 12;
837 
838  SubtractMoneyFromCompany(CommandCost(EXPENSES_LOAN_INT, up_to_this_month - up_to_previous_month));
839 
840  SubtractMoneyFromCompany(CommandCost(EXPENSES_OTHER, _price[PR_STATION_VALUE] >> 2));
841  }
842  cur_company.Restore();
843 }
844 
845 static void HandleEconomyFluctuations()
846 {
847  if (_settings_game.difficulty.economy != 0) {
848  /* When economy is Fluctuating, decrease counter */
849  _economy.fluct--;
850  } else if (EconomyIsInRecession()) {
851  /* When it's Steady and we are in recession, end it now */
852  _economy.fluct = -12;
853  } else {
854  /* No need to do anything else in other cases */
855  return;
856  }
857 
858  if (_economy.fluct == 0) {
859  _economy.fluct = -(int)GB(Random(), 0, 2);
860  AddNewsItem(STR_NEWS_BEGIN_OF_RECESSION, NT_ECONOMY, NF_NORMAL);
861  } else if (_economy.fluct == -12) {
862  _economy.fluct = GB(Random(), 0, 8) + 312;
863  AddNewsItem(STR_NEWS_END_OF_RECESSION, NT_ECONOMY, NF_NORMAL);
864  }
865 }
866 
867 
872 {
873  memset(_price_base_multiplier, 0, sizeof(_price_base_multiplier));
874 }
875 
883 void SetPriceBaseMultiplier(Price price, int factor)
884 {
885  assert(price < PR_END);
886  _price_base_multiplier[price] = Clamp(factor, MIN_PRICE_MODIFIER, MAX_PRICE_MODIFIER);
887 }
888 
893 void StartupIndustryDailyChanges(bool init_counter)
894 {
895  uint map_size = MapLogX() + MapLogY();
896  /* After getting map size, it needs to be scaled appropriately and divided by 31,
897  * which stands for the days in a month.
898  * Using just 31 will make it so that a monthly reset (based on the real number of days of that month)
899  * would not be needed.
900  * Since it is based on "fractional parts", the leftover days will not make much of a difference
901  * on the overall total number of changes performed */
902  _economy.industry_daily_increment = (1 << map_size) / 31;
903 
904  if (init_counter) {
905  /* A new game or a savegame from an older version will require the counter to be initialized */
906  _economy.industry_daily_change_counter = 0;
907  }
908 }
909 
910 void StartupEconomy()
911 {
915  _economy.fluct = GB(Random(), 0, 8) + 168;
916 
917  /* Set up prices */
918  RecomputePrices();
919 
920  StartupIndustryDailyChanges(true); // As we are starting a new game, initialize the counter too
921 
922 }
923 
928 {
929  _economy.inflation_prices = _economy.inflation_payment = 1 << 16;
932 }
933 
942 Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift)
943 {
944  if (index >= PR_END) return 0;
945 
946  Money cost = _price[index] * cost_factor;
947  if (grf_file != nullptr) shift += grf_file->price_base_multipliers[index];
948 
949  if (shift >= 0) {
950  cost <<= shift;
951  } else {
952  cost >>= -shift;
953  }
954 
955  return cost;
956 }
957 
958 Money GetTransportedGoodsIncome(uint num_pieces, uint dist, byte transit_days, CargoID cargo_type)
959 {
960  const CargoSpec *cs = CargoSpec::Get(cargo_type);
961  if (!cs->IsValid()) {
962  /* User changed newgrfs and some vehicle still carries some cargo which is no longer available. */
963  return 0;
964  }
965 
966  /* Use callback to calculate cargo profit, if available */
968  uint32 var18 = min(dist, 0xFFFF) | (min(num_pieces, 0xFF) << 16) | (transit_days << 24);
969  uint16 callback = GetCargoCallback(CBID_CARGO_PROFIT_CALC, 0, var18, cs);
970  if (callback != CALLBACK_FAILED) {
971  int result = GB(callback, 0, 14);
972 
973  /* Simulate a 15 bit signed value */
974  if (HasBit(callback, 14)) result -= 0x4000;
975 
976  /* "The result should be a signed multiplier that gets multiplied
977  * by the amount of cargo moved and the price factor, then gets
978  * divided by 8192." */
979  return result * num_pieces * cs->current_payment / 8192;
980  }
981  }
982 
983  static const int MIN_TIME_FACTOR = 31;
984  static const int MAX_TIME_FACTOR = 255;
985 
986  const int days1 = cs->transit_days[0];
987  const int days2 = cs->transit_days[1];
988  const int days_over_days1 = max( transit_days - days1, 0);
989  const int days_over_days2 = max(days_over_days1 - days2, 0);
990 
991  /*
992  * The time factor is calculated based on the time it took
993  * (transit_days) compared two cargo-depending values. The
994  * range is divided into three parts:
995  *
996  * - constant for fast transits
997  * - linear decreasing with time with a slope of -1 for medium transports
998  * - linear decreasing with time with a slope of -2 for slow transports
999  *
1000  */
1001  const int time_factor = max(MAX_TIME_FACTOR - days_over_days1 - days_over_days2, MIN_TIME_FACTOR);
1002 
1003  return BigMulS(dist * time_factor * num_pieces, cs->current_payment, 21);
1004 }
1005 
1007 static SmallIndustryList _cargo_delivery_destinations;
1008 
1019 static uint DeliverGoodsToIndustry(const Station *st, CargoID cargo_type, uint num_pieces, IndustryID source, CompanyID company)
1020 {
1021  /* Find the nearest industrytile to the station sign inside the catchment area, whose industry accepts the cargo.
1022  * This fails in three cases:
1023  * 1) The station accepts the cargo because there are enough houses around it accepting the cargo.
1024  * 2) The industries in the catchment area temporarily reject the cargo, and the daily station loop has not yet updated station acceptance.
1025  * 3) The results of callbacks CBID_INDUSTRY_REFUSE_CARGO and CBID_INDTILE_CARGO_ACCEPTANCE are inconsistent. (documented behaviour)
1026  */
1027 
1028  uint accepted = 0;
1029 
1030  for (Industry *ind : st->industries_near) {
1031  if (num_pieces == 0) break;
1032 
1033  if (ind->index == source) continue;
1034 
1035  uint cargo_index;
1036  for (cargo_index = 0; cargo_index < lengthof(ind->accepts_cargo); cargo_index++) {
1037  if (cargo_type == ind->accepts_cargo[cargo_index]) break;
1038  }
1039  /* Check if matching cargo has been found */
1040  if (cargo_index >= lengthof(ind->accepts_cargo)) continue;
1041 
1042  /* Check if industry temporarily refuses acceptance */
1043  if (IndustryTemporarilyRefusesCargo(ind, cargo_type)) continue;
1044 
1045  /* Insert the industry into _cargo_delivery_destinations, if not yet contained */
1047 
1048  uint amount = min(num_pieces, 0xFFFFU - ind->incoming_cargo_waiting[cargo_index]);
1049  ind->incoming_cargo_waiting[cargo_index] += amount;
1050  ind->last_cargo_accepted_at[cargo_index] = _date;
1051  num_pieces -= amount;
1052  accepted += amount;
1053 
1054  /* Update the cargo monitor. */
1055  AddCargoDelivery(cargo_type, company, amount, ST_INDUSTRY, source, st, ind->index);
1056  }
1057 
1058  return accepted;
1059 }
1060 
1074 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)
1075 {
1076  assert(num_pieces > 0);
1077 
1078  Station *st = Station::Get(dest);
1079 
1080  /* Give the goods to the industry. */
1081  uint accepted_ind = DeliverGoodsToIndustry(st, cargo_type, num_pieces, src_type == ST_INDUSTRY ? src : INVALID_INDUSTRY, company->index);
1082 
1083  /* If this cargo type is always accepted, accept all */
1084  uint accepted_total = HasBit(st->always_accepted, cargo_type) ? num_pieces : accepted_ind;
1085 
1086  /* Update station statistics */
1087  if (accepted_total > 0) {
1091  }
1092 
1093  /* Update company statistics */
1094  company->cur_economy.delivered_cargo[cargo_type] += accepted_total;
1095 
1096  /* Increase town's counter for town effects */
1097  const CargoSpec *cs = CargoSpec::Get(cargo_type);
1098  st->town->received[cs->town_effect].new_act += accepted_total;
1099 
1100  /* Determine profit */
1101  Money profit = GetTransportedGoodsIncome(accepted_total, DistanceManhattan(source_tile, st->xy), days_in_transit, cargo_type);
1102 
1103  /* Update the cargo monitor. */
1104  AddCargoDelivery(cargo_type, company->index, accepted_total - accepted_ind, src_type, src, st);
1105 
1106  /* Modify profit if a subsidy is in effect */
1107  if (CheckSubsidised(cargo_type, company->index, src_type, src, st)) {
1109  case 0: profit += profit >> 1; break;
1110  case 1: profit *= 2; break;
1111  case 2: profit *= 3; break;
1112  default: profit *= 4; break;
1113  }
1114  }
1115 
1116  return profit;
1117 }
1118 
1125 {
1126  const IndustrySpec *indspec = GetIndustrySpec(i->type);
1127  uint16 callback = indspec->callback_mask;
1128 
1129  i->was_cargo_delivered = true;
1130 
1132  if (HasBit(callback, CBM_IND_PRODUCTION_CARGO_ARRIVAL)) {
1134  } else {
1136  }
1137  } else {
1138  for (uint ci_in = 0; ci_in < lengthof(i->incoming_cargo_waiting); ci_in++) {
1139  uint cargo_waiting = i->incoming_cargo_waiting[ci_in];
1140  if (cargo_waiting == 0) continue;
1141 
1142  for (uint ci_out = 0; ci_out < lengthof(i->produced_cargo_waiting); ci_out++) {
1143  i->produced_cargo_waiting[ci_out] = min(i->produced_cargo_waiting[ci_out] + (cargo_waiting * indspec->input_cargo_multiplier[ci_in][ci_out] / 256), 0xFFFF);
1144  }
1145 
1146  i->incoming_cargo_waiting[ci_in] = 0;
1147  }
1148  }
1149 
1151  StartStopIndustryTileAnimation(i, IAT_INDUSTRY_RECEIVED_CARGO);
1152 }
1153 
1159  front(front),
1160  current_station(front->last_station_visited)
1161 {
1162 }
1163 
1164 CargoPayment::~CargoPayment()
1165 {
1166  if (this->CleaningPool()) return;
1167 
1168  this->front->cargo_payment = nullptr;
1169 
1170  if (this->visual_profit == 0 && this->visual_transfer == 0) return;
1171 
1172  Backup<CompanyID> cur_company(_current_company, this->front->owner, FILE_LINE);
1173 
1175  this->front->profit_this_year += (this->visual_profit + this->visual_transfer) << 8;
1176 
1177  if (this->route_profit != 0 && IsLocalCompany() && !PlayVehicleSound(this->front, VSE_LOAD_UNLOAD)) {
1178  SndPlayVehicleFx(SND_14_CASHTILL, this->front);
1179  }
1180 
1181  if (this->visual_transfer != 0) {
1182  ShowFeederIncomeAnimation(this->front->x_pos, this->front->y_pos,
1183  this->front->z_pos, this->visual_transfer, -this->visual_profit);
1184  } else if (this->visual_profit != 0) {
1185  ShowCostOrIncomeAnimation(this->front->x_pos, this->front->y_pos,
1186  this->front->z_pos, -this->visual_profit);
1187  }
1188 
1189  cur_company.Restore();
1190 }
1191 
1197 void CargoPayment::PayFinalDelivery(const CargoPacket *cp, uint count)
1198 {
1199  if (this->owner == nullptr) {
1200  this->owner = Company::Get(this->front->owner);
1201  }
1202 
1203  /* Handle end of route payment */
1204  Money profit = DeliverGoods(count, this->ct, this->current_station, cp->SourceStationXY(), cp->DaysInTransit(), this->owner, cp->SourceSubsidyType(), cp->SourceSubsidyID());
1205  this->route_profit += profit;
1206 
1207  /* The vehicle's profit is whatever route profit there is minus feeder shares. */
1208  this->visual_profit += profit - cp->FeederShare(count);
1209 }
1210 
1218 {
1219  Money profit = GetTransportedGoodsIncome(
1220  count,
1221  /* pay transfer vehicle for only the part of transfer it has done: ie. cargo_loaded_at_xy to here */
1223  cp->DaysInTransit(),
1224  this->ct);
1225 
1226  profit = profit * _settings_game.economy.feeder_payment_share / 100;
1227 
1228  this->visual_transfer += profit; // accumulate transfer profits for whole vehicle
1229  return profit; // account for the (virtual) profit already made for the cargo packet
1230 }
1231 
1236 void PrepareUnload(Vehicle *front_v)
1237 {
1238  Station *curr_station = Station::Get(front_v->last_station_visited);
1239  curr_station->loading_vehicles.push_back(front_v);
1240 
1241  /* At this moment loading cannot be finished */
1243 
1244  /* Start unloading at the first possible moment */
1245  front_v->load_unload_ticks = 1;
1246 
1247  assert(front_v->cargo_payment == nullptr);
1248  /* One CargoPayment per vehicle and the vehicle limit equals the
1249  * limit in number of CargoPayments. Can't go wrong. */
1252  front_v->cargo_payment = new CargoPayment(front_v);
1253 
1254  StationIDStack next_station = front_v->GetNextStoppingStation();
1255  if (front_v->orders.list == nullptr || (front_v->current_order.GetUnloadType() & OUFB_NO_UNLOAD) == 0) {
1256  Station *st = Station::Get(front_v->last_station_visited);
1257  for (Vehicle *v = front_v; v != nullptr; v = v->Next()) {
1258  const GoodsEntry *ge = &st->goods[v->cargo_type];
1259  if (v->cargo_cap > 0 && v->cargo.TotalCount() > 0) {
1260  v->cargo.Stage(
1262  front_v->last_station_visited, next_station,
1263  front_v->current_order.GetUnloadType(), ge,
1264  front_v->cargo_payment);
1265  if (v->cargo.UnloadCount() > 0) SetBit(v->vehicle_flags, VF_CARGO_UNLOADING);
1266  }
1267  }
1268  }
1269 }
1270 
1277 static uint GetLoadAmount(Vehicle *v)
1278 {
1279  const Engine *e = v->GetEngine();
1280  uint load_amount = e->info.load_amount;
1281 
1282  /* The default loadamount for mail is 1/4 of the load amount for passengers */
1283  bool air_mail = v->type == VEH_AIRCRAFT && !Aircraft::From(v)->IsNormalAircraft();
1284  if (air_mail) load_amount = CeilDiv(load_amount, 4);
1285 
1287  uint16 cb_load_amount = CALLBACK_FAILED;
1288  if (e->GetGRF() != nullptr && e->GetGRF()->grf_version >= 8) {
1289  /* Use callback 36 */
1290  cb_load_amount = GetVehicleProperty(v, PROP_VEHICLE_LOAD_AMOUNT, CALLBACK_FAILED);
1291  } else if (HasBit(e->info.callback_mask, CBM_VEHICLE_LOAD_AMOUNT)) {
1292  /* Use callback 12 */
1293  cb_load_amount = GetVehicleCallback(CBID_VEHICLE_LOAD_AMOUNT, 0, 0, v->engine_type, v);
1294  }
1295  if (cb_load_amount != CALLBACK_FAILED) {
1296  if (e->GetGRF()->grf_version < 8) cb_load_amount = GB(cb_load_amount, 0, 8);
1297  if (cb_load_amount >= 0x100) {
1299  } else if (cb_load_amount != 0) {
1300  load_amount = cb_load_amount;
1301  }
1302  }
1303  }
1304 
1305  /* Scale load amount the same as capacity */
1306  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);
1307 
1308  /* Zero load amount breaks a lot of things. */
1309  return max(1u, load_amount);
1310 }
1311 
1321 template<class Taction>
1322 bool IterateVehicleParts(Vehicle *v, Taction action)
1323 {
1324  for (Vehicle *w = v; w != nullptr;
1325  w = w->HasArticulatedPart() ? w->GetNextArticulatedPart() : nullptr) {
1326  if (!action(w)) return false;
1327  if (w->type == VEH_TRAIN) {
1328  Train *train = Train::From(w);
1329  if (train->IsMultiheaded() && !action(train->other_multiheaded_part)) return false;
1330  }
1331  }
1332  if (v->type == VEH_AIRCRAFT && Aircraft::From(v)->IsNormalAircraft()) return action(v->Next());
1333  return true;
1334 }
1335 
1340 {
1346  bool operator()(const Vehicle *v)
1347  {
1348  return v->cargo.StoredCount() == 0;
1349  }
1350 };
1351 
1356 {
1358  CargoTypes &refit_mask;
1359 
1365  PrepareRefitAction(CargoArray &consist_capleft, CargoTypes &refit_mask) :
1366  consist_capleft(consist_capleft), refit_mask(refit_mask) {}
1367 
1374  bool operator()(const Vehicle *v)
1375  {
1376  this->consist_capleft[v->cargo_type] -= v->cargo_cap - v->cargo.ReservedCount();
1377  this->refit_mask |= EngInfo(v->engine_type)->refit_mask;
1378  return true;
1379  }
1380 };
1381 
1386 {
1388  StationID next_hop;
1389 
1395  ReturnCargoAction(Station *st, StationID next_one) : st(st), next_hop(next_one) {}
1396 
1403  {
1404  v->cargo.Return(UINT_MAX, &this->st->goods[v->cargo_type].cargo, this->next_hop);
1405  return true;
1406  }
1407 };
1408 
1413 {
1417  bool do_reserve;
1418 
1426  FinalizeRefitAction(CargoArray &consist_capleft, Station *st, StationIDStack &next_station, bool do_reserve) :
1427  consist_capleft(consist_capleft), st(st), next_station(next_station), do_reserve(do_reserve) {}
1428 
1436  {
1437  if (this->do_reserve) {
1438  this->st->goods[v->cargo_type].cargo.Reserve(v->cargo_cap - v->cargo.RemainingCount(),
1439  &v->cargo, st->xy, this->next_station);
1440  }
1441  this->consist_capleft[v->cargo_type] += v->cargo_cap - v->cargo.RemainingCount();
1442  return true;
1443  }
1444 };
1445 
1454 static void HandleStationRefit(Vehicle *v, CargoArray &consist_capleft, Station *st, StationIDStack next_station, CargoID new_cid)
1455 {
1456  Vehicle *v_start = v->GetFirstEnginePart();
1457  if (!IterateVehicleParts(v_start, IsEmptyAction())) return;
1458 
1459  Backup<CompanyID> cur_company(_current_company, v->owner, FILE_LINE);
1460 
1461  CargoTypes refit_mask = v->GetEngine()->info.refit_mask;
1462 
1463  /* Remove old capacity from consist capacity and collect refit mask. */
1464  IterateVehicleParts(v_start, PrepareRefitAction(consist_capleft, refit_mask));
1465 
1466  bool is_auto_refit = new_cid == CT_AUTO_REFIT;
1467  if (is_auto_refit) {
1468  /* Get a refittable cargo type with waiting cargo for next_station or INVALID_STATION. */
1469  CargoID cid;
1470  new_cid = v_start->cargo_type;
1471  FOR_EACH_SET_CARGO_ID(cid, refit_mask) {
1472  if (st->goods[cid].cargo.HasCargoFor(next_station)) {
1473  /* Try to find out if auto-refitting would succeed. In case the refit is allowed,
1474  * the returned refit capacity will be greater than zero. */
1475  DoCommand(v_start->tile, v_start->index, cid | 1U << 24 | 0xFF << 8 | 1U << 16, DC_QUERY_COST, GetCmdRefitVeh(v_start)); // Auto-refit and only this vehicle including artic parts.
1476  /* Try to balance different loadable cargoes between parts of the consist, so that
1477  * all of them can be loaded. Avoid a situation where all vehicles suddenly switch
1478  * to the first loadable cargo for which there is only one packet. If the capacities
1479  * are equal refit to the cargo of which most is available. This is important for
1480  * consists of only a single vehicle as those will generally have a consist_capleft
1481  * of 0 for all cargoes. */
1482  if (_returned_refit_capacity > 0 && (consist_capleft[cid] < consist_capleft[new_cid] ||
1483  (consist_capleft[cid] == consist_capleft[new_cid] &&
1484  st->goods[cid].cargo.AvailableCount() > st->goods[new_cid].cargo.AvailableCount()))) {
1485  new_cid = cid;
1486  }
1487  }
1488  }
1489  }
1490 
1491  /* Refit if given a valid cargo. */
1492  if (new_cid < NUM_CARGO && new_cid != v_start->cargo_type) {
1493  /* INVALID_STATION because in the DT_MANUAL case that's correct and in the DT_(A)SYMMETRIC
1494  * cases the next hop of the vehicle doesn't really tell us anything if the cargo had been
1495  * "via any station" before reserving. We rather produce some more "any station" cargo than
1496  * misrouting it. */
1497  IterateVehicleParts(v_start, ReturnCargoAction(st, INVALID_STATION));
1498  CommandCost cost = DoCommand(v_start->tile, v_start->index, new_cid | 1U << 24 | 0xFF << 8 | 1U << 16, DC_EXEC, GetCmdRefitVeh(v_start)); // Auto-refit and only this vehicle including artic parts.
1499  if (cost.Succeeded()) v->First()->profit_this_year -= cost.GetCost() << 8;
1500  }
1501 
1502  /* Add new capacity to consist capacity and reserve cargo */
1503  IterateVehicleParts(v_start, FinalizeRefitAction(consist_capleft, st, next_station,
1504  is_auto_refit || (v->First()->current_order.GetLoadType() & OLFB_FULL_LOAD) != 0));
1505 
1506  cur_company.Restore();
1507 }
1508 
1515 static bool MayLoadUnderExclusiveRights(const Station *st, const Vehicle *v)
1516 {
1517  return st->owner != OWNER_NONE || st->town->exclusive_counter == 0 || st->town->exclusivity == v->owner;
1518 }
1519 
1521  Station *st;
1522  StationIDStack *next_station;
1523 
1524  ReserveCargoAction(Station *st, StationIDStack *next_station) :
1525  st(st), next_station(next_station) {}
1526 
1527  bool operator()(Vehicle *v)
1528  {
1529  if (v->cargo_cap > v->cargo.RemainingCount() && MayLoadUnderExclusiveRights(st, v)) {
1531  &v->cargo, st->xy, *next_station);
1532  }
1533 
1534  return true;
1535  }
1536 
1537 };
1538 
1547 static void ReserveConsist(Station *st, Vehicle *u, CargoArray *consist_capleft, StationIDStack *next_station)
1548 {
1549  /* If there is a cargo payment not all vehicles of the consist have tried to do the refit.
1550  * In that case, only reserve if it's a fixed refit and the equivalent of "articulated chain"
1551  * a vehicle belongs to already has the right cargo. */
1552  bool must_reserve = !u->current_order.IsRefit() || u->cargo_payment == nullptr;
1553  for (Vehicle *v = u; v != nullptr; v = v->Next()) {
1554  assert(v->cargo_cap >= v->cargo.RemainingCount());
1555 
1556  /* Exclude various ways in which the vehicle might not be the head of an equivalent of
1557  * "articulated chain". Also don't do the reservation if the vehicle is going to refit
1558  * to a different cargo and hasn't tried to do so, yet. */
1559  if (!v->IsArticulatedPart() &&
1560  (v->type != VEH_TRAIN || !Train::From(v)->IsRearDualheaded()) &&
1561  (v->type != VEH_AIRCRAFT || Aircraft::From(v)->IsNormalAircraft()) &&
1562  (must_reserve || u->current_order.GetRefitCargo() == v->cargo_type)) {
1563  IterateVehicleParts(v, ReserveCargoAction(st, next_station));
1564  }
1565  if (consist_capleft == nullptr || v->cargo_cap == 0) continue;
1566  (*consist_capleft)[v->cargo_type] += v->cargo_cap - v->cargo.RemainingCount();
1567  }
1568 }
1569 
1577 static void UpdateLoadUnloadTicks(Vehicle *front, const Station *st, int ticks)
1578 {
1579  if (front->type == VEH_TRAIN) {
1580  /* Each platform tile is worth 2 rail vehicles. */
1581  int overhang = front->GetGroundVehicleCache()->cached_total_length - st->GetPlatformLength(front->tile) * TILE_SIZE;
1582  if (overhang > 0) {
1583  ticks <<= 1;
1584  ticks += (overhang * ticks) / 8;
1585  }
1586  }
1587  /* Always wait at least 1, otherwise we'll wait 'infinitively' long. */
1588  front->load_unload_ticks = max(1, ticks);
1589 }
1590 
1596 {
1597  assert(front->current_order.IsType(OT_LOADING));
1598 
1599  StationID last_visited = front->last_station_visited;
1600  Station *st = Station::Get(last_visited);
1601 
1602  StationIDStack next_station = front->GetNextStoppingStation();
1603  bool use_autorefit = front->current_order.IsRefit() && front->current_order.GetRefitCargo() == CT_AUTO_REFIT;
1604  CargoArray consist_capleft;
1605  if (_settings_game.order.improved_load && use_autorefit ?
1606  front->cargo_payment == nullptr : (front->current_order.GetLoadType() & OLFB_FULL_LOAD) != 0) {
1607  ReserveConsist(st, front,
1608  (use_autorefit && front->load_unload_ticks != 0) ? &consist_capleft : nullptr,
1609  &next_station);
1610  }
1611 
1612  /* We have not waited enough time till the next round of loading/unloading */
1613  if (front->load_unload_ticks != 0) return;
1614 
1615  if (front->type == VEH_TRAIN && (!IsTileType(front->tile, MP_STATION) || GetStationIndex(front->tile) != st->index)) {
1616  /* The train reversed in the station. Take the "easy" way
1617  * out and let the train just leave as it always did. */
1619  front->load_unload_ticks = 1;
1620  return;
1621  }
1622 
1623  int new_load_unload_ticks = 0;
1624  bool dirty_vehicle = false;
1625  bool dirty_station = false;
1626 
1627  bool completely_emptied = true;
1628  bool anything_unloaded = false;
1629  bool anything_loaded = false;
1630  CargoTypes full_load_amount = 0;
1631  CargoTypes cargo_not_full = 0;
1632  CargoTypes cargo_full = 0;
1633  CargoTypes reservation_left = 0;
1634 
1635  front->cur_speed = 0;
1636 
1637  CargoPayment *payment = front->cargo_payment;
1638 
1639  uint artic_part = 0; // Articulated part we are currently trying to load. (not counting parts without capacity)
1640  for (Vehicle *v = front; v != nullptr; v = v->Next()) {
1641  if (v == front || !v->Previous()->HasArticulatedPart()) artic_part = 0;
1642  if (v->cargo_cap == 0) continue;
1643  artic_part++;
1644 
1645  GoodsEntry *ge = &st->goods[v->cargo_type];
1646 
1647  if (HasBit(v->vehicle_flags, VF_CARGO_UNLOADING) && (front->current_order.GetUnloadType() & OUFB_NO_UNLOAD) == 0) {
1648  uint cargo_count = v->cargo.UnloadCount();
1649  uint amount_unloaded = _settings_game.order.gradual_loading ? min(cargo_count, GetLoadAmount(v)) : cargo_count;
1650  bool remaining = false; // Are there cargo entities in this vehicle that can still be unloaded here?
1651 
1652  assert(payment != nullptr);
1653  payment->SetCargo(v->cargo_type);
1654 
1655  if (!HasBit(ge->status, GoodsEntry::GES_ACCEPTANCE) && v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER) > 0) {
1656  /* The station does not accept our goods anymore. */
1658  /* Transfer instead of delivering. */
1660  v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER), INVALID_STATION);
1661  } else {
1662  uint new_remaining = v->cargo.RemainingCount() + v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER);
1663  if (v->cargo_cap < new_remaining) {
1664  /* Return some of the reserved cargo to not overload the vehicle. */
1665  v->cargo.Return(new_remaining - v->cargo_cap, &ge->cargo, INVALID_STATION);
1666  }
1667 
1668  /* Keep instead of delivering. This may lead to no cargo being unloaded, so ...*/
1670  v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER));
1671 
1672  /* ... say we unloaded something, otherwise we'll think we didn't unload
1673  * something and we didn't load something, so we must be finished
1674  * at this station. Setting the unloaded means that we will get a
1675  * retry for loading in the next cycle. */
1676  anything_unloaded = true;
1677  }
1678  }
1679 
1680  if (v->cargo.ActionCount(VehicleCargoList::MTA_TRANSFER) > 0) {
1681  /* Mark the station dirty if we transfer, but not if we only deliver. */
1682  dirty_station = true;
1683 
1684  if (!ge->HasRating()) {
1685  /* Upon transferring cargo, make sure the station has a rating. Fake a pickup for the
1686  * first unload to prevent the cargo from quickly decaying after the initial drop. */
1687  ge->time_since_pickup = 0;
1689  }
1690  }
1691 
1692  amount_unloaded = v->cargo.Unload(amount_unloaded, &ge->cargo, payment);
1693  remaining = v->cargo.UnloadCount() > 0;
1694  if (amount_unloaded > 0) {
1695  dirty_vehicle = true;
1696  anything_unloaded = true;
1697  new_load_unload_ticks += amount_unloaded;
1698 
1699  /* Deliver goods to the station */
1700  st->time_since_unload = 0;
1701  }
1702 
1703  if (_settings_game.order.gradual_loading && remaining) {
1704  completely_emptied = false;
1705  } else {
1706  /* We have finished unloading (cargo count == 0) */
1707  ClrBit(v->vehicle_flags, VF_CARGO_UNLOADING);
1708  }
1709 
1710  continue;
1711  }
1712 
1713  /* Do not pick up goods when we have no-load set or loading is stopped. */
1714  if (front->current_order.GetLoadType() & OLFB_NO_LOAD || HasBit(front->vehicle_flags, VF_STOP_LOADING)) continue;
1715 
1716  /* This order has a refit, if this is the first vehicle part carrying cargo and the whole vehicle is empty, try refitting. */
1717  if (front->current_order.IsRefit() && artic_part == 1) {
1718  HandleStationRefit(v, consist_capleft, st, next_station, front->current_order.GetRefitCargo());
1719  ge = &st->goods[v->cargo_type];
1720  }
1721 
1722  /* As we're loading here the following link can carry the full capacity of the vehicle. */
1723  v->refit_cap = v->cargo_cap;
1724 
1725  /* update stats */
1726  int t;
1727  switch (front->type) {
1728  case VEH_TRAIN:
1729  case VEH_SHIP:
1730  t = front->vcache.cached_max_speed;
1731  break;
1732 
1733  case VEH_ROAD:
1734  t = front->vcache.cached_max_speed / 2;
1735  break;
1736 
1737  case VEH_AIRCRAFT:
1738  t = Aircraft::From(front)->GetSpeedOldUnits(); // Convert to old units.
1739  break;
1740 
1741  default: NOT_REACHED();
1742  }
1743 
1744  /* if last speed is 0, we treat that as if no vehicle has ever visited the station. */
1745  ge->last_speed = min(t, 255);
1746  ge->last_age = min(_cur_year - front->build_year, 255);
1747 
1748  assert(v->cargo_cap >= v->cargo.StoredCount());
1749  /* Capacity available for loading more cargo. */
1750  uint cap_left = v->cargo_cap - v->cargo.StoredCount();
1751 
1752  if (cap_left > 0) {
1753  /* If vehicle can load cargo, reset time_since_pickup. */
1754  ge->time_since_pickup = 0;
1755 
1756  /* If there's goods waiting at the station, and the vehicle
1757  * has capacity for it, load it on the vehicle. */
1758  if ((v->cargo.ActionCount(VehicleCargoList::MTA_LOAD) > 0 || ge->cargo.AvailableCount() > 0) && MayLoadUnderExclusiveRights(st, v)) {
1759  if (v->cargo.StoredCount() == 0) TriggerVehicle(v, VEHICLE_TRIGGER_NEW_CARGO);
1760  if (_settings_game.order.gradual_loading) cap_left = min(cap_left, GetLoadAmount(v));
1761 
1762  uint loaded = ge->cargo.Load(cap_left, &v->cargo, st->xy, next_station);
1763  if (v->cargo.ActionCount(VehicleCargoList::MTA_LOAD) > 0) {
1764  /* Remember if there are reservations left so that we don't stop
1765  * loading before they're loaded. */
1766  SetBit(reservation_left, v->cargo_type);
1767  }
1768 
1769  /* Store whether the maximum possible load amount was loaded or not.*/
1770  if (loaded == cap_left) {
1771  SetBit(full_load_amount, v->cargo_type);
1772  } else {
1773  ClrBit(full_load_amount, v->cargo_type);
1774  }
1775 
1776  /* TODO: Regarding this, when we do gradual loading, we
1777  * should first unload all vehicles and then start
1778  * loading them. Since this will cause
1779  * VEHICLE_TRIGGER_EMPTY to be called at the time when
1780  * the whole vehicle chain is really totally empty, the
1781  * completely_emptied assignment can then be safely
1782  * removed; that's how TTDPatch behaves too. --pasky */
1783  if (loaded > 0) {
1784  completely_emptied = false;
1785  anything_loaded = true;
1786 
1787  st->time_since_load = 0;
1788  st->last_vehicle_type = v->type;
1789 
1790  if (ge->cargo.TotalCount() == 0) {
1791  TriggerStationRandomisation(st, st->xy, SRT_CARGO_TAKEN, v->cargo_type);
1792  TriggerStationAnimation(st, st->xy, SAT_CARGO_TAKEN, v->cargo_type);
1793  AirportAnimationTrigger(st, AAT_STATION_CARGO_TAKEN, v->cargo_type);
1794  }
1795 
1796  new_load_unload_ticks += loaded;
1797 
1798  dirty_vehicle = dirty_station = true;
1799  }
1800  }
1801  }
1802 
1803  if (v->cargo.StoredCount() >= v->cargo_cap) {
1804  SetBit(cargo_full, v->cargo_type);
1805  } else {
1806  SetBit(cargo_not_full, v->cargo_type);
1807  }
1808  }
1809 
1810  if (anything_loaded || anything_unloaded) {
1811  if (front->type == VEH_TRAIN) {
1813  TriggerStationAnimation(st, front->tile, SAT_TRAIN_LOADS);
1814  }
1815  }
1816 
1817  /* Only set completely_emptied, if we just unloaded all remaining cargo */
1818  completely_emptied &= anything_unloaded;
1819 
1820  if (!anything_unloaded) delete payment;
1821 
1823  if (anything_loaded || anything_unloaded) {
1825  /* The time it takes to load one 'slice' of cargo or passengers depends
1826  * on the vehicle type - the values here are those found in TTDPatch */
1827  const uint gradual_loading_wait_time[] = { 40, 20, 10, 20 };
1828 
1829  new_load_unload_ticks = gradual_loading_wait_time[front->type];
1830  }
1831  /* We loaded less cargo than possible for all cargo types and it's not full
1832  * load and we're not supposed to wait any longer: stop loading. */
1833  if (!anything_unloaded && full_load_amount == 0 && reservation_left == 0 && !(front->current_order.GetLoadType() & OLFB_FULL_LOAD) &&
1834  front->current_order_time >= (uint)max(front->current_order.GetTimetabledWait() - front->lateness_counter, 0)) {
1836  }
1837 
1838  UpdateLoadUnloadTicks(front, st, new_load_unload_ticks);
1839  } else {
1840  UpdateLoadUnloadTicks(front, st, 20); // We need the ticks for link refreshing.
1841  bool finished_loading = true;
1842  if (front->current_order.GetLoadType() & OLFB_FULL_LOAD) {
1843  if (front->current_order.GetLoadType() == OLF_FULL_LOAD_ANY) {
1844  /* if the aircraft carries passengers and is NOT full, then
1845  * continue loading, no matter how much mail is in */
1846  if ((front->type == VEH_AIRCRAFT && IsCargoInClass(front->cargo_type, CC_PASSENGERS) && front->cargo_cap > front->cargo.StoredCount()) ||
1847  (cargo_not_full != 0 && (cargo_full & ~cargo_not_full) == 0)) { // There are still non-full cargoes
1848  finished_loading = false;
1849  }
1850  } else if (cargo_not_full != 0) {
1851  finished_loading = false;
1852  }
1853 
1854  /* Refresh next hop stats if we're full loading to make the links
1855  * known to the distribution algorithm and allow cargo to be sent
1856  * along them. Otherwise the vehicle could wait for cargo
1857  * indefinitely if it hasn't visited the other links yet, or if the
1858  * links die while it's loading. */
1859  if (!finished_loading) LinkRefresher::Run(front, true, true);
1860  }
1861 
1862  SB(front->vehicle_flags, VF_LOADING_FINISHED, 1, finished_loading);
1863  }
1864 
1865  /* Calculate the loading indicator fill percent and display
1866  * In the Game Menu do not display indicators
1867  * If _settings_client.gui.loading_indicators == 2, show indicators (bool can be promoted to int as 0 or 1 - results in 2 > 0,1 )
1868  * if _settings_client.gui.loading_indicators == 1, _local_company must be the owner or must be a spectator to show ind., so 1 > 0
1869  * if _settings_client.gui.loading_indicators == 0, do not display indicators ... 0 is never greater than anything
1870  */
1871  if (_game_mode != GM_MENU && (_settings_client.gui.loading_indicators > (uint)(front->owner != _local_company && _local_company != COMPANY_SPECTATOR))) {
1872  StringID percent_up_down = STR_NULL;
1873  int percent = CalcPercentVehicleFilled(front, &percent_up_down);
1874  if (front->fill_percent_te_id == INVALID_TE_ID) {
1875  front->fill_percent_te_id = ShowFillingPercent(front->x_pos, front->y_pos, front->z_pos + 20, percent, percent_up_down);
1876  } else {
1877  UpdateFillingPercent(front->fill_percent_te_id, percent, percent_up_down);
1878  }
1879  }
1880 
1881  if (completely_emptied) {
1882  /* Make sure the vehicle is marked dirty, since we need to update the NewGRF
1883  * properties such as weight, power and TE whenever the trigger runs. */
1884  dirty_vehicle = true;
1885  TriggerVehicle(front, VEHICLE_TRIGGER_EMPTY);
1886  }
1887 
1888  if (dirty_vehicle) {
1891  front->MarkDirty();
1892  }
1893  if (dirty_station) {
1894  st->MarkTilesDirty(true);
1895  SetWindowDirty(WC_STATION_VIEW, last_visited);
1896  InvalidateWindowData(WC_STATION_LIST, last_visited);
1897  }
1898 }
1899 
1906 {
1907  /* No vehicle is here... */
1908  if (st->loading_vehicles.empty()) return;
1909 
1910  Vehicle *last_loading = nullptr;
1911  std::list<Vehicle *>::iterator iter;
1912 
1913  /* Check if anything will be loaded at all. Otherwise we don't need to reserve either. */
1914  for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end(); ++iter) {
1915  Vehicle *v = *iter;
1916 
1917  if ((v->vehstatus & (VS_STOPPED | VS_CRASHED))) continue;
1918 
1919  assert(v->load_unload_ticks != 0);
1920  if (--v->load_unload_ticks == 0) last_loading = v;
1921  }
1922 
1923  /* We only need to reserve and load/unload up to the last loading vehicle.
1924  * Anything else will be forgotten anyway after returning from this function.
1925  *
1926  * Especially this means we do _not_ need to reserve cargo for a single
1927  * consist in a station which is not allowed to load yet because its
1928  * load_unload_ticks is still not 0.
1929  */
1930  if (last_loading == nullptr) return;
1931 
1932  for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end(); ++iter) {
1933  Vehicle *v = *iter;
1934  if (!(v->vehstatus & (VS_STOPPED | VS_CRASHED))) LoadUnloadVehicle(v);
1935  if (v == last_loading) break;
1936  }
1937 
1938  /* Call the production machinery of industries */
1939  for (Industry *iid : _cargo_delivery_destinations) {
1941  }
1942  _cargo_delivery_destinations.clear();
1943 }
1944 
1949 {
1952  AddInflation();
1953  RecomputePrices();
1954  }
1956  HandleEconomyFluctuations();
1957 }
1958 
1959 static void DoAcquireCompany(Company *c)
1960 {
1961  CompanyID ci = c->index;
1962 
1963  CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
1965 
1966  SetDParam(0, STR_NEWS_COMPANY_MERGER_TITLE);
1967  SetDParam(1, c->bankrupt_value == 0 ? STR_NEWS_MERGER_TAKEOVER_TITLE : STR_NEWS_COMPANY_MERGER_DESCRIPTION);
1968  SetDParamStr(2, cni->company_name);
1970  SetDParam(4, c->bankrupt_value);
1971  AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, cni);
1972  AI::BroadcastNewEvent(new ScriptEventCompanyMerger(ci, _current_company));
1973  Game::NewEvent(new ScriptEventCompanyMerger(ci, _current_company));
1974 
1976 
1977  if (c->bankrupt_value == 0) {
1979  owner->current_loan += c->current_loan;
1980  }
1981 
1982  if (c->is_ai) AI::Stop(c->index);
1983 
1989 
1990  delete c;
1991 }
1992 
1993 extern int GetAmountOwnedBy(const Company *c, Owner owner);
1994 
2004 CommandCost CmdBuyShareInCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2005 {
2007  CompanyID target_company = (CompanyID)p1;
2008  Company *c = Company::GetIfValid(target_company);
2009 
2010  /* Check if buying shares is allowed (protection against modified clients)
2011  * Cannot buy own shares */
2012  if (c == nullptr || !_settings_game.economy.allow_shares || _current_company == target_company) return CMD_ERROR;
2013 
2014  /* Protect new companies from hostile takeovers */
2016 
2017  /* Those lines are here for network-protection (clients can be slow) */
2018  if (GetAmountOwnedBy(c, COMPANY_SPECTATOR) == 0) return cost;
2019 
2020  if (GetAmountOwnedBy(c, COMPANY_SPECTATOR) == 1) {
2021  if (!c->is_ai) return cost; // We can not buy out a real company (temporarily). TODO: well, enable it obviously.
2022 
2023  if (GetAmountOwnedBy(c, _current_company) == 3 && !MayCompanyTakeOver(_current_company, target_company)) return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
2024  }
2025 
2026 
2027  cost.AddCost(CalculateCompanyValue(c) >> 2);
2028  if (flags & DC_EXEC) {
2029  Owner *b = c->share_owners;
2030 
2031  while (*b != COMPANY_SPECTATOR) b++; // share owners is guaranteed to contain at least one COMPANY_SPECTATOR
2032  *b = _current_company;
2033 
2034  for (int i = 0; c->share_owners[i] == _current_company;) {
2035  if (++i == 4) {
2036  c->bankrupt_value = 0;
2037  DoAcquireCompany(c);
2038  break;
2039  }
2040  }
2041  InvalidateWindowData(WC_COMPANY, target_company);
2042  CompanyAdminUpdate(c);
2043  }
2044  return cost;
2045 }
2046 
2056 CommandCost CmdSellShareInCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2057 {
2058  CompanyID target_company = (CompanyID)p1;
2059  Company *c = Company::GetIfValid(target_company);
2060 
2061  /* Cannot sell own shares */
2062  if (c == nullptr || _current_company == target_company) return CMD_ERROR;
2063 
2064  /* Check if selling shares is allowed (protection against modified clients).
2065  * However, we must sell shares of companies being closed down. */
2066  if (!_settings_game.economy.allow_shares && !(flags & DC_BANKRUPT)) return CMD_ERROR;
2067 
2068  /* Those lines are here for network-protection (clients can be slow) */
2069  if (GetAmountOwnedBy(c, _current_company) == 0) return CommandCost();
2070 
2071  /* adjust it a little to make it less profitable to sell and buy */
2072  Money cost = CalculateCompanyValue(c) >> 2;
2073  cost = -(cost - (cost >> 7));
2074 
2075  if (flags & DC_EXEC) {
2076  Owner *b = c->share_owners;
2077  while (*b != _current_company) b++; // share owners is guaranteed to contain company
2078  *b = COMPANY_SPECTATOR;
2079  InvalidateWindowData(WC_COMPANY, target_company);
2080  CompanyAdminUpdate(c);
2081  }
2082  return CommandCost(EXPENSES_OTHER, cost);
2083 }
2084 
2097 CommandCost CmdBuyCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2098 {
2099  CompanyID target_company = (CompanyID)p1;
2100  Company *c = Company::GetIfValid(target_company);
2101  if (c == nullptr) return CMD_ERROR;
2102 
2103  /* Disable takeovers when not asked */
2104  if (!HasBit(c->bankrupt_asked, _current_company)) return CMD_ERROR;
2105 
2106  /* Disable taking over the local company in single player */
2107  if (!_networking && _local_company == c->index) return CMD_ERROR;
2108 
2109  /* Do not allow companies to take over themselves */
2110  if (target_company == _current_company) return CMD_ERROR;
2111 
2112  /* Disable taking over when not allowed. */
2113  if (!MayCompanyTakeOver(_current_company, target_company)) return CMD_ERROR;
2114 
2115  /* Get the cost here as the company is deleted in DoAcquireCompany. */
2116  CommandCost cost(EXPENSES_OTHER, c->bankrupt_value);
2117 
2118  if (flags & DC_EXEC) {
2119  DoAcquireCompany(c);
2120  }
2121  return cost;
2122 }
Functions related to OTTD&#39;s strings.
void TriggerStationRandomisation(Station *st, TileIndex tile, StationRandomTrigger trigger, CargoID cargo_type)
Trigger station randomisation.
SourceType
Types of cargo source and destination.
Definition: cargo_type.h:146
Owner
Enum for all companies/owners.
Definition: company_type.h:18
void ChangeTileOwner(TileIndex tile, Owner old_owner, Owner new_owner)
Change the owner of a tile.
Definition: landscape.cpp:600
byte infl_amount_pr
inflation rate for payment rates
Definition: economy_type.h:24
static bool IsLocalCompany()
Is the current company the local company?
Definition: company_func.h:43
uint RemainingCount() const
Returns the sum of cargo to be kept in the vehicle at the current station.
Definition: cargopacket.h:387
Vehicle * Previous() const
Get the previous vehicle of this vehicle.
Definition: vehicle_base.h:586
Vehicle is stopped by the player.
Definition: vehicle_base.h:31
Money Prices[PR_END]
Prices of everything.
Definition: economy_type.h:144
void AddTrackToSignalBuffer(TileIndex tile, Track track, Owner owner)
Add track to signal update buffer.
Definition: signal.cpp:580
int CompanyServiceInterval(const Company *c, VehicleType type)
Get the service interval for the given company and vehicle type.
Trigger station when cargo is completely taken.
VehicleCargoList cargo
The cargo this vehicle is carrying.
Definition: vehicle_base.h:307
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:79
static void NewEvent(class ScriptEvent *event)
Queue a new event for a Game Script.
Definition: game_core.cpp:141
used in multiplayer to create a new companies etc.
Definition: command_type.h:278
static Titem * GetIfValid(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:302
const ScoreInfo _score_info[]
Score info, values used for computing the detailed performance rating.
Definition: economy.cpp:83
bool _networking
are we in networking mode?
Definition: network.cpp:52
bool operator()(Vehicle *v)
Reserve cargo from the station and update the remaining consist capacities with the vehicle&#39;s remaini...
Definition: economy.cpp:1435
Functions for NewGRF engines.
static void CompaniesGenStatistics()
Update the finances of all companies.
Definition: economy.cpp:640
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
void LoadUnloadStation(Station *st)
Load/unload the vehicles in this station according to the order they entered.
Definition: economy.cpp:1905
virtual void MarkDirty()
Marks the vehicles to be redrawn and updates cached variables.
Definition: vehicle_base.h:362
TransportedCargoStat< uint16 > received[NUM_TE]
Cargo statistics about received cargotypes.
Definition: town.h:78
byte infl_amount
inflation amount
Definition: economy_type.h:23
Definition of link refreshing utility.
Station * st
Station to give the returned cargo to.
Definition: economy.cpp:1387
Minimal stack that uses a pool to avoid pointers.
Money start_price
Default value at game start, before adding multipliers.
Definition: economy_type.h:182
static int32 BigMulS(const int32 a, const int32 b, const uint8 shift)
Multiply two integer values and shift the results to right.
Definition: economy.cpp:73
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition: window.cpp:3215
An invalid owner.
Definition: company_type.h:29
Vehicle * GetFirstEnginePart()
Get the first part of an articulated engine.
Definition: vehicle_base.h:919
byte GetCount() const
Get the amount of cargos that have an amount.
Definition: cargo_type.h:134
EconomySettings economy
settings to change the economy
Vehicle has finished loading.
Definition: vehicle_base.h:42
Train vehicle type.
Definition: vehicle_type.h:24
union Vehicle::@49 orders
The orders currently assigned to the vehicle.
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:291
int32 performance_history
Company score (scale 0-1000)
Definition: company_base.h:25
Functions related to dates.
static const Year ORIGINAL_MAX_YEAR
The maximum year of the original TTD.
Definition: date_type.h:53
Cargo has been delivered.
Company * owner
The owner of the vehicle.
Definition: economy_base.h:31
Base for the train class.
static uint MapLogX()
Logarithm of the map size along the X side.
Definition: map_func.h:51
Year inaugurated_year
Year of starting the company.
Definition: company_base.h:78
static bool HasSignalOnTrack(TileIndex tile, Track track)
Checks for the presence of signals (either way) on the given track on the given rail tile...
Definition: rail_map.h:413
static T SetBit(T &x, const uint8 y)
Set a bit in a variable.
change the server interval of a vehicle
Definition: command_type.h:230
uint16 cur_speed
current speed
Definition: vehicle_base.h:291
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)
Delivers goods to industries/towns and calculates the payment.
Definition: economy.cpp:1074
query cost only, don&#39;t build.
Definition: command_type.h:346
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
Definition: command_func.h:23
Ship vehicle type.
Definition: vehicle_type.h:26
Replace vehicle window; Window numbers:
Definition: window_type.h:211
uint64 inflation_prices
Cumulated inflation of prices since game start; 16 bit fractional part.
Definition: economy_type.h:27
Set when cargo was delivered for final delivery during the current STATION_ACCEPTANCE_TICKS interval...
Definition: station_base.h:211
uint16 _returned_refit_capacity
Stores the capacity after a refit operation.
Definition: vehicle.cpp:85
Used for iterations.
Definition: road_type.h:26
Specification of a cargo type.
Definition: cargotype.h:55
Money FeederShare() const
Gets the amount of money already paid to earlier vehicles in the feeder chain.
Definition: cargopacket.h:109
OrderList * list
Pointer to the order list for this vehicle.
Definition: vehicle_base.h:319
byte interest_rate
Interest.
Definition: economy_type.h:22
CompanyMask bankrupt_asked
which companies were asked about buying it?
Definition: company_base.h:81
Functions related to vehicles.
Set when cargo was delivered for final delivery this month.
Definition: station_base.h:205
uint16 callback_mask
Bitmask of industry callbacks that have to be called.
Definition: industrytype.h:137
uint32 current_order_time
How many ticks have passed since this order started.
Definition: base_consist.h:21
uint TotalCount() const
Returns total count of cargo at the station, including cargo which is already reserved for loading...
Definition: cargopacket.h:526
Struct about goals, current and completed.
Definition: goal_base.h:21
Price
Enumeration of all base prices for use with Prices.
Definition: economy_type.h:65
CommandCost CmdBuyShareInCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Acquire shares in an opposing company.
Definition: economy.cpp:2004
Build vehicle; Window numbers:
Definition: window_type.h:376
Vehicle data structure.
Definition: vehicle_base.h:210
Called to calculate the income of delivered cargo.
Action for returning reserved cargo.
Definition: economy.cpp:1385
void Change(const U &new_value)
Change the value of the variable.
Definition: backup_type.hpp:84
Defines the internal data of a functional industry.
Definition: industry.h:40
custom profit calculation
DifficultySettings difficulty
settings related to the difficulty
static void BroadcastNewEvent(ScriptEvent *event, CompanyID skip_company=MAX_COMPANIES)
Broadcast a new event to all active AIs.
Definition: ai_core.cpp:259
Stores station stats for a single cargo.
Definition: station_base.h:170
Tindex index
Index of this pool item.
Definition: pool_type.hpp:189
void IndustryProductionCallback(Industry *ind, int reason)
Get the industry production callback and apply it to the industry.
static Money SignalMaintenanceCost(uint32 num)
Calculates the maintenance cost of a number of signals.
Definition: rail.h:438
byte months_of_bankruptcy
Number of months that the company is unable to pay its debts.
Definition: company_base.h:80
This must always be the last entry.
Definition: economy_type.h:47
TileIndex SourceStationXY() const
Gets the coordinates of the cargo&#39;s source station.
Definition: cargopacket.h:167
Payment rates graph; Window numbers:
Definition: window_type.h:558
Company value graph; Window numbers:
Definition: window_type.h:546
byte subsidy_multiplier
amount of subsidy
Definition: settings_type.h:62
Date last_cargo_accepted_at[INDUSTRY_NUM_INPUTS]
Last day each cargo type was accepted by this industry.
Definition: industry.h:69
static SigSegState UpdateSignalsInBuffer(Owner owner)
Updates blocks in _globset buffer.
Definition: signal.cpp:470
Vehicle is unloading cargo.
Definition: vehicle_base.h:43
bool IsMultiheaded() const
Check if the vehicle is a multiheaded engine.
Base for aircraft.
Representation of a waypoint.
Definition: waypoint_base.h:16
Other expenses.
Definition: economy_type.h:161
StationID last_station_visited
The last station we stopped at.
Definition: vehicle_base.h:300
uint16 input_cargo_multiplier[INDUSTRY_NUM_INPUTS][INDUSTRY_NUM_OUTPUTS]
Input cargo multipliers (multiply amount of incoming cargo for the produced cargoes) ...
Definition: industrytype.h:121
void MarkTilesDirty(bool cargo_change) const
Marks the tiles of the station as dirty.
Definition: station.cpp:218
Data that needs to be stored for company news messages.
Definition: news_type.h:148
A railway.
Definition: tile_type.h:42
static Pool::IterateWrapper< Station > Iterate(size_t from=0)
Returns an iterable ensemble of all valid stations of type T.
Money GetCost() const
The costs as made up to this moment.
Definition: command_type.h:82
initial rating
Definition: town_type.h:44
byte was_cargo_delivered
flag that indicate this has been the closest industry chosen for cargo delivery by a station...
Definition: industry.h:61
Refit preparation action.
Definition: economy.cpp:1355
static uint MapLogY()
Logarithm of the map size along the y side.
Definition: map_func.h:62
int32 lateness_counter
How many ticks late (or early if negative) this vehicle is.
Definition: base_consist.h:22
FinalizeRefitAction(CargoArray &consist_capleft, Station *st, StationIDStack &next_station, bool do_reserve)
Create a finalizing action.
Definition: economy.cpp:1426
Automatically choose cargo type when doing auto refitting.
Definition: cargo_type.h:66
Common return value for all commands.
Definition: command_type.h:23
StationIDStack & next_station
Next hops to reserve cargo for.
Definition: economy.cpp:1416
RoadType
The different roadtypes we support.
Definition: road_type.h:22
StationCargoList cargo
The cargo packets of cargo waiting in this station.
Definition: station_base.h:255
static T max(const T a, const T b)
Returns the maximum of two values.
Definition: math_func.hpp:24
Town * town
The town this station is associated with.
static void UpdateLoadUnloadTicks(Vehicle *front, const Station *st, int ticks)
Update the vehicle&#39;s load_unload_ticks, the time it will wait until it tries to load or unload again...
Definition: economy.cpp:1577
bool HasRating() const
Does this cargo have a rating at this station?
Definition: station_base.h:273
byte vehstatus
Status.
Definition: vehicle_base.h:315
uint32 max_loan
the maximum initial loan
Definition: settings_type.h:57
Types related to cargoes...
Year _cur_year
Current year, starting at 0.
Definition: date.cpp:24
static bool MayLoadUnderExclusiveRights(const Station *st, const Vehicle *v)
Test whether a vehicle can load cargo at a station even if exclusive transport rights are present...
Definition: economy.cpp:1515
uint StoredCount() const
Returns sum of cargo on board the vehicle (ie not only reserved).
Definition: cargopacket.h:351
bool improved_load
improved loading algorithm
uint Return(uint max_move, StationCargoList *dest, StationID next_station)
Returns reserved cargo to the station and removes it from the cache.
bool infrastructure_maintenance
enable monthly maintenance fee for owner infrastructure
static Aircraft * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
Tstorage new_act
Actually transported this month.
Definition: town_type.h:116
static const int MIN_PRICE_MODIFIER
Maximum NewGRF price modifiers.
Definition: economy_type.h:206
uint16 cached_max_speed
Maximum speed of the consist (minimum of the max speed of all vehicles in the consist).
Definition: vehicle_base.h:121
CompanySettings settings
settings specific for each company
Definition: company_base.h:127
Trigger platform when train loads/unloads.
Generates sequence of free UnitID numbers.
const Engine * GetEngine() const
Retrieves the engine of the vehicle.
Definition: vehicle.cpp:741
uint Load(uint max_move, VehicleCargoList *dest, TileIndex load_place, StationIDStack next)
Loads cargo onto a vehicle.
void DeleteCompanyWindows(CompanyID company)
Delete all windows of a company.
Definition: window.cpp:1197
bool IsNormalAircraft() const
Check if the aircraft type is a normal flying device; eg not a rotor or a shadow. ...
Definition: aircraft.h:121
static const uint TILE_SIZE
Tile size in world coordinates.
Definition: tile_type.h:13
GoodsEntry goods[NUM_CARGO]
Goods at this station.
Definition: station_base.h:479
uint32 industry_daily_increment
The value which will increment industry_daily_change_counter. Computed value. NOSAVE.
Definition: economy_type.h:26
bool operator()(const Vehicle *v)
Checks if the vehicle has stored cargo.
Definition: economy.cpp:1346
Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift)
Determine a certain price.
Definition: economy.cpp:942
CargoArray & consist_capleft
Capacities left in the consist.
Definition: economy.cpp:1414
void AddCost(const Money &cost)
Adds the given cost to the cost of the command.
Definition: command_type.h:62
static T SB(T &x, const uint8 s, const uint8 n, const U d)
Set n bits in x starting at bit s to d.
bool IndustryTemporarilyRefusesCargo(Industry *ind, CargoID cargo_type)
Check whether an industry temporarily refuses to accept a certain cargo.
uint32 GetGRFID() const
Retrieve the GRF ID of the NewGRF the engine is tied to.
Definition: engine.cpp:160
uint16 servint_ships
service interval for ships
CargoID ct
The currently handled cargo type.
Definition: economy_base.h:33
void InitializeEconomy()
Resets economy to initial values.
Definition: economy.cpp:927
Class to backup a specific variable and restore it later.
Definition: backup_type.hpp:21
company bankrupts, skip money check, skip vehicle on tile check in some cases
Definition: command_type.h:350
bool allow_shares
allow the buying/selling of shares
char company_name[64]
The name of the company.
Definition: news_type.h:149
uint16 multiplier
Capacity multiplier for vehicles. (8 fractional bits)
Definition: cargotype.h:61
PriceMultipliers price_base_multipliers
Price base multipliers as set by the grf.
Definition: newgrf.h:146
Income graph; Window numbers:
Definition: window_type.h:522
Money expenses
The amount of expenses.
Definition: company_base.h:23
static const size_t MAX_SIZE
Make template parameter accessible from outside.
Definition: pool_type.hpp:86
SourceID SourceSubsidyID() const
Gets the ID of the cargo&#39;s source.
Definition: cargopacket.h:149
TextEffectID fill_percent_te_id
a text-effect id to a loading indicator object
Definition: vehicle_base.h:288
void InvalidateWindowClassesData(WindowClass cls, int data, bool gui_scope)
Mark window data of all windows of a given class as invalid (in need of re-computing) Note that by de...
Definition: window.cpp:3334
TextEffectID ShowFillingPercent(int x, int y, int z, uint8 percent, StringID string)
Display vehicle loading indicators.
Definition: misc_gui.cpp:624
uint16 cargo_cap
total capacity
Definition: vehicle_base.h:305
void SetPriceBaseMultiplier(Price price, int factor)
Change a price base by the given factor.
Definition: economy.cpp:883
static bool IsTileOwner(TileIndex tile, Owner owner)
Checks if a tile belongs to the given owner.
Definition: tile_map.h:214
void SetDParamStr(uint n, const char *str)
This function is used to "bind" a C string to a OpenTTD dparam slot.
Definition: strings.cpp:279
Struct about stories, current and completed.
Definition: story_base.h:64
Some methods of Pool are placed here in order to reduce compilation time and binary size...
Vehicle is crashed.
Definition: vehicle_base.h:37
The tile has no ownership.
Definition: company_type.h:25
static bool IsTileType(TileIndex tile, TileType type)
Checks if a tile is a given tiletype.
Definition: tile_map.h:150
Triggered when a cargo type is completely removed from the station (for all tiles at the same time)...
How many scores are there..
Definition: economy_type.h:48
bool MayCompanyTakeOver(CompanyID cbig, CompanyID csmall)
May company cbig buy company csmall?
byte num_valid_stat_ent
Number of valid statistical entries in old_economy.
Definition: company_base.h:98
static void LoadUnloadVehicle(Vehicle *front)
Loads/unload the vehicle if possible.
Definition: economy.cpp:1595
CommandCost DoCommand(const CommandContainer *container, DoCommandFlag flags)
Shorthand for calling the long DoCommand with a container.
Definition: command.cpp:441
This indicates whether a cargo has a rating at the station.
Definition: station_base.h:187
byte DaysInTransit() const
Gets the number of days this cargo has been in transit.
Definition: cargopacket.h:131
The client is spectating.
Definition: company_type.h:35
Vehicle * front
The front vehicle to do the payment of.
Definition: economy_base.h:25
bool IsRefit() const
Is this order a refit order.
Definition: order_base.h:108
Price is affected by "construction cost" difficulty setting.
Definition: economy_type.h:175
VehicleDefaultSettings vehicle
default settings for vehicles
IndustryList industries_near
Cached list of industries near the station that can accept cargo,.
Definition: station_base.h:482
GroundVehicleCache * GetGroundVehicleCache()
Access the ground vehicle cache of the vehicle.
Definition: vehicle.cpp:2824
CommandCost CmdBuyCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Buy up another company.
Definition: economy.cpp:2097
Do not load anything.
Definition: order_type.h:66
Don&#39;t load anymore during the next load cycle.
Definition: vehicle_base.h:48
bool IsType(OrderType type) const
Check whether this order is of the given type.
Definition: order_base.h:61
DoCommandFlag
List of flags for a command.
Definition: command_type.h:342
Money current_loan
Amount of money borrowed from the bank.
Definition: company_base.h:67
Money PayTransfer(const CargoPacket *cp, uint count)
Handle payment for transfer of the given cargo packet.
Definition: economy.cpp:1217
byte callback_mask
Bitmask of vehicle callbacks that have to be called.
Definition: engine_type.h:143
ClientSettings _settings_client
The current settings for this game.
Definition: settings.cpp:78
bool operator()(const Vehicle *v)
Prepares for refitting of a vehicle, subtracting its free capacity from consist_capleft and adding th...
Definition: economy.cpp:1374
byte status
Status of this cargo, see GoodsEntryStatus.
Definition: station_base.h:226
Money visual_profit
The visual profit to show.
Definition: economy_base.h:27
Interest payments over the loan.
Definition: economy_type.h:160
void UpdateCompanyHQ(TileIndex tile, uint score)
Update the CompanyHQ to the state associated with the given score.
Definition: object_cmd.cpp:155
Money AirportMaintenanceCost(Owner owner)
Calculates the maintenance cost of all airports of a company.
Definition: station.cpp:653
bool Succeeded() const
Did this command succeed?
Definition: command_type.h:150
Container for cargo from the same location and time.
Definition: cargopacket.h:42
void PrepareUnload(Vehicle *front_v)
Prepare the vehicle to be unloaded.
Definition: economy.cpp:1236
const IndustrySpec * GetIndustrySpec(IndustryType thistype)
Accessor for array _industry_specs.
TileIndex location_of_HQ
Northern tile of HQ; INVALID_TILE when there is none.
Definition: company_base.h:73
Definition of base types and functions in a cross-platform compatible way.
static Money RoadMaintenanceCost(RoadType roadtype, uint32 num, uint32 total_num)
Calculates the maintenance cost of a number of road bits.
Definition: road_func.h:125
virtual ExpensesType GetExpenseType(bool income) const
Sets the expense type associated to this vehicle type.
Definition: vehicle_base.h:421
void NetworkClientsToSpectators(CompanyID cid)
Move the clients of a company to the spectators.
A number of safeguards to prevent using unsafe methods.
void SetLocalCompany(CompanyID new_company)
Sets the local company and updates the settings that are set on a per-company basis to reflect the co...
static void Run(Vehicle *v, bool allow_merge=true, bool is_full_loading=false)
Refresh all links the given vehicle will visit.
Definition: refresh.cpp:26
uint8 min_years_for_shares
minimum age of a company for it to trade shares
IndustryType type
type of industry.
Definition: industry.h:57
Base of waypoints.
void PayFinalDelivery(const CargoPacket *cp, uint count)
Handle payment for final delivery of the given cargo packet.
Definition: economy.cpp:1197
bool inflation
disable inflation
static uint CeilDiv(uint a, uint b)
Computes ceil(a / b) for non-negative a and b.
Definition: math_func.hpp:314
int score
How much score it will give.
Definition: economy_type.h:58
uint8 callback_mask
Bitmask of cargo callbacks that have to be called.
Definition: cargotype.h:68
Money route_profit
The amount of money to add/remove from the bank account.
Definition: economy_base.h:26
Station * st
Station to reserve cargo from.
Definition: economy.cpp:1415
Operating profit graph; Window numbers:
Definition: window_type.h:528
Company league window; Window numbers:
Definition: window_type.h:552
CargoID cargo_type
type of cargo this vehicle is carrying
Definition: vehicle_base.h:303
CargoPayment()
Constructor for pool saveload.
Definition: economy_base.h:36
GUI Functions related to companies.
Trigger when cargo is received .
uint16 load_unload_ticks
Ticks to wait before starting next cycle.
Definition: vehicle_base.h:323
TrackBits
Bitfield corresponding to Track.
Definition: track_type.h:38
Normal news item. (Newspaper with text only)
Definition: news_type.h:78
Money CalculateCompanyValue(const Company *c, bool including_loan)
Calculate the value of the company.
Definition: economy.cpp:111
byte misc_flags
Miscellaneous flags.
Definition: engine_type.h:142
byte vehicle_costs
amount of money spent on vehicle running cost
Definition: settings_type.h:59
TileIndex tile
Current tile index.
Definition: vehicle_base.h:228
Road vehicle list; Window numbers:
Definition: window_type.h:307
Defines the data structure for constructing industry.
Definition: industrytype.h:106
void ClearCargoPickupMonitoring(CompanyID company)
Clear all pick-up cargo monitors.
static void CountVehicle(const Vehicle *v, int delta)
Update num_vehicle when adding or removing a vehicle.
Definition: group_cmd.cpp:133
bool is_ai
If true, the company is (also) controlled by the computer (a NoAI program).
Definition: company_base.h:93
bool HasArticulatedPart() const
Check if an engine has an articulated part.
Definition: vehicle_base.h:899
Money money
Money owned by the company.
Definition: company_base.h:65
Station view; Window numbers:
Definition: window_type.h:338
OrderLoadFlags GetLoadType() const
How must the consist be loaded?
Definition: order_base.h:127
Basic functions/variables used all over the place.
bool IsRearDualheaded() const
Tell if we are dealing with the rear end of a multiheaded engine.
CargoID accepts_cargo[INDUSTRY_NUM_INPUTS]
16 input cargo slots
Definition: industry.h:49
Owner owner
Which company owns the vehicle?
Definition: vehicle_base.h:271
bool DoCommandP(const CommandContainer *container, bool my_cmd)
Shortcut for the long DoCommandP when having a container with the data.
Definition: command.cpp:532
Industry view; Window numbers:
Definition: window_type.h:356
uint16 incoming_cargo_waiting[INDUSTRY_NUM_INPUTS]
incoming cargo waiting to be processed
Definition: industry.h:46
#define lengthof(x)
Return the length of an fixed size array.
Definition: depend.cpp:40
byte last_speed
Maximum speed (up to 255) of the last vehicle that tried to load this cargo.
Definition: station_base.h:246
static void ReserveConsist(Station *st, Vehicle *u, CargoArray *consist_capleft, StationIDStack *next_station)
Reserves cargo if the full load order and improved_load is set or if the current order allows autoref...
Definition: economy.cpp:1547
CommandCost CmdSellShareInCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Sell shares in an opposing company.
Definition: economy.cpp:2056
SourceType SourceSubsidyType() const
Gets the type of the cargo&#39;s source.
Definition: cargopacket.h:140
uint Reserve(uint max_move, VehicleCargoList *dest, TileIndex load_place, StationIDStack next)
Reserves cargo for loading onto the vehicle.
static T min(const T a, const T b)
Returns the minimum of two values.
Definition: math_func.hpp:40
#define MAX_UVALUE(type)
The largest value that can be entered in a variable.
Definition: stdafx.h:469
static bool EconomyIsInRecession()
Is the economy in recession?
Definition: economy_func.h:47
Helper class to perform the cargo payment.
Definition: economy_base.h:24
void FillData(const struct Company *c, const struct Company *other=nullptr)
Fill the CompanyNewsInformation struct with the required data.
Deliver the cargo to some town or industry.
Definition: cargopacket.h:215
static bool IsCargoInClass(CargoID c, CargoClass cc)
Does cargo c have cargo class cc?
Definition: cargotype.h:148
bool CheckSubsidised(CargoID cargo_type, CompanyID company, SourceType src_type, SourceID src, const Station *st)
Tests whether given delivery is subsidised and possibly awards the subsidy to delivering company...
Definition: subsidy.cpp:544
Functions related to sound.
static void RemoveAllEngineReplacementForCompany(Company *c)
Remove all engine replacement settings for the given company.
void ChangeOwnershipOfCompanyItems(Owner old_owner, Owner new_owner)
Change the ownership of all the items of a company.
Definition: economy.cpp:282
static const Year ORIGINAL_BASE_YEAR
The minimum starting year/base year of the original TTD.
Definition: date_type.h:49
uint32 StringID
Numeric value that represents a string, independent of the selected language.
Definition: strings_type.h:16
Money max_loan
NOSAVE: Maximum possible loan.
Definition: economy_type.h:20
Vehicle * First() const
Get the first vehicle of this vehicle chain.
Definition: vehicle_base.h:592
void CompanyAdminUpdate(const Company *company)
Called whenever company related information changes in order to notify admins.
NewGRF handling of industry tiles.
Delete a company.
Definition: company_type.h:67
The max score that can be in the performance history.
Definition: economy_type.h:50
Data of the economy.
Definition: economy_type.h:19
byte last_age
Age in years (up to 255) of the last vehicle that tried to load this cargo.
Definition: station_base.h:252
Action for finalizing a refit.
Definition: economy.cpp:1412
void UpdateLevelCrossing(TileIndex tile, bool sound=true)
Sets correct crossing state.
Definition: train_cmd.cpp:1672
static void Stop(CompanyID company)
Stop a company to be controlled by an AI.
Definition: ai_core.cpp:102
void ClearCargoDeliveryMonitoring(CompanyID company)
Clear all delivery cargo monitors.
ReturnCargoAction(Station *st, StationID next_one)
Construct a cargo return action.
Definition: economy.cpp:1395
int16 bankrupt_timeout
If bigger than 0, amount of time to wait for an answer on an offer to buy this company.
Definition: company_base.h:82
bool IterateVehicleParts(Vehicle *v, Taction action)
Iterate the articulated parts of a vehicle, also considering the special cases of "normal" aircraft a...
Definition: economy.cpp:1322
Year build_year
Year the vehicle has been built.
Definition: vehicle_base.h:255
bool PlayVehicleSound(const Vehicle *v, VehicleSoundEvent event)
Checks whether a NewGRF wants to play a different vehicle sound effect.
Transfer all cargo onto the platform.
Definition: order_type.h:55
NewGRF handling of airport tiles.
#define return_cmd_error(errcode)
Returns from a function with a specific StringID as error.
Definition: command_func.h:33
StationID next_hop
Next hop the cargo should be assigned to.
Definition: economy.cpp:1388
Base class for all pools.
Definition: pool_type.hpp:82
Station list; Window numbers:
Definition: window_type.h:295
static T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition: math_func.hpp:137
static bool HasSignals(TileIndex t)
Checks if a rail tile has signals.
Definition: rail_map.h:72
OrderUnloadFlags GetUnloadType() const
How must the consist be unloaded?
Definition: order_base.h:129
Struct about subsidies, offered and awarded.
Definition: subsidy_base.h:22
&#39;Train&#39; is either a loco or a wagon.
Definition: train.h:85
Performance detail window; Window numbers:
Definition: window_type.h:564
void UpdateFillingPercent(TextEffectID te_id, uint8 percent, StringID string)
Update vehicle loading indicators.
Definition: misc_gui.cpp:639
Month _cur_month
Current month (0..11)
Definition: date.cpp:25
static TrackBits GetTrackBits(TileIndex tile)
Gets the track bits of the given tile.
Definition: rail_map.h:136
#define INSTANTIATE_POOL_METHODS(name)
Force instantiation of pool methods so we don&#39;t get linker errors.
Definition: pool_func.hpp:224
Owner share_owners[4]
Owners of the 4 shares of the company. INVALID_OWNER if nobody has bought them yet.
Definition: company_base.h:76
CargoTypes & refit_mask
Bitmask of possible refit cargoes.
Definition: economy.cpp:1358
static void TriggerIndustryProduction(Industry *i)
Inform the industry about just delivered cargo DeliverGoodsToIndustry() silently incremented incoming...
Definition: economy.cpp:1124
execute the given command
Definition: command_type.h:344
Company infrastructure overview; Window numbers:
Definition: window_type.h:570
static bool CleaningPool()
Returns current state of pool cleaning - yes or no.
Definition: pool_type.hpp:270
Set when a vehicle ever delivered cargo to the station for final delivery.
Definition: station_base.h:193
static uint GetLoadAmount(Vehicle *v)
Gets the amount of cargo the given vehicle can load in the current tick.
Definition: economy.cpp:1277
Price Bases.
Functions related to companies.
void TriggerIndustry(Industry *ind, IndustryTileTrigger trigger)
Trigger a random trigger for all industry tiles.
TileIndex LoadedAtXY() const
Gets the coordinates of the cargo&#39;s last loading station.
Definition: cargopacket.h:176
static StationID GetStationIndex(TileIndex t)
Get StationID from a tile.
Definition: station_map.h:28
void SetCargo(CargoID ct)
Sets the currently handled cargo type.
Definition: economy_base.h:47
uint16 GetTimetabledWait() const
Get the time in ticks a vehicle should wait at the destination or 0 if it&#39;s not timetabled.
Definition: order_base.h:179
An invalid company.
Definition: company_type.h:30
No track.
Definition: track_type.h:39
static uint MapSize()
Get the size of the map.
Definition: map_func.h:92
TownEffect town_effect
The effect that delivering this cargo type has on towns. Also affects destination of subsidies...
Definition: cargotype.h:66
void ErrorUnknownCallbackResult(uint32 grfid, uint16 cbid, uint16 cb_res)
Record that a NewGRF returned an unknown/invalid callback result.
Class for storing amounts of cargo.
Definition: cargo_type.h:81
Determine the amount of cargo to load per unit of time when using gradual loading.
Used for iterations.
Definition: road_type.h:23
Base class for engines.
static const uint MAX_HISTORY_QUARTERS
The maximum number of quarters kept as performance&#39;s history.
Definition: company_type.h:42
Header file for NewGRF stations.
static void CompanyCheckBankrupt(Company *c)
Check for bankruptcy of a company.
Definition: economy.cpp:549
RailType
Enumeration for all possible railtypes.
Definition: rail_type.h:27
static T ClrBit(T &x, const uint8 y)
Clears a bit in a variable.
void CompaniesMonthlyLoop()
Monthly update of the economic data (of the companies as well as economic fluctuations).
Definition: economy.cpp:1948
uint16 produced_cargo_waiting[INDUSTRY_NUM_OUTPUTS]
amount of cargo produced per cargo
Definition: industry.h:45
GUISettings gui
settings related to the GUI
const GRFFile * GetGRF() const
Retrieve the NewGRF the engine is tied to.
Definition: engine_base.h:138
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
Definition: pool_type.hpp:340
Subsidy base class.
static Track RemoveFirstTrack(TrackBits *tracks)
Removes first Track from TrackBits and returns it.
Definition: track_func.h:139
void RecomputePrices()
Computes all prices, payments and maximum loan.
Definition: economy.cpp:746
Whenever cargo payment is made for a vehicle.
Definition: newgrf_sound.h:27
static Money StationMaintenanceCost(uint32 num)
Calculates the maintenance cost of a number of station tiles.
Definition: station_func.h:65
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo ID.
Definition: cargotype.h:117
Action to check if a vehicle has no stored cargo.
Definition: economy.cpp:1339
bool gradual_loading
load vehicles gradually
static SmallIndustryList _cargo_delivery_destinations
The industries we&#39;ve currently brought cargo to.
Definition: economy.cpp:1007
Ships list; Window numbers:
Definition: window_type.h:313
uint32 TileIndex
The index/ID of a Tile.
Definition: tile_type.h:78
Functions related to objects.
uint DistanceManhattan(TileIndex t0, TileIndex t1)
Gets the Manhattan distance between the two given tiles.
Definition: map.cpp:157
Cargo support for NewGRFs.
uint16 servint_trains
service interval for trains
static const uint64 MAX_INFLATION
Maximum inflation (including fractional part) without causing overflows in int64 price computations...
Definition: economy_type.h:199
Vehicle * Next() const
Get the next vehicle of this vehicle.
Definition: vehicle_base.h:579
sell a share from a company
Definition: command_type.h:257
The company went belly-up.
Definition: company_type.h:58
bool include(std::vector< T > &vec, const T &item)
Helper function to append an item to a vector if it is not already contained Consider using std::set...
CargoPayment * cargo_payment
The cargo payment we&#39;re currently in.
Definition: vehicle_base.h:241
static bool IsLevelCrossingTile(TileIndex t)
Return whether a tile is a level crossing tile.
Definition: road_map.h:94
OrderSettings order
settings related to orders
CargoArray delivered_cargo
The amount of delivered cargo.
Definition: company_base.h:24
Track
These are used to specify a single track.
Definition: track_type.h:19
int UpdateCompanyRatingAndValue(Company *c, bool update)
if update is set to true, the economy is updated with this score (also the house is updated...
Definition: economy.cpp:149
uint16 SourceID
Contains either industry ID, town ID or company ID (or INVALID_SOURCE)
Definition: cargo_type.h:152
Property costs.
Definition: economy_type.h:155
Cargo transport monitoring declarations.
bool servint_ispercent
service intervals are in percents
void AddCargoDelivery(CargoID cargo_type, CompanyID company, uint32 amount, SourceType src_type, SourceID src, const Station *st, IndustryID dest)
Cargo was delivered to its final destination, update the pickup and delivery maps.
StationIDStack GetNextStoppingStation() const
Get the next station the vehicle will stop at.
Definition: vehicle_base.h:697
UnitID NextID()
Returns next free UnitID.
Definition: vehicle.cpp:1711
TileIndex xy
Base tile of the station.
Trigger platform when train loads/unloads.
static void UpdateAutoreplace(CompanyID company)
Update autoreplace_defined and autoreplace_finished of all statistics of a company.
Definition: group_cmd.cpp:204
void RebuildSubsidisedSourceAndDestinationCache()
Perform a full rebuild of the subsidies cache.
Definition: subsidy.cpp:131
static uint GB(const T x, const uint8 s, const uint8 n)
Fetch n bits from x, started at bit s.
uint16 cached_total_length
Length of the whole vehicle (valid only for the first engine).
Trains list; Window numbers:
Definition: window_type.h:301
CompanyEconomyEntry old_economy[MAX_HISTORY_QUARTERS]
Economic data of the company of the last MAX_HISTORY_QUARTERS quarters.
Definition: company_base.h:97
Full load all cargoes of the consist.
Definition: order_type.h:64
VehicleType type
Type of vehicle.
Definition: vehicle_type.h:52
void SubtractMoneyFromCompany(CommandCost cost)
Subtract money from the _current_company, if the company is valid.
void ResetPriceBaseMultipliers()
Reset changes to the price base multipliers.
Definition: economy.cpp:871
A tile of a station.
Definition: tile_type.h:46
Goal base class.
PrepareRefitAction(CargoArray &consist_capleft, CargoTypes &refit_mask)
Create a refit preparation action.
Definition: economy.cpp:1365
Maximum number of companies.
Definition: company_type.h:23
call production callback when cargo arrives at the industry
Town data structure.
Definition: town.h:53
uint32 industry_daily_change_counter
Bits 31-16 are number of industry to be performed, 15-0 are fractional collected daily.
Definition: economy_type.h:25
int16 fluct
Economy fluctuation status.
Definition: economy_type.h:21
uint8 loading_indicators
show loading indicators
uint64 inflation_payment
Cumulated inflation of cargo paypent since game start; 16 bit fractional part.
Definition: economy_type.h:28
uint16 servint_aircraft
service interval for aircraft
Group data.
Definition: group.h:65
uint8 exclusive_counter
months till the exclusivity expires
Definition: town.h:74
Totally no unloading will be done.
Definition: order_type.h:56
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function() ...
Definition: pool_type.hpp:261
static Money CanalMaintenanceCost(uint32 num)
Calculates the maintenance cost of a number of canal tiles.
Definition: water.h:51
Aircraft list; Window numbers:
Definition: window_type.h:319
int32 z_pos
z coordinate.
Definition: vehicle_base.h:268
Vehicle details; Window numbers:
Definition: window_type.h:193
static uint CountBits(T value)
Counts the number of set bits in a variable.
Base functions for all Games.
Functions related to commands.
Network functions used by other parts of OpenTTD.
bool _network_server
network-server is active
Definition: network.cpp:53
CargoPaymentPool _cargo_payment_pool("CargoPayment")
The actual pool to store cargo payments in.
uint8 CalcPercentVehicleFilled(const Vehicle *front, StringID *colour)
Calculates how full a vehicle is.
Definition: vehicle.cpp:1377
bool HasCargoFor(StationIDStack next) const
Check for cargo headed for a specific station.
Definition: cargopacket.h:484
CompanyID _current_company
Company currently doing an action.
Definition: company_cmd.cpp:45
Owner owner
The owner of this station.
static void CountEngine(const Vehicle *v, int delta)
Update num_engines when adding/removing an engine.
Definition: group_cmd.cpp:156
Base classes related to the economy.
uint ReservedCount() const
Returns sum of reserved cargo.
Definition: cargopacket.h:369
static WindowClass GetWindowClassForVehicleType(VehicleType vt)
Get WindowClass for vehicle list of given vehicle type.
Definition: vehicle_gui.h:91
void StartupIndustryDailyChanges(bool init_counter)
Initialize the variables that will maintain the daily industry change system.
Definition: economy.cpp:893
uint16 GetVehicleCallback(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v)
Evaluate a newgrf callback for vehicles.
StoryPage base class.
Delivered cargo graph; Window numbers:
Definition: window_type.h:534
ScoreID
Score categories in the detailed performance rating.
Definition: economy_type.h:36
void ChangeWindowOwner(Owner old_owner, Owner new_owner)
Change the owner of all the windows one company can take over from another company in the case of a c...
Definition: window.cpp:1223
Base of all industries.
Aircraft vehicle type.
Definition: vehicle_type.h:27
bool economy
how volatile is the economy
Definition: settings_type.h:66
void ShowFeederIncomeAnimation(int x, int y, int z, Money transfer, Money income)
Display animated feeder income.
Definition: misc_gui.cpp:597
Price is affected by "vehicle running cost" difficulty setting.
Definition: economy_type.h:174
Statistics about the economy.
Definition: company_base.h:21
EngineID engine_type
The type of engine used for this vehicle.
Definition: vehicle_base.h:286
Used for iterations.
Definition: rail_type.h:33
Passengers.
Definition: cargotype.h:39
int32 x_pos
x coordinate.
Definition: vehicle_base.h:266
byte initial_interest
amount of interest (to pay over the loan)
Definition: settings_type.h:58
uint16 vehicle_flags
Used for gradual loading and other miscellaneous things (.
Definition: base_consist.h:30
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
bool IsValid() const
Tests for validity of this cargospec.
Definition: cargotype.h:98
Functions related to NewGRF provided sounds.
void Restore()
Restore the variable.
Base functions for all AIs.
void AddNewsItem(StringID string, NewsType type, NewsFlag flags, NewsReferenceType reftype1=NR_NONE, uint32 ref1=UINT32_MAX, NewsReferenceType reftype2=NR_NONE, uint32 ref2=UINT32_MAX, void *free_data=nullptr)
Add a new newsitem to be shown.
Definition: news_gui.cpp:745
Base of the town class.
Data structure for storing how the score is computed for a single score id.
Definition: economy_type.h:56
bool AddInflation(bool check_year)
Add monthly inflation.
Definition: economy.cpp:708
int needed
How much you need to get the perfect score.
Definition: economy_type.h:57
GameCreationSettings game_creation
settings used during the creation of a game (map)
uint AvailableCount() const
Returns sum of cargo still available for loading at the sation.
Definition: cargopacket.h:507
uint16 servint_roadveh
service interval for road vehicles
byte CargoID
Cargo slots to indicate a cargo type within a game.
Definition: cargo_type.h:20
Money income
The amount of income.
Definition: company_base.h:22
int32 y_pos
y coordinate.
Definition: vehicle_base.h:267
static void CompaniesPayInterest()
Let all companies pay the monthly interest on their loan.
Definition: economy.cpp:814
Money company_value
The value of the company.
Definition: company_base.h:26
byte time_since_pickup
Number of rating-intervals (up to 255) since the last vehicle tried to load this cargo.
Definition: station_base.h:233
Functions related to water (management)
void ShowCostOrIncomeAnimation(int x, int y, int z, Money cost)
Display animated income or costs on the map.
Definition: misc_gui.cpp:576
Force unloading all cargo onto the platform, possibly not getting paid.
Definition: order_type.h:54
Money profit_this_year
Profit this year << 8, low 8 bits are fract.
Definition: vehicle_base.h:237
CompanyEconomyEntry cur_economy
Economic data of the company of this quarter.
Definition: company_base.h:96
Use the new capacity algorithm. The default cargotype of the vehicle does not affect capacity multipl...
Definition: engine_type.h:159
static Money RailMaintenanceCost(RailType railtype, uint32 num, uint32 total_num)
Calculates the maintenance cost of a number of track bits.
Definition: rail.h:427
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
Definition: window.cpp:3243
Trigger station when cargo is completely taken.
Functions related to news.
Base classes/functions for stations.
call production callback every 256 ticks
CargoArray & consist_capleft
Capacities left in the consist.
Definition: economy.cpp:1357
VehicleCache vcache
Cache of often used vehicle values.
Definition: vehicle_base.h:328
static Station * Get(size_t index)
Gets station with given index.
Date _date
Current date in days (day counter)
Definition: date.cpp:26
static uint DeliverGoodsToIndustry(const Station *st, CargoID cargo_type, uint num_pieces, IndustryID source, CompanyID company)
Transfer goods from station to industry.
Definition: economy.cpp:1019
Functions related to autoreplacing.
StationID current_station
The current station.
Definition: economy_base.h:32
Company view; Window numbers:
Definition: window_type.h:362
CompanyID exclusivity
which company has exclusivity
Definition: town.h:73
static void HandleStationRefit(Vehicle *v, CargoArray &consist_capleft, Station *st, StationIDStack next_station, CargoID new_cid)
Refit a vehicle in a station.
Definition: economy.cpp:1454
uint GetPlatformLength(TileIndex tile, DiagDirection dir) const override
Determines the REMAINING length of a platform, starting at (and including) the given tile...
Definition: station.cpp:267
byte construction_cost
how expensive is building
Definition: settings_type.h:63
Full load a single cargo of the consist.
Definition: order_type.h:65
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Definition: company_cmd.cpp:44
uint8 feeder_payment_share
percentage of leg payment to virtually pay in feeder systems
static bool IsCompanyBuildableVehicleType(VehicleType type)
Is the given vehicle type buildable by a company?
Definition: vehicle_func.h:89
Year starting_year
starting date
Base class and functions for all vehicles that move through ground.
Class for backupping variables and making sure they are restored later.
Station data structure.
Definition: station_base.h:450
char other_company_name[64]
The name of the company taking over this one.
Definition: news_type.h:151
Functions related to subsidies.
Road vehicle type.
Definition: vehicle_type.h:25
Set when the station accepts the cargo currently for final deliveries.
Definition: station_base.h:177
Used for iterations.
Definition: rail_type.h:28
Order current_order
The current order (+ status, like: loading)
Definition: vehicle_base.h:316
bool do_reserve
If the vehicle should reserve.
Definition: economy.cpp:1417
const T GetSum() const
Get the sum of all cargo amounts.
Definition: cargo_type.h:121
Performance history graph; Window numbers:
Definition: window_type.h:540
void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
Mark window data of the window of a given class and specific window number as invalid (in need of re-...
Definition: window.cpp:3316
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition: gfx.cpp:1462
CargoID GetRefitCargo() const
Get the cargo to to refit to.
Definition: order_base.h:122
Source/destination is an industry.
Definition: cargo_type.h:147
bool operator()(Vehicle *v)
Return all reserved cargo from a vehicle.
Definition: economy.cpp:1402
Economic changes (recession, industry up/dowm)
Definition: news_type.h:28
Dynamic data of a loaded NewGRF.
Definition: newgrf.h:105
Base class for signs.
static void SetDParam(uint n, uint64 v)
Set a string parameter v at index n in the global string parameter array.
Definition: strings_func.h:199
CargoTypes always_accepted
Bitmask of always accepted cargo types (by houses, HQs, industry tiles when industry doesn&#39;t accept c...
Definition: station_base.h:480
Money visual_transfer
The transfer credits to be shown.
Definition: economy_base.h:28