OpenTTD Source 20261129-master-g72a8bdc861
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 <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "stdafx.h"
11#include <ranges>
12#include "company_base.h"
13#include "company_func.h"
14#include "command_func.h"
15#include "industry.h"
16#include "town.h"
17#include "news_func.h"
18#include "network/network.h"
20#include "ai/ai.hpp"
21#include "aircraft.h"
22#include "train.h"
23#include "newgrf_engine.h"
24#include "engine_base.h"
25#include "ground_vehicle.hpp"
26#include "newgrf_cargo.h"
27#include "newgrf_sound.h"
29#include "newgrf_station.h"
30#include "newgrf_airporttiles.h"
31#include "newgrf_roadstop.h"
32#include "object.h"
33#include "strings_func.h"
34#include "vehicle_func.h"
35#include "sound_func.h"
36#include "autoreplace_func.h"
37#include "company_gui.h"
38#include "signs_base.h"
39#include "subsidy_base.h"
40#include "subsidy_func.h"
41#include "station_base.h"
42#include "station_func.h"
43#include "vehicle_gui.h"
44#include "waypoint_base.h"
45#include "economy_base.h"
46#include "core/pool_func.hpp"
47#include "core/backup_type.hpp"
49#include "cargo_type.h"
50#include "water.h"
51#include "game/game.hpp"
52#include "cargomonitor.h"
53#include "goal_base.h"
54#include "story_base.h"
55#include "linkgraph/refresh.h"
56#include "company_cmd.h"
57#include "economy_cmd.h"
58#include "vehicle_cmd.h"
59#include "script/api/script_event_types.hpp"
60#include "timer/timer.h"
63
64#include "table/strings.h"
65#include "table/pricebase.h"
66
67#include "safeguards.h"
68
69
70/* Initialize the cargo payment-pool */
73
74typedef std::vector<Industry *> SmallIndustryList;
75
80 ScoreInfo(100, 120), // ScoreID::Vehicles
81 ScoreInfo(100, 80), // ScoreID::Stations
82 ScoreInfo(100, 10000), // ScoreID::MinProfit
83 ScoreInfo(50, 50000), // ScoreID::MinIncome
84 ScoreInfo(100, 100000), // ScoreID::MaxIncome
85 ScoreInfo(400, 40000), // ScoreID::Delivered
86 ScoreInfo(50, 8), // ScoreID::Cargo
87 ScoreInfo(50, 10000000), // ScoreID::Money
88 ScoreInfo(50, 250000), // ScoreID::Loan
89 ScoreInfo(0, 0), // ScoreID::Total
90};
91
93Economy _economy;
95static PriceMultipliers _price_base_multiplier;
96
104{
105 Owner owner = c->index;
106
107 uint num = 0;
108
109 for (const Station *st : Station::Iterate()) {
110 if (st->owner == owner) num += st->facilities.Count();
111 }
112
113 Money value = num * _price[Price::StationValue] * 25;
114
115 for (const Vehicle *v : Vehicle::Iterate()) {
116 if (v->owner != owner) continue;
117
118 if (v->type == VehicleType::Train ||
119 v->type == VehicleType::Road ||
120 (v->type == VehicleType::Aircraft && Aircraft::From(v)->IsNormalAircraft()) ||
121 v->type == VehicleType::Ship) {
122 value += v->value * 3 >> 1;
123 }
124 }
125
126 return value;
127}
128
138Money CalculateCompanyValue(const Company *c, bool including_loan)
139{
140 Money value = CalculateCompanyAssetValue(c);
141
142 /* Add real money value */
143 if (including_loan) value -= c->current_loan;
144 value += c->money;
145
146 return std::max<Money>(value, 1);
147}
148
166{
167 Money value = CalculateCompanyAssetValue(c);
168
169 value += c->current_loan;
170 /* Negative balance is basically a loan. */
171 if (c->money < 0) {
172 value += -c->money;
173 }
174
175 for (int quarter = 0; quarter < 4; quarter++) {
176 value += std::max<Money>(c->old_economy[quarter].income + c->old_economy[quarter].expenses, 0) * 2;
177 }
178
179 return std::max<Money>(value, 1);
180}
181
191{
192 Owner owner = c->index;
193 int score = 0;
194
195 _score_part[owner].fill(0);
196
197 /* Count vehicles */
198 {
199 Money min_profit = 0;
200 bool min_profit_first = true;
201 uint num = 0;
202
203 for (const Vehicle *v : Vehicle::Iterate()) {
204 if (v->owner != owner) continue;
205 if (IsCompanyBuildableVehicleType(v->type) && v->IsPrimaryVehicle()) {
206 if (v->profit_last_year > 0) num++; // For the vehicle score only count profitable vehicles
207 if (v->economy_age > VEHICLE_PROFIT_MIN_AGE) {
208 /* Find the vehicle with the lowest amount of profit */
209 if (min_profit_first || min_profit > v->profit_last_year) {
210 min_profit = v->profit_last_year;
211 min_profit_first = false;
212 }
213 }
214 }
215 }
216
217 min_profit >>= 8; // remove the fract part
218
219 _score_part[owner][ScoreID::Vehicles] = num;
220 /* Don't allow negative min_profit to show */
221 if (min_profit > 0) {
222 _score_part[owner][ScoreID::MinProfit] = min_profit;
223 }
224 }
225
226 /* Count stations */
227 {
228 uint num = 0;
229 for (const Station *st : Station::Iterate()) {
230 /* Only count stations that are actually serviced */
231 if (st->owner == owner && (st->time_since_load <= 20 || st->time_since_unload <= 20)) num += st->facilities.Count();
232 }
233 _score_part[owner][ScoreID::Stations] = num;
234 }
235
236 /* Generate statistics depending on recent income statistics */
237 {
238 int numec = std::min<uint>(c->num_valid_stat_ent, 12u);
239 if (numec != 0) {
240 auto [min_income, max_income] = std::ranges::minmax(c->old_economy | std::views::take(numec) | std::views::transform([](const auto &ce) { return ce.income + ce.expenses; }));
241
242 if (min_income > 0) _score_part[owner][ScoreID::MinIncome] = min_income;
243 _score_part[owner][ScoreID::MaxIncome] = max_income;
244 }
245 }
246
247 /* Generate score depending on amount of transported cargo */
248 {
249 int numec = std::min<uint>(c->num_valid_stat_ent, 4u);
250 if (numec != 0) {
251 OverflowSafeInt64 total_delivered = 0;
252 for (auto &ce : c->old_economy | std::views::take(numec)) total_delivered += ce.delivered_cargo.GetSum<OverflowSafeInt64>();
253
254 _score_part[owner][ScoreID::Delivered] = total_delivered;
255 }
256 }
257
258 /* Generate score for variety of cargo */
259 {
260 _score_part[owner][ScoreID::Cargo] = c->old_economy[0].delivered_cargo.GetCount();
261 }
262
263 /* Generate score for company's money */
264 {
265 if (c->money > 0) {
266 _score_part[owner][ScoreID::Money] = c->money;
267 }
268 }
269
270 /* Generate score for loan */
271 {
272 _score_part[owner][ScoreID::Loan] = _score_info[ScoreID::Loan].needed - c->current_loan;
273 }
274
275 /* Now we calculate the score for each item.. */
276 {
277 int total_score = 0;
278 int s;
279 score = 0;
280 for (ScoreID i : EnumRange(ScoreID::End)) {
281 /* Skip the total */
282 if (i == ScoreID::Total) continue;
283 /* Check the score */
284 s = Clamp<int64_t>(_score_part[owner][i], 0, _score_info[i].needed) * _score_info[i].score / _score_info[i].needed;
285 score += s;
286 total_score += _score_info[i].score;
287 }
288
289 _score_part[owner][ScoreID::Total] = score;
290
291 /* We always want the score scaled to SCORE_MAX (1000) */
292 if (total_score != SCORE_MAX) score = score * SCORE_MAX / total_score;
293 }
294
295 if (update) {
296 c->old_economy[0].performance_history = score;
298 c->old_economy[0].company_value = CalculateCompanyValue(c);
299 }
300
301 SetWindowDirty(WindowClass::PerformanceDetail, 0);
302 return score;
303}
304
310void ChangeOwnershipOfCompanyItems(Owner old_owner, Owner new_owner)
311{
312 /* We need to set _current_company to old_owner before we try to move
313 * the client. This is needed as it needs to know whether "you" really
314 * are the current local company. */
315 AutoRestoreBackup cur_company(_current_company, old_owner);
316 /* In all cases, make spectators of clients connected to that company */
318 if (old_owner == _local_company) {
319 /* Single player cheated to AI company.
320 * There are no spectators in singleplayer mode, so we must pick some other company. */
321 assert(!_networking);
323 for (const Company *c : Company::Iterate()) {
324 if (c->index != old_owner) {
325 SetLocalCompany(c->index);
326 break;
327 }
328 }
329 cur_company2.Restore();
330 assert(old_owner != _local_company);
331 }
332
333 assert(old_owner != new_owner);
334
335 /* Temporarily increase the company's money, to be sure that
336 * removing their property doesn't fail because of lack of money.
337 * Not too drastically though, because it could overflow */
338 if (new_owner == INVALID_OWNER) {
339 Company::Get(old_owner)->money = INT64_MAX / 2; // jackpot ;p
340 }
341
342 for (Subsidy *s : Subsidy::Iterate()) {
343 if (s->awarded == old_owner) {
344 if (new_owner == INVALID_OWNER) {
345 delete s;
346 } else {
347 s->awarded = new_owner;
348 }
349 }
350 }
352
353 /* Take care of rating and transport rights in towns */
354 for (Town *t : Town::Iterate()) {
355 /* If a company takes over, give the ratings to that company. */
356 if (new_owner != INVALID_OWNER) {
357 if (t->have_ratings.Test(old_owner)) {
358 if (t->have_ratings.Test(new_owner)) {
359 /* use max of the two ratings. */
360 t->ratings[new_owner] = std::max(t->ratings[new_owner], t->ratings[old_owner]);
361 } else {
362 t->have_ratings.Set(new_owner);
363 t->ratings[new_owner] = t->ratings[old_owner];
364 }
365 }
366 t->unwanted[new_owner] = std::max(t->unwanted[old_owner], t->unwanted[new_owner]);
367 }
368
369 /* Reset the ratings for the old owner */
370 t->ratings[old_owner] = RATING_INITIAL;
371 t->have_ratings.Reset(old_owner);
372 t->unwanted[old_owner] = 0;
373
374 /* Transfer exclusive rights */
375 if (t->exclusive_counter > 0 && t->exclusivity == old_owner) {
376 if (new_owner != INVALID_OWNER) {
377 t->exclusivity = new_owner;
378 } else {
379 t->exclusive_counter = 0;
380 t->exclusivity = CompanyID::Invalid();
381 }
382 }
383 }
384
385 {
386 for (Vehicle *v : Vehicle::Iterate()) {
387 if (v->owner == old_owner && IsCompanyBuildableVehicleType(v->type)) {
388 if (new_owner == INVALID_OWNER) {
389 if (v->Previous() == nullptr) delete v;
390 } else {
391 if (v->IsEngineCountable()) GroupStatistics::CountEngine(v, -1);
392 if (v->IsPrimaryVehicle()) GroupStatistics::CountVehicle(v, -1);
393 }
394 }
395 }
396 }
397
398 /* In all cases clear replace engine rules.
399 * Even if it was copied, it could interfere with new owner's rules */
401
402 if (new_owner == INVALID_OWNER) {
403 RemoveAllGroupsForCompany(old_owner);
404 } else {
405 Company *c = Company::Get(new_owner);
406 for (Group *g : Group::Iterate()) {
407 if (g->owner == old_owner) {
408 g->owner = new_owner;
409 g->number = c->freegroups.UseID(c->freegroups.NextID());
410 }
411 }
412 }
413
414 {
415 Company *new_company = new_owner == INVALID_OWNER ? nullptr : Company::Get(new_owner);
416
417 /* Override company settings to new company defaults in case we need to convert them.
418 * This is required as the CmdChangeServiceInt doesn't copy the supplied value when it is non-custom
419 */
420 if (new_owner != INVALID_OWNER) {
421 Company *old_company = Company::Get(old_owner);
422
424 old_company->settings.vehicle.servint_trains = new_company->settings.vehicle.servint_trains;
426 old_company->settings.vehicle.servint_ships = new_company->settings.vehicle.servint_ships;
428 }
429
430 for (Vehicle *v : Vehicle::Iterate()) {
431 if (v->owner == old_owner && IsCompanyBuildableVehicleType(v->type)) {
432 assert(new_owner != INVALID_OWNER);
433
434 /* Correct default values of interval settings while maintaining custom set ones.
435 * This prevents invalid values on mismatching company defaults being accepted.
436 */
437 if (!v->ServiceIntervalIsCustom()) {
438 /* Technically, passing the interval is not needed as the command will query the default value itself.
439 * However, do not rely on that behaviour.
440 */
441 int interval = CompanyServiceInterval(new_company, v->type);
442 Command<Commands::ChangeServiceInterval>::Do({DoCommandFlag::Execute, DoCommandFlag::Bankrupt}, v->index, interval, false, new_company->settings.vehicle.servint_ispercent);
443 }
444
445 v->owner = new_owner;
446
447 /* Owner changes, clear cache */
448 v->colourmap = PAL_NONE;
449 v->InvalidateNewGRFCache();
450
451 if (v->IsEngineCountable()) {
453 }
454 if (v->IsPrimaryVehicle()) {
456 auto &unitidgen = new_company->freeunits[v->type];
457 v->unitnumber = unitidgen.UseID(unitidgen.NextID());
458 }
459 }
460 }
461
462 if (new_owner != INVALID_OWNER) GroupStatistics::UpdateAutoreplace(new_owner);
463 }
464
465 /* Change ownership of tiles */
466 {
467 for (const auto tile : Map::Iterate()) {
468 ChangeTileOwner(tile, old_owner, new_owner);
469 }
470
471 if (new_owner != INVALID_OWNER) {
472 /* Update all signals because there can be new segment that was owned by two companies
473 * and signals were not propagated
474 * Similar with crossings - it is needed to bar crossings that weren't before
475 * because of different owner of crossing and approaching train */
476 for (const auto tile : Map::Iterate()) {
477 if (IsTileType(tile, TileType::Railway) && IsTileOwner(tile, new_owner) && HasSignals(tile)) {
478 for (Track track : GetTrackBits(tile)) {
479 if (IsSignalPresent(tile, SignalOnTrack(track))) AddTrackToSignalBuffer(tile, track, new_owner);
480 }
481 } else if (IsLevelCrossingTile(tile) && IsTileOwner(tile, new_owner)) {
483 }
484 }
485 }
486
487 /* update signals in buffer */
489 }
490
491 /* Add airport infrastructure count of the old company to the new one. */
492 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.airport += Company::Get(old_owner)->infrastructure.airport;
493
494 /* convert owner of stations (including deleted ones, but excluding buoys) */
495 for (Station *st : Station::Iterate()) {
496 if (st->owner == old_owner) {
497 /* if a company goes bankrupt, set owner to OWNER_NONE so the sign doesn't disappear immediately
498 * also, drawing station window would cause reading invalid company's colour */
499 st->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner;
500 }
501 }
502
503 /* do the same for waypoints (we need to do this here so deleted waypoints are converted too) */
504 for (Waypoint *wp : Waypoint::Iterate()) {
505 if (wp->owner == old_owner) {
506 wp->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner;
507 }
508 }
509
510 for (Sign *si : Sign::Iterate()) {
511 if (si->owner == old_owner) si->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner;
512 }
513
514 /* Remove Game Script created Goals, CargoMonitors and Story pages. */
515 for (Goal *g : Goal::Iterate()) {
516 if (g->company == old_owner) delete g;
517 }
518
521
522 for (StoryPage *sp : StoryPage::Iterate()) {
523 if (sp->company == old_owner) delete sp;
524 }
525
526 /* Change colour of existing windows */
527 if (new_owner != INVALID_OWNER) ChangeWindowOwner(old_owner, new_owner);
528
530}
531
537{
538 /* If "Infinite money" setting is on, companies should not go bankrupt. */
539 if (_settings_game.difficulty.infinite_money) return;
540
541 /* If the company has money again, it does not go bankrupt */
542 if (c->money - c->current_loan >= -c->GetMaxLoan()) {
543 int previous_months_of_bankruptcy = CeilDiv(c->months_of_bankruptcy, 3);
546 if (previous_months_of_bankruptcy != 0) CompanyAdminUpdate(c);
547 return;
548 }
549
551
552 switch (c->months_of_bankruptcy) {
553 /* All the boring cases (months) with a bad balance where no action is taken */
554 case 0:
555 case 1:
556 case 2:
557 case 3:
558
559 case 5:
560 case 6:
561
562 case 8:
563 case 9:
564 break;
565
566 /* Warn about bankruptcy after 3 months */
567 case 4: {
568 auto cni = std::make_unique<CompanyNewsInformation>(STR_NEWS_COMPANY_IN_TROUBLE_TITLE, c);
569 EncodedString headline = GetEncodedString(STR_NEWS_COMPANY_IN_TROUBLE_DESCRIPTION, cni->company_name);
570 AddCompanyNewsItem(std::move(headline), std::move(cni));
571 AI::BroadcastNewEvent(new ScriptEventCompanyInTrouble(c->index));
572 Game::NewEvent(new ScriptEventCompanyInTrouble(c->index));
573 break;
574 }
575
576 /* Offer company for sale after 6 months */
577 case 7: {
578 /* Don't consider the loan */
579 Money val = CalculateCompanyValue(c, false);
580
581 c->bankrupt_value = val;
582 c->bankrupt_asked = CompanyMask{}.Set(c->index); // Don't ask the owner
583 c->bankrupt_timeout = 0;
584
585 /* The company assets should always have some value */
586 assert(c->bankrupt_value > 0);
587 break;
588 }
589
590 /* Bankrupt company after 6 months (if the company has no value) or latest
591 * after 9 months (if it still had value after 6 months) */
592 default:
593 case 10: {
594 if (!_networking && _local_company == c->index) {
595 /* If we are in singleplayer mode, leave the company playing. Eg. there
596 * is no THE-END, otherwise mark the client as spectator to make sure
597 * they are no longer in control of this company. However... when you
598 * join another company (cheat) the "unowned" company can bankrupt. */
599 c->bankrupt_asked.Set();
600 break;
601 }
602
603 /* Actually remove the company, but not when we're a network client.
604 * In case of network clients we will be getting a command from the
605 * server. It is done in this way as we are called from the
606 * StateGameLoop which can't change the current company, and thus
607 * updating the local company triggers an assert later on. In the
608 * case of a network game the command will be processed at a time
609 * that changing the current company is okay. In case of single
610 * player we are sure (the above check) that we are not the local
611 * company and thus we won't be moved. */
613 Command<Commands::CompanyControl>::Post(CompanyCtrlAction::Delete, c->index, CompanyRemoveReason::Bankrupt, ClientID::Invalid);
614 return;
615 }
616 break;
617 }
618 }
619
621}
622
628{
629 /* Check for bankruptcy each month */
630 for (Company *c : Company::Iterate()) {
632 }
633
634 /* Pay Infrastructure Maintenance, if enabled */
635 if (_settings_game.economy.infrastructure_maintenance) {
636 /* Improved monthly infrastructure costs. */
637 for (const Company *c : Company::Iterate()) {
639 uint32_t rail_total = c->infrastructure.GetRailTotal();
640 for (RailType rt : EnumRange(RAILTYPE_END)) {
641 if (c->infrastructure.rail[rt] != 0) cost.AddCost(RailMaintenanceCost(rt, c->infrastructure.rail[rt], rail_total));
642 }
643 cost.AddCost(SignalMaintenanceCost(c->infrastructure.signal));
644 uint32_t road_total = c->infrastructure.GetRoadTotal();
645 uint32_t tram_total = c->infrastructure.GetTramTotal();
646 for (RoadType rt : EnumRange(ROADTYPE_END)) {
647 if (c->infrastructure.road[rt] != 0) cost.AddCost(RoadMaintenanceCost(rt, c->infrastructure.road[rt], RoadTypeIsRoad(rt) ? road_total : tram_total));
648 }
649 cost.AddCost(CanalMaintenanceCost(c->infrastructure.water));
650 cost.AddCost(StationMaintenanceCost(c->infrastructure.station));
651 cost.AddCost(AirportMaintenanceCost(c->index));
652
653 SubtractMoneyFromCompany(c->index, cost);
654 }
655 }
656
657 /* Only run the economic statistics and update company stats every 3rd economy month (1st of quarter). */
658 if (!HasBit(1 << 0 | 1 << 3 | 1 << 6 | 1 << 9, TimerGameEconomy::month)) return;
659
660 for (Company *c : Company::Iterate()) {
661 /* Drop the oldest history off the end */
662 std::copy_backward(c->old_economy.data(), c->old_economy.data() + MAX_HISTORY_QUARTERS - 1, c->old_economy.data() + MAX_HISTORY_QUARTERS);
663 c->old_economy[0] = c->cur_economy;
664 c->cur_economy = {};
665
666 if (c->num_valid_stat_ent != MAX_HISTORY_QUARTERS) c->num_valid_stat_ent++;
667
669 if (c->block_preview != 0) c->block_preview--;
670 }
671
672 SetWindowDirty(WindowClass::IncomeGraph, 0);
673 SetWindowDirty(WindowClass::OperatingProfitGraph, 0);
674 SetWindowDirty(WindowClass::DeliveredCargoGraph, 0);
675 SetWindowDirty(WindowClass::PerformanceGraph, 0);
676 SetWindowDirty(WindowClass::CompanyValueGraph, 0);
677 SetWindowDirty(WindowClass::CompanyLeague, 0);
678}
679
685bool AddInflation(bool check_year)
686{
687 /* The cargo payment inflation differs from the normal inflation, so the
688 * relative amount of money you make with a transport decreases slowly over
689 * the 170 years. After a few hundred years we reach a level in which the
690 * games will become unplayable as the maximum income will be less than
691 * the minimum running cost.
692 *
693 * Furthermore there are a lot of inflation related overflows all over the
694 * place. Solving them is hardly possible because inflation will always
695 * reach the overflow threshold some day. So we'll just perform the
696 * inflation mechanism during the first 170 years (the amount of years that
697 * one had in the original TTD) and stop doing the inflation after that
698 * because it only causes problems that can't be solved nicely and the
699 * inflation doesn't add anything after that either; it even makes playing
700 * it impossible due to the diverging cost and income rates.
701 */
703
704 if (_economy.inflation_prices == MAX_INFLATION || _economy.inflation_payment == MAX_INFLATION) return true;
705
706 /* Approximation for (100 + infl_amount)% ** (1 / 12) - 100%
707 * scaled by 65536
708 * 12 -> months per year
709 * This is only a good approximation for small values
710 */
711 _economy.inflation_prices += (_economy.inflation_prices * _economy.infl_amount * 54) >> 16;
712 _economy.inflation_payment += (_economy.inflation_payment * _economy.infl_amount_pr * 54) >> 16;
713
714 if (_economy.inflation_prices > MAX_INFLATION) _economy.inflation_prices = MAX_INFLATION;
715 if (_economy.inflation_payment > MAX_INFLATION) _economy.inflation_payment = MAX_INFLATION;
716
717 return false;
718}
719
724{
725 /* Setup maximum loan as a rounded down multiple of LOAN_INTERVAL. */
726 _economy.max_loan = ClampTo<int64_t>(((uint64_t)_settings_game.difficulty.max_loan * _economy.inflation_prices >> 16) / LOAN_INTERVAL * LOAN_INTERVAL);
727
728 /* Setup price bases */
729 for (Price i : EnumRange(Price::End)) {
730 Money price = _price_base_specs[i].start_price;
731
732 /* Apply difficulty settings */
733 uint mod = 1;
734 switch (_price_base_specs[i].category) {
736 mod = _settings_game.difficulty.vehicle_costs;
737 break;
738
740 mod = _settings_game.difficulty.construction_cost;
741 break;
742
743 default: break;
744 }
745 switch (mod) {
746 case 0: price *= 6; break;
747 case 1: price *= 8; break; // normalised to 1 below
748 case 2: price *= 9; break;
749 default: NOT_REACHED();
750 }
751
752 /* Apply inflation */
753 price *= ClampTo<int64_t>(_economy.inflation_prices);
754
755 /* Apply newgrf modifiers, remove fractional part of inflation, and normalise on medium difficulty. */
756 int shift = _price_base_multiplier[i] - 16 - 3;
757 if (shift >= 0) {
758 price <<= shift;
759 } else {
760 price >>= -shift;
761 }
762
763 /* Make sure the price does not get reduced to zero.
764 * Zero breaks quite a few commands that use a zero
765 * cost to see whether something got changed or not
766 * and based on that cause an error. When the price
767 * is zero that fails even when things are done. */
768 if (price == 0) {
769 price = Clamp(_price_base_specs[i].start_price, -1, 1);
770 /* No base price should be zero, but be sure. */
771 assert(price != 0);
772 }
773 /* Store value */
774 _price[i] = price;
775 }
776
777 /* Setup cargo payment */
778 for (CargoSpec *cs : CargoSpec::Iterate()) {
779 cs->current_payment = (cs->initial_payment * (int64_t)_economy.inflation_payment) >> 16;
780 }
781
782 SetWindowClassesDirty(WindowClass::BuildVehicle);
783 SetWindowClassesDirty(WindowClass::ReplaceVehicle);
784 SetWindowClassesDirty(WindowClass::VehicleDetails);
785 SetWindowClassesDirty(WindowClass::CompanyInfrastructure);
786 InvalidateWindowData(WindowClass::CargoPaymentRatesGraph, 0);
787}
788
791{
792 for (const Company *c : Company::Iterate()) {
793 /* Over a year the paid interest should be "loan * interest percentage",
794 * but... as that number is likely not dividable by 12 (pay each month),
795 * one needs to account for that in the monthly fee calculations.
796 *
797 * To easily calculate what one should pay "this" month, you calculate
798 * what (total) should have been paid up to this month and you subtract
799 * whatever has been paid in the previous months. This will mean one month
800 * it'll be a bit more and the other it'll be a bit less than the average
801 * monthly fee, but on average it will be exact.
802 *
803 * In order to prevent cheating or abuse (just not paying interest by not
804 * taking a loan) we make companies pay interest on negative cash as well,
805 * except if infinite money is enabled.
806 */
807 Money yearly_fee = c->current_loan * _economy.interest_rate / 100;
808 Money available_money = GetAvailableMoney(c->index);
809 if (available_money < 0) {
810 yearly_fee += -available_money * _economy.interest_rate / 100;
811 }
812 Money up_to_previous_month = yearly_fee * TimerGameEconomy::month / 12;
813 Money up_to_this_month = yearly_fee * (TimerGameEconomy::month + 1) / 12;
814
815 SubtractMoneyFromCompany(c->index, CommandCost(ExpensesType::LoanInterest, up_to_this_month - up_to_previous_month));
816
818 }
819}
820
821static void HandleEconomyFluctuations()
822{
823 if (_settings_game.difficulty.economy != 0) {
824 /* When economy is Fluctuating, decrease counter */
825 _economy.fluct--;
826 } else if (EconomyIsInRecession()) {
827 /* When it's Steady and we are in recession, end it now */
828 _economy.fluct = -12;
829 } else {
830 /* No need to do anything else in other cases */
831 return;
832 }
833
834 if (_economy.fluct == 0) {
835 _economy.fluct = -(int)GB(Random(), 0, 2);
836 AddNewsItem(GetEncodedString(STR_NEWS_BEGIN_OF_RECESSION), NewsType::Economy, NewsStyle::Normal, {});
837 } else if (_economy.fluct == -12) {
838 _economy.fluct = GB(Random(), 0, 8) + 312;
839 AddNewsItem(GetEncodedString(STR_NEWS_END_OF_RECESSION), NewsType::Economy, NewsStyle::Normal, {});
840 }
841}
842
843
848{
849 _price_base_multiplier.fill(0);
850}
851
859void SetPriceBaseMultiplier(Price price, int factor)
860{
861 assert(price < Price::End);
862 _price_base_multiplier[price] = Clamp(factor, MIN_PRICE_MODIFIER, MAX_PRICE_MODIFIER);
863}
864
869void StartupIndustryDailyChanges(bool init_counter)
870{
871 uint map_size = Map::LogX() + Map::LogY();
872 /* After getting map size, it needs to be scaled appropriately and divided by 31,
873 * which stands for the days in a month.
874 * Using just 31 will make it so that a monthly reset (based on the real number of days of that month)
875 * would not be needed.
876 * Since it is based on "fractional parts", the leftover days will not make much of a difference
877 * on the overall total number of changes performed */
878 _economy.industry_daily_increment = (1 << map_size) / 31;
879
880 if (init_counter) {
881 /* A new game or a savegame from an older version will require the counter to be initialized */
882 _economy.industry_daily_change_counter = 0;
883 }
884}
885
886void StartupEconomy()
887{
888 _economy.interest_rate = _settings_game.difficulty.initial_interest;
889 _economy.infl_amount = _settings_game.difficulty.initial_interest;
890 _economy.infl_amount_pr = std::max(0, _settings_game.difficulty.initial_interest - 1);
891 _economy.fluct = GB(Random(), 0, 8) + 168;
892
893 if (_settings_game.economy.inflation) {
894 /* Apply inflation that happened before our game start year. */
896 for (int i = 0; i < months; i++) {
897 AddInflation(false);
898 }
899 }
900
901 /* Set up prices */
903
904 StartupIndustryDailyChanges(true); // As we are starting a new game, initialize the counter too
905
906}
907
912{
913 _economy.inflation_prices = _economy.inflation_payment = 1 << 16;
916}
917
926Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift)
927{
928 if (index >= Price::End) return 0;
929
930 Money cost = _price[index] * cost_factor;
931 if (grf_file != nullptr) shift += grf_file->price_base_multipliers[index];
932
933 if (shift >= 0) {
934 cost <<= shift;
935 } else {
936 cost >>= -shift;
937 }
938
939 return cost;
940}
941
942Money GetTransportedGoodsIncome(uint num_pieces, uint dist, uint16_t transit_periods, CargoType cargo_type)
943{
944 const CargoSpec *cs = CargoSpec::Get(cargo_type);
945 if (!cs->IsValid()) {
946 /* User changed newgrfs and some vehicle still carries some cargo which is no longer available. */
947 return 0;
948 }
949
950 /* Scale transit periods according to the game setting. We also pass this scaled value to the NewGRF callback. */
951 transit_periods = ScaleByPercentage<uint16_t, uint32_t>(transit_periods, _settings_game.economy.cargo_aging_rate);
952
953 /* Use callback to calculate cargo profit, if available */
955 uint32_t var18 = ClampTo<uint16_t>(dist) | (ClampTo<uint8_t>(num_pieces) << 16) | (ClampTo<uint8_t>(transit_periods) << 24);
956 uint16_t callback = GetCargoCallback(CBID_CARGO_PROFIT_CALC, 0, var18, cs);
957 if (callback != CALLBACK_FAILED) {
958 int result = GB(callback, 0, 14);
959
960 /* Simulate a 15 bit signed value */
961 if (HasBit(callback, 14)) result -= 0x4000;
962
963 /* "The result should be a signed multiplier that gets multiplied
964 * by the amount of cargo moved and the price factor, then gets
965 * divided by 8192." */
966 return result * num_pieces * cs->current_payment / 8192;
967 }
968 }
969
970 static const int MIN_TIME_FACTOR = 31;
971 static const int MAX_TIME_FACTOR = 255;
972 static const int TIME_FACTOR_FRAC_BITS = 4;
973 static const int TIME_FACTOR_FRAC = 1 << TIME_FACTOR_FRAC_BITS;
974
975 const int periods1 = cs->transit_periods[0];
976 const int periods2 = cs->transit_periods[1];
977 const int periods_over_periods1 = std::max(transit_periods - periods1, 0);
978 const int periods_over_periods2 = std::max(periods_over_periods1 - periods2, 0);
979 int periods_over_max = MIN_TIME_FACTOR - MAX_TIME_FACTOR;
980 if (periods2 > -periods_over_max) {
981 periods_over_max += transit_periods - periods1;
982 } else {
983 periods_over_max += 2 * (transit_periods - periods1) - periods2;
984 }
985
986 /*
987 * The time factor is calculated based on the time it took
988 * (transit_periods) compared two cargo-depending values. The
989 * range is divided into four parts:
990 *
991 * - constant for fast transits
992 * - linear decreasing with time with a slope of -1 for medium transports
993 * - linear decreasing with time with a slope of -2 for slow transports
994 * - after hitting MIN_TIME_FACTOR, the time factor will be asymptotically decreased to a limit of 1 with a scaled 1/(x+1) function.
995 *
996 */
997 if (periods_over_max > 0) {
998 const int time_factor = std::max(2 * MIN_TIME_FACTOR * TIME_FACTOR_FRAC * TIME_FACTOR_FRAC / (periods_over_max + 2 * TIME_FACTOR_FRAC), 1); // MIN_TIME_FACTOR / (x/(2 * TIME_FACTOR_FRAC) + 1) + 1, expressed as fixed point with TIME_FACTOR_FRAC_BITS.
999 return (cs->current_payment * dist * time_factor * num_pieces) >> (21 + TIME_FACTOR_FRAC_BITS);
1000 } else {
1001 const int time_factor = std::max(MAX_TIME_FACTOR - periods_over_periods1 - periods_over_periods2, MIN_TIME_FACTOR);
1002 return (cs->current_payment * dist * time_factor * num_pieces) >> 21;
1003 }
1004}
1005
1007static SmallIndustryList _cargo_delivery_destinations;
1008
1019static uint DeliverGoodsToIndustry(const Station *st, CargoType cargo_type, uint num_pieces, IndustryID source, CompanyID company)
1020{
1021 /* Find the nearest industrytile to the station sign inside the catchment area, whose industry accepts the cargo.
1022 * This fails in three cases:
1023 * 1) The station accepts the cargo because there are enough houses around it accepting the cargo.
1024 * 2) The industries in the catchment area temporarily reject the cargo, and the daily station loop has not yet updated station acceptance.
1025 * 3) The results of callbacks CBID_INDUSTRY_REFUSE_CARGO and CBID_INDTILE_CARGO_ACCEPTANCE are inconsistent. (documented behaviour)
1026 */
1027
1028 uint accepted = 0;
1029
1030 for (const auto &i : st->industries_near) {
1031 if (num_pieces == 0) break;
1032
1033 Industry *ind = i.industry;
1034 if (ind->index == source) continue;
1035
1036 auto it = ind->GetCargoAccepted(cargo_type);
1037 /* Check if matching cargo has been found */
1038 if (it == std::end(ind->accepted)) continue;
1039
1040 /* Check if industry temporarily refuses acceptance */
1041 if (IndustryTemporarilyRefusesCargo(ind, cargo_type)) continue;
1042
1043 if (ind->exclusive_supplier != INVALID_OWNER && ind->exclusive_supplier != st->owner) continue;
1044
1045 /* Insert the industry into _cargo_delivery_destinations, if not yet contained */
1047
1048 uint amount = std::min(num_pieces, 0xFFFFu - it->waiting);
1049 it->waiting += amount;
1050 it->GetOrCreateHistory()[THIS_MONTH].accepted += amount;
1051 it->last_accepted = TimerGameEconomy::date;
1052 num_pieces -= amount;
1053 accepted += amount;
1054
1055 /* Update the cargo monitor. */
1056 AddCargoDelivery(cargo_type, company, amount, {source, SourceType::Industry}, st, ind->index);
1057 }
1058
1059 return accepted;
1060}
1061
1074static Money DeliverGoods(int num_pieces, CargoType cargo_type, StationID dest, uint distance, uint16_t periods_in_transit, Company *company, Source src)
1075{
1076 assert(num_pieces > 0);
1077
1078 Station *st = Station::Get(dest);
1079
1080 /* Give the goods to the industry. */
1081 uint accepted_ind = DeliverGoodsToIndustry(st, cargo_type, num_pieces, src.type == SourceType::Industry ? src.ToIndustryID() : IndustryID::Invalid(), company->index);
1082
1083 /* If this cargo type is always accepted, accept all */
1084 uint accepted_total = st->always_accepted.Test(cargo_type) ? num_pieces : accepted_ind;
1085
1086 /* Update station statistics */
1087 if (accepted_total > 0) {
1089 st->goods[cargo_type].GetOrCreateHistory().accepted += accepted_total;
1090
1091 /* Update company statistics */
1092 company->cur_economy.delivered_cargo[cargo_type] += accepted_total;
1093
1094 /* Increase town's counter for town effects */
1095 const CargoSpec *cs = CargoSpec::Get(cargo_type);
1096 st->town->received[cs->town_acceptance_effect].new_act += accepted_total;
1097 if (accepted_total - accepted_ind > 0) {
1098 /* Cargo not delivered to an industry must go to the town. */
1099 st->town->GetOrCreateCargoAccepted(cargo_type).history[THIS_MONTH].accepted += accepted_total - accepted_ind;
1100 }
1101 }
1102
1103 /* Determine profit */
1104 Money profit = GetTransportedGoodsIncome(accepted_total, distance, periods_in_transit, cargo_type);
1105
1106 /* Update the cargo monitor. Only count the amount not accepted by an industry, as DeliverGoodsToIndustry will
1107 * have updated the cargo monitor for that already. */
1108 AddCargoDelivery(cargo_type, company->index, accepted_total - accepted_ind, src, st);
1109
1110 /* Modify profit if a subsidy is in effect */
1111 if (CheckSubsidised(cargo_type, company->index, src, st)) {
1112 switch (_settings_game.difficulty.subsidy_multiplier) {
1113 case 0: profit += profit >> 1; break;
1114 case 1: profit *= 2; break;
1115 case 2: profit *= 3; break;
1116 default: profit *= 4; break;
1117 }
1118 }
1119
1120 return profit;
1121}
1122
1129{
1130 const IndustrySpec *indspec = GetIndustrySpec(i->type);
1131 IndustryCallbackMasks cbm = indspec->callback_mask;
1132
1133 i->was_cargo_delivered = true;
1134
1138 } else {
1139 SetWindowDirty(WindowClass::IndustryView, i->index);
1140 }
1141 } else {
1142 for (auto ita = std::begin(i->accepted); ita != std::end(i->accepted); ++ita) {
1143 if (ita->waiting == 0 || !IsValidCargoType(ita->cargo)) continue;
1144
1145 for (auto itp = std::begin(i->produced); itp != std::end(i->produced); ++itp) {
1146 if (!IsValidCargoType(itp->cargo)) continue;
1147 itp->waiting = ClampTo<uint16_t>(itp->waiting + (ita->waiting * indspec->input_cargo_multiplier[ita - std::begin(i->accepted)][itp - std::begin(i->produced)] / 256));
1148 }
1149
1150 ita->waiting = 0;
1151 }
1152 }
1153
1155 TriggerIndustryAnimation(i, IndustryAnimationTrigger::CargoReceived);
1156}
1157
1163CargoPayment::CargoPayment(CargoPaymentID index, Vehicle *front) :
1165 current_station(front->last_station_visited),
1166 front(front)
1167{
1168}
1169
1172{
1173 if (CleaningPool()) return;
1174
1175 this->front->cargo_payment = nullptr;
1176
1177 if (this->visual_profit == 0 && this->visual_transfer == 0) return;
1178
1179 AutoRestoreBackup cur_company(_current_company, this->front->owner);
1180
1181 SubtractMoneyFromCompany(_current_company, CommandCost(this->front->GetExpenseType(true), -this->route_profit));
1182 this->front->profit_this_year += (this->visual_profit + this->visual_transfer) << 8;
1183
1184 const Vehicle *moving_front = this->front->GetMovingFront();
1186 SndPlayVehicleFx(SND_14_CASHTILL, this->front);
1187 }
1188
1189 if (this->visual_transfer != 0) {
1190 ShowFeederIncomeAnimation(moving_front->x_pos, moving_front->y_pos,
1191 moving_front->z_pos, this->visual_transfer, -this->visual_profit);
1192 } else {
1193 ShowCostOrIncomeAnimation(moving_front->x_pos, moving_front->y_pos,
1194 moving_front->z_pos, -this->visual_profit);
1195 }
1196}
1197
1205void CargoPayment::PayFinalDelivery(CargoType cargo, const CargoPacket *cp, uint count, TileIndex current_tile)
1206{
1207 /* Handle end of route payment */
1208 Money profit = DeliverGoods(count, cargo, this->current_station, cp->GetDistance(current_tile), cp->GetPeriodsInTransit(), Company::Get(this->front->owner), cp->GetSource());
1209 this->route_profit += profit;
1210
1211 /* The vehicle's profit is whatever route profit there is minus feeder shares. */
1212 this->visual_profit += profit - cp->GetFeederShare(count);
1213}
1214
1223Money CargoPayment::PayTransfer(CargoType cargo, const CargoPacket *cp, uint count, TileIndex current_tile)
1224{
1225 /* Pay transfer vehicle the difference between the payment for the journey from
1226 * the source to the current point, and the sum of the previous transfer payments */
1227 Money profit = -cp->GetFeederShare(count) + GetTransportedGoodsIncome(
1228 count,
1229 cp->GetDistance(current_tile),
1230 cp->GetPeriodsInTransit(),
1231 cargo);
1232
1233 profit = profit * _settings_game.economy.feeder_payment_share / 100;
1234
1235 this->visual_transfer += profit; // accumulate transfer profits for whole vehicle
1236 return profit; // account for the (virtual) profit already made for the cargo packet
1237}
1238
1244{
1245 Station *curr_station = Station::Get(front_v->last_station_visited);
1246 curr_station->loading_vehicles.push_back(front_v);
1247
1248 /* At this moment loading cannot be finished */
1250
1251 /* Start unloading at the first possible moment */
1252 front_v->load_unload_ticks = 1;
1253
1254 assert(front_v->cargo_payment == nullptr);
1255 /* One CargoPayment per vehicle and the vehicle limit equals the
1256 * limit in number of CargoPayments. Can't go wrong. */
1259 front_v->cargo_payment = CargoPayment::Create(front_v);
1260
1261 std::vector<StationID> next_station;
1262 front_v->GetNextStoppingStation(next_station);
1263 if (front_v->orders == nullptr || front_v->current_order.GetUnloadType() != OrderUnloadType::NoUnload) {
1265 for (Vehicle *v = front_v; v != nullptr; v = v->Next()) {
1266 const GoodsEntry *ge = &st->goods[v->cargo_type];
1267 if (v->cargo_cap > 0 && v->cargo.TotalCount() > 0) {
1268 v->cargo.Stage(
1270 front_v->last_station_visited, next_station,
1271 front_v->current_order.GetUnloadType(), ge,
1272 v->cargo_type, front_v->cargo_payment,
1273 v->GetMovingFront()->GetCargoTile());
1274 if (v->cargo.UnloadCount() > 0) v->vehicle_flags.Set(VehicleFlag::CargoUnloading);
1275 }
1276 }
1277 }
1278}
1279
1286static uint GetLoadAmount(Vehicle *v)
1287{
1288 const Engine *e = v->GetEngine();
1289 uint load_amount = e->info.load_amount;
1290
1291 /* The default loadamount for mail is 1/4 of the load amount for passengers */
1292 bool air_mail = v->type == VehicleType::Aircraft && !Aircraft::From(v)->IsNormalAircraft();
1293 if (air_mail) load_amount = CeilDiv(load_amount, 4);
1294
1295 if (_settings_game.order.gradual_loading) {
1296 uint16_t cb_load_amount = CALLBACK_FAILED;
1297 if (e->GetGRF() != nullptr && e->GetGRF()->grf_version >= 8) {
1298 /* Use callback 36 */
1299 cb_load_amount = GetVehicleProperty(v, PROP_VEHICLE_LOAD_AMOUNT, CALLBACK_FAILED);
1301 /* Use callback 12 */
1302 cb_load_amount = GetVehicleCallback(CBID_VEHICLE_LOAD_AMOUNT, 0, 0, v->engine_type, v);
1303 }
1304 if (cb_load_amount != CALLBACK_FAILED) {
1305 if (e->GetGRF()->grf_version < 8) cb_load_amount = GB(cb_load_amount, 0, 8);
1306 if (cb_load_amount >= 0x100) {
1308 } else if (cb_load_amount != 0) {
1309 load_amount = cb_load_amount;
1310 }
1311 }
1312 }
1313
1314 /* Scale load amount the same as capacity */
1315 if (e->info.misc_flags.Test(EngineMiscFlag::NoDefaultCargoMultiplier) && !air_mail) load_amount = CeilDiv(load_amount * CargoSpec::Get(v->cargo_type)->multiplier, 0x100);
1316
1317 /* Zero load amount breaks a lot of things. */
1318 return std::max(1u, load_amount);
1319}
1320
1330template <class Taction>
1331bool IterateVehicleParts(Vehicle *v, Taction action)
1332{
1333 for (Vehicle *w = v; w != nullptr;
1334 w = w->HasArticulatedPart() ? w->GetNextArticulatedPart() : nullptr) {
1335 if (!action(w)) return false;
1336 if (w->type == VehicleType::Train) {
1337 Train *train = Train::From(w);
1338 if (train->IsMultiheaded() && !action(train->other_multiheaded_part)) return false;
1339 }
1340 }
1341 if (v->type == VehicleType::Aircraft && Aircraft::From(v)->IsNormalAircraft()) return action(v->Next());
1342 return true;
1343}
1344
1349{
1355 bool operator()(const Vehicle *v)
1356 {
1357 return v->cargo.StoredCount() == 0;
1358 }
1359};
1360
1365{
1368
1376
1383 bool operator()(const Vehicle *v)
1384 {
1385 this->consist_capleft[v->cargo_type] -= v->cargo_cap - v->cargo.ReservedCount();
1386 this->refit_mask.Set(EngInfo(v->engine_type)->refit_mask);
1387 return true;
1388 }
1389};
1390
1395{
1397 StationID next_hop;
1398
1404 ReturnCargoAction(Station *st, StationID next_one) : st(st), next_hop(next_one) {}
1405
1412 {
1413 v->cargo.Return(UINT_MAX, &this->st->goods[v->cargo_type].GetOrCreateData().cargo, this->next_hop, v->GetCargoTile());
1414 return true;
1415 }
1416};
1417
1422{
1425 std::span<const StationID> next_station;
1427
1437
1445 {
1446 if (this->do_reserve) {
1447 this->st->goods[v->cargo_type].GetOrCreateData().cargo.Reserve(v->cargo_cap - v->cargo.RemainingCount(),
1448 &v->cargo, this->next_station, v->GetCargoTile());
1449 }
1450 this->consist_capleft[v->cargo_type] += v->cargo_cap - v->cargo.RemainingCount();
1451 return true;
1452 }
1453};
1454
1463static void HandleStationRefit(Vehicle *v, CargoArray &consist_capleft, Station *st, std::span<const StationID> next_station, CargoType new_cargo_type)
1464{
1465 Vehicle *v_start = v->GetFirstEnginePart();
1466 if (!IterateVehicleParts(v_start, IsEmptyAction())) return;
1467
1468 AutoRestoreBackup cur_company(_current_company, v->owner);
1469
1470 CargoTypes refit_mask = v->GetEngine()->info.refit_mask;
1471
1472 /* Remove old capacity from consist capacity and collect refit mask. */
1473 IterateVehicleParts(v_start, PrepareRefitAction(consist_capleft, refit_mask));
1474
1475 bool is_auto_refit = new_cargo_type == CARGO_AUTO_REFIT;
1476 if (is_auto_refit) {
1477 /* Get a refittable cargo type with waiting cargo for next_station or StationID::Invalid(). */
1478 new_cargo_type = v_start->cargo_type;
1479 for (CargoType cargo_type : refit_mask) {
1480 if (st->goods[cargo_type].HasData() && st->goods[cargo_type].GetData().cargo.HasCargoFor(next_station)) {
1481 /* Try to find out if auto-refitting would succeed. In case the refit is allowed,
1482 * the returned refit capacity will be greater than zero. */
1483 auto [cc, refit_capacity, mail_capacity, cargo_capacities] = Command<Commands::RefitVehicle>::Do(DoCommandFlag::QueryCost, v_start->index, cargo_type, 0xFF, true, false, 1); // Auto-refit and only this vehicle including artic parts.
1484 /* Try to balance different loadable cargoes between parts of the consist, so that
1485 * all of them can be loaded. Avoid a situation where all vehicles suddenly switch
1486 * to the first loadable cargo for which there is only one packet. If the capacities
1487 * are equal refit to the cargo of which most is available. This is important for
1488 * consists of only a single vehicle as those will generally have a consist_capleft
1489 * of 0 for all cargoes. */
1490 if (refit_capacity > 0 && (consist_capleft[cargo_type] < consist_capleft[new_cargo_type] ||
1491 (consist_capleft[cargo_type] == consist_capleft[new_cargo_type] &&
1492 st->goods[cargo_type].AvailableCount() > st->goods[new_cargo_type].AvailableCount()))) {
1493 new_cargo_type = cargo_type;
1494 }
1495 }
1496 }
1497 }
1498
1499 /* Refit if given a valid cargo. */
1500 if (new_cargo_type < NUM_CARGO && new_cargo_type != v_start->cargo_type) {
1501 /* StationID::Invalid() because in the DistributionType::Manual case that's correct and in the DT_(A)SYMMETRIC
1502 * cases the next hop of the vehicle doesn't really tell us anything if the cargo had been
1503 * "via any station" before reserving. We rather produce some more "any station" cargo than
1504 * misrouting it. */
1505 IterateVehicleParts(v_start, ReturnCargoAction(st, StationID::Invalid()));
1506 CommandCost cost = ExtractCommandCost(Command<Commands::RefitVehicle>::Do(DoCommandFlag::Execute, v_start->index, new_cargo_type, 0xFF, true, false, 1)); // Auto-refit and only this vehicle including artic parts.
1507 if (cost.Succeeded()) v->First()->profit_this_year -= cost.GetCost() << 8;
1508 }
1509
1510 /* Add new capacity to consist capacity and reserve cargo */
1511 IterateVehicleParts(v_start, FinalizeRefitAction(consist_capleft, st, next_station,
1512 is_auto_refit || v->First()->current_order.IsFullLoadOrder()));
1513}
1514
1521static bool MayLoadUnderExclusiveRights(const Station *st, const Vehicle *v)
1522{
1523 return st->owner != OWNER_NONE || st->town->exclusive_counter == 0 || st->town->exclusivity == v->owner;
1524}
1525
1526struct ReserveCargoAction {
1527 Station *st;
1528 std::span<const StationID> next_station;
1529
1530 ReserveCargoAction(Station *st, std::span<const StationID> next_station) :
1531 st(st), next_station(next_station) {}
1532
1533 bool operator()(Vehicle *v)
1534 {
1536 st->goods[v->cargo_type].GetOrCreateData().cargo.Reserve(v->cargo_cap - v->cargo.RemainingCount(),
1537 &v->cargo, next_station, v->GetCargoTile());
1538 }
1539
1540 return true;
1541 }
1542
1543};
1544
1553static void ReserveConsist(Station *st, Vehicle *u, CargoArray *consist_capleft, std::span<const StationID> next_station)
1554{
1555 /* If there is a cargo payment not all vehicles of the consist have tried to do the refit.
1556 * In that case, only reserve if it's a fixed refit and the equivalent of "articulated chain"
1557 * a vehicle belongs to already has the right cargo. */
1558 bool must_reserve = !u->current_order.IsRefit() || u->cargo_payment == nullptr;
1559 for (Vehicle *v = u; v != nullptr; v = v->Next()) {
1560 assert(v->cargo_cap >= v->cargo.RemainingCount());
1561
1562 /* Exclude various ways in which the vehicle might not be the head of an equivalent of
1563 * "articulated chain". Also don't do the reservation if the vehicle is going to refit
1564 * to a different cargo and hasn't tried to do so, yet. */
1565 if (!v->IsArticulatedPart() &&
1566 (v->type != VehicleType::Train || !Train::From(v)->IsRearDualheaded()) &&
1567 (v->type != VehicleType::Aircraft || Aircraft::From(v)->IsNormalAircraft()) &&
1568 (must_reserve || u->current_order.GetRefitCargo() == v->cargo_type)) {
1569 IterateVehicleParts(v, ReserveCargoAction(st, next_station));
1570 }
1571 if (consist_capleft == nullptr || v->cargo_cap == 0) continue;
1572 (*consist_capleft)[v->cargo_type] += v->cargo_cap - v->cargo.RemainingCount();
1573 }
1574}
1575
1583static void UpdateLoadUnloadTicks(Vehicle *front, const Station *st, int ticks)
1584{
1585 if (front->type == VehicleType::Train && _settings_game.order.station_length_loading_penalty) {
1586 /* Each platform tile is worth 2 rail vehicles. */
1587 int overhang = front->GetGroundVehicleCache()->cached_total_length - st->GetPlatformLength(front->GetMovingFront()->tile) * TILE_SIZE;
1588 if (overhang > 0) {
1589 ticks <<= 1;
1590 ticks += (overhang * ticks) / 8;
1591 }
1592 }
1593 /* Always wait at least 1, otherwise we'll wait 'infinitively' long. */
1594 front->load_unload_ticks = std::max(1, ticks);
1595}
1596
1601static void LoadUnloadVehicle(Vehicle *front)
1602{
1603 assert(front->current_order.IsType(OT_LOADING));
1604
1605 StationID last_visited = front->last_station_visited;
1606 Station *st = Station::Get(last_visited);
1607
1608 std::vector<StationID> next_station;
1609 front->GetNextStoppingStation(next_station);
1610 bool use_autorefit = front->current_order.IsRefit() && front->current_order.GetRefitCargo() == CARGO_AUTO_REFIT;
1611 CargoArray consist_capleft{};
1612 if (_settings_game.order.improved_load && use_autorefit ?
1613 front->cargo_payment == nullptr : (front->current_order.IsFullLoadOrder())) {
1614 ReserveConsist(st, front,
1615 (use_autorefit && front->load_unload_ticks != 0) ? &consist_capleft : nullptr,
1616 next_station);
1617 }
1618
1619 /* We have not waited enough time till the next round of loading/unloading */
1620 if (front->load_unload_ticks != 0) return;
1621
1622 const Vehicle *moving_front = front->GetMovingFront();
1623 if (front->type == VehicleType::Train && (!IsTileType(moving_front->tile, TileType::Station) || GetStationIndex(moving_front->tile) != st->index)) {
1624 /* The train reversed in the station. Take the "easy" way
1625 * out and let the train just leave as it always did. */
1627 front->load_unload_ticks = 1;
1628 return;
1629 }
1630
1631 int new_load_unload_ticks = 0;
1632 bool dirty_vehicle = false;
1633 bool dirty_station = false;
1634
1635 bool completely_emptied = true;
1636 bool anything_unloaded = false;
1637 bool anything_loaded = false;
1638 CargoTypes full_load_amount{};
1639 CargoTypes cargo_not_full{};
1640 CargoTypes cargo_full{};
1641 CargoTypes reservation_left{};
1642
1643 front->cur_speed = 0;
1644
1645 CargoPayment *payment = front->cargo_payment;
1646
1647 uint artic_part = 0; // Articulated part we are currently trying to load. (not counting parts without capacity)
1648 for (Vehicle *v = front; v != nullptr; v = v->Next()) {
1649 if (v == front || !v->Previous()->HasArticulatedPart()) artic_part = 0;
1650 if (v->cargo_cap == 0) continue;
1651 artic_part++;
1652
1653 GoodsEntry *ge = &st->goods[v->cargo_type];
1654
1655 if (v->vehicle_flags.Test(VehicleFlag::CargoUnloading) && front->current_order.GetUnloadType() != OrderUnloadType::NoUnload) {
1656 uint cargo_count = v->cargo.UnloadCount();
1657 uint amount_unloaded = _settings_game.order.gradual_loading ? std::min(cargo_count, GetLoadAmount(v)) : cargo_count;
1658 bool remaining = false; // Are there cargo entities in this vehicle that can still be unloaded here?
1659
1660 if (!ge->status.Test(GoodsEntry::State::Acceptance) && v->cargo.ActionCount(VehicleCargoList::MoveToAction::Deliver) > 0) {
1661 /* The station does not accept our goods anymore. */
1663 /* Transfer instead of delivering. */
1664 v->cargo.Reassign<VehicleCargoList::MoveToAction::Deliver, VehicleCargoList::MoveToAction::Transfer>(
1665 v->cargo.ActionCount(VehicleCargoList::MoveToAction::Deliver));
1666 } else {
1667 uint new_remaining = v->cargo.RemainingCount() + v->cargo.ActionCount(VehicleCargoList::MoveToAction::Deliver);
1668 if (v->cargo_cap < new_remaining) {
1669 /* Return some of the reserved cargo to not overload the vehicle. */
1670 v->cargo.Return(new_remaining - v->cargo_cap, &ge->GetOrCreateData().cargo, StationID::Invalid(), v->GetCargoTile());
1671 }
1672
1673 /* Keep instead of delivering. This may lead to no cargo being unloaded, so ...*/
1674 v->cargo.Reassign<VehicleCargoList::MoveToAction::Deliver, VehicleCargoList::MoveToAction::Keep>(
1675 v->cargo.ActionCount(VehicleCargoList::MoveToAction::Deliver));
1676
1677 /* ... say we unloaded something, otherwise we'll think we didn't unload
1678 * something and we didn't load something, so we must be finished
1679 * at this station. Setting the unloaded means that we will get a
1680 * retry for loading in the next cycle. */
1681 anything_unloaded = true;
1682 }
1683 }
1684
1685 if (v->cargo.ActionCount(VehicleCargoList::MoveToAction::Transfer) > 0) {
1686 /* Mark the station dirty if we transfer, but not if we only deliver. */
1687 dirty_station = true;
1688
1689 if (!ge->HasRating()) {
1690 /* Upon transferring cargo, make sure the station has a rating. Fake a pickup for the
1691 * first unload to prevent the cargo from quickly decaying after the initial drop. */
1692 ge->time_since_pickup = 0;
1694 }
1695 }
1696
1697 assert(payment != nullptr);
1698 amount_unloaded = v->cargo.Unload(amount_unloaded, &ge->GetOrCreateData().cargo, v->cargo_type, payment, v->GetCargoTile());
1699 remaining = v->cargo.UnloadCount() > 0;
1700 if (amount_unloaded > 0) {
1701 dirty_vehicle = true;
1702 anything_unloaded = true;
1703 new_load_unload_ticks += amount_unloaded;
1704
1705 /* Deliver goods to the station */
1706 st->time_since_unload = 0;
1707 }
1708
1709 if (_settings_game.order.gradual_loading && remaining) {
1710 completely_emptied = false;
1711 } else {
1712 /* We have finished unloading (cargo count == 0) */
1713 v->vehicle_flags.Reset(VehicleFlag::CargoUnloading);
1714 }
1715
1716 continue;
1717 }
1718
1719 /* Do not pick up goods when we have no-load set or loading is stopped. */
1721
1722 /* This order has a refit, if this is the first vehicle part carrying cargo and the whole vehicle is empty, try refitting. */
1723 if (front->current_order.IsRefit() && artic_part == 1) {
1724 HandleStationRefit(v, consist_capleft, st, next_station, front->current_order.GetRefitCargo());
1725 ge = &st->goods[v->cargo_type];
1726 }
1727
1728 /* As we're loading here the following link can carry the full capacity of the vehicle. */
1729 v->refit_cap = v->cargo_cap;
1730
1731 /* update stats */
1732 int t;
1733 switch (front->type) {
1734 case VehicleType::Train:
1735 case VehicleType::Ship:
1736 t = front->vcache.cached_max_speed;
1737 break;
1738
1739 case VehicleType::Road:
1740 t = front->vcache.cached_max_speed / 2;
1741 break;
1742
1744 t = Aircraft::From(front)->GetSpeedOldUnits(); // Convert to old units.
1745 break;
1746
1747 default: NOT_REACHED();
1748 }
1749
1750 /* if last speed is 0, we treat that as if no vehicle has ever visited the station. */
1753
1754 assert(v->cargo_cap >= v->cargo.StoredCount());
1755 /* Capacity available for loading more cargo. */
1756 uint cap_left = v->cargo_cap - v->cargo.StoredCount();
1757
1758 if (cap_left > 0) {
1759 /* If vehicle can load cargo, reset time_since_pickup. */
1760 ge->time_since_pickup = 0;
1761
1762 /* If there's goods waiting at the station, and the vehicle
1763 * has capacity for it, load it on the vehicle. */
1764 if ((v->cargo.ActionCount(VehicleCargoList::MoveToAction::Load) > 0 || ge->AvailableCount() > 0) && MayLoadUnderExclusiveRights(st, v)) {
1765 if (v->cargo.StoredCount() == 0) TriggerVehicleRandomisation(v, VehicleRandomTrigger::NewCargo);
1766 if (_settings_game.order.gradual_loading) cap_left = std::min(cap_left, GetLoadAmount(v));
1767
1768 uint loaded = ge->GetOrCreateData().cargo.Load(cap_left, &v->cargo, next_station, v->GetCargoTile());
1769 if (v->cargo.ActionCount(VehicleCargoList::MoveToAction::Load) > 0) {
1770 /* Remember if there are reservations left so that we don't stop
1771 * loading before they're loaded. */
1772 reservation_left.Set(v->cargo_type);
1773 }
1774
1775 /* Store whether the maximum possible load amount was loaded or not.*/
1776 if (loaded == cap_left) {
1777 full_load_amount.Set(v->cargo_type);
1778 } else {
1779 full_load_amount.Reset(v->cargo_type);
1780 }
1781
1782 /* TODO: Regarding this, when we do gradual loading, we
1783 * should first unload all vehicles and then start
1784 * loading them. Since this will cause
1785 * VEHICLE_TRIGGER_EMPTY to be called at the time when
1786 * the whole vehicle chain is really totally empty, the
1787 * completely_emptied assignment can then be safely
1788 * removed; that's how TTDPatch behaves too. --pasky */
1789 if (loaded > 0) {
1790 completely_emptied = false;
1791 anything_loaded = true;
1792
1793 st->time_since_load = 0;
1794 st->last_vehicle_type = v->type;
1795
1796 if (ge->GetData().cargo.TotalCount() == 0) {
1798 TriggerStationAnimation(st, st->xy, StationAnimationTrigger::CargoTaken, v->cargo_type);
1799 TriggerAirportAnimation(st, AirportAnimationTrigger::CargoTaken, v->cargo_type);
1801 TriggerRoadStopAnimation(st, st->xy, StationAnimationTrigger::CargoTaken, v->cargo_type);
1802 }
1803
1804 new_load_unload_ticks += loaded;
1805
1806 dirty_vehicle = dirty_station = true;
1807 }
1808 }
1809 }
1810
1811 if (v->cargo.StoredCount() >= v->cargo_cap) {
1812 cargo_full.Set(v->cargo_type);
1813 } else {
1814 cargo_not_full.Set(v->cargo_type);
1815 }
1816 }
1817
1818 if (anything_loaded || anything_unloaded) {
1819 if (front->type == VehicleType::Train) {
1821 TriggerStationAnimation(st, moving_front->tile, StationAnimationTrigger::VehicleLoads);
1822 } else if (front->type == VehicleType::Road) {
1824 TriggerRoadStopAnimation(st, front->tile, StationAnimationTrigger::VehicleLoads);
1825 }
1826 }
1827
1828 /* Only set completely_emptied, if we just unloaded all remaining cargo */
1829 completely_emptied &= anything_unloaded;
1830
1831 if (!anything_unloaded) delete payment;
1832
1834 if (anything_loaded || anything_unloaded) {
1835 if (_settings_game.order.gradual_loading) {
1836 /* The time it takes to load one 'slice' of cargo or passengers depends
1837 * on the vehicle type - the values here are those found in TTDPatch */
1838 constexpr VehicleTypeIndexArray<const uint> gradual_loading_wait_time = { 40, 20, 10, 20 };
1839
1840 new_load_unload_ticks = gradual_loading_wait_time[front->type];
1841 }
1842 /* We loaded less cargo than possible for all cargo types and it's not full
1843 * load and we're not supposed to wait any longer: stop loading. */
1844 if (!anything_unloaded && full_load_amount.None() && reservation_left.None() && !front->current_order.IsFullLoadOrder() &&
1845 front->current_order_time >= std::max(front->current_order.GetTimetabledWait() - front->lateness_counter, 0)) {
1847 }
1848
1849 UpdateLoadUnloadTicks(front, st, new_load_unload_ticks);
1850 } else {
1851 UpdateLoadUnloadTicks(front, st, 20); // We need the ticks for link refreshing.
1852 bool finished_loading = true;
1853 if (front->current_order.IsFullLoadOrder()) {
1855 /* if the aircraft carries passengers and is NOT full, then
1856 * continue loading, no matter how much mail is in */
1857 if ((front->type == VehicleType::Aircraft && IsCargoInClass(front->cargo_type, CargoClass::Passengers) && front->cargo_cap > front->cargo.StoredCount()) ||
1858 (cargo_not_full.Any() && cargo_full.Reset(cargo_not_full).None())) { // There are still non-full cargoes
1859 finished_loading = false;
1860 }
1861 } else if (cargo_not_full.Any()) {
1862 finished_loading = false;
1863 }
1864
1865 /* Refresh next hop stats if we're full loading to make the links
1866 * known to the distribution algorithm and allow cargo to be sent
1867 * along them. Otherwise the vehicle could wait for cargo
1868 * indefinitely if it hasn't visited the other links yet, or if the
1869 * links die while it's loading. */
1870 if (!finished_loading) LinkRefresher::Run(front, true, true);
1871 }
1872
1873 front->vehicle_flags.Set(VehicleFlag::LoadingFinished, finished_loading);
1874 }
1875
1876 /* Calculate the loading indicator fill percent and display
1877 * In the Game Menu do not display indicators
1878 * If _settings_client.gui.loading_indicators == 2, show indicators (bool can be promoted to int as 0 or 1 - results in 2 > 0,1 )
1879 * if _settings_client.gui.loading_indicators == 1, _local_company must be the owner or must be a spectator to show ind., so 1 > 0
1880 * if _settings_client.gui.loading_indicators == 0, do not display indicators ... 0 is never greater than anything
1881 */
1882 if (_game_mode != GameMode::Menu && (_settings_client.gui.loading_indicators > (uint)(front->owner != _local_company && _local_company != COMPANY_SPECTATOR))) {
1883 StringID percent_up_down = STR_NULL;
1884 int percent = CalcPercentVehicleFilled(front, &percent_up_down);
1885 if (front->fill_percent_te_id == INVALID_TE_ID) {
1886 front->fill_percent_te_id = ShowFillingPercent(moving_front->x_pos, moving_front->y_pos, moving_front->z_pos + 20, percent, percent_up_down);
1887 } else {
1888 UpdateFillingPercent(front->fill_percent_te_id, percent, percent_up_down);
1889 }
1890 }
1891
1892 if (completely_emptied) {
1893 /* Make sure the vehicle is marked dirty, since we need to update the NewGRF
1894 * properties such as weight, power and TE whenever the trigger runs. */
1895 dirty_vehicle = true;
1896 TriggerVehicleRandomisation(front, VehicleRandomTrigger::Empty);
1897 }
1898
1899 if (dirty_vehicle) {
1901 SetWindowDirty(WindowClass::VehicleDetails, front->index);
1902 front->MarkDirty();
1903 }
1904 if (dirty_station) {
1905 st->MarkTilesDirty(true);
1906 SetWindowDirty(WindowClass::StationView, st->index);
1907 SetWindowDirty(WindowClass::StationList, st->owner);
1908 }
1909}
1910
1917{
1918 /* No vehicle is here... */
1919 if (st->loading_vehicles.empty()) return;
1920
1921 Vehicle *last_loading = nullptr;
1922
1923 /* Check if anything will be loaded at all. Otherwise we don't need to reserve either. */
1924 for (Vehicle *v : st->loading_vehicles) {
1925 if (v->vehstatus.Any({VehState::Stopped, VehState::Crashed})) continue;
1926
1927 assert(v->load_unload_ticks != 0);
1928 if (--v->load_unload_ticks == 0) last_loading = v;
1929 }
1930
1931 /* We only need to reserve and load/unload up to the last loading vehicle.
1932 * Anything else will be forgotten anyway after returning from this function.
1933 *
1934 * Especially this means we do _not_ need to reserve cargo for a single
1935 * consist in a station which is not allowed to load yet because its
1936 * load_unload_ticks is still not 0.
1937 */
1938 if (last_loading == nullptr) return;
1939
1940 for (Vehicle *v : st->loading_vehicles) {
1941 if (!v->vehstatus.Any({VehState::Stopped, VehState::Crashed})) LoadUnloadVehicle(v);
1942 if (v == last_loading) break;
1943 }
1944
1945 /* Call the production machinery of industries */
1948 }
1950}
1951
1955static const IntervalTimer<TimerGameCalendar> _calendar_inflation_monthly({TimerGameCalendar::Trigger::Month, TimerGameCalendar::Priority::Company}, [](auto)
1956{
1957 if (_settings_game.economy.inflation) {
1958 AddInflation();
1960 }
1961});
1962
1966static const IntervalTimer<TimerGameEconomy> _economy_companies_monthly({ TimerGameEconomy::Trigger::Month, TimerGameEconomy::Priority::Company }, [](auto)
1967{
1970 HandleEconomyFluctuations();
1971});
1972
1973static void DoAcquireCompany(Company *c, bool hostile_takeover)
1974{
1975 CompanyID ci = c->index;
1976
1977 auto cni = std::make_unique<CompanyNewsInformation>(STR_NEWS_COMPANY_MERGER_TITLE, c, Company::Get(_current_company));
1978 EncodedString headline = hostile_takeover
1979 ? GetEncodedString(STR_NEWS_MERGER_TAKEOVER_TITLE, cni->company_name, cni->other_company_name)
1980 : GetEncodedString(STR_NEWS_COMPANY_MERGER_DESCRIPTION, cni->company_name, cni->other_company_name, c->bankrupt_value);
1981 AddCompanyNewsItem(std::move(headline), std::move(cni));
1982 AI::BroadcastNewEvent(new ScriptEventCompanyMerger(ci, _current_company));
1983 Game::NewEvent(new ScriptEventCompanyMerger(ci, _current_company));
1984
1986
1987 if (c->is_ai) AI::Stop(c->index);
1988
1990 InvalidateWindowClassesData(WindowClass::TrainList, 0);
1991 InvalidateWindowClassesData(WindowClass::ShipList, 0);
1992 InvalidateWindowClassesData(WindowClass::RoadVehicleList, 0);
1993 InvalidateWindowClassesData(WindowClass::AircraftList, 0);
1994 InvalidateWindowData(WindowClass::NetworkClientList, 0);
1995
1996 delete c;
1997}
1998
2009CommandCost CmdBuyCompany(DoCommandFlags flags, CompanyID target_company, bool hostile_takeover)
2010{
2011 Company *c = Company::GetIfValid(target_company);
2012 if (c == nullptr) return CMD_ERROR;
2013
2014 /* If you do a hostile takeover but the company went bankrupt, buy it via bankruptcy rules. */
2015 if (hostile_takeover && c->bankrupt_asked.Test(_current_company)) hostile_takeover = false;
2016
2017 /* Disable takeovers when not asked */
2018 if (!hostile_takeover && !c->bankrupt_asked.Test(_current_company)) return CMD_ERROR;
2019
2020 /* Only allow hostile takeover of AI companies and when in single player */
2021 if (hostile_takeover && !c->is_ai) return CMD_ERROR;
2022 if (hostile_takeover && _networking) return CMD_ERROR;
2023
2024 /* Disable taking over the local company in singleplayer mode */
2025 if (!_networking && _local_company == c->index) return CMD_ERROR;
2026
2027 /* Do not allow companies to take over themselves */
2028 if (target_company == _current_company) return CMD_ERROR;
2029
2030 /* Do not allow takeover if the resulting company would have too many vehicles. */
2031 if (!CheckTakeoverVehicleLimit(_current_company, target_company)) return CommandCost(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
2032
2033 /* Get the cost here as the company is deleted in DoAcquireCompany.
2034 * For bankruptcy this amount is calculated when the offer was made;
2035 * for hostile takeover you pay the current price. */
2036 CommandCost cost(ExpensesType::Other, hostile_takeover ? CalculateHostileTakeoverValue(c) : c->bankrupt_value);
2037
2038 if (flags.Test(DoCommandFlag::Execute)) {
2039 DoAcquireCompany(c, hostile_takeover);
2040 }
2041 return cost;
2042}
Base functions for all AIs.
Base for aircraft.
void RemoveAllEngineReplacementForCompany(CompanyID company)
Remove all engine replacements for a company.
Functions related to autoreplacing.
Class for backupping variables and making sure they are restored later.
@ StopLoading
Don't load anymore during the next load cycle.
@ LoadingFinished
Vehicle has finished loading.
@ CargoUnloading
Vehicle is unloading cargo.
static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
Types related to cargoes...
bool IsValidCargoType(CargoType cargo)
Test whether cargo type is not INVALID_CARGO.
Definition cargo_type.h:112
static constexpr CargoType CARGO_AUTO_REFIT
Automatically choose cargo type when doing auto refitting.
Definition cargo_type.h:80
EnumBitSet< CargoType, uint64_t > CargoTypes
Bitset of CargoType elements.
Definition cargo_type.h:115
CargoType
Cargo slots to indicate a cargo type within a game.
Definition cargo_type.h:22
void ClearCargoDeliveryMonitoring(CompanyID company)
Clear all delivery cargo monitors.
void AddCargoDelivery(CargoType cargo_type, CompanyID company, int amount, Source src, const Station *st, IndustryID dest)
Cargo was delivered to its final destination, update the pickup and delivery maps.
void ClearCargoPickupMonitoring(CompanyID company)
Clear all pick-up cargo monitors.
Cargo transport monitoring declarations.
@ Passengers
Passengers.
Definition cargotype.h:50
bool IsCargoInClass(CargoType cargo, CargoClasses cc)
Does a given cargo have any cargo class from cc.
Definition cargotype.h:288
static void BroadcastNewEvent(ScriptEvent *event, CompanyID skip_company=CompanyID::Invalid())
Broadcast a new event to all active AIs.
Definition ai_core.cpp:250
static void Stop(CompanyID company)
Stop a company to be controlled by an AI.
Definition ai_core.cpp:113
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
constexpr bool None() const
Test if none of the values are set.
constexpr Timpl & Reset()
Reset all bits.
constexpr Timpl & Set()
Set all bits.
constexpr bool Any(const Timpl &other) const
Test if any of the given values are set.
Common return value for all commands.
bool Succeeded() const
Did this command succeed?
void AddCost(const Money &cost)
Adds the given cost to the cost of the command.
Money GetCost() const
The costs as made up to this moment.
Container for an encoded string, created by GetEncodedString.
const GRFFile * GetGRF() const
Retrieve the NewGRF the engine is tied to.
GrfID GetGRFID() const
Retrieve the GRF ID of the NewGRF the engine is tied to.
Definition engine.cpp:185
Iterate a range of enum values.
UnitID UseID(UnitID index)
Use a unit number.
Definition vehicle.cpp:1892
UnitID NextID() const
Find first unused unit number.
Definition vehicle.cpp:1877
static void NewEvent(class ScriptEvent *event)
Queue a new event for the game script.
An interval timer will fire every interval, and will continue to fire until it is deleted.
Definition timer.h:76
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
uint TotalCount() const
Returns total count of cargo at the station, including cargo which is already reserved for loading.
uint Load(uint max_move, VehicleCargoList *dest, std::span< const StationID > next, TileIndex current_tile)
Loads cargo onto a vehicle.
static Year year
Current year, starting at 0.
static constexpr TimerGame< struct Calendar >::Year ORIGINAL_MAX_YEAR
static constexpr TimerGame< struct Calendar >::Year ORIGINAL_BASE_YEAR
static Date date
Current date in days (day counter).
static Month month
Current month (0..11).
A sort-of mixin that implements 'at(pos)' and 'operator[](pos)' only for a specific type.
uint Return(uint max_move, StationCargoList *dest, StationID next_station, TileIndex current_tile)
Returns reserved cargo to the station and removes it from the cache.
uint ReservedCount() const
Returns sum of reserved cargo.
uint RemainingCount() const
Returns the sum of cargo to be kept in the vehicle at the current station.
uint StoredCount() const
Returns sum of cargo on board the vehicle (ie not only reserved).
Functions related to commands.
CommandCost & ExtractCommandCost(Tret &ret)
Extract the CommandCost from a command proc result.
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
@ QueryCost
query cost only, don't build.
@ Execute
execute the given command
@ Bankrupt
company bankrupts, skip money check, skip vehicle on tile check in some cases
EnumBitSet< DoCommandFlag, uint16_t > DoCommandFlags
Bitset of DoCommandFlag elements.
Definition of stuff that is very close to a company, like the company struct itself.
int CompanyServiceInterval(const Company *c, VehicleType type)
Get the service interval for the given company and vehicle type.
static void SubtractMoneyFromCompany(Company *c, const CommandCost &cost)
Deduct costs of a command from the money of a company.
void SetLocalCompany(CompanyID new_company, bool switching_game)
Sets the local company and updates the settings that are set on a per-company basis to reflect the co...
void CompanyAdminUpdate(const Company *company)
Called whenever company related information changes in order to notify admins.
Money GetAvailableMoney(CompanyID company)
Get the amount of money that a company has available, or INT64_MAX if there is no such valid company.
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
bool CheckTakeoverVehicleLimit(CompanyID cbig, CompanyID csmall)
Can company cbig buy company csmall without exceeding vehicle limits?
CompanyID _current_company
Company currently doing an action.
Command definitions related to companies.
Functions related to companies.
bool IsLocalCompany()
Is the current company the local company?
GUI Functions related to companies.
void CloseCompanyWindows(CompanyID company)
Close all windows of a company.
Definition window.cpp:1271
@ Delete
Delete a company.
static constexpr CompanyID COMPANY_SPECTATOR
The client is spectating.
static const uint MAX_HISTORY_QUARTERS
The maximum number of quarters kept as performance's history.
static constexpr Owner OWNER_NONE
The tile has no ownership.
static constexpr Owner INVALID_OWNER
An invalid owner.
@ Bankrupt
The company went belly-up.
Some simple functions to help with accessing containers.
bool include(Container &container, typename Container::const_reference &item)
Helper function to append an item to a container if it is not already contained.
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:1521
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:1583
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:190
static void ReserveConsist(Station *st, Vehicle *u, CargoArray *consist_capleft, std::span< const StationID > next_station)
Reserves cargo if the full load order and improved_load is set or if the current order allows autoref...
Definition economy.cpp:1553
void ChangeOwnershipOfCompanyItems(Owner old_owner, Owner new_owner)
Change the ownership of all the items of a company.
Definition economy.cpp:310
static void CompaniesPayInterest()
Let all companies pay the monthly interest on their loan.
Definition economy.cpp:790
static const IntervalTimer< TimerGameEconomy > _economy_companies_monthly({ TimerGameEconomy::Trigger::Month, TimerGameEconomy::Priority::Company }, [](auto) { CompaniesGenStatistics();CompaniesPayInterest();HandleEconomyFluctuations();})
Every economy month update of company economic data, plus economy fluctuations.
static const IntervalTimer< TimerGameCalendar > _calendar_inflation_monthly({TimerGameCalendar::Trigger::Month, TimerGameCalendar::Priority::Company}, [](auto) { if(_settings_game.economy.inflation) { AddInflation();RecomputePrices();} })
Every calendar month update of inflation.
void LoadUnloadStation(Station *st)
Load/unload the vehicles in this station according to the order they entered.
Definition economy.cpp:1916
void RecomputePrices()
Computes all prices, payments and maximum loan.
Definition economy.cpp:723
static uint DeliverGoodsToIndustry(const Station *st, CargoType cargo_type, uint num_pieces, IndustryID source, CompanyID company)
Transfer goods from station to industry.
Definition economy.cpp:1019
static void LoadUnloadVehicle(Vehicle *front)
Loads/unload the vehicle if possible.
Definition economy.cpp:1601
Money CalculateHostileTakeoverValue(const Company *c)
Calculate what you have to pay to take over a company.
Definition economy.cpp:165
static Money CalculateCompanyAssetValue(const Company *c)
Calculate the value of the assets of a company.
Definition economy.cpp:103
static SmallIndustryList _cargo_delivery_destinations
The industries we've currently brought cargo to.
Definition economy.cpp:1007
void PrepareUnload(Vehicle *front_v)
Prepare the vehicle to be unloaded.
Definition economy.cpp:1243
static uint GetLoadAmount(Vehicle *v)
Gets the amount of cargo the given vehicle can load in the current tick.
Definition economy.cpp:1286
static void HandleStationRefit(Vehicle *v, CargoArray &consist_capleft, Station *st, std::span< const StationID > next_station, CargoType new_cargo_type)
Refit a vehicle in a station.
Definition economy.cpp:1463
void SetPriceBaseMultiplier(Price price, int factor)
Change a price base by the given factor.
Definition economy.cpp:859
Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift)
Determine a certain price.
Definition economy.cpp:926
static void TriggerIndustryProduction(Industry *i)
Inform the industry about just delivered cargo DeliverGoodsToIndustry() silently incremented incoming...
Definition economy.cpp:1128
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:1331
static Money DeliverGoods(int num_pieces, CargoType cargo_type, StationID dest, uint distance, uint16_t periods_in_transit, Company *company, Source src)
Delivers goods to industries/towns and calculates the payment.
Definition economy.cpp:1074
Prices _price
Prices and also the fractional part.
Definition economy.cpp:94
void InitializeEconomy()
Resets economy to initial values.
Definition economy.cpp:911
static void CompanyCheckBankrupt(Company *c)
Check for bankruptcy of a company.
Definition economy.cpp:536
void ResetPriceBaseMultipliers()
Reset changes to the price base multipliers.
Definition economy.cpp:847
static void CompaniesGenStatistics()
Update the finances of all companies.
Definition economy.cpp:627
bool AddInflation(bool check_year)
Add monthly inflation.
Definition economy.cpp:685
CommandCost CmdBuyCompany(DoCommandFlags flags, CompanyID target_company, bool hostile_takeover)
Buy up another company.
Definition economy.cpp:2009
const EnumIndexArray< ScoreInfo, ScoreID, ScoreID::End > _score_info
Score info, values used for computing the detailed performance rating.
Definition economy.cpp:79
Money CalculateCompanyValue(const Company *c, bool including_loan)
Calculate the value of the company.
Definition economy.cpp:138
void StartupIndustryDailyChanges(bool init_counter)
Initialize the variables that will maintain the daily industry change system.
Definition economy.cpp:869
Base classes related to the economy.
Pool< CargoPayment, CargoPaymentID, 512 > CargoPaymentPool
Type of pool to store cargo payments in; little over 1 million.
CargoPaymentPool _cargo_payment_pool
The actual pool to store cargo payments in.
Command definitions related to the economy.
bool EconomyIsInRecession()
Is the economy in recession?
ScoreID
Score categories in the detailed performance rating.
@ Delivered
Units of cargo delivered in the last four quarter.
@ MinIncome
Income in the quarter with the lowest profit of the last 12 quarters.
@ Vehicles
Number of vehicles that turned profit last year.
@ End
Score ID end marker.
@ Stations
Number of recently-serviced stations.
@ Total
Total points out of possible points ,must always be the last entry.
@ Loan
The amount of money company can take as a loan.
@ MaxIncome
Income in the quarter with the highest profit of the last 12 quarters.
@ MinProfit
The profit of the vehicle with the lowest income.
@ Money
Amount of money company has in the bank.
@ Cargo
Number of types of cargo delivered in the last four quarter.
static const int MIN_PRICE_MODIFIER
Maximum NewGRF price modifiers.
EnumIndexArray< Money, Price, Price::End > Prices
Prices of everything.
@ LoanInterest
Interest payments over the loan.
@ Property
Property costs.
@ Other
Other expenses.
@ Construction
Price is affected by "construction cost" difficulty setting.
@ Running
Price is affected by "vehicle running cost" difficulty setting.
static const int LOAN_INTERVAL
The "steps" in loan size, in British Pounds!
static const uint64_t MAX_INFLATION
Maximum inflation (including fractional part) without causing overflows in int64_t price computations...
Price
Enumeration of all base prices for use with Prices.
@ End
Price base end marker.
@ StationValue
Stations value and additional constant company running fee.
static constexpr int SCORE_MAX
The max score that can be in the performance history.
Base class for engines.
@ NoDefaultCargoMultiplier
Use the new capacity algorithm. The default cargotype of the vehicle does not affect capacity multipl...
EnumClassIndexContainer< std::array< T, to_underlying(N)>, Index > EnumIndexArray
A typedef for EnumClassIndexContainer using std::array as the backing container type.
Base functions for all Games.
Goal base class.
Base class and functions for all vehicles that move through ground.
void MarkTilesDirty(bool cargo_change) const
Marks the tiles of the station as dirty.
Definition station.cpp:250
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition gfx.cpp:1548
virtual void MarkDirty()
Marks the vehicles to be redrawn and updates cached variables.
Base of all industries.
const IndustrySpec * GetIndustrySpec(IndustryType thistype)
Accessor for array _industry_specs.
@ CargoReceived
Cargo has been delivered.
@ CargoReceived
Trigger when cargo is received .
void ChangeTileOwner(TileIndex tile, Owner old_owner, Owner new_owner)
Change the owner of a tile.
constexpr T ScaleByPercentage(U num, uint16_t percentage)
Scale a number by the required percentage.
constexpr uint CeilDiv(uint a, uint b)
Computes ceil(a / b) for non-negative a and b.
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition math_func.hpp:79
constexpr To ClampTo(From value)
Clamp the given value down to lie within the requested type.
void ShowCostOrIncomeAnimation(int x, int y, int z, Money cost)
Display animated income or costs on the map.
Definition misc_gui.cpp:508
void ShowFeederIncomeAnimation(int x, int y, int z, Money transfer, Money income)
Display animated feeder income.
Definition misc_gui.cpp:531
void UpdateFillingPercent(TextEffectID te_id, uint8_t percent, StringID string)
Update vehicle loading indicators.
Definition misc_gui.cpp:571
TextEffectID ShowFillingPercent(int x, int y, int z, uint8_t percent, StringID string)
Display vehicle loading indicators.
Definition misc_gui.cpp:556
bool _networking
are we in networking mode?
Definition network.cpp:63
bool _network_server
network-server is active
Definition network.cpp:64
Basic functions/variables used all over the place.
void NetworkClientsToSpectators(CompanyID cid)
Move the clients of a company to the spectators.
Network functions used by other parts of OpenTTD.
@ Invalid
Client is not part of anything.
NewGRF handling of airport tiles.
@ ProfitCalc
custom profit calculation
@ Production256Ticks
call production callback every 256 ticks
@ ProductionCargoArrival
call production callback when cargo arrives at the industry
@ CBID_CARGO_PROFIT_CALC
Called to calculate the income of delivered cargo.
@ CBID_VEHICLE_LOAD_AMOUNT
Determine the amount of cargo to load per unit of time when using gradual loading.
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
EnumBitSet< IndustryCallbackMask, uint16_t > IndustryCallbackMasks
Bitset of IndustryCallbackMask elements.
Cargo support for NewGRFs.
void ErrorUnknownCallbackResult(GrfID grfid, uint16_t cbid, uint16_t cb_res)
Record that a NewGRF returned an unknown/invalid callback result.
uint16_t GetVehicleCallback(CallbackID callback, uint32_t param1, uint32_t param2, EngineID engine, const Vehicle *v, std::span< int32_t > regs100)
Evaluate a newgrf callback for vehicles.
Functions for NewGRF engines.
void IndustryProductionCallback(Industry *ind, int reason)
Get the industry production callback and apply it to the industry.
bool IndustryTemporarilyRefusesCargo(Industry *ind, CargoType cargo_type)
Check whether an industry temporarily refuses to accept a certain cargo.
void TriggerIndustryRandomisation(Industry *ind, IndustryRandomTrigger trigger)
Trigger a random trigger for all industry tiles.
NewGRF handling of industry tiles.
@ PROP_VEHICLE_LOAD_AMOUNT
Loading speed.
void TriggerRoadStopRandomisation(BaseStation *st, TileIndex tile, StationRandomTrigger trigger, CargoType cargo_type)
Trigger road stop randomisation.
NewGRF definitions and structures for road stops.
bool PlayVehicleSound(const Vehicle *v, VehicleSoundEvent event, bool force)
Checks whether a NewGRF wants to play a different vehicle sound effect.
Functions related to NewGRF provided sounds.
@ LoadUnload
Whenever cargo payment is made for a vehicle.
void TriggerStationRandomisation(BaseStation *st, TileIndex trigger_tile, StationRandomTrigger trigger, CargoType cargo_type)
Trigger station randomisation.
Header file for NewGRF stations.
Functions related to news.
void AddNewsItem(EncodedString &&headline, NewsType type, NewsStyle style, NewsFlags flags, NewsReference ref1={}, NewsReference ref2={}, std::unique_ptr< NewsAllocatedData > &&data=nullptr, AdviceType advice_type=AdviceType::Invalid)
Add a new newsitem to be shown.
Definition news_gui.cpp:919
@ Economy
Economic changes (recession, industry up/dowm).
Definition news_type.h:40
@ Normal
Normal news item. (Newspaper with text only).
Definition news_type.h:83
Functions related to objects.
void UpdateCompanyHQ(TileIndex tile, uint score)
Update the CompanyHQ to the state associated with the given score.
@ Menu
In the main menu.
Definition openttd.h:19
@ Transfer
Transfer all cargo onto the platform.
Definition order_type.h:70
@ NoUnload
Totally no unloading will be done.
Definition order_type.h:71
@ Unload
Force unloading all cargo onto the platform, possibly not getting paid.
Definition order_type.h:69
@ NoLoad
Do not load anything.
Definition order_type.h:81
@ FullLoadAny
Full load a single cargo of the consist.
Definition order_type.h:80
OverflowSafeInt< int64_t > OverflowSafeInt64
A 64-bit overflow safe type.
Some methods of Pool are placed here in order to reduce compilation time and binary size.
#define INSTANTIATE_POOL_METHODS(name)
Force instantiation of pool methods so we don't get linker errors.
Table of all default price bases.
Money RailMaintenanceCost(RailType railtype, uint32_t num, uint32_t total_num)
Calculates the maintenance cost of a number of track bits.
Definition rail.h:503
Money SignalMaintenanceCost(uint32_t num)
Calculates the maintenance cost of a number of signals.
Definition rail.h:514
TrackBits GetTrackBits(Tile tile)
Gets the track bits of the given tile.
Definition rail_map.h:136
bool IsSignalPresent(Tile t, uint8_t signalbit)
Checks whether the given signals is present.
Definition rail_map.h:462
bool HasSignals(Tile t)
Checks if a rail tile has signals.
Definition rail_map.h:72
RailType
Enumeration for all possible railtypes.
Definition rail_type.h:26
@ RAILTYPE_END
Used for iterations.
Definition rail_type.h:32
Declaration of link refreshing utility.
Money RoadMaintenanceCost(RoadType roadtype, uint32_t num, uint32_t total_num)
Calculates the maintenance cost of a number of road bits.
Definition road_func.h:107
void UpdateLevelCrossing(TileIndex tile, bool sound=true, bool force_bar=false)
Update a level crossing to barred or open (crossing may include multiple adjacent tiles).
bool IsLevelCrossingTile(Tile t)
Return whether a tile is a level crossing tile.
Definition road_map.h:79
RoadType
The different roadtypes we support.
Definition road_type.h:24
@ ROADTYPE_END
Used for iterations.
Definition road_type.h:28
A number of safeguards to prevent using unsafe methods.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition settings.cpp:61
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:60
void AddTrackToSignalBuffer(TileIndex tile, Track track, Owner owner)
Add track to signal update buffer.
Definition signal.cpp:597
void UpdateSignalsInBuffer()
Update signals in buffer Called from 'outside'.
Definition signal.cpp:581
uint8_t SignalOnTrack(Track track)
Maps a Track to the bits that store the status of the two signals that can be present on the given tr...
Definition signal_func.h:48
Base class for signs.
Functions related to sound.
@ SND_14_CASHTILL
18 == 0x12 Income from cargo delivery
Definition sound_type.h:65
@ Industry
Source/destination is an industry.
Definition source_type.h:21
Money AirportMaintenanceCost(Owner owner)
Calculates the maintenance cost of all airports of a company.
Definition station.cpp:548
Base classes/functions for stations.
Functions related to stations.
Money StationMaintenanceCost(uint32_t num)
Calculates the maintenance cost of a number of station tiles.
StationID GetStationIndex(Tile t)
Get StationID from a tile.
Definition station_map.h:26
@ CargoTaken
Trigger station when cargo is completely taken.
@ VehicleLoads
Trigger platform when train loads/unloads.
@ CargoTaken
Trigger station when cargo is completely taken.
@ VehicleLoads
Trigger platform when train loads/unloads.
@ CargoTaken
Triggered when a cargo type is completely removed from the station (for all tiles at the same time).
Definition of base types and functions in a cross-platform compatible way.
StoryPage base class.
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Definition strings.cpp:89
Functions related to OTTD's strings.
StrongType::Typedef< uint32_t, struct StringIDTag, StrongType::Compare, StrongType::Integer > StringID
Numeric value that represents a string, independent of the selected language.
bool IsNormalAircraft() const
Check if the aircraft type is a normal flying device; eg not a rotor or a shadow.
Definition aircraft.h:123
Class to backup a specific variable and restore it upon destruction of this object to prevent stack v...
Class to backup a specific variable and restore it later.
void Restore()
Restore the variable.
TimerGameTick::Ticks current_order_time
How many ticks have passed since this order started.
VehicleFlags vehicle_flags
Used for gradual loading and other miscellaneous things (.
TimerGameTick::Ticks lateness_counter
How many ticks late (or early if negative) this vehicle is.
TileIndex xy
Base tile of the station.
Owner owner
The owner of this station.
Town * town
The town this station is associated with.
VehicleType type
Type of vehicle.
Class for storing amounts of cargo.
Definition cargo_type.h:120
Container for cargo from the same location and time.
Definition cargopacket.h:40
Money GetFeederShare() const
Gets the amount of money already paid to earlier vehicles in the feeder chain.
uint GetDistance(TileIndex current_tile) const
Get the current distance the cargo has traveled.
uint16_t GetPeriodsInTransit() const
Gets the number of cargo aging periods this cargo has been in transit.
Source GetSource() const
Gets the source of the packet for subsidy purposes.
Helper class to perform the cargo payment.
void PayFinalDelivery(CargoType cargo, const CargoPacket *cp, uint count, TileIndex current_tile)
Handle payment for final delivery of the given cargo packet.
Definition economy.cpp:1205
~CargoPayment()
Execute the actual payment to the coffers of the company.
Definition economy.cpp:1171
StationID current_station
NOSAVE: The current station.
Money PayTransfer(CargoType cargo, const CargoPacket *cp, uint count, TileIndex current_tile)
Handle payment for transfer of the given cargo packet.
Definition economy.cpp:1223
Vehicle * front
The front vehicle to do the payment of.
Money visual_transfer
The transfer credits to be shown.
Money visual_profit
The visual profit to show.
Money route_profit
The amount of money to add/remove from the bank account.
Specification of a cargo type.
Definition cargotype.h:76
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo type.
Definition cargotype.h:140
static IterateWrapper Iterate(size_t from=0)
Returns an iterable ensemble of all valid CargoSpec.
Definition cargotype.h:239
Money current_payment
Payment rate scaled by inflation.
Definition cargotype.h:104
uint8_t transit_periods[2]
Values used to calculate timefactor for cargo payment alghoritm.
Definition cargotype.h:85
TownAcceptanceEffect town_acceptance_effect
The effect that delivering this cargo type has on towns. Also affects destination of subsidies.
Definition cargotype.h:88
CargoCallbackMasks callback_mask
Bitmask of cargo callbacks that have to be called.
Definition cargotype.h:91
bool IsValid() const
Tests for validity of this cargospec.
Definition cargotype.h:120
CargoArray delivered_cargo
The amount of delivered cargo.
TileIndex location_of_HQ
Northern tile of HQ; INVALID_TILE when there is none.
uint8_t months_of_bankruptcy
Number of months that the company is unable to pay its debts.
CompanyMask bankrupt_asked
which companies were asked about buying it?
int16_t bankrupt_timeout
If bigger than 0, amount of time to wait for an answer on an offer to buy this company.
CompanySettings settings
settings specific for each company
bool is_ai
If true, the company is (also) controlled by the computer (a NoAI program).
Money current_loan
Amount of money borrowed from the bank.
CompanyEconomyEntry cur_economy
Economic data of the company of this quarter.
std::array< CompanyEconomyEntry, MAX_HISTORY_QUARTERS > old_economy
Economic data of the company of the last MAX_HISTORY_QUARTERS quarters.
Money money
Money owned by the company.
uint8_t num_valid_stat_ent
Number of valid statistical entries in old_economy.
VehicleDefaultSettings vehicle
default settings for vehicles
Money GetMaxLoan() const
Calculate the max allowed loan for this company.
Data of the economy.
EngineMiscFlags misc_flags
Miscellaneous flags.
VehicleCallbackMasks callback_mask
Bitmask of vehicle callbacks that have to be called.
Action for finalizing a refit.
Definition economy.cpp:1422
std::span< const StationID > next_station
Next hops to reserve cargo for.
Definition economy.cpp:1425
CargoArray & consist_capleft
Capacities left in the consist.
Definition economy.cpp:1423
bool do_reserve
If the vehicle should reserve.
Definition economy.cpp:1426
FinalizeRefitAction(CargoArray &consist_capleft, Station *st, std::span< const StationID > next_station, bool do_reserve)
Create a finalizing action.
Definition economy.cpp:1435
bool operator()(Vehicle *v)
Reserve cargo from the station and update the remaining consist capacities with the vehicle's remaini...
Definition economy.cpp:1444
Station * st
Station to reserve cargo from.
Definition economy.cpp:1424
Dynamic data of a loaded NewGRF.
Definition newgrf.h:126
uint8_t grf_version
GRF version (See https://newgrf-specs.tt-wiki.net/wiki/Version_numbers#GRF_version).
Definition newgrf.h:129
PriceMultipliers price_base_multipliers
Price base multipliers as set by the grf.
Definition newgrf.h:171
Struct about goals, current and completed.
Definition goal_base.h:22
StationCargoList cargo
The cargo packets of cargo waiting in this station.
Stores station stats for a single cargo.
bool HasRating() const
Does this cargo have a rating at this station?
uint8_t last_speed
Maximum speed (up to 255) of the last vehicle that tried to load this cargo.
uint8_t last_age
Age in years (up to 255) of the last vehicle that tried to load this cargo.
uint8_t time_since_pickup
Number of rating-intervals (up to 255) since the last vehicle tried to load this cargo.
States status
Status of this cargo, see State.
@ Acceptance
Set when the station accepts the cargo currently for final deliveries.
@ EverAccepted
Set when a vehicle ever delivered cargo to the station for final delivery.
@ Rating
This indicates whether a cargo has a rating at the station.
@ AcceptedBigtick
Set when cargo was delivered for final delivery during the current STATION_ACCEPTANCE_TICKS interval.
@ CurrentMonth
Set when cargo was delivered for final delivery this month.
const GoodsEntryData & GetData() const
Get optional cargo packet/flow data.
GoodsEntryData & GetOrCreateData()
Get optional cargo packet/flow data.
uint AvailableCount() const
Returns sum of cargo still available for loading at the station.
uint16_t cached_total_length
Length of the whole vehicle (valid only for the first engine).
bool IsMultiheaded() const
Check if the vehicle is a multiheaded engine.
static void CountVehicle(const Vehicle *v, int delta)
Update num_vehicle when adding or removing a vehicle.
static void CountEngine(const Vehicle *v, int delta)
Update num_engines when adding/removing an engine.
static void UpdateAutoreplace(CompanyID company)
Update autoreplace_defined and autoreplace_finished of all statistics of a company.
Group data.
Definition group.h:77
Defines the data structure for constructing industry.
IndustryCallbackMasks callback_mask
Bitmask of industry callbacks that have to be called.
uint16_t input_cargo_multiplier[INDUSTRY_NUM_INPUTS][INDUSTRY_NUM_OUTPUTS]
Input cargo multipliers (multiply amount of incoming cargo for the produced cargoes).
Defines the internal data of a functional industry.
Definition industry.h:64
IndustryType type
type of industry.
Definition industry.h:117
Owner exclusive_supplier
Which company has exclusive rights to deliver cargo (INVALID_OWNER = anyone).
Definition industry.h:132
ProducedCargoes produced
produced cargo slots
Definition industry.h:112
AcceptedCargoes accepted
accepted cargo slots
Definition industry.h:113
uint8_t was_cargo_delivered
flag that indicate this has been the closest industry chosen for cargo delivery by a station....
Definition industry.h:121
AcceptedCargoes::iterator GetCargoAccepted(CargoType cargo)
Get accepted cargo slot for a specific cargo type.
Definition industry.h:204
Action to check if a vehicle has no stored cargo.
Definition economy.cpp:1349
bool operator()(const Vehicle *v)
Checks if the vehicle has stored cargo.
Definition economy.cpp:1355
static IterateWrapper Iterate()
Returns an iterable ensemble of all Tiles.
Definition map_func.h:366
static uint LogX()
Logarithm of the map size along the X side.
Definition map_func.h:243
static uint LogY()
Logarithm of the map size along the y side.
Definition map_func.h:253
bool IsType(OrderType type) const
Check whether this order is of the given type.
Definition order_base.h:66
CargoType GetRefitCargo() const
Get the cargo to to refit to.
Definition order_base.h:127
bool IsFullLoadOrder() const
Is this order a OrderLoadType::FullLoad or OrderLoadType::FullLoadAny?
Definition order_base.h:135
OrderUnloadType GetUnloadType() const
How must the consist be unloaded?
Definition order_base.h:151
OrderLoadType GetLoadType() const
How must the consist be loaded?
Definition order_base.h:145
uint16_t 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:282
bool IsRefit() const
Is this order a refit order.
Definition order_base.h:113
static Pool::IterateWrapper< Vehicle > Iterate(size_t from=0)
static Company * Get(auto index)
static Company * GetIfValid(auto index)
Refit preparation action.
Definition economy.cpp:1365
CargoTypes & refit_mask
Bitmask of possible refit cargoes.
Definition economy.cpp:1367
PrepareRefitAction(CargoArray &consist_capleft, CargoTypes &refit_mask)
Create a refit preparation action.
Definition economy.cpp:1374
CargoArray & consist_capleft
Capacities left in the consist.
Definition economy.cpp:1366
bool operator()(const Vehicle *v)
Prepares for refitting of a vehicle, subtracting its free capacity from consist_capleft and adding th...
Definition economy.cpp:1383
Action for returning reserved cargo.
Definition economy.cpp:1395
Station * st
Station to give the returned cargo to.
Definition economy.cpp:1396
bool operator()(Vehicle *v)
Return all reserved cargo from a vehicle.
Definition economy.cpp:1411
ReturnCargoAction(Station *st, StationID next_one)
Construct a cargo return action.
Definition economy.cpp:1404
StationID next_hop
Next hop the cargo should be assigned to.
Definition economy.cpp:1397
Data structure for storing how the score is computed for a single score id.
A location from where cargo can come from (or go to).
Definition source_type.h:32
SourceType type
Type of source_id.
Definition source_type.h:37
static Pool::IterateWrapper< Station > Iterate(size_t from=0)
static Station * Get(auto index)
Station data structure.
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:292
IndustryList industries_near
Cached list of industries near the station that can accept cargo,.
CargoTypes always_accepted
Bitmask of always accepted cargo types (by houses, HQs, industry tiles when industry doesn't accept c...
std::array< GoodsEntry, NUM_CARGO > goods
Goods at this station.
Struct about stories, current and completed.
Definition story_base.h:157
Struct about subsidies, offered and awarded.
HistoryData< AcceptedHistory > history
Histor data of accepted cargo.
Definition town.h:118
Town data structure.
Definition town.h:64
AcceptedCargo & GetOrCreateCargoAccepted(CargoType cargo)
Get or create the storage for an accepted cargo.
Definition town.h:160
CompanyID exclusivity
which company has exclusivity
Definition town.h:87
uint8_t exclusive_counter
months till the exclusivity expires
Definition town.h:88
EnumIndexArray< TransportedCargoStat< uint16_t >, TownAcceptanceEffect, TownAcceptanceEffect::End > received
Cargo statistics about received cargotypes.
Definition town.h:133
'Train' is either a loco or a wagon.
Definition train.h:97
Train * other_multiheaded_part
Link between the two ends of a multiheaded engine.
Definition train.h:105
uint16_t cached_max_speed
Maximum speed of the consist (minimum of the max speed of all vehicles in the consist).
uint16_t servint_aircraft
service interval for aircraft
uint16_t servint_roadveh
service interval for road vehicles
uint16_t servint_ships
service interval for ships
bool servint_ispercent
service intervals are in percents
uint16_t servint_trains
service interval for trains
Vehicle data structure.
CargoPayment * cargo_payment
The cargo payment we're currently in.
EngineID engine_type
The type of engine used for this vehicle.
int32_t z_pos
z coordinate.
const Engine * GetEngine() const
Retrieves the engine of the vehicle.
Definition vehicle.cpp:752
virtual TileIndex GetCargoTile() const
Tile to use for economic calculations when moving cargo into or out of this vehicle.
VehicleCargoList cargo
The cargo this vehicle is carrying.
uint16_t cargo_cap
total capacity
Vehicle * GetFirstEnginePart()
Get the first part of an articulated engine.
Money profit_this_year
Profit this year << 8, low 8 bits are fract.
bool HasArticulatedPart() const
Check if an engine has an articulated part.
VehStates vehstatus
Status.
void GetNextStoppingStation(std::vector< StationID > &next_station) const
Get the next station the vehicle will stop at.
CargoType cargo_type
type of cargo this vehicle is carrying
Vehicle * First() const
Get the first vehicle of this vehicle chain.
Order current_order
The current order (+ status, like: loading).
Vehicle * Next() const
Get the next vehicle of this vehicle.
int32_t y_pos
y coordinate.
int32_t x_pos
x coordinate.
OrderList * orders
Pointer to the order list for this vehicle.
Vehicle * GetMovingFront() const
Get the moving front of the vehicle chain.
VehicleCache vcache
Cache of often used vehicle values.
GroundVehicleCache * GetGroundVehicleCache()
Access the ground vehicle cache of the vehicle.
Definition vehicle.cpp:3214
uint16_t load_unload_ticks
Ticks to wait before starting next cycle.
uint16_t cur_speed
current speed
TextEffectID fill_percent_te_id
a text-effect id to a loading indicator object
Vehicle * Previous() const
Get the previous vehicle of this vehicle.
TileIndex tile
Current tile index.
StationID last_station_visited
The last station we stopped at.
TimerGameCalendar::Year build_year
Year the vehicle has been built.
Owner owner
Which company owns the vehicle?
Representation of a waypoint.
void RebuildSubsidisedSourceAndDestinationCache()
Perform a full rebuild of the subsidies cache.
Definition subsidy.cpp:103
bool CheckSubsidised(CargoType cargo_type, CompanyID company, Source src, const Station *st)
Tests whether given delivery is subsidised and possibly awards the subsidy to delivering company.
Definition subsidy.cpp:493
Subsidy base class.
Functions related to subsidies.
static bool IsTileType(Tile tile, TileType type)
Checks if a tile is a given tiletype.
Definition tile_map.h:150
bool IsTileOwner(Tile tile, Owner owner)
Checks if a tile belongs to the given owner.
Definition tile_map.h:214
StrongType::Typedef< uint32_t, struct TileIndexTag, StrongType::Compare, StrongType::Integer, StrongType::Compatible< int32_t >, StrongType::Compatible< int64_t > > TileIndex
The index/ID of a Tile.
Definition tile_type.h:92
static constexpr uint TILE_SIZE
Tile size in world coordinates.
Definition tile_type.h:15
@ Station
A tile of a station or airport.
Definition tile_type.h:54
@ Railway
A tile with railway.
Definition tile_type.h:50
Definition of Interval and OneShot timers.
Definition of the game-calendar-timer.
Definition of the game-economy-timer.
Base of the town class.
static constexpr int RATING_INITIAL
initial rating
Definition town_type.h:44
Track
These are used to specify a single track.
Definition track_type.h:19
Base for the train class.
uint8_t CalcPercentVehicleFilled(const Vehicle *front, StringID *colour)
Calculates how full a vehicle is.
Definition vehicle.cpp:1507
Command definitions for vehicles.
Functions related to vehicles.
static const TimerGameEconomy::Date VEHICLE_PROFIT_MIN_AGE
Only vehicles older than this have a meaningful profit.
bool IsCompanyBuildableVehicleType(VehicleType type)
Is the given vehicle type buildable by a company?
Functions related to the vehicle's GUIs.
WindowClass GetWindowClassForVehicleType(VehicleType vt)
Get WindowClass for vehicle list of given vehicle type.
Definition vehicle_gui.h:96
@ Ship
Ship vehicle type.
@ Aircraft
Aircraft vehicle type.
@ Road
Road vehicle type.
@ Train
Train vehicle type.
@ NewCargo
Affected vehicle only: Vehicle is loaded with cargo, after it was empty.
@ Empty
Front vehicle only: Entire consist is empty.
EnumIndexArray< T, VehicleType, Tend > VehicleTypeIndexArray
Array with VehicleType as index.
Functions related to water management.
Money CanalMaintenanceCost(uint32_t num)
Calculates the maintenance cost of a number of canal tiles.
Definition water.h:53
Base of waypoints.
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:1291
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting).
Definition window.cpp:3285
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:3377
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting).
Definition window.cpp:3255
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:3395