OpenTTD Source 20250312-master-gcdcc6b491d
company_cmd.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
7
10#include "stdafx.h"
11#include "company_base.h"
12#include "company_func.h"
13#include "company_gui.h"
14#include "core/backup_type.hpp"
15#include "town.h"
16#include "news_func.h"
17#include "command_func.h"
18#include "network/network.h"
22#include "ai/ai.hpp"
23#include "ai/ai_instance.hpp"
24#include "ai/ai_config.hpp"
26#include "window_func.h"
27#include "strings_func.h"
28#include "sound_func.h"
29#include "rail.h"
30#include "core/pool_func.hpp"
31#include "settings_func.h"
32#include "vehicle_base.h"
33#include "vehicle_func.h"
34#include "smallmap_gui.h"
35#include "game/game.hpp"
36#include "goal_base.h"
37#include "story_base.h"
38#include "company_cmd.h"
39#include "timer/timer.h"
42
44
45#include "table/strings.h"
46
47#include "safeguards.h"
48
50void UpdateObjectColours(const Company *c);
51
57
60
61
66Company::Company(StringID name_1, bool is_ai)
67{
68 this->name_1 = name_1;
69 this->is_ai = is_ai;
70 this->terraform_limit = (uint32_t)_settings_game.construction.terraform_frame_burst << 16;
71 this->clear_limit = (uint32_t)_settings_game.construction.clear_frame_burst << 16;
72 this->tree_limit = (uint32_t)_settings_game.construction.tree_frame_burst << 16;
73 this->build_object_limit = (uint32_t)_settings_game.construction.build_object_frame_burst << 16;
74
75 InvalidateWindowData(WC_PERFORMANCE_DETAIL, 0, CompanyID::Invalid());
76}
77
80{
81 if (CleaningPool()) return;
82
84}
85
90void Company::PostDestructor(size_t index)
91{
96 /* If the currently shown error message has this company in it, then close it. */
98}
99
105{
106 if (this->max_loan == COMPANY_MAX_LOAN_DEFAULT) return _economy.max_loan;
107 return this->max_loan;
108}
109
116void SetLocalCompany(CompanyID new_company)
117{
118 /* company could also be COMPANY_SPECTATOR or OWNER_NONE */
119 assert(Company::IsValidID(new_company) || new_company == COMPANY_SPECTATOR || new_company == OWNER_NONE);
120
121 /* If actually changing to another company, several windows need closing */
122 bool switching_company = _local_company != new_company;
123
124 /* Delete the chat window, if you were team chatting. */
126
127 assert(IsLocalCompany());
128
129 _current_company = _local_company = new_company;
130
131 if (switching_company) {
133 /* Delete any construction windows... */
135 }
136
137 /* ... and redraw the whole screen. */
141}
142
149{
150 if (!Company::IsValidID(company)) return (TextColour)GetColourGradient(COLOUR_WHITE, SHADE_NORMAL) | TC_IS_PALETTE_COLOUR;
151 return (TextColour)GetColourGradient(_company_colours[company], SHADE_NORMAL) | TC_IS_PALETTE_COLOUR;
152}
153
160void DrawCompanyIcon(CompanyID c, int x, int y)
161{
162 DrawSprite(SPR_COMPANY_ICON, COMPANY_SPRITE_COLOUR(c), x, y);
163}
164
172{
173 if (!AreCompanyManagerFaceBitsValid(cmf, CMFV_GEN_ETHN, GE_WM)) return false;
174
176 bool has_moustache = !HasBit(ge, GENDER_FEMALE) && GetCompanyManagerFaceBits(cmf, CMFV_HAS_MOUSTACHE, ge) != 0;
177 bool has_tie_earring = !HasBit(ge, GENDER_FEMALE) || GetCompanyManagerFaceBits(cmf, CMFV_HAS_TIE_EARRING, ge) != 0;
178 bool has_glasses = GetCompanyManagerFaceBits(cmf, CMFV_HAS_GLASSES, ge) != 0;
179
180 if (!AreCompanyManagerFaceBitsValid(cmf, CMFV_EYE_COLOUR, ge)) return false;
181 for (CompanyManagerFaceVariable cmfv = CMFV_CHEEKS; cmfv < CMFV_END; cmfv++) {
182 switch (cmfv) {
183 case CMFV_MOUSTACHE: if (!has_moustache) continue; break;
184 case CMFV_LIPS:
185 case CMFV_NOSE: if (has_moustache) continue; break;
186 case CMFV_TIE_EARRING: if (!has_tie_earring) continue; break;
187 case CMFV_GLASSES: if (!has_glasses) continue; break;
188 default: break;
189 }
190 if (!AreCompanyManagerFaceBitsValid(cmf, cmfv, ge)) return false;
191 }
192
193 return true;
194}
195
201{
202 CompanyID cid = company->index;
203
206}
207
216{
217 if (_settings_game.difficulty.infinite_money) return INT64_MAX;
218 if (!Company::IsValidID(company)) return INT64_MAX;
219 return Company::Get(company)->money;
220}
221
233
241{
242 if (cost.GetCost() <= 0) return true;
244
246 if (c != nullptr && cost.GetCost() > c->money) {
247 cost.MakeError(STR_ERROR_NOT_ENOUGH_CASH_REQUIRES_CURRENCY);
248 if (IsLocalCompany()) {
249 cost.SetEncodedMessage(GetEncodedString(STR_ERROR_NOT_ENOUGH_CASH_REQUIRES_CURRENCY, cost.GetCost()));
250 }
251 return false;
252 }
253 return true;
254}
255
262{
263 if (cost.GetCost() == 0) return;
264 assert(cost.GetExpensesType() != INVALID_EXPENSES);
265
266 c->money -= cost.GetCost();
267 c->yearly_expenses[0][cost.GetExpensesType()] += cost.GetCost();
268
273 c->cur_economy.income -= cost.GetCost();
274 } else if (HasBit(1 << EXPENSES_TRAIN_RUN |
277 1 << EXPENSES_SHIP_RUN |
278 1 << EXPENSES_PROPERTY |
280 c->cur_economy.expenses -= cost.GetCost();
281 }
282
284}
285
291{
293 if (c != nullptr) SubtractMoneyFromAnyCompany(c, cost);
294}
295
302{
303 Company *c = Company::Get(company);
304 uint8_t m = c->money_fraction;
305 Money cost = cst.GetCost();
306
307 c->money_fraction = m - (uint8_t)cost;
308 cost >>= 8;
309 if (c->money_fraction > m) cost++;
310 if (cost != 0) SubtractMoneyFromAnyCompany(c, CommandCost(cst.GetExpensesType(), cost));
311}
312
313static constexpr void UpdateLandscapingLimit(uint32_t &limit, uint64_t per_64k_frames, uint64_t burst)
314{
315 limit = static_cast<uint32_t>(std::min<uint64_t>(limit + per_64k_frames, burst << 16));
316}
317
328
335std::array<StringParameter, 2> GetParamsForOwnedBy(Owner owner, TileIndex tile)
336{
337 if (owner == OWNER_TOWN) {
338 assert(tile != 0);
339 const Town *t = ClosestTownFromTile(tile, UINT_MAX);
340 return {STR_TOWN_NAME, t->index};
341 }
342
343 if (!Company::IsValidID(owner)) {
344 return {STR_COMPANY_SOMEONE, std::monostate{}};
345 }
346
347 return {STR_COMPANY_NAME, owner};
348}
349
359{
360 assert(owner < OWNER_END);
361 assert(owner != OWNER_TOWN || tile != 0);
362
363 if (owner == _current_company) return CommandCost();
364
365 CommandCost error{STR_ERROR_OWNED_BY};
366 if (IsLocalCompany()) {
367 auto params = GetParamsForOwnedBy(owner, tile);
368 error.SetEncodedMessage(GetEncodedStringWithArgs(STR_ERROR_OWNED_BY, params));
369 if (owner != OWNER_TOWN) error.SetErrorOwner(owner);
370 }
371 return error;
372}
373
382{
383 return CheckOwnership(GetTileOwner(tile), tile);
384}
385
391{
392 if (c->name_1 != STR_SV_UNNAMED) return;
393 if (c->last_build_coordinate == 0) return;
394
396
397 StringID str;
398 uint32_t strp;
399 std::string name;
400 if (t->name.empty() && IsInsideMM(t->townnametype, SPECSTR_TOWNNAME_START, SPECSTR_TOWNNAME_END)) {
401 str = t->townnametype - SPECSTR_TOWNNAME_START + SPECSTR_COMPANY_NAME_START;
402 strp = t->townnameparts;
403
404verify_name:;
405 /* No companies must have this name already */
406 for (const Company *cc : Company::Iterate()) {
407 if (cc->name_1 == str && cc->name_2 == strp) goto bad_town_name;
408 }
409
410 name = GetString(str, strp);
411 if (Utf8StringLength(name) >= MAX_LENGTH_COMPANY_NAME_CHARS) goto bad_town_name;
412
413set_name:;
414 c->name_1 = str;
415 c->name_2 = strp;
416
418 AI::BroadcastNewEvent(new ScriptEventCompanyRenamed(c->index, name));
419 Game::NewEvent(new ScriptEventCompanyRenamed(c->index, name));
420
421 if (c->is_ai) {
422 auto cni = std::make_unique<CompanyNewsInformation>(STR_NEWS_COMPANY_LAUNCH_TITLE, c);
423 EncodedString headline = GetEncodedString(STR_NEWS_COMPANY_LAUNCH_DESCRIPTION, cni->company_name, t->index);
424 AddNewsItem(std::move(headline),
426 }
427 return;
428 }
429bad_town_name:;
430
432 str = SPECSTR_ANDCO_NAME;
433 strp = c->president_name_2;
434 goto set_name;
435 } else {
436 str = SPECSTR_ANDCO_NAME;
437 strp = Random();
438 goto verify_name;
439 }
440}
441
443static const uint8_t _colour_sort[COLOUR_END] = {2, 2, 3, 2, 3, 2, 3, 2, 3, 2, 2, 2, 3, 1, 1, 1};
445static const Colours _similar_colour[COLOUR_END][2] = {
446 { COLOUR_BLUE, COLOUR_LIGHT_BLUE }, // COLOUR_DARK_BLUE
447 { COLOUR_GREEN, COLOUR_DARK_GREEN }, // COLOUR_PALE_GREEN
448 { INVALID_COLOUR, INVALID_COLOUR }, // COLOUR_PINK
449 { COLOUR_ORANGE, INVALID_COLOUR }, // COLOUR_YELLOW
450 { INVALID_COLOUR, INVALID_COLOUR }, // COLOUR_RED
451 { COLOUR_DARK_BLUE, COLOUR_BLUE }, // COLOUR_LIGHT_BLUE
452 { COLOUR_PALE_GREEN, COLOUR_DARK_GREEN }, // COLOUR_GREEN
453 { COLOUR_PALE_GREEN, COLOUR_GREEN }, // COLOUR_DARK_GREEN
454 { COLOUR_DARK_BLUE, COLOUR_LIGHT_BLUE }, // COLOUR_BLUE
455 { COLOUR_BROWN, COLOUR_ORANGE }, // COLOUR_CREAM
456 { COLOUR_PURPLE, INVALID_COLOUR }, // COLOUR_MAUVE
457 { COLOUR_MAUVE, INVALID_COLOUR }, // COLOUR_PURPLE
458 { COLOUR_YELLOW, COLOUR_CREAM }, // COLOUR_ORANGE
459 { COLOUR_CREAM, INVALID_COLOUR }, // COLOUR_BROWN
460 { COLOUR_WHITE, INVALID_COLOUR }, // COLOUR_GREY
461 { COLOUR_GREY, INVALID_COLOUR }, // COLOUR_WHITE
462};
463
468static Colours GenerateCompanyColour()
469{
470 Colours colours[COLOUR_END];
471
472 /* Initialize array */
473 for (uint i = 0; i < COLOUR_END; i++) colours[i] = static_cast<Colours>(i);
474
475 /* And randomize it */
476 for (uint i = 0; i < 100; i++) {
477 uint r = Random();
478 Swap(colours[GB(r, 0, 4)], colours[GB(r, 4, 4)]);
479 }
480
481 /* Bubble sort it according to the values in table 1 */
482 for (uint i = 0; i < COLOUR_END; i++) {
483 for (uint j = 1; j < COLOUR_END; j++) {
484 if (_colour_sort[colours[j - 1]] < _colour_sort[colours[j]]) {
485 Swap(colours[j - 1], colours[j]);
486 }
487 }
488 }
489
490 /* Move the colours that look similar to each company's colour to the side */
491 for (const Company *c : Company::Iterate()) {
492 Colours pcolour = c->colour;
493
494 for (uint i = 0; i < COLOUR_END; i++) {
495 if (colours[i] == pcolour) {
496 colours[i] = INVALID_COLOUR;
497 break;
498 }
499 }
500
501 for (uint j = 0; j < 2; j++) {
502 Colours similar = _similar_colour[pcolour][j];
503 if (similar == INVALID_COLOUR) break;
504
505 for (uint i = 1; i < COLOUR_END; i++) {
506 if (colours[i - 1] == similar) Swap(colours[i - 1], colours[i]);
507 }
508 }
509 }
510
511 /* Return the first available colour */
512 for (uint i = 0; i < COLOUR_END; i++) {
513 if (colours[i] != INVALID_COLOUR) return colours[i];
514 }
515
516 NOT_REACHED();
517}
518
524{
525 for (;;) {
526restart:;
529
530 /* Reserve space for extra unicode character. We need to do this to be able
531 * to detect too long president name. */
532 std::string name = GetString(STR_PRESIDENT_NAME, c->index);
534
535 for (const Company *cc : Company::Iterate()) {
536 if (c != cc) {
537 std::string other_name = GetString(STR_PRESIDENT_NAME, cc->index);
538 if (name == other_name) goto restart;
539 }
540 }
541 return;
542 }
543}
544
551{
552 for (LiveryScheme scheme = LS_BEGIN; scheme < LS_END; scheme++) {
553 c->livery[scheme].in_use = 0;
554 c->livery[scheme].colour1 = c->colour;
555 c->livery[scheme].colour2 = c->colour;
556 }
557
558 for (Group *g : Group::Iterate()) {
559 if (g->owner == c->index) {
560 g->livery.in_use = 0;
561 g->livery.colour1 = c->colour;
562 g->livery.colour2 = c->colour;
563 }
564 }
565}
566
574Company *DoStartupNewCompany(bool is_ai, CompanyID company = CompanyID::Invalid())
575{
576 if (!Company::CanAllocateItem()) return nullptr;
577
578 /* we have to generate colour before this company is valid */
579 Colours colour = GenerateCompanyColour();
580
581 Company *c;
582 if (company == CompanyID::Invalid()) {
583 c = new Company(STR_SV_UNNAMED, is_ai);
584 } else {
585 if (Company::IsValidID(company)) return nullptr;
586 c = new (company) Company(STR_SV_UNNAMED, is_ai);
587 }
588
589 c->colour = colour;
590
593
594 /* Scale the initial loan based on the inflation rounded down to the loan interval. The maximum loan has already been inflation adjusted. */
595 c->money = c->current_loan = std::min<int64_t>((INITIAL_LOAN * _economy.inflation_prices >> 16) / LOAN_INTERVAL * LOAN_INTERVAL, _economy.max_loan);
596
601
602 /* If starting a player company in singleplayer and a favorite company manager face is selected, choose it. Otherwise, use a random face.
603 * In a network game, we'll choose the favorite face later in CmdCompanyCtrl to sync it to all clients. */
604 if (_company_manager_face != 0 && !is_ai && !_networking) {
606 } else {
608 }
609
612
614
620
621 if (is_ai && (!_networking || _network_server)) AI::StartNew(c->index);
622
623 AI::BroadcastNewEvent(new ScriptEventCompanyNew(c->index), c->index);
624 Game::NewEvent(new ScriptEventCompanyNew(c->index));
625
626 return c;
627}
628
630TimeoutTimer<TimerGameTick> _new_competitor_timeout({ TimerGameTick::Priority::COMPETITOR_TIMEOUT, 0 }, []() {
631 if (_game_mode == GM_MENU || !AI::CanStartNew()) return;
634
635 /* count number of competitors */
636 uint8_t n = 0;
637 for (const Company *c : Company::Iterate()) {
638 if (c->is_ai) n++;
639 }
640
642
643 /* Send a command to all clients to start up a new AI.
644 * Works fine for Multiplayer and Singleplayer */
646});
647
650{
651 /* Ensure the timeout is aborted, so it doesn't fire based on information of the last game. */
653}
654
660
668{
669 const Company *c1 = Company::Get(cbig);
670 const Company *c2 = Company::Get(csmall);
671
672 /* Do the combined vehicle counts stay within the limits? */
673 return c1->group_all[VEH_TRAIN].num_vehicle + c2->group_all[VEH_TRAIN].num_vehicle <= _settings_game.vehicle.max_trains &&
674 c1->group_all[VEH_ROAD].num_vehicle + c2->group_all[VEH_ROAD].num_vehicle <= _settings_game.vehicle.max_roadveh &&
675 c1->group_all[VEH_SHIP].num_vehicle + c2->group_all[VEH_SHIP].num_vehicle <= _settings_game.vehicle.max_ships &&
676 c1->group_all[VEH_AIRCRAFT].num_vehicle + c2->group_all[VEH_AIRCRAFT].num_vehicle <= _settings_game.vehicle.max_aircraft;
677}
678
689{
690 /* Amount of time out for each company to take over a company;
691 * Timeout is a quarter (3 months of 30 days) divided over the
692 * number of companies. The minimum number of days in a quarter
693 * is 90: 31 in January, 28 in February and 31 in March.
694 * Note that the company going bankrupt can't buy itself. */
695 static const int TAKE_OVER_TIMEOUT = 3 * 30 * Ticks::DAY_TICKS / (MAX_COMPANIES - 1);
696
697 assert(c->bankrupt_asked.Any());
698
699 /* We're currently asking some company to buy 'us' */
700 if (c->bankrupt_timeout != 0) {
701 c->bankrupt_timeout -= MAX_COMPANIES;
702 if (c->bankrupt_timeout > 0) return;
703 c->bankrupt_timeout = 0;
704
705 return;
706 }
707
708 /* Did we ask everyone for bankruptcy? If so, bail out. */
709 if (c->bankrupt_asked.All()) return;
710
711 Company *best = nullptr;
712 int32_t best_performance = -1;
713
714 /* Ask the company with the highest performance history first */
715 for (Company *c2 : Company::Iterate()) {
716 if (c2->bankrupt_asked.None() && // Don't ask companies going bankrupt themselves
717 !c->bankrupt_asked.Test(c2->index) &&
718 best_performance < c2->old_economy[1].performance_history &&
719 CheckTakeoverVehicleLimit(c2->index, c->index)) {
720 best_performance = c2->old_economy[1].performance_history;
721 best = c2;
722 }
723 }
724
725 /* Asked all companies? */
726 if (best_performance == -1) {
727 c->bankrupt_asked.Set();
728 return;
729 }
730
731 c->bankrupt_asked.Set(best->index);
732
733 c->bankrupt_timeout = TAKE_OVER_TIMEOUT;
734
735 AI::NewEvent(best->index, new ScriptEventCompanyAskMerger(c->index, c->bankrupt_value));
736 if (IsInteractiveCompany(best->index)) {
737 ShowBuyCompanyDialog(c->index, false);
738 }
739}
740
743{
744 if (_game_mode == GM_EDITOR) return;
745
747 if (c != nullptr) {
748 if (c->name_1 != 0) GenerateCompanyName(c);
750 }
751
752 if (_new_competitor_timeout.HasFired() && _game_mode != GM_MENU && AI::CanStartNew()) {
754 /* If the interval is zero, start as many competitors as needed then check every ~10 minutes if a company went bankrupt and needs replacing. */
755 if (timeout == 0) {
756 /* count number of competitors */
757 uint8_t num_ais = 0;
758 for (const Company *cc : Company::Iterate()) {
759 if (cc->is_ai) num_ais++;
760 }
761
762 size_t num_companies = Company::GetNumItems();
763 for (auto i = 0; i < _settings_game.difficulty.max_no_competitors; i++) {
764 if (_networking && num_companies++ >= _settings_client.network.max_companies) break;
765 if (num_ais++ >= _settings_game.difficulty.max_no_competitors) break;
767 }
768 timeout = 10 * 60 * Ticks::TICKS_PER_SECOND;
769 }
770 /* Randomize a bit when the AI is actually going to start; ranges from 87.5% .. 112.5% of indicated value. */
771 timeout += ScriptObject::GetRandomizer(OWNER_NONE).Next(timeout / 4) - timeout / 8;
772
773 _new_competitor_timeout.Reset({ TimerGameTick::Priority::COMPETITOR_TIMEOUT, static_cast<uint>(std::max(1, timeout)) });
774 }
775
776 _cur_company_tick_index = (_cur_company_tick_index + 1) % MAX_COMPANIES;
777}
778
783static IntervalTimer<TimerGameEconomy> _economy_companies_yearly({TimerGameEconomy::YEAR, TimerGameEconomy::Priority::COMPANY}, [](auto)
784{
785 /* Copy statistics */
786 for (Company *c : Company::Iterate()) {
787 /* Move expenses to previous years. */
788 std::rotate(std::rbegin(c->yearly_expenses), std::rbegin(c->yearly_expenses) + 1, std::rend(c->yearly_expenses));
789 c->yearly_expenses[0] = {};
791 }
792
796 if (c->num_valid_stat_ent > 5 && c->old_economy[0].performance_history < c->old_economy[4].performance_history) {
798 } else {
800 }
801 }
802});
803
810{
811 this->company_name = GetString(STR_COMPANY_NAME, c->index);
812
813 if (other != nullptr) {
814 this->other_company_name = GetString(STR_COMPANY_NAME, other->index);
815 c = other;
816 }
817
818 this->president_name = GetString(STR_PRESIDENT_NAME_MANAGER, c->index);
819
820 this->title = title;
821 this->colour = c->colour;
822 this->face = c->face;
823
824}
825
830void CompanyAdminUpdate(const Company *company)
831{
833}
834
844
854{
856
857 switch (cca) {
858 case CCA_NEW: { // Create a new company
859 /* This command is only executed in a multiplayer game */
860 if (!_networking) return CMD_ERROR;
861
862 /* Has the network client a correct ClientID? */
863 if (!flags.Test(DoCommandFlag::Execute)) return CommandCost();
864
866
867 /* Delete multiplayer progress bar */
869
870 Company *c = DoStartupNewCompany(false);
871
872 /* A new company could not be created, revert to being a spectator */
873 if (c == nullptr) {
874 /* We check for "ci != nullptr" as a client could have left by
875 * the time we execute this command. */
876 if (_network_server && ci != nullptr) {
879 }
880 break;
881 }
882
885
886 /* This is the client (or non-dedicated server) who wants a new company */
887 if (client_id == _network_own_client_id) {
890
891 /*
892 * If a favorite company manager face is selected, choose it. Otherwise, use a random face.
893 * Because this needs to be synchronised over the network, only the client knows
894 * its configuration and we are currently in the execution of a command, we have
895 * to circumvent the normal ::Post logic for commands and just send the command.
896 */
898
899 /* Now that we have a new company, broadcast our company settings to
900 * all clients so everything is in sync */
902
904 }
905 break;
906 }
907
908 case CCA_NEW_AI: { // Make a new AI company
909 if (company_id != CompanyID::Invalid() && company_id >= MAX_COMPANIES) return CMD_ERROR;
910
911 /* For network games, company deletion is delayed. */
912 if (!_networking && company_id != CompanyID::Invalid() && Company::IsValidID(company_id)) return CMD_ERROR;
913
914 if (!flags.Test(DoCommandFlag::Execute)) return CommandCost();
915
916 /* For network game, just assume deletion happened. */
917 assert(company_id == CompanyID::Invalid() || !Company::IsValidID(company_id));
918
919 Company *c = DoStartupNewCompany(true, company_id);
920 if (c != nullptr) {
922 NetworkServerNewCompany(c, nullptr);
923 }
924 break;
925 }
926
927 case CCA_DELETE: { // Delete a company
928 if (reason >= CRR_END) return CMD_ERROR;
929
930 /* We can't delete the last existing company in singleplayer mode. */
931 if (!_networking && Company::GetNumItems() == 1) return CMD_ERROR;
932
933 Company *c = Company::GetIfValid(company_id);
934 if (c == nullptr) return CMD_ERROR;
935
936 if (!flags.Test(DoCommandFlag::Execute)) return CommandCost();
937
938 /* Show the bankrupt news */
939 auto cni = std::make_unique<CompanyNewsInformation>(STR_NEWS_COMPANY_BANKRUPT_TITLE, c);
940 EncodedString headline = GetEncodedString(STR_NEWS_COMPANY_BANKRUPT_DESCRIPTION, cni->company_name);
941 AddCompanyNewsItem(std::move(headline), std::move(cni));
942
943 /* Remove the company */
945 if (c->is_ai) AI::Stop(c->index);
946
947 CompanyID c_index = c->index;
948 delete c;
949 AI::BroadcastNewEvent(new ScriptEventCompanyBankrupt(c_index));
950 Game::NewEvent(new ScriptEventCompanyBankrupt(c_index));
951 CompanyAdminRemove(c_index, (CompanyRemoveReason)reason);
952
955
956 break;
957 }
958
959 default: return CMD_ERROR;
960 }
961
965
966 return CommandCost();
967}
968
969static bool ExecuteAllowListCtrlAction(CompanyAllowListCtrlAction action, Company *c, const std::string &public_key)
970{
971 switch (action) {
972 case CALCA_ADD:
973 return c->allow_list.Add(public_key);
974
975 case CALCA_REMOVE:
976 return c->allow_list.Remove(public_key);
977
978 default:
979 NOT_REACHED();
980 }
981}
982
991{
993 if (c == nullptr) return CMD_ERROR;
994
995 /* The public key length includes the '\0'. */
996 if (public_key.size() != NETWORK_PUBLIC_KEY_LENGTH - 1) return CMD_ERROR;
997
998 switch (action) {
999 case CALCA_ADD:
1000 case CALCA_REMOVE:
1001 break;
1002
1003 default:
1004 return CMD_ERROR;
1005 }
1006
1007 if (flags.Test(DoCommandFlag::Execute)) {
1008 if (ExecuteAllowListCtrlAction(action, c, public_key)) {
1011 }
1012 }
1013
1014 return CommandCost();
1015}
1016
1024{
1025 if (!IsValidCompanyManagerFace(cmf)) return CMD_ERROR;
1026
1027 if (flags.Test(DoCommandFlag::Execute)) {
1028 Company::Get(_current_company)->face = cmf;
1030 }
1031 return CommandCost();
1032}
1033
1040{
1041 for (int i = 1; i < LS_END; i++) {
1042 if (!HasBit(c->livery[i].in_use, 0)) c->livery[i].colour1 = c->livery[LS_DEFAULT].colour1;
1043 if (!HasBit(c->livery[i].in_use, 1)) c->livery[i].colour2 = c->livery[LS_DEFAULT].colour2;
1044 }
1046}
1047
1056CommandCost CmdSetCompanyColour(DoCommandFlags flags, LiveryScheme scheme, bool primary, Colours colour)
1057{
1058 if (scheme >= LS_END || (colour >= COLOUR_END && colour != INVALID_COLOUR)) return CMD_ERROR;
1059
1060 /* Default scheme can't be reset to invalid. */
1061 if (scheme == LS_DEFAULT && colour == INVALID_COLOUR) return CMD_ERROR;
1062
1064
1065 /* Ensure no two companies have the same primary colour */
1066 if (scheme == LS_DEFAULT && primary) {
1067 for (const Company *cc : Company::Iterate()) {
1068 if (cc != c && cc->colour == colour) return CMD_ERROR;
1069 }
1070 }
1071
1072 if (flags.Test(DoCommandFlag::Execute)) {
1073 if (primary) {
1074 if (scheme != LS_DEFAULT) AssignBit(c->livery[scheme].in_use, 0, colour != INVALID_COLOUR);
1075 if (colour == INVALID_COLOUR) colour = c->livery[LS_DEFAULT].colour1;
1076 c->livery[scheme].colour1 = colour;
1077
1078 /* If setting the first colour of the default scheme, adjust the
1079 * original and cached company colours too. */
1080 if (scheme == LS_DEFAULT) {
1083 c->colour = colour;
1085 }
1086 } else {
1087 if (scheme != LS_DEFAULT) AssignBit(c->livery[scheme].in_use, 1, colour != INVALID_COLOUR);
1088 if (colour == INVALID_COLOUR) colour = c->livery[LS_DEFAULT].colour2;
1089 c->livery[scheme].colour2 = colour;
1090
1091 if (scheme == LS_DEFAULT) {
1093 }
1094 }
1095
1096 if (c->livery[scheme].in_use != 0) {
1097 /* If enabling a scheme, set the default scheme to be in use too */
1098 c->livery[LS_DEFAULT].in_use = 1;
1099 } else {
1100 /* Else loop through all schemes to see if any are left enabled.
1101 * If not, disable the default scheme too. */
1102 c->livery[LS_DEFAULT].in_use = 0;
1103 for (scheme = LS_DEFAULT; scheme < LS_END; scheme++) {
1104 if (c->livery[scheme].in_use != 0) {
1105 c->livery[LS_DEFAULT].in_use = 1;
1106 break;
1107 }
1108 }
1109 }
1110
1111 ResetVehicleColourMap();
1113
1114 /* All graph related to companies use the company colour. */
1121 /* The smallmap owner view also stores the company colours. */
1124
1125 /* Company colour data is indirectly cached. */
1126 for (Vehicle *v : Vehicle::Iterate()) {
1127 if (v->owner == _current_company) v->InvalidateNewGRFCache();
1128 }
1129
1131 }
1132 return CommandCost();
1133}
1134
1140static bool IsUniqueCompanyName(const std::string &name)
1141{
1142 for (const Company *c : Company::Iterate()) {
1143 if (!c->name.empty() && c->name == name) return false;
1144 }
1145
1146 return true;
1147}
1148
1155CommandCost CmdRenameCompany(DoCommandFlags flags, const std::string &text)
1156{
1157 bool reset = text.empty();
1158
1159 if (!reset) {
1161 if (!IsUniqueCompanyName(text)) return CommandCost(STR_ERROR_NAME_MUST_BE_UNIQUE);
1162 }
1163
1164 if (flags.Test(DoCommandFlag::Execute)) {
1166 if (reset) {
1167 c->name.clear();
1168 } else {
1169 c->name = text;
1170 }
1173
1174 std::string new_name = GetString(STR_COMPANY_NAME, c->index);
1175 AI::BroadcastNewEvent(new ScriptEventCompanyRenamed(c->index, new_name));
1176 Game::NewEvent(new ScriptEventCompanyRenamed(c->index, new_name));
1177 }
1178
1179 return CommandCost();
1180}
1181
1187static bool IsUniquePresidentName(const std::string &name)
1188{
1189 for (const Company *c : Company::Iterate()) {
1190 if (!c->president_name.empty() && c->president_name == name) return false;
1191 }
1192
1193 return true;
1194}
1195
1202CommandCost CmdRenamePresident(DoCommandFlags flags, const std::string &text)
1203{
1204 bool reset = text.empty();
1205
1206 if (!reset) {
1208 if (!IsUniquePresidentName(text)) return CommandCost(STR_ERROR_NAME_MUST_BE_UNIQUE);
1209 }
1210
1211 if (flags.Test(DoCommandFlag::Execute)) {
1213
1214 if (reset) {
1215 c->president_name.clear();
1216 } else {
1217 c->president_name = text;
1218
1219 if (c->name_1 == STR_SV_UNNAMED && c->name.empty()) {
1221 }
1222 }
1223
1227
1228 std::string new_name = GetString(STR_PRESIDENT_NAME, c->index);
1229 AI::BroadcastNewEvent(new ScriptEventPresidentRenamed(c->index, new_name));
1230 Game::NewEvent(new ScriptEventPresidentRenamed(c->index, new_name));
1231 }
1232
1233 return CommandCost();
1234}
1235
1243{
1244 const VehicleDefaultSettings *vds = (c == nullptr) ? &_settings_client.company.vehicle : &c->settings.vehicle;
1245 switch (type) {
1246 default: NOT_REACHED();
1247 case VEH_TRAIN: return vds->servint_trains;
1248 case VEH_ROAD: return vds->servint_roadveh;
1249 case VEH_AIRCRAFT: return vds->servint_aircraft;
1250 case VEH_SHIP: return vds->servint_ships;
1251 }
1252}
1253
1259{
1260 uint32_t total = 0;
1261 for (RoadType rt = ROADTYPE_BEGIN; rt != ROADTYPE_END; rt++) {
1262 if (RoadTypeIsRoad(rt)) total += this->road[rt];
1263 }
1264 return total;
1265}
1266
1272{
1273 uint32_t total = 0;
1274 for (RoadType rt = ROADTYPE_BEGIN; rt != ROADTYPE_END; rt++) {
1275 if (RoadTypeIsTram(rt)) total += this->road[rt];
1276 }
1277 return total;
1278}
1279
1291{
1293
1295 CommandCost amount(EXPENSES_OTHER, std::min<Money>(money, 20000000LL));
1296
1297 /* You can only transfer funds that is in excess of your loan */
1298 if (c->money - c->current_loan < amount.GetCost() || amount.GetCost() < 0) return CommandCost(STR_ERROR_INSUFFICIENT_FUNDS);
1299 if (!Company::IsValidID(dest_company)) return CMD_ERROR;
1300
1301 if (flags.Test(DoCommandFlag::Execute)) {
1302 /* Add money to company */
1303 Backup<CompanyID> cur_company(_current_company, dest_company);
1305 cur_company.Restore();
1306
1307 if (_networking) {
1308 std::string dest_company_name = GetString(STR_COMPANY_NAME, dest_company);
1309 std::string from_company_name = GetString(STR_COMPANY_NAME, _current_company);
1310
1311 NetworkTextMessage(NETWORK_ACTION_GIVE_MONEY, GetDrawStringCompanyColour(_current_company), false, from_company_name, dest_company_name, amount.GetCost());
1312 }
1313 }
1314
1315 /* Subtract money from local-company */
1316 return amount;
1317}
1318
1329{
1330 for (Company *c : Company::Iterate()) {
1331 if (Company::IsHumanID(c->index)) {
1332 return c->index;
1333 }
1334 }
1335
1337 for (CompanyID c = CompanyID::Begin(); c < MAX_COMPANIES; ++c) {
1338 if (!Company::IsValidID(c)) {
1339 return c;
1340 }
1341 }
1342 }
1343
1344 return CompanyID::Begin();
1345}
Base functions for all AIs.
AIConfig stores the configuration settings of every AI.
The AIInstance tracks an AI.
Class for backupping variables and making sure they are restored later.
debug_inline constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
constexpr T AssignBit(T &x, const uint8_t y, bool value)
Assigns a bit in a variable.
debug_inline static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
static void BroadcastNewEvent(ScriptEvent *event, CompanyID skip_company=CompanyID::Invalid())
Broadcast a new event to all active AIs.
Definition ai_core.cpp:263
static bool CanStartNew()
Is it possible to start a new AI company?
Definition ai_core.cpp:30
static void StartNew(CompanyID company)
Start a new AI company.
Definition ai_core.cpp:36
static void Stop(CompanyID company)
Stop a company to be controlled by an AI.
Definition ai_core.cpp:107
static void NewEvent(CompanyID company, ScriptEvent *event)
Queue a new event for an AI.
Definition ai_core.cpp:243
constexpr bool All(const Timpl &other) const
Test if all of the values are set.
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
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.
ExpensesType GetExpensesType() const
The expense type of the cost.
void MakeError(StringID message)
Makes this CommandCost behave like an error command.
Money GetCost() const
The costs as made up to this moment.
static void SetEncodedMessage(EncodedString &&message)
Set the encoded message string.
Container for an encoded string, created by GetEncodedString.
Enum-as-bit-set wrapper.
static void NewEvent(class ScriptEvent *event)
Queue a new event for a Game Script.
An interval timer will fire every interval, and will continue to fire until it is deleted.
Definition timer.h:76
bool Add(std::string_view key)
Add the given key to the authorized keys, when it is not already contained.
Definition network.cpp:188
bool Remove(std::string_view key)
Remove the given key from the authorized keys, when it is exists.
Definition network.cpp:204
A sort-of mixin that adds 'at(pos)' and 'operator[](pos)' implementations for 'ConvertibleThroughBase...
static constexpr TimerGameTick::Ticks DAY_TICKS
1 day is 74 ticks; TimerGameCalendar::date_fract used to be uint16_t and incremented by 885.
static constexpr TimerGameTick::Ticks TICKS_PER_SECOND
Estimation of how many ticks fit in a single second.
A timeout timer will fire once after the interval.
Definition timer.h:116
void Abort()
Abort the timer so it doesn't fire if it hasn't yet.
Definition timer.h:161
static Year year
Current year, starting at 0.
static Year year
Current year, starting at 0.
Functions related to commands.
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
@ Execute
execute the given command
Definition of stuff that is very close to a company, like the company struct itself.
void ClearEnginesHiddenFlagOfCompany(CompanyID cid)
Clear the 'hidden' flag for all engines of a new company.
Definition engine.cpp:1005
void UpdateObjectColours(const Company *c)
Updates the colour of the object whenever a company changes.
TimeoutTimer< TimerGameTick > _new_competitor_timeout({ TimerGameTick::Priority::COMPETITOR_TIMEOUT, 0 }, []() { if(_game_mode==GM_MENU||!AI::CanStartNew()) return;if(_networking &&Company::GetNumItems() >=_settings_client.network.max_companies) return;if(_settings_game.difficulty.competitors_interval==0) return;uint8_t n=0;for(const Company *c :Company::Iterate()) { if(c->is_ai) n++;} if(n >=_settings_game.difficulty.max_no_competitors) return;Command< CMD_COMPANY_CTRL >::Post(CCA_NEW_AI, CompanyID::Invalid(), CRR_NONE, INVALID_CLIENT_ID);})
Start a new competitor company if possible.
static void GenerateCompanyName(Company *c)
Generate the name of a company from the last build coordinate.
static bool IsValidCompanyManagerFace(CompanyManagerFace cmf)
Checks whether a company manager's face is a valid encoding.
void OnTick_Companies()
Called every tick for updating some company info.
static IntervalTimer< TimerGameEconomy > _economy_companies_yearly({TimerGameEconomy::YEAR, TimerGameEconomy::Priority::COMPANY}, [](auto) { for(Company *c :Company::Iterate()) { std::rotate(std::rbegin(c->yearly_expenses), std::rbegin(c->yearly_expenses)+1, std::rend(c->yearly_expenses));c->yearly_expenses[0]={};InvalidateWindowData(WC_FINANCES, c->index);} if(_settings_client.gui.show_finances &&_local_company !=COMPANY_SPECTATOR) { ShowCompanyFinances(_local_company);Company *c=Company::Get(_local_company);if(c->num_valid_stat_ent > 5 &&c->old_economy[0].performance_history< c->old_economy[4].performance_history) { if(_settings_client.sound.new_year) SndPlayFx(SND_01_BAD_YEAR);} else { if(_settings_client.sound.new_year) SndPlayFx(SND_00_GOOD_YEAR);} } })
A year has passed, update the economic data of all companies, and perhaps show the financial overview...
static void SubtractMoneyFromAnyCompany(Company *c, const CommandCost &cost)
Deduct costs of a command from the money of a company.
std::array< StringParameter, 2 > GetParamsForOwnedBy(Owner owner, TileIndex tile)
Set the right DParams for STR_ERROR_OWNED_BY.
CommandCost CmdCompanyAllowListCtrl(DoCommandFlags flags, CompanyAllowListCtrlAction action, const std::string &public_key)
Add or remove the given public key to the allow list of this company.
Company * DoStartupNewCompany(bool is_ai, CompanyID company=CompanyID::Invalid())
Create a new company and sets all company variables default values.
void DrawCompanyIcon(CompanyID c, int x, int y)
Draw the icon of a company.
static Colours GenerateCompanyColour()
Generate a company colour.
static void GeneratePresidentName(Company *c)
Generate a random president name of a company.
static const Colours _similar_colour[COLOUR_END][2]
Similar colours, so we can try to prevent same coloured companies.
void ResetCompanyLivery(Company *c)
Reset the livery schemes to the company's primary colour.
void UpdateCompanyLiveries(Company *c)
Update liveries for a company.
CommandCost CheckTileOwnership(TileIndex tile)
Check whether the current owner owns the stuff on the given tile.
CommandCost CmdSetCompanyColour(DoCommandFlags flags, LiveryScheme scheme, bool primary, Colours colour)
Change the company's company-colour.
CommandCost CmdSetCompanyManagerFace(DoCommandFlags flags, CompanyManagerFace cmf)
Change the company manager's face.
CommandCost CmdCompanyCtrl(DoCommandFlags flags, CompanyCtrlAction cca, CompanyID company_id, CompanyRemoveReason reason, ClientID client_id)
Control the companies: add, delete, etc.
void InvalidateCompanyWindows(const Company *company)
Refresh all windows owned by a company.
int CompanyServiceInterval(const Company *c, VehicleType type)
Get the service interval for the given company and vehicle type.
bool CheckCompanyHasMoney(CommandCost &cost)
Verify whether the company can pay the bill.
CompanyID GetFirstPlayableCompanyID()
Get the index of the first available company.
TextColour GetDrawStringCompanyColour(CompanyID company)
Get the colour for DrawString-subroutines which matches the colour of the company.
Money GetAvailableMoneyForCommand()
This functions returns the money which can be used to execute a command.
void CompanyAdminUpdate(const Company *company)
Called whenever company related information changes in order to notify admins.
CommandCost CheckOwnership(Owner owner, TileIndex tile)
Check whether the current owner owns something.
void CompanyAdminRemove(CompanyID company_id, CompanyRemoveReason reason)
Called whenever a company is removed in order to notify admins.
ReferenceThroughBaseContainer< std::array< Colours, MAX_COMPANIES > > _company_colours
NOSAVE: can be determined from company structs.
CommandCost CmdRenamePresident(DoCommandFlags flags, const std::string &text)
Change the name of the president.
void SubtractMoneyFromCompany(const CommandCost &cost)
Subtract money from the _current_company, if the company is valid.
CompanyPool _company_pool("Company")
Pool of companies.
Money GetAvailableMoney(CompanyID company)
Get the amount of money that a company has available, or INT64_MAX if there is no such valid company.
void UpdateLandscapingLimits()
Update the landscaping limits per company.
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
void InitializeCompanies()
Initialize the pool of companies.
uint _cur_company_tick_index
used to generate a name for one company that doesn't have a name yet per tick
void StartupCompanies()
Start of a new game.
bool CheckTakeoverVehicleLimit(CompanyID cbig, CompanyID csmall)
Can company cbig buy company csmall without exceeding vehicle limits?
CompanyManagerFace _company_manager_face
for company manager face storage in openttd.cfg
static bool IsUniqueCompanyName(const std::string &name)
Is the given name in use as name of a company?
void SetLocalCompany(CompanyID new_company)
Sets the local company and updates the settings that are set on a per-company basis to reflect the co...
static bool IsUniquePresidentName(const std::string &name)
Is the given name in use as president name of a company?
CompanyID _current_company
Company currently doing an action.
CommandCost CmdGiveMoney(DoCommandFlags flags, Money money, CompanyID dest_company)
Transfer funds (money) from one company to another.
static void HandleBankruptcyTakeover(Company *c)
Handle the bankruptcy take over of a company.
CommandCost CmdRenameCompany(DoCommandFlags flags, const std::string &text)
Change the name of the company.
void SubtractMoneyFromCompanyFract(CompanyID company, const CommandCost &cst)
Subtract money from a company, including the money fraction.
static const uint8_t _colour_sort[COLOUR_END]
Sorting weights for the company colours.
Command definitions related to companies.
Functions related to companies.
bool IsInteractiveCompany(CompanyID company)
Is the user representing company?
void ChangeOwnershipOfCompanyItems(Owner old_owner, Owner new_owner)
Change the ownership of all the items of a company.
Definition economy.cpp:322
void ShowBuyCompanyDialog(CompanyID company, bool hostile_takeover)
Show the query to buy another company.
bool IsLocalCompany()
Is the current company the local company?
void ShowCompanyFinances(CompanyID company)
Open the finances window of a company.
GUI Functions related to companies.
void CloseCompanyWindows(CompanyID company)
Close all windows of a company.
Definition window.cpp:1171
Functionality related to the company manager's face.
uint GetCompanyManagerFaceBits(CompanyManagerFace cmf, CompanyManagerFaceVariable cmfv, GenderEthnicity ge)
Make sure the table's size is right.
GenderEthnicity
The gender/race combinations that we have faces for.
@ GE_WM
A male of Caucasian origin (white)
@ GENDER_FEMALE
This bit set means a female, otherwise male.
void RandomCompanyManagerFaceBits(CompanyManagerFace &cmf, GenderEthnicity ge, bool adv, Randomizer &randomizer)
Make a random new face.
CompanyManagerFaceVariable
Bitgroups of the CompanyManagerFace variable.
bool AreCompanyManagerFaceBitsValid(CompanyManagerFace cmf, CompanyManagerFaceVariable cmfv, GenderEthnicity ge)
Checks whether the company manager's face bits have a valid range.
static const uint MAX_LENGTH_PRESIDENT_NAME_CHARS
The maximum length of a president name in characters including '\0'.
static const uint MAX_LENGTH_COMPANY_NAME_CHARS
The maximum length of a company name in characters including '\0'.
CompanyCtrlAction
The action to do with CMD_COMPANY_CTRL.
@ CCA_NEW_AI
Create a new AI company.
@ CCA_DELETE
Delete a company.
@ CCA_NEW
Create a new company.
static constexpr CompanyID COMPANY_SPECTATOR
The client is spectating.
static constexpr Owner OWNER_END
Last + 1 owner.
CompanyAllowListCtrlAction
The action to do with CMD_COMPANY_ALLOW_LIST_CTRL.
@ CALCA_REMOVE
Remove a public key.
@ CALCA_ADD
Create a public key.
static constexpr Owner OWNER_TOWN
A town owns the tile, or a town is expanding.
uint32_t CompanyManagerFace
Company manager face bits, info see in company_manager_face.h.
static constexpr Owner OWNER_NONE
The tile has no ownership.
static constexpr Owner INVALID_OWNER
An invalid owner.
CompanyRemoveReason
The reason why the company was removed.
@ CRR_END
Sentinel for end.
@ CRR_NONE
Dummy reason for actions that don't need one.
static const uint NETWORK_PUBLIC_KEY_LENGTH
The maximum length of the hexadecimal encoded public keys, in bytes including '\0'.
Definition config.h:101
@ EXPENSES_ROADVEH_RUN
Running costs road vehicles.
@ EXPENSES_TRAIN_RUN
Running costs trains.
@ EXPENSES_AIRCRAFT_REVENUE
Revenue from aircraft.
@ EXPENSES_AIRCRAFT_RUN
Running costs aircraft.
@ EXPENSES_ROADVEH_REVENUE
Revenue from road vehicles.
@ EXPENSES_PROPERTY
Property costs.
@ EXPENSES_OTHER
Other expenses.
@ EXPENSES_SHIP_REVENUE
Revenue from ships.
@ EXPENSES_LOAN_INTEREST
Interest payments over the loan.
@ EXPENSES_TRAIN_REVENUE
Revenue from trains.
@ EXPENSES_SHIP_RUN
Running costs ships.
@ INVALID_EXPENSES
Invalid expense type.
static const int LOAN_INTERVAL
The "steps" in loan size, in British Pounds!
static const int64_t INITIAL_LOAN
The size of loan for a new company, in British Pounds!
Base functions for all Games.
void DrawSprite(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub, ZoomLevel zoom)
Draw a sprite, not in a viewport.
Definition gfx.cpp:989
TextColour
Colour of the strings, see _string_colourmap in table/string_colours.h or docs/ottd-colourtext-palett...
Definition gfx_type.h:294
@ TC_IS_PALETTE_COLOUR
Colour value is already a real palette colour index, not an index of a StringColour.
Definition gfx_type.h:317
Goal base class.
void UpdateCompanyGroupLiveries(const Company *c)
Update group liveries for a company.
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition gfx.cpp:1500
@ Random
Randomise borders.
LiveryScheme
List of different livery schemes.
Definition livery.h:21
constexpr bool IsInsideMM(const size_t x, const size_t min, const size_t max) noexcept
Checks if a value is in an interval.
constexpr void Swap(T &a, T &b)
Type safe swap operation.
bool _networking
are we in networking mode?
Definition network.cpp:65
bool _network_server
network-server is active
Definition network.cpp:66
ClientID _network_own_client_id
Our client identifier.
Definition network.cpp:70
Basic functions/variables used all over the place.
void NetworkAdminCompanyUpdate(const Company *company)
Notify the admin network of company updates.
void NetworkAdminCompanyNew(const Company *company)
Notify the admin network of a new company.
void NetworkAdminCompanyRemove(CompanyID company_id, AdminCompanyRemoveReason bcrr)
Notify the admin network of a company to be removed (including the reason why).
Server part of the admin network protocol.
Base core network types and some helper functions to access them.
Network functions used by other parts of OpenTTD.
void NetworkServerNewCompany(const Company *company, NetworkClientInfo *ci)
Perform all the server specific administration of a new company.
void NetworkUpdateClientInfo(ClientID client_id)
Send updated client info of a particular client.
@ DESTTYPE_TEAM
Send message/notice to everyone playing the same company (Team)
ClientID
'Unique' identifier to be given to clients
@ INVALID_CLIENT_ID
Client is not part of anything.
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:902
@ CompanyInfo
Company info (new companies, bankruptcy messages)
@ Company
Company news item. (Newspaper with face)
uint8_t GetColourGradient(Colours colour, ColourShade shade)
Get colour gradient palette index.
Definition palette.cpp:387
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.
RailTypes GetCompanyRailTypes(CompanyID company, bool introduces)
Get the rail types the given company can build.
Definition rail.cpp:251
Rail specific functions.
Randomizer _random
Random used in the game state calculations.
RoadTypes GetCompanyRoadTypes(CompanyID company, bool introduces)
Get the road types the given company can build.
Definition road.cpp:199
RoadType
The different roadtypes we support.
Definition road_type.h:25
@ ROADTYPE_END
Used for iterations.
Definition road_type.h:29
@ ROADTYPE_BEGIN
Used for iterations.
Definition road_type.h:26
A number of safeguards to prevent using unsafe methods.
void SyncCompanySettings()
Sync all company settings in a multiplayer game.
void SetDefaultCompanySettings(CompanyID cid)
Set the company settings for a new company to their default values.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition settings.cpp:58
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:57
Functions related to setting/changing the settings.
void BuildOwnerLegend()
Completes the array for the owned property legend.
Smallmap GUI functions.
Functions related to sound.
@ SND_01_BAD_YEAR
40 == 0x28 New year: performance declined
Definition sound_type.h:87
@ SND_00_GOOD_YEAR
39 == 0x27 New year: performance improved
Definition sound_type.h:86
Types related to the statusbar widgets.
@ WID_S_RIGHT
Right part; bank balance.
Definition of base types and functions in a cross-platform compatible way.
StoryPage base class.
size_t Utf8StringLength(const char *s)
Get the length of an UTF-8 encoded string in number of characters and thus not the number of bytes th...
Definition string.cpp:377
EncodedString GetEncodedStringWithArgs(StringID str, std::span< const StringParameter > params)
Encode a string with its parameters into an encoded string.
Definition strings.cpp:102
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Definition strings.cpp:90
std::string GetString(StringID string)
Resolve the given StringID into a std::string with formatting but no parameters.
Definition strings.cpp:426
Functions related to OTTD's strings.
uint32_t StringID
Numeric value that represents a string, independent of the selected language.
static constexpr StringID SPECSTR_COMPANY_NAME_START
Special strings for company names on the form "TownName transport".
static constexpr StringID SPECSTR_ANDCO_NAME
Special string for Surname & Co company names.
static constexpr StringID SPECSTR_PRESIDENT_NAME
Special string for the president's name.
static constexpr StringID SPECSTR_TOWNNAME_START
Special strings for town names.
Class to backup a specific variable and restore it later.
void Restore()
Restore the variable.
CompanySettings company
default values for per-company settings
NetworkSettings network
settings related to the network
SoundSettings sound
sound effect settings
GUISettings gui
settings related to the GUI
Money income
The amount of income.
Money expenses
The amount of expenses.
std::array< uint32_t, ROADTYPE_END > road
Count of company owned track bits for each road type.
uint32_t GetRoadTotal() const
Get total sum of all owned road bits.
uint32_t GetTramTotal() const
Get total sum of all owned tram bits.
uint32_t face
The face of the president.
Definition news_type.h:167
Colours colour
The colour related to the company.
Definition news_type.h:168
CompanyNewsInformation(StringID title, const struct Company *c, const struct Company *other=nullptr)
Fill the CompanyNewsInformation struct with the required data.
std::string president_name
The name of the president.
Definition news_type.h:163
std::string company_name
The name of the company.
Definition news_type.h:162
std::string other_company_name
The name of the company taking over this one.
Definition news_type.h:164
CompanyMask bankrupt_asked
which companies were asked about buying it?
std::string president_name
Name of the president if the user changed 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
NetworkAuthorizedKeys allow_list
Public keys of clients that are allowed to join this company.
uint32_t name_2
Parameter of name_1.
uint8_t money_fraction
Fraction of money of the company, too small to represent in money.
bool is_ai
If true, the company is (also) controlled by the computer (a NoAI program).
uint32_t president_name_2
Parameter of president_name_1.
StringID name_1
Name of the company if the user did not change it.
Money current_loan
Amount of money borrowed from the bank.
TimerGameCalendar::Year inaugurated_year_calendar
Calendar year of starting the company. Used to display proper Inauguration year while in wallclock mo...
TimerGameEconomy::Year inaugurated_year
Economy year of starting the company.
CompanyEconomyEntry cur_economy
Economic data of the company of this quarter.
Colours colour
Company colour.
std::array< CompanyEconomyEntry, MAX_HISTORY_QUARTERS > old_economy
Economic data of the company of the last MAX_HISTORY_QUARTERS quarters.
CompanyManagerFace face
Face description of the president.
Money max_loan
Max allowed amount of the loan or COMPANY_MAX_LOAN_DEFAULT.
std::array< Expenses, 3 > yearly_expenses
Expenses of the company for the last three years.
TileIndex last_build_coordinate
Coordinate of the last build thing by this company.
StringID president_name_1
Name of the president if the user did not change it.
std::string name
Name of the company if the user changed it.
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.
static bool IsHumanID(auto index)
Is this company a company not controlled by a NoAI program?
std::array< GroupStatistics, VEH_COMPANY_END > group_all
NOSAVE: Statistics for the ALL_GROUP group.
RoadTypes avail_roadtypes
Road types available to this company.
~Company()
Destructor.
RailTypes avail_railtypes
Rail types available to this company.
static void PostDestructor(size_t index)
Invalidating some stuff after removing item from the pool.
uint32_t clear_per_64k_frames
how many tiles may, over a long period, be cleared per 65536 frames?
uint32_t tree_per_64k_frames
how many trees may, over a long period, be planted per 65536 frames?
uint16_t terraform_frame_burst
how many tile heights may, over a short period, be terraformed?
uint16_t tree_frame_burst
how many trees may, over a short period, be planted?
uint16_t build_object_frame_burst
how many tiles may, over a short period, be purchased or have objects built on them?
uint32_t build_object_per_64k_frames
how many tiles may, over a long period, be purchased or have objects built on them per 65536 frames?
uint32_t terraform_per_64k_frames
how many tile heights may, over a long period, be terraformed per 65536 frames?
uint16_t clear_frame_burst
how many tiles may, over a short period, be cleared?
uint8_t max_no_competitors
the number of competitors (AIs)
bool infinite_money
whether spending money despite negative balance is allowed
uint16_t competitors_interval
the interval (in minutes) between adding competitors
bool give_money
allow giving other companies money
uint64_t inflation_prices
Cumulated inflation of prices since game start; 16 bit fractional part.
Money max_loan
NOSAVE: Maximum possible loan.
bool show_finances
show finances at end of year
EconomySettings economy
settings to change the economy
ConstructionSettings construction
construction of things in-game
DifficultySettings difficulty
settings related to the difficulty
VehicleSettings vehicle
options for vehicles
Group data.
Definition group.h:72
Container for all information known about a client.
static NetworkClientInfo * GetByClientID(ClientID client_id)
Return the CI given it's client-identifier.
Definition network.cpp:116
CompanyID client_playas
As which company is this client playing (CompanyID)
ClientID client_id
Client identifier (same as ClientState->client_id)
uint8_t max_companies
maximum amount of companies
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
static Titem * Get(auto index)
Returns Titem with given index.
static size_t GetNumItems()
Returns number of valid items in the pool.
Tindex index
Index of this pool item.
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function()
static bool IsValidID(auto index)
Tests whether given index can be used to get valid (non-nullptr) Titem.
static bool CleaningPool()
Returns current state of pool cleaning - yes or no.
static Titem * GetIfValid(auto index)
Returns Titem with given index.
Base class for all pools.
bool new_year
Play sound on new year, summarising the performance during the last year.
Town data structure.
Definition town.h:52
std::string name
Custom town name. If empty, the town was not renamed and uses the generated name.
Definition town.h:61
Default settings for vehicles.
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
uint16_t servint_trains
service interval for trains
UnitID max_ships
max ships in game per company
UnitID max_trains
max trains in game per company
UnitID max_aircraft
max planes in game per company
UnitID max_roadveh
max trucks in game per company
Vehicle data structure.
AdminCompanyRemoveReason
Reasons for removing a company - communicated to admins.
Definition tcp_admin.h:108
Owner GetTileOwner(Tile tile)
Returns the owner of a tile.
Definition tile_map.h:178
Definition of Interval and OneShot timers.
Definition of the game-economy-timer.
Definition of the tick-based game-timer.
Base of the town class.
Town * ClosestTownFromTile(TileIndex tile, uint threshold)
Return the town closest (in distance or ownership) to a given tile, within a given threshold.
Base class for all vehicles.
Functions related to vehicles.
VehicleType
Available vehicle types.
@ VEH_ROAD
Road vehicle type.
@ VEH_AIRCRAFT
Aircraft vehicle type.
@ VEH_SHIP
Ship vehicle type.
@ VEH_TRAIN
Train vehicle type.
void CloseConstructionWindows()
Close all windows that are used for construction of vehicle etc.
Definition window.cpp:3310
void CloseWindowById(WindowClass cls, WindowNumber number, bool force, int data)
Close a window by its class and window number (if it is open).
Definition window.cpp:1143
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:3224
void SetWindowWidgetDirty(WindowClass cls, WindowNumber number, WidgetID widget_index)
Mark a particular widget in a particular window as dirty (in need of repainting)
Definition window.cpp:3119
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition window.cpp:3106
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:3241
Window functions not directly related to making/drawing windows.
@ WN_NETWORK_STATUS_WINDOW_JOIN
Network join status.
Definition window_type.h:41
@ WC_PERFORMANCE_HISTORY
Performance history graph; Window numbers:
@ WC_COMPANY_LEAGUE
Company league window; Window numbers:
@ WC_SIGN_LIST
Sign list; Window numbers:
@ WC_PERFORMANCE_DETAIL
Performance detail window; Window numbers:
@ WC_GRAPH_LEGEND
Legend for graphs; Window numbers:
@ WC_LINKGRAPH_LEGEND
Linkgraph legend; Window numbers:
@ WC_STATUS_BAR
Statusbar (at the bottom of your screen); Window numbers:
Definition window_type.h:66
@ WC_SEND_NETWORK_MSG
Chatbox; Window numbers:
@ WC_ERRMSG
Error message; Window numbers:
@ WC_SCRIPT_SETTINGS
Script settings; Window numbers:
@ WC_SCRIPT_LIST
Scripts list; Window numbers:
@ WC_GOALS_LIST
Goals list; Window numbers:
@ WC_OPERATING_PROFIT
Operating profit graph; Window numbers:
@ WC_CLIENT_LIST
Client list; Window numbers:
@ WC_GAME_OPTIONS
Game options window; Window numbers:
@ WC_FINANCES
Finances of a company; Window numbers:
@ WC_INCOME_GRAPH
Income graph; Window numbers:
@ WC_SMALLMAP
Small map; Window numbers:
@ WC_DELIVERED_CARGO
Delivered cargo graph; Window numbers:
@ WC_COMPANY_VALUE
Company value graph; Window numbers:
@ WC_MAIN_TOOLBAR
Main toolbar (the long bar at the top); Window numbers:
Definition window_type.h:60
@ WC_COMPANY
Company view; Window numbers:
@ WC_NETWORK_STATUS_WINDOW
Network status window; Window numbers: