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