Doc: Clarify comment that SND_05_TRAIN_THROUGH_TUNNEL is only for steam engines ...
[openttd-github.git] / src / company_cmd.cpp
blobab9e7e12ef21c119657bfb3a9dca363d84c0d607
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 */
8 /** @file company_cmd.cpp Handling of companies. */
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 "cmd_helper.h"
18 #include "command_func.h"
19 #include "network/network.h"
20 #include "network/network_func.h"
21 #include "network/network_base.h"
22 #include "network/network_admin.h"
23 #include "ai/ai.hpp"
24 #include "company_manager_face.h"
25 #include "window_func.h"
26 #include "strings_func.h"
27 #include "date_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 "widgets/statusbar_widget.h"
40 #include "table/strings.h"
42 #include "safeguards.h"
44 void ClearEnginesHiddenFlagOfCompany(CompanyID cid);
46 CompanyID _local_company; ///< Company controlled by the human player at this client. Can also be #COMPANY_SPECTATOR.
47 CompanyID _current_company; ///< Company currently doing an action.
48 Colours _company_colours[MAX_COMPANIES]; ///< NOSAVE: can be determined from company structs.
49 CompanyManagerFace _company_manager_face; ///< for company manager face storage in openttd.cfg
50 uint _next_competitor_start; ///< the number of ticks before the next AI is started
51 uint _cur_company_tick_index; ///< used to generate a name for one company that doesn't have a name yet per tick
53 CompanyPool _company_pool("Company"); ///< Pool of companies.
54 INSTANTIATE_POOL_METHODS(Company)
56 /**
57 * Constructor.
58 * @param name_1 Name of the company.
59 * @param is_ai A computer program is running for this company.
61 Company::Company(uint16 name_1, bool is_ai)
63 this->name_1 = name_1;
64 this->location_of_HQ = INVALID_TILE;
65 this->is_ai = is_ai;
66 this->terraform_limit = (uint32)_settings_game.construction.terraform_frame_burst << 16;
67 this->clear_limit = (uint32)_settings_game.construction.clear_frame_burst << 16;
68 this->tree_limit = (uint32)_settings_game.construction.tree_frame_burst << 16;
70 for (uint j = 0; j < 4; j++) this->share_owners[j] = COMPANY_SPECTATOR;
71 InvalidateWindowData(WC_PERFORMANCE_DETAIL, 0, INVALID_COMPANY);
74 /** Destructor. */
75 Company::~Company()
77 if (CleaningPool()) return;
79 DeleteCompanyWindows(this->index);
82 /**
83 * Invalidating some stuff after removing item from the pool.
84 * @param index index of deleted item
86 void Company::PostDestructor(size_t index)
88 InvalidateWindowData(WC_GRAPH_LEGEND, 0, (int)index);
89 InvalidateWindowData(WC_PERFORMANCE_DETAIL, 0, (int)index);
90 InvalidateWindowData(WC_COMPANY_LEAGUE, 0, 0);
91 InvalidateWindowData(WC_LINKGRAPH_LEGEND, 0);
92 /* If the currently shown error message has this company in it, then close it. */
93 InvalidateWindowData(WC_ERRMSG, 0);
96 /**
97 * Sets the local company and updates the settings that are set on a
98 * per-company basis to reflect the core's state in the GUI.
99 * @param new_company the new company
100 * @pre Company::IsValidID(new_company) || new_company == COMPANY_SPECTATOR || new_company == OWNER_NONE
102 void SetLocalCompany(CompanyID new_company)
104 /* company could also be COMPANY_SPECTATOR or OWNER_NONE */
105 assert(Company::IsValidID(new_company) || new_company == COMPANY_SPECTATOR || new_company == OWNER_NONE);
107 /* If actually changing to another company, several windows need closing */
108 bool switching_company = _local_company != new_company;
110 /* Delete the chat window, if you were team chatting. */
111 if (switching_company) InvalidateWindowData(WC_SEND_NETWORK_MSG, DESTTYPE_TEAM, _local_company);
113 assert(IsLocalCompany());
115 _current_company = _local_company = new_company;
117 /* Delete any construction windows... */
118 if (switching_company) DeleteConstructionWindows();
120 /* ... and redraw the whole screen. */
121 MarkWholeScreenDirty();
122 InvalidateWindowClassesData(WC_SIGN_LIST, -1);
123 InvalidateWindowClassesData(WC_GOALS_LIST);
127 * Get the colour for DrawString-subroutines which matches the colour of the company.
128 * @param company Company to get the colour of.
129 * @return Colour of \a company.
131 TextColour GetDrawStringCompanyColour(CompanyID company)
133 if (!Company::IsValidID(company)) return (TextColour)_colour_gradient[COLOUR_WHITE][4] | TC_IS_PALETTE_COLOUR;
134 return (TextColour)_colour_gradient[_company_colours[company]][4] | TC_IS_PALETTE_COLOUR;
138 * Draw the icon of a company.
139 * @param c Company that needs its icon drawn.
140 * @param x Horizontal coordinate of the icon.
141 * @param y Vertical coordinate of the icon.
143 void DrawCompanyIcon(CompanyID c, int x, int y)
145 DrawSprite(SPR_COMPANY_ICON, COMPANY_SPRITE_COLOUR(c), x, y);
149 * Checks whether a company manager's face is a valid encoding.
150 * Unused bits are not enforced to be 0.
151 * @param cmf the fact to check
152 * @return true if and only if the face is valid
154 static bool IsValidCompanyManagerFace(CompanyManagerFace cmf)
156 if (!AreCompanyManagerFaceBitsValid(cmf, CMFV_GEN_ETHN, GE_WM)) return false;
158 GenderEthnicity ge = (GenderEthnicity)GetCompanyManagerFaceBits(cmf, CMFV_GEN_ETHN, GE_WM);
159 bool has_moustache = !HasBit(ge, GENDER_FEMALE) && GetCompanyManagerFaceBits(cmf, CMFV_HAS_MOUSTACHE, ge) != 0;
160 bool has_tie_earring = !HasBit(ge, GENDER_FEMALE) || GetCompanyManagerFaceBits(cmf, CMFV_HAS_TIE_EARRING, ge) != 0;
161 bool has_glasses = GetCompanyManagerFaceBits(cmf, CMFV_HAS_GLASSES, ge) != 0;
163 if (!AreCompanyManagerFaceBitsValid(cmf, CMFV_EYE_COLOUR, ge)) return false;
164 for (CompanyManagerFaceVariable cmfv = CMFV_CHEEKS; cmfv < CMFV_END; cmfv++) {
165 switch (cmfv) {
166 case CMFV_MOUSTACHE: if (!has_moustache) continue; break;
167 case CMFV_LIPS:
168 case CMFV_NOSE: if (has_moustache) continue; break;
169 case CMFV_TIE_EARRING: if (!has_tie_earring) continue; break;
170 case CMFV_GLASSES: if (!has_glasses) continue; break;
171 default: break;
173 if (!AreCompanyManagerFaceBitsValid(cmf, cmfv, ge)) return false;
176 return true;
180 * Refresh all windows owned by a company.
181 * @param company Company that changed, and needs its windows refreshed.
183 void InvalidateCompanyWindows(const Company *company)
185 CompanyID cid = company->index;
187 if (cid == _local_company) SetWindowWidgetDirty(WC_STATUS_BAR, 0, WID_S_RIGHT);
188 SetWindowDirty(WC_FINANCES, cid);
192 * Verify whether the company can pay the bill.
193 * @param[in,out] cost Money to pay, is changed to an error if the company does not have enough money.
194 * @return Function returns \c true if the company has enough money, else it returns \c false.
196 bool CheckCompanyHasMoney(CommandCost &cost)
198 if (cost.GetCost() > 0) {
199 const Company *c = Company::GetIfValid(_current_company);
200 if (c != nullptr && cost.GetCost() > c->money) {
201 SetDParam(0, cost.GetCost());
202 cost.MakeError(STR_ERROR_NOT_ENOUGH_CASH_REQUIRES_CURRENCY);
203 return false;
206 return true;
210 * Deduct costs of a command from the money of a company.
211 * @param c Company to pay the bill.
212 * @param cost Money to pay.
214 static void SubtractMoneyFromAnyCompany(Company *c, const CommandCost &cost)
216 if (cost.GetCost() == 0) return;
217 assert(cost.GetExpensesType() != INVALID_EXPENSES);
219 c->money -= cost.GetCost();
220 c->yearly_expenses[0][cost.GetExpensesType()] += cost.GetCost();
222 if (HasBit(1 << EXPENSES_TRAIN_INC |
223 1 << EXPENSES_ROADVEH_INC |
224 1 << EXPENSES_AIRCRAFT_INC |
225 1 << EXPENSES_SHIP_INC, cost.GetExpensesType())) {
226 c->cur_economy.income -= cost.GetCost();
227 } else if (HasBit(1 << EXPENSES_TRAIN_RUN |
228 1 << EXPENSES_ROADVEH_RUN |
229 1 << EXPENSES_AIRCRAFT_RUN |
230 1 << EXPENSES_SHIP_RUN |
231 1 << EXPENSES_PROPERTY |
232 1 << EXPENSES_LOAN_INT, cost.GetExpensesType())) {
233 c->cur_economy.expenses -= cost.GetCost();
236 InvalidateCompanyWindows(c);
240 * Subtract money from the #_current_company, if the company is valid.
241 * @param cost Money to pay.
243 void SubtractMoneyFromCompany(const CommandCost &cost)
245 Company *c = Company::GetIfValid(_current_company);
246 if (c != nullptr) SubtractMoneyFromAnyCompany(c, cost);
250 * Subtract money from a company, including the money fraction.
251 * @param company Company paying the bill.
252 * @param cst Cost of a command.
254 void SubtractMoneyFromCompanyFract(CompanyID company, const CommandCost &cst)
256 Company *c = Company::Get(company);
257 byte m = c->money_fraction;
258 Money cost = cst.GetCost();
260 c->money_fraction = m - (byte)cost;
261 cost >>= 8;
262 if (c->money_fraction > m) cost++;
263 if (cost != 0) SubtractMoneyFromAnyCompany(c, CommandCost(cst.GetExpensesType(), cost));
266 /** Update the landscaping limits per company. */
267 void UpdateLandscapingLimits()
269 for (Company *c : Company::Iterate()) {
270 c->terraform_limit = std::min<uint64>((uint64)c->terraform_limit + _settings_game.construction.terraform_per_64k_frames, (uint64)_settings_game.construction.terraform_frame_burst << 16);
271 c->clear_limit = std::min<uint64>((uint64)c->clear_limit + _settings_game.construction.clear_per_64k_frames, (uint64)_settings_game.construction.clear_frame_burst << 16);
272 c->tree_limit = std::min<uint64>((uint64)c->tree_limit + _settings_game.construction.tree_per_64k_frames, (uint64)_settings_game.construction.tree_frame_burst << 16);
277 * Set the right DParams to get the name of an owner.
278 * @param owner the owner to get the name of.
279 * @param tile optional tile to get the right town.
280 * @pre if tile == 0, then owner can't be OWNER_TOWN.
282 void GetNameOfOwner(Owner owner, TileIndex tile)
284 SetDParam(2, owner);
286 if (owner != OWNER_TOWN) {
287 if (!Company::IsValidID(owner)) {
288 SetDParam(0, STR_COMPANY_SOMEONE);
289 } else {
290 SetDParam(0, STR_COMPANY_NAME);
291 SetDParam(1, owner);
293 } else {
294 assert(tile != 0);
295 const Town *t = ClosestTownFromTile(tile, UINT_MAX);
297 SetDParam(0, STR_TOWN_NAME);
298 SetDParam(1, t->index);
304 * Check whether the current owner owns something.
305 * If that isn't the case an appropriate error will be given.
306 * @param owner the owner of the thing to check.
307 * @param tile optional tile to get the right town.
308 * @pre if tile == 0 then the owner can't be OWNER_TOWN.
309 * @return A succeeded command iff it's owned by the current company, else a failed command.
311 CommandCost CheckOwnership(Owner owner, TileIndex tile)
313 assert(owner < OWNER_END);
314 assert(owner != OWNER_TOWN || tile != 0);
316 if (owner == _current_company) return CommandCost();
318 GetNameOfOwner(owner, tile);
319 return_cmd_error(STR_ERROR_OWNED_BY);
323 * Check whether the current owner owns the stuff on
324 * the given tile. If that isn't the case an
325 * appropriate error will be given.
326 * @param tile the tile to check.
327 * @return A succeeded command iff it's owned by the current company, else a failed command.
329 CommandCost CheckTileOwnership(TileIndex tile)
331 Owner owner = GetTileOwner(tile);
333 assert(owner < OWNER_END);
335 if (owner == _current_company) return CommandCost();
337 /* no need to get the name of the owner unless we're the local company (saves some time) */
338 if (IsLocalCompany()) GetNameOfOwner(owner, tile);
339 return_cmd_error(STR_ERROR_OWNED_BY);
343 * Generate the name of a company from the last build coordinate.
344 * @param c Company to give a name.
346 static void GenerateCompanyName(Company *c)
348 /* Reserve space for extra unicode character. We need to do this to be able
349 * to detect too long company name. */
350 char buffer[(MAX_LENGTH_COMPANY_NAME_CHARS + 1) * MAX_CHAR_LENGTH];
352 if (c->name_1 != STR_SV_UNNAMED) return;
353 if (c->last_build_coordinate == 0) return;
355 Town *t = ClosestTownFromTile(c->last_build_coordinate, UINT_MAX);
357 StringID str;
358 uint32 strp;
359 if (t->name.empty() && IsInsideMM(t->townnametype, SPECSTR_TOWNNAME_START, SPECSTR_TOWNNAME_LAST + 1)) {
360 str = t->townnametype - SPECSTR_TOWNNAME_START + SPECSTR_COMPANY_NAME_START;
361 strp = t->townnameparts;
363 verify_name:;
364 /* No companies must have this name already */
365 for (const Company *cc : Company::Iterate()) {
366 if (cc->name_1 == str && cc->name_2 == strp) goto bad_town_name;
369 GetString(buffer, str, lastof(buffer));
370 if (Utf8StringLength(buffer) >= MAX_LENGTH_COMPANY_NAME_CHARS) goto bad_town_name;
372 set_name:;
373 c->name_1 = str;
374 c->name_2 = strp;
376 MarkWholeScreenDirty();
378 if (c->is_ai) {
379 CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
380 cni->FillData(c);
381 SetDParam(0, STR_NEWS_COMPANY_LAUNCH_TITLE);
382 SetDParam(1, STR_NEWS_COMPANY_LAUNCH_DESCRIPTION);
383 SetDParamStr(2, cni->company_name);
384 SetDParam(3, t->index);
385 AddNewsItem(STR_MESSAGE_NEWS_FORMAT, NT_COMPANY_INFO, NF_COMPANY, NR_TILE, c->last_build_coordinate, NR_NONE, UINT32_MAX, cni);
387 return;
389 bad_town_name:;
391 if (c->president_name_1 == SPECSTR_PRESIDENT_NAME) {
392 str = SPECSTR_ANDCO_NAME;
393 strp = c->president_name_2;
394 goto set_name;
395 } else {
396 str = SPECSTR_ANDCO_NAME;
397 strp = Random();
398 goto verify_name;
402 /** Sorting weights for the company colours. */
403 static const byte _colour_sort[COLOUR_END] = {2, 2, 3, 2, 3, 2, 3, 2, 3, 2, 2, 2, 3, 1, 1, 1};
404 /** Similar colours, so we can try to prevent same coloured companies. */
405 static const Colours _similar_colour[COLOUR_END][2] = {
406 { COLOUR_BLUE, COLOUR_LIGHT_BLUE }, // COLOUR_DARK_BLUE
407 { COLOUR_GREEN, COLOUR_DARK_GREEN }, // COLOUR_PALE_GREEN
408 { INVALID_COLOUR, INVALID_COLOUR }, // COLOUR_PINK
409 { COLOUR_ORANGE, INVALID_COLOUR }, // COLOUR_YELLOW
410 { INVALID_COLOUR, INVALID_COLOUR }, // COLOUR_RED
411 { COLOUR_DARK_BLUE, COLOUR_BLUE }, // COLOUR_LIGHT_BLUE
412 { COLOUR_PALE_GREEN, COLOUR_DARK_GREEN }, // COLOUR_GREEN
413 { COLOUR_PALE_GREEN, COLOUR_GREEN }, // COLOUR_DARK_GREEN
414 { COLOUR_DARK_BLUE, COLOUR_LIGHT_BLUE }, // COLOUR_BLUE
415 { COLOUR_BROWN, COLOUR_ORANGE }, // COLOUR_CREAM
416 { COLOUR_PURPLE, INVALID_COLOUR }, // COLOUR_MAUVE
417 { COLOUR_MAUVE, INVALID_COLOUR }, // COLOUR_PURPLE
418 { COLOUR_YELLOW, COLOUR_CREAM }, // COLOUR_ORANGE
419 { COLOUR_CREAM, INVALID_COLOUR }, // COLOUR_BROWN
420 { COLOUR_WHITE, INVALID_COLOUR }, // COLOUR_GREY
421 { COLOUR_GREY, INVALID_COLOUR }, // COLOUR_WHITE
425 * Generate a company colour.
426 * @return Generated company colour.
428 static Colours GenerateCompanyColour()
430 Colours colours[COLOUR_END];
432 /* Initialize array */
433 for (uint i = 0; i < COLOUR_END; i++) colours[i] = (Colours)i;
435 /* And randomize it */
436 for (uint i = 0; i < 100; i++) {
437 uint r = Random();
438 Swap(colours[GB(r, 0, 4)], colours[GB(r, 4, 4)]);
441 /* Bubble sort it according to the values in table 1 */
442 for (uint i = 0; i < COLOUR_END; i++) {
443 for (uint j = 1; j < COLOUR_END; j++) {
444 if (_colour_sort[colours[j - 1]] < _colour_sort[colours[j]]) {
445 Swap(colours[j - 1], colours[j]);
450 /* Move the colours that look similar to each company's colour to the side */
451 for (const Company *c : Company::Iterate()) {
452 Colours pcolour = (Colours)c->colour;
454 for (uint i = 0; i < COLOUR_END; i++) {
455 if (colours[i] == pcolour) {
456 colours[i] = INVALID_COLOUR;
457 break;
461 for (uint j = 0; j < 2; j++) {
462 Colours similar = _similar_colour[pcolour][j];
463 if (similar == INVALID_COLOUR) break;
465 for (uint i = 1; i < COLOUR_END; i++) {
466 if (colours[i - 1] == similar) Swap(colours[i - 1], colours[i]);
471 /* Return the first available colour */
472 for (uint i = 0; i < COLOUR_END; i++) {
473 if (colours[i] != INVALID_COLOUR) return colours[i];
476 NOT_REACHED();
480 * Generate a random president name of a company.
481 * @param c Company that needs a new president name.
483 static void GeneratePresidentName(Company *c)
485 for (;;) {
486 restart:;
487 c->president_name_2 = Random();
488 c->president_name_1 = SPECSTR_PRESIDENT_NAME;
490 /* Reserve space for extra unicode character. We need to do this to be able
491 * to detect too long president name. */
492 char buffer[(MAX_LENGTH_PRESIDENT_NAME_CHARS + 1) * MAX_CHAR_LENGTH];
493 SetDParam(0, c->index);
494 GetString(buffer, STR_PRESIDENT_NAME, lastof(buffer));
495 if (Utf8StringLength(buffer) >= MAX_LENGTH_PRESIDENT_NAME_CHARS) continue;
497 for (const Company *cc : Company::Iterate()) {
498 if (c != cc) {
499 /* Reserve extra space so even overlength president names can be compared. */
500 char buffer2[(MAX_LENGTH_PRESIDENT_NAME_CHARS + 1) * MAX_CHAR_LENGTH];
501 SetDParam(0, cc->index);
502 GetString(buffer2, STR_PRESIDENT_NAME, lastof(buffer2));
503 if (strcmp(buffer2, buffer) == 0) goto restart;
506 return;
511 * Reset the livery schemes to the company's primary colour.
512 * This is used on loading games without livery information and on new company start up.
513 * @param c Company to reset.
515 void ResetCompanyLivery(Company *c)
517 for (LiveryScheme scheme = LS_BEGIN; scheme < LS_END; scheme++) {
518 c->livery[scheme].in_use = 0;
519 c->livery[scheme].colour1 = c->colour;
520 c->livery[scheme].colour2 = c->colour;
523 for (Group *g : Group::Iterate()) {
524 if (g->owner == c->index) {
525 g->livery.in_use = 0;
526 g->livery.colour1 = c->colour;
527 g->livery.colour2 = c->colour;
533 * Create a new company and sets all company variables default values
535 * @param is_ai is an AI company?
536 * @param company CompanyID to use for the new company
537 * @return the company struct
539 Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY)
541 if (!Company::CanAllocateItem()) return nullptr;
543 /* we have to generate colour before this company is valid */
544 Colours colour = GenerateCompanyColour();
546 Company *c;
547 if (company == INVALID_COMPANY) {
548 c = new Company(STR_SV_UNNAMED, is_ai);
549 } else {
550 if (Company::IsValidID(company)) return nullptr;
551 c = new (company) Company(STR_SV_UNNAMED, is_ai);
554 c->colour = colour;
556 ResetCompanyLivery(c);
557 _company_colours[c->index] = (Colours)c->colour;
559 c->money = c->current_loan = (std::min<int64>(INITIAL_LOAN, _economy.max_loan) * _economy.inflation_prices >> 16) / 50000 * 50000;
561 c->share_owners[0] = c->share_owners[1] = c->share_owners[2] = c->share_owners[3] = INVALID_OWNER;
563 c->avail_railtypes = GetCompanyRailtypes(c->index);
564 c->avail_roadtypes = GetCompanyRoadTypes(c->index);
565 c->inaugurated_year = _cur_year;
566 RandomCompanyManagerFaceBits(c->face, (GenderEthnicity)Random(), false, false); // create a random company manager face
568 SetDefaultCompanySettings(c->index);
569 ClearEnginesHiddenFlagOfCompany(c->index);
571 GeneratePresidentName(c);
573 SetWindowDirty(WC_GRAPH_LEGEND, 0);
574 SetWindowClassesDirty(WC_CLIENT_LIST_POPUP);
575 SetWindowDirty(WC_CLIENT_LIST, 0);
576 InvalidateWindowData(WC_LINKGRAPH_LEGEND, 0);
577 BuildOwnerLegend();
578 InvalidateWindowData(WC_SMALLMAP, 0, 1);
580 if (is_ai && (!_networking || _network_server)) AI::StartNew(c->index);
582 AI::BroadcastNewEvent(new ScriptEventCompanyNew(c->index), c->index);
583 Game::NewEvent(new ScriptEventCompanyNew(c->index));
585 return c;
588 /** Start the next competitor now. */
589 void StartupCompanies()
591 _next_competitor_start = 0;
594 /** Start a new competitor company if possible. */
595 static bool MaybeStartNewCompany()
597 if (_networking && Company::GetNumItems() >= _settings_client.network.max_companies) return false;
599 /* count number of competitors */
600 uint n = 0;
601 for (const Company *c : Company::Iterate()) {
602 if (c->is_ai) n++;
605 if (n < (uint)_settings_game.difficulty.max_no_competitors) {
606 /* Send a command to all clients to start up a new AI.
607 * Works fine for Multiplayer and Singleplayer */
608 return DoCommandP(0, CCA_NEW_AI | INVALID_COMPANY << 16, 0, CMD_COMPANY_CTRL);
611 return false;
614 /** Initialize the pool of companies. */
615 void InitializeCompanies()
617 _cur_company_tick_index = 0;
621 * May company \a cbig buy company \a csmall?
622 * @param cbig Company buying \a csmall.
623 * @param csmall Company getting bought.
624 * @return Return \c true if it is allowed.
626 bool MayCompanyTakeOver(CompanyID cbig, CompanyID csmall)
628 const Company *c1 = Company::Get(cbig);
629 const Company *c2 = Company::Get(csmall);
631 /* Do the combined vehicle counts stay within the limits? */
632 return c1->group_all[VEH_TRAIN].num_vehicle + c2->group_all[VEH_TRAIN].num_vehicle <= _settings_game.vehicle.max_trains &&
633 c1->group_all[VEH_ROAD].num_vehicle + c2->group_all[VEH_ROAD].num_vehicle <= _settings_game.vehicle.max_roadveh &&
634 c1->group_all[VEH_SHIP].num_vehicle + c2->group_all[VEH_SHIP].num_vehicle <= _settings_game.vehicle.max_ships &&
635 c1->group_all[VEH_AIRCRAFT].num_vehicle + c2->group_all[VEH_AIRCRAFT].num_vehicle <= _settings_game.vehicle.max_aircraft;
639 * Handle the bankruptcy take over of a company.
640 * Companies going bankrupt will ask the other companies in order of their
641 * performance rating, so better performing companies get the 'do you want to
642 * merge with Y' question earlier. The question will then stay till either the
643 * company has gone bankrupt or got merged with a company.
645 * @param c the company that is going bankrupt.
647 static void HandleBankruptcyTakeover(Company *c)
649 /* Amount of time out for each company to take over a company;
650 * Timeout is a quarter (3 months of 30 days) divided over the
651 * number of companies. The minimum number of days in a quarter
652 * is 90: 31 in January, 28 in February and 31 in March.
653 * Note that the company going bankrupt can't buy itself. */
654 static const int TAKE_OVER_TIMEOUT = 3 * 30 * DAY_TICKS / (MAX_COMPANIES - 1);
656 assert(c->bankrupt_asked != 0);
658 /* We're currently asking some company to buy 'us' */
659 if (c->bankrupt_timeout != 0) {
660 c->bankrupt_timeout -= MAX_COMPANIES;
661 if (c->bankrupt_timeout > 0) return;
662 c->bankrupt_timeout = 0;
664 return;
667 /* Did we ask everyone for bankruptcy? If so, bail out. */
668 if (c->bankrupt_asked == MAX_UVALUE(CompanyMask)) return;
670 Company *best = nullptr;
671 int32 best_performance = -1;
673 /* Ask the company with the highest performance history first */
674 for (Company *c2 : Company::Iterate()) {
675 if (c2->bankrupt_asked == 0 && // Don't ask companies going bankrupt themselves
676 !HasBit(c->bankrupt_asked, c2->index) &&
677 best_performance < c2->old_economy[1].performance_history &&
678 MayCompanyTakeOver(c2->index, c->index)) {
679 best_performance = c2->old_economy[1].performance_history;
680 best = c2;
684 /* Asked all companies? */
685 if (best_performance == -1) {
686 c->bankrupt_asked = MAX_UVALUE(CompanyMask);
687 return;
690 SetBit(c->bankrupt_asked, best->index);
692 c->bankrupt_timeout = TAKE_OVER_TIMEOUT;
693 if (best->is_ai) {
694 AI::NewEvent(best->index, new ScriptEventCompanyAskMerger(c->index, ClampToI32(c->bankrupt_value)));
695 } else if (IsInteractiveCompany(best->index)) {
696 ShowBuyCompanyDialog(c->index);
700 /** Called every tick for updating some company info. */
701 void OnTick_Companies()
703 if (_game_mode == GM_EDITOR) return;
705 Company *c = Company::GetIfValid(_cur_company_tick_index);
706 if (c != nullptr) {
707 if (c->name_1 != 0) GenerateCompanyName(c);
708 if (c->bankrupt_asked != 0) HandleBankruptcyTakeover(c);
711 if (_next_competitor_start == 0) {
712 /* AI::GetStartNextTime() can return 0. */
713 _next_competitor_start = std::max(1, AI::GetStartNextTime() * DAY_TICKS);
716 if (_game_mode != GM_MENU && AI::CanStartNew() && --_next_competitor_start == 0) {
717 /* Allow multiple AIs to possibly start in the same tick. */
718 do {
719 if (!MaybeStartNewCompany()) break;
721 /* In networking mode, we can only send a command to start but it
722 * didn't execute yet, so we cannot loop. */
723 if (_networking) break;
724 } while (AI::GetStartNextTime() == 0);
727 _cur_company_tick_index = (_cur_company_tick_index + 1) % MAX_COMPANIES;
731 * A year has passed, update the economic data of all companies, and perhaps show the
732 * financial overview window of the local company.
734 void CompaniesYearlyLoop()
736 /* Copy statistics */
737 for (Company *c : Company::Iterate()) {
738 memmove(&c->yearly_expenses[1], &c->yearly_expenses[0], sizeof(c->yearly_expenses) - sizeof(c->yearly_expenses[0]));
739 memset(&c->yearly_expenses[0], 0, sizeof(c->yearly_expenses[0]));
740 SetWindowDirty(WC_FINANCES, c->index);
743 if (_settings_client.gui.show_finances && _local_company != COMPANY_SPECTATOR) {
744 ShowCompanyFinances(_local_company);
745 Company *c = Company::Get(_local_company);
746 if (c->num_valid_stat_ent > 5 && c->old_economy[0].performance_history < c->old_economy[4].performance_history) {
747 if (_settings_client.sound.new_year) SndPlayFx(SND_01_BAD_YEAR);
748 } else {
749 if (_settings_client.sound.new_year) SndPlayFx(SND_00_GOOD_YEAR);
755 * Fill the CompanyNewsInformation struct with the required data.
756 * @param c the current company.
757 * @param other the other company (use \c nullptr if not relevant).
759 void CompanyNewsInformation::FillData(const Company *c, const Company *other)
761 SetDParam(0, c->index);
762 GetString(this->company_name, STR_COMPANY_NAME, lastof(this->company_name));
764 if (other == nullptr) {
765 *this->other_company_name = '\0';
766 } else {
767 SetDParam(0, other->index);
768 GetString(this->other_company_name, STR_COMPANY_NAME, lastof(this->other_company_name));
769 c = other;
772 SetDParam(0, c->index);
773 GetString(this->president_name, STR_PRESIDENT_NAME_MANAGER, lastof(this->president_name));
775 this->colour = c->colour;
776 this->face = c->face;
781 * Called whenever company related information changes in order to notify admins.
782 * @param company The company data changed of.
784 void CompanyAdminUpdate(const Company *company)
786 if (_network_server) NetworkAdminCompanyUpdate(company);
790 * Called whenever a company is removed in order to notify admins.
791 * @param company_id The company that was removed.
792 * @param reason The reason the company was removed.
794 void CompanyAdminRemove(CompanyID company_id, CompanyRemoveReason reason)
796 if (_network_server) NetworkAdminCompanyRemove(company_id, (AdminCompanyRemoveReason)reason);
800 * Control the companies: add, delete, etc.
801 * @param tile unused
802 * @param flags operation to perform
803 * @param p1 various functionality
804 * - bits 0..15: CompanyCtrlAction
805 * - bits 16..23: CompanyID
806 * - bits 24..31: CompanyRemoveReason (with CCA_DELETE)
807 * @param p2 ClientID
808 * @param text unused
809 * @return the cost of this operation or an error
811 CommandCost CmdCompanyCtrl(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
813 InvalidateWindowData(WC_COMPANY_LEAGUE, 0, 0);
814 CompanyID company_id = (CompanyID)GB(p1, 16, 8);
816 switch ((CompanyCtrlAction)GB(p1, 0, 16)) {
817 case CCA_NEW: { // Create a new company
818 /* This command is only executed in a multiplayer game */
819 if (!_networking) return CMD_ERROR;
821 /* Has the network client a correct ClientIndex? */
822 if (!(flags & DC_EXEC)) return CommandCost();
824 ClientID client_id = (ClientID)p2;
825 NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
827 /* Delete multiplayer progress bar */
828 DeleteWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
830 Company *c = DoStartupNewCompany(false);
832 /* A new company could not be created, revert to being a spectator */
833 if (c == nullptr) {
834 /* We check for "ci != nullptr" as a client could have left by
835 * the time we execute this command. */
836 if (_network_server && ci != nullptr) {
837 ci->client_playas = COMPANY_SPECTATOR;
838 NetworkUpdateClientInfo(ci->client_id);
840 break;
843 /* This is the client (or non-dedicated server) who wants a new company */
844 if (client_id == _network_own_client_id) {
845 assert(_local_company == COMPANY_SPECTATOR);
846 SetLocalCompany(c->index);
847 if (!StrEmpty(_settings_client.network.default_company_pass)) {
848 NetworkChangeCompanyPassword(_local_company, _settings_client.network.default_company_pass);
851 /* Now that we have a new company, broadcast our company settings to
852 * all clients so everything is in sync */
853 SyncCompanySettings();
855 MarkWholeScreenDirty();
858 NetworkServerNewCompany(c, ci);
859 break;
862 case CCA_NEW_AI: { // Make a new AI company
863 if (company_id != INVALID_COMPANY && company_id >= MAX_COMPANIES) return CMD_ERROR;
865 /* For network games, company deletion is delayed. */
866 if (!_networking && company_id != INVALID_COMPANY && Company::IsValidID(company_id)) return CMD_ERROR;
868 if (!(flags & DC_EXEC)) return CommandCost();
870 /* For network game, just assume deletion happened. */
871 assert(company_id == INVALID_COMPANY || !Company::IsValidID(company_id));
873 Company *c = DoStartupNewCompany(true, company_id);
874 if (c != nullptr) NetworkServerNewCompany(c, nullptr);
875 break;
878 case CCA_DELETE: { // Delete a company
879 CompanyRemoveReason reason = (CompanyRemoveReason)GB(p1, 24, 8);
880 if (reason >= CRR_END) return CMD_ERROR;
882 /* We can't delete the last existing company in singleplayer mode. */
883 if (!_networking && Company::GetNumItems() == 1) return CMD_ERROR;
885 Company *c = Company::GetIfValid(company_id);
886 if (c == nullptr) return CMD_ERROR;
888 if (!(flags & DC_EXEC)) return CommandCost();
890 /* Delete any open window of the company */
891 DeleteCompanyWindows(c->index);
892 CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
893 cni->FillData(c);
895 /* Show the bankrupt news */
896 SetDParam(0, STR_NEWS_COMPANY_BANKRUPT_TITLE);
897 SetDParam(1, STR_NEWS_COMPANY_BANKRUPT_DESCRIPTION);
898 SetDParamStr(2, cni->company_name);
899 AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, cni);
901 /* Remove the company */
902 ChangeOwnershipOfCompanyItems(c->index, INVALID_OWNER);
903 if (c->is_ai) AI::Stop(c->index);
905 CompanyID c_index = c->index;
906 delete c;
907 AI::BroadcastNewEvent(new ScriptEventCompanyBankrupt(c_index));
908 Game::NewEvent(new ScriptEventCompanyBankrupt(c_index));
909 CompanyAdminRemove(c_index, (CompanyRemoveReason)reason);
911 if (StoryPage::GetNumItems() == 0 || Goal::GetNumItems() == 0) InvalidateWindowData(WC_MAIN_TOOLBAR, 0);
912 break;
915 default: return CMD_ERROR;
918 InvalidateWindowClassesData(WC_GAME_OPTIONS);
919 InvalidateWindowClassesData(WC_AI_SETTINGS);
920 InvalidateWindowClassesData(WC_AI_LIST);
922 return CommandCost();
926 * Change the company manager's face.
927 * @param tile unused
928 * @param flags operation to perform
929 * @param p1 unused
930 * @param p2 face bitmasked
931 * @param text unused
932 * @return the cost of this operation or an error
934 CommandCost CmdSetCompanyManagerFace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
936 CompanyManagerFace cmf = (CompanyManagerFace)p2;
938 if (!IsValidCompanyManagerFace(cmf)) return CMD_ERROR;
940 if (flags & DC_EXEC) {
941 Company::Get(_current_company)->face = cmf;
942 MarkWholeScreenDirty();
944 return CommandCost();
948 * Change the company's company-colour
949 * @param tile unused
950 * @param flags operation to perform
951 * @param p1 bitstuffed:
952 * p1 bits 0-7 scheme to set
953 * p1 bit 8 set first/second colour
954 * @param p2 new colour for vehicles, property, etc.
955 * @param text unused
956 * @return the cost of this operation or an error
958 CommandCost CmdSetCompanyColour(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
960 Colours colour = Extract<Colours, 0, 8>(p2);
961 LiveryScheme scheme = Extract<LiveryScheme, 0, 8>(p1);
962 bool second = HasBit(p1, 8);
964 if (scheme >= LS_END || (colour >= COLOUR_END && colour != INVALID_COLOUR)) return CMD_ERROR;
966 /* Default scheme can't be reset to invalid. */
967 if (scheme == LS_DEFAULT && colour == INVALID_COLOUR) return CMD_ERROR;
969 Company *c = Company::Get(_current_company);
971 /* Ensure no two companies have the same primary colour */
972 if (scheme == LS_DEFAULT && !second) {
973 for (const Company *cc : Company::Iterate()) {
974 if (cc != c && cc->colour == colour) return CMD_ERROR;
978 if (flags & DC_EXEC) {
979 if (!second) {
980 if (scheme != LS_DEFAULT) SB(c->livery[scheme].in_use, 0, 1, colour != INVALID_COLOUR);
981 if (colour == INVALID_COLOUR) colour = (Colours)c->livery[LS_DEFAULT].colour1;
982 c->livery[scheme].colour1 = colour;
984 /* If setting the first colour of the default scheme, adjust the
985 * original and cached company colours too. */
986 if (scheme == LS_DEFAULT) {
987 for (int i = 1; i < LS_END; i++) {
988 if (!HasBit(c->livery[i].in_use, 0)) c->livery[i].colour1 = colour;
990 _company_colours[_current_company] = colour;
991 c->colour = colour;
992 CompanyAdminUpdate(c);
994 } else {
995 if (scheme != LS_DEFAULT) SB(c->livery[scheme].in_use, 1, 1, colour != INVALID_COLOUR);
996 if (colour == INVALID_COLOUR) colour = (Colours)c->livery[LS_DEFAULT].colour2;
997 c->livery[scheme].colour2 = colour;
999 if (scheme == LS_DEFAULT) {
1000 for (int i = 1; i < LS_END; i++) {
1001 if (!HasBit(c->livery[i].in_use, 1)) c->livery[i].colour2 = colour;
1006 if (c->livery[scheme].in_use != 0) {
1007 /* If enabling a scheme, set the default scheme to be in use too */
1008 c->livery[LS_DEFAULT].in_use = 1;
1009 } else {
1010 /* Else loop through all schemes to see if any are left enabled.
1011 * If not, disable the default scheme too. */
1012 c->livery[LS_DEFAULT].in_use = 0;
1013 for (scheme = LS_DEFAULT; scheme < LS_END; scheme++) {
1014 if (c->livery[scheme].in_use != 0) {
1015 c->livery[LS_DEFAULT].in_use = 1;
1016 break;
1021 ResetVehicleColourMap();
1022 MarkWholeScreenDirty();
1024 /* All graph related to companies use the company colour. */
1025 InvalidateWindowData(WC_INCOME_GRAPH, 0);
1026 InvalidateWindowData(WC_OPERATING_PROFIT, 0);
1027 InvalidateWindowData(WC_DELIVERED_CARGO, 0);
1028 InvalidateWindowData(WC_PERFORMANCE_HISTORY, 0);
1029 InvalidateWindowData(WC_COMPANY_VALUE, 0);
1030 InvalidateWindowData(WC_LINKGRAPH_LEGEND, 0);
1031 /* The smallmap owner view also stores the company colours. */
1032 BuildOwnerLegend();
1033 InvalidateWindowData(WC_SMALLMAP, 0, 1);
1035 /* Company colour data is indirectly cached. */
1036 for (Vehicle *v : Vehicle::Iterate()) {
1037 if (v->owner == _current_company) v->InvalidateNewGRFCache();
1040 extern void UpdateObjectColours(const Company *c);
1041 UpdateObjectColours(c);
1043 return CommandCost();
1047 * Is the given name in use as name of a company?
1048 * @param name Name to search.
1049 * @return \c true if the name us unique (that is, not in use), else \c false.
1051 static bool IsUniqueCompanyName(const char *name)
1053 for (const Company *c : Company::Iterate()) {
1054 if (!c->name.empty() && c->name == name) return false;
1057 return true;
1061 * Change the name of the company.
1062 * @param tile unused
1063 * @param flags operation to perform
1064 * @param p1 unused
1065 * @param p2 unused
1066 * @param text the new name or an empty string when resetting to the default
1067 * @return the cost of this operation or an error
1069 CommandCost CmdRenameCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1071 bool reset = StrEmpty(text);
1073 if (!reset) {
1074 if (Utf8StringLength(text) >= MAX_LENGTH_COMPANY_NAME_CHARS) return CMD_ERROR;
1075 if (!IsUniqueCompanyName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1078 if (flags & DC_EXEC) {
1079 Company *c = Company::Get(_current_company);
1080 if (reset) {
1081 c->name.clear();
1082 } else {
1083 c->name = text;
1085 MarkWholeScreenDirty();
1086 CompanyAdminUpdate(c);
1089 return CommandCost();
1093 * Is the given name in use as president name of a company?
1094 * @param name Name to search.
1095 * @return \c true if the name us unique (that is, not in use), else \c false.
1097 static bool IsUniquePresidentName(const char *name)
1099 for (const Company *c : Company::Iterate()) {
1100 if (!c->president_name.empty() && c->president_name == name) return false;
1103 return true;
1107 * Change the name of the president.
1108 * @param tile unused
1109 * @param flags operation to perform
1110 * @param p1 unused
1111 * @param p2 unused
1112 * @param text the new name or an empty string when resetting to the default
1113 * @return the cost of this operation or an error
1115 CommandCost CmdRenamePresident(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1117 bool reset = StrEmpty(text);
1119 if (!reset) {
1120 if (Utf8StringLength(text) >= MAX_LENGTH_PRESIDENT_NAME_CHARS) return CMD_ERROR;
1121 if (!IsUniquePresidentName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1124 if (flags & DC_EXEC) {
1125 Company *c = Company::Get(_current_company);
1127 if (reset) {
1128 c->president_name.clear();
1129 } else {
1130 c->president_name = text;
1132 if (c->name_1 == STR_SV_UNNAMED && c->name.empty()) {
1133 char buf[80];
1135 seprintf(buf, lastof(buf), "%s Transport", text);
1136 DoCommand(0, 0, 0, DC_EXEC, CMD_RENAME_COMPANY, buf);
1140 MarkWholeScreenDirty();
1141 CompanyAdminUpdate(c);
1144 return CommandCost();
1148 * Get the service interval for the given company and vehicle type.
1149 * @param c The company, or nullptr for client-default settings.
1150 * @param type The vehicle type to get the interval for.
1151 * @return The service interval.
1153 int CompanyServiceInterval(const Company *c, VehicleType type)
1155 const VehicleDefaultSettings *vds = (c == nullptr) ? &_settings_client.company.vehicle : &c->settings.vehicle;
1156 switch (type) {
1157 default: NOT_REACHED();
1158 case VEH_TRAIN: return vds->servint_trains;
1159 case VEH_ROAD: return vds->servint_roadveh;
1160 case VEH_AIRCRAFT: return vds->servint_aircraft;
1161 case VEH_SHIP: return vds->servint_ships;
1166 * Get total sum of all owned road bits.
1167 * @return Combined total road road bits.
1169 uint32 CompanyInfrastructure::GetRoadTotal() const
1171 uint32 total = 0;
1172 for (RoadType rt = ROADTYPE_BEGIN; rt != ROADTYPE_END; rt++) {
1173 if (RoadTypeIsRoad(rt)) total += this->road[rt];
1175 return total;
1179 * Get total sum of all owned tram bits.
1180 * @return Combined total of tram road bits.
1182 uint32 CompanyInfrastructure::GetTramTotal() const
1184 uint32 total = 0;
1185 for (RoadType rt = ROADTYPE_BEGIN; rt != ROADTYPE_END; rt++) {
1186 if (RoadTypeIsTram(rt)) total += this->road[rt];
1188 return total;
1192 * Transfer funds (money) from one company to another.
1193 * To prevent abuse in multiplayer games you can only send money to other
1194 * companies if you have paid off your loan (either explicitly, or implicitly
1195 * given the fact that you have more money than loan).
1196 * @param tile unused
1197 * @param flags operation to perform
1198 * @param p1 the amount of money to transfer; max 20.000.000
1199 * @param p2 the company to transfer the money to
1200 * @param text unused
1201 * @return the cost of this operation or an error
1203 CommandCost CmdGiveMoney(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1205 if (!_settings_game.economy.give_money) return CMD_ERROR;
1207 const Company *c = Company::Get(_current_company);
1208 CommandCost amount(EXPENSES_OTHER, std::min<Money>(p1, 20000000LL));
1209 CompanyID dest_company = (CompanyID)p2;
1211 /* You can only transfer funds that is in excess of your loan */
1212 if (c->money - c->current_loan < amount.GetCost() || amount.GetCost() < 0) return_cmd_error(STR_ERROR_INSUFFICIENT_FUNDS);
1213 if (!Company::IsValidID(dest_company)) return CMD_ERROR;
1215 if (flags & DC_EXEC) {
1216 /* Add money to company */
1217 Backup<CompanyID> cur_company(_current_company, dest_company, FILE_LINE);
1218 SubtractMoneyFromCompany(CommandCost(EXPENSES_OTHER, -amount.GetCost()));
1219 cur_company.Restore();
1221 if (_networking) {
1222 char dest_company_name[MAX_LENGTH_COMPANY_NAME_CHARS * MAX_CHAR_LENGTH];
1223 SetDParam(0, dest_company);
1224 GetString(dest_company_name, STR_COMPANY_NAME, lastof(dest_company_name));
1226 char from_company_name[MAX_LENGTH_COMPANY_NAME_CHARS * MAX_CHAR_LENGTH];
1227 SetDParam(0, _current_company);
1228 GetString(from_company_name, STR_COMPANY_NAME, lastof(from_company_name));
1230 NetworkTextMessage(NETWORK_ACTION_GIVE_MONEY, GetDrawStringCompanyColour(_current_company), false, from_company_name, dest_company_name, amount.GetCost());
1234 /* Subtract money from local-company */
1235 return amount;