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/>.
8 /** @file company_cmd.cpp Handling of companies. */
11 #include "company_base.h"
12 #include "company_func.h"
13 #include "company_gui.h"
14 #include "core/backup_type.hpp"
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"
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"
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
)
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
;
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
] = INVALID_OWNER
;
71 InvalidateWindowData(WC_PERFORMANCE_DETAIL
, 0, INVALID_COMPANY
);
77 if (CleaningPool()) return;
79 CloseCompanyWindows(this->index
);
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);
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
) CloseConstructionWindows();
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
++) {
166 case CMFV_MOUSTACHE
: if (!has_moustache
) continue; break;
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;
173 if (!AreCompanyManagerFaceBitsValid(cmf
, cmfv
, ge
)) return false;
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
);
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
;
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
)
286 if (owner
!= OWNER_TOWN
) {
287 if (!Company::IsValidID(owner
)) {
288 SetDParam(0, STR_COMPANY_SOMEONE
);
290 SetDParam(0, STR_COMPANY_NAME
);
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
);
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
;
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
;
376 MarkWholeScreenDirty();
379 CompanyNewsInformation
*cni
= new CompanyNewsInformation(c
);
380 SetDParam(0, STR_NEWS_COMPANY_LAUNCH_TITLE
);
381 SetDParam(1, STR_NEWS_COMPANY_LAUNCH_DESCRIPTION
);
382 SetDParamStr(2, cni
->company_name
);
383 SetDParam(3, t
->index
);
384 AddNewsItem(STR_MESSAGE_NEWS_FORMAT
, NT_COMPANY_INFO
, NF_COMPANY
, NR_TILE
, c
->last_build_coordinate
, NR_NONE
, UINT32_MAX
, cni
);
390 if (c
->president_name_1
== SPECSTR_PRESIDENT_NAME
) {
391 str
= SPECSTR_ANDCO_NAME
;
392 strp
= c
->president_name_2
;
395 str
= SPECSTR_ANDCO_NAME
;
401 /** Sorting weights for the company colours. */
402 static const byte _colour_sort
[COLOUR_END
] = {2, 2, 3, 2, 3, 2, 3, 2, 3, 2, 2, 2, 3, 1, 1, 1};
403 /** Similar colours, so we can try to prevent same coloured companies. */
404 static const Colours _similar_colour
[COLOUR_END
][2] = {
405 { COLOUR_BLUE
, COLOUR_LIGHT_BLUE
}, // COLOUR_DARK_BLUE
406 { COLOUR_GREEN
, COLOUR_DARK_GREEN
}, // COLOUR_PALE_GREEN
407 { INVALID_COLOUR
, INVALID_COLOUR
}, // COLOUR_PINK
408 { COLOUR_ORANGE
, INVALID_COLOUR
}, // COLOUR_YELLOW
409 { INVALID_COLOUR
, INVALID_COLOUR
}, // COLOUR_RED
410 { COLOUR_DARK_BLUE
, COLOUR_BLUE
}, // COLOUR_LIGHT_BLUE
411 { COLOUR_PALE_GREEN
, COLOUR_DARK_GREEN
}, // COLOUR_GREEN
412 { COLOUR_PALE_GREEN
, COLOUR_GREEN
}, // COLOUR_DARK_GREEN
413 { COLOUR_DARK_BLUE
, COLOUR_LIGHT_BLUE
}, // COLOUR_BLUE
414 { COLOUR_BROWN
, COLOUR_ORANGE
}, // COLOUR_CREAM
415 { COLOUR_PURPLE
, INVALID_COLOUR
}, // COLOUR_MAUVE
416 { COLOUR_MAUVE
, INVALID_COLOUR
}, // COLOUR_PURPLE
417 { COLOUR_YELLOW
, COLOUR_CREAM
}, // COLOUR_ORANGE
418 { COLOUR_CREAM
, INVALID_COLOUR
}, // COLOUR_BROWN
419 { COLOUR_WHITE
, INVALID_COLOUR
}, // COLOUR_GREY
420 { COLOUR_GREY
, INVALID_COLOUR
}, // COLOUR_WHITE
424 * Generate a company colour.
425 * @return Generated company colour.
427 static Colours
GenerateCompanyColour()
429 Colours colours
[COLOUR_END
];
431 /* Initialize array */
432 for (uint i
= 0; i
< COLOUR_END
; i
++) colours
[i
] = (Colours
)i
;
434 /* And randomize it */
435 for (uint i
= 0; i
< 100; i
++) {
437 Swap(colours
[GB(r
, 0, 4)], colours
[GB(r
, 4, 4)]);
440 /* Bubble sort it according to the values in table 1 */
441 for (uint i
= 0; i
< COLOUR_END
; i
++) {
442 for (uint j
= 1; j
< COLOUR_END
; j
++) {
443 if (_colour_sort
[colours
[j
- 1]] < _colour_sort
[colours
[j
]]) {
444 Swap(colours
[j
- 1], colours
[j
]);
449 /* Move the colours that look similar to each company's colour to the side */
450 for (const Company
*c
: Company::Iterate()) {
451 Colours pcolour
= (Colours
)c
->colour
;
453 for (uint i
= 0; i
< COLOUR_END
; i
++) {
454 if (colours
[i
] == pcolour
) {
455 colours
[i
] = INVALID_COLOUR
;
460 for (uint j
= 0; j
< 2; j
++) {
461 Colours similar
= _similar_colour
[pcolour
][j
];
462 if (similar
== INVALID_COLOUR
) break;
464 for (uint i
= 1; i
< COLOUR_END
; i
++) {
465 if (colours
[i
- 1] == similar
) Swap(colours
[i
- 1], colours
[i
]);
470 /* Return the first available colour */
471 for (uint i
= 0; i
< COLOUR_END
; i
++) {
472 if (colours
[i
] != INVALID_COLOUR
) return colours
[i
];
479 * Generate a random president name of a company.
480 * @param c Company that needs a new president name.
482 static void GeneratePresidentName(Company
*c
)
486 c
->president_name_2
= Random();
487 c
->president_name_1
= SPECSTR_PRESIDENT_NAME
;
489 /* Reserve space for extra unicode character. We need to do this to be able
490 * to detect too long president name. */
491 char buffer
[(MAX_LENGTH_PRESIDENT_NAME_CHARS
+ 1) * MAX_CHAR_LENGTH
];
492 SetDParam(0, c
->index
);
493 GetString(buffer
, STR_PRESIDENT_NAME
, lastof(buffer
));
494 if (Utf8StringLength(buffer
) >= MAX_LENGTH_PRESIDENT_NAME_CHARS
) continue;
496 for (const Company
*cc
: Company::Iterate()) {
498 /* Reserve extra space so even overlength president names can be compared. */
499 char buffer2
[(MAX_LENGTH_PRESIDENT_NAME_CHARS
+ 1) * MAX_CHAR_LENGTH
];
500 SetDParam(0, cc
->index
);
501 GetString(buffer2
, STR_PRESIDENT_NAME
, lastof(buffer2
));
502 if (strcmp(buffer2
, buffer
) == 0) goto restart
;
510 * Reset the livery schemes to the company's primary colour.
511 * This is used on loading games without livery information and on new company start up.
512 * @param c Company to reset.
514 void ResetCompanyLivery(Company
*c
)
516 for (LiveryScheme scheme
= LS_BEGIN
; scheme
< LS_END
; scheme
++) {
517 c
->livery
[scheme
].in_use
= 0;
518 c
->livery
[scheme
].colour1
= c
->colour
;
519 c
->livery
[scheme
].colour2
= c
->colour
;
522 for (Group
*g
: Group::Iterate()) {
523 if (g
->owner
== c
->index
) {
524 g
->livery
.in_use
= 0;
525 g
->livery
.colour1
= c
->colour
;
526 g
->livery
.colour2
= c
->colour
;
532 * Create a new company and sets all company variables default values
534 * @param is_ai is an AI company?
535 * @param company CompanyID to use for the new company
536 * @return the company struct
538 Company
*DoStartupNewCompany(bool is_ai
, CompanyID company
= INVALID_COMPANY
)
540 if (!Company::CanAllocateItem()) return nullptr;
542 /* we have to generate colour before this company is valid */
543 Colours colour
= GenerateCompanyColour();
546 if (company
== INVALID_COMPANY
) {
547 c
= new Company(STR_SV_UNNAMED
, is_ai
);
549 if (Company::IsValidID(company
)) return nullptr;
550 c
= new (company
) Company(STR_SV_UNNAMED
, is_ai
);
555 ResetCompanyLivery(c
);
556 _company_colours
[c
->index
] = (Colours
)c
->colour
;
558 c
->money
= c
->current_loan
= (std::min
<int64
>(INITIAL_LOAN
, _economy
.max_loan
) * _economy
.inflation_prices
>> 16) / 50000 * 50000;
560 c
->share_owners
[0] = c
->share_owners
[1] = c
->share_owners
[2] = c
->share_owners
[3] = INVALID_OWNER
;
562 c
->avail_railtypes
= GetCompanyRailtypes(c
->index
);
563 c
->avail_roadtypes
= GetCompanyRoadTypes(c
->index
);
564 c
->inaugurated_year
= _cur_year
;
565 RandomCompanyManagerFaceBits(c
->face
, (GenderEthnicity
)Random(), false, false); // create a random company manager face
567 SetDefaultCompanySettings(c
->index
);
568 ClearEnginesHiddenFlagOfCompany(c
->index
);
570 GeneratePresidentName(c
);
572 SetWindowDirty(WC_GRAPH_LEGEND
, 0);
573 InvalidateWindowData(WC_CLIENT_LIST
, 0);
574 InvalidateWindowData(WC_LINKGRAPH_LEGEND
, 0);
576 InvalidateWindowData(WC_SMALLMAP
, 0, 1);
578 if (is_ai
&& (!_networking
|| _network_server
)) AI::StartNew(c
->index
);
580 AI::BroadcastNewEvent(new ScriptEventCompanyNew(c
->index
), c
->index
);
581 Game::NewEvent(new ScriptEventCompanyNew(c
->index
));
586 /** Start the next competitor now. */
587 void StartupCompanies()
589 _next_competitor_start
= 0;
592 /** Start a new competitor company if possible. */
593 static bool MaybeStartNewCompany()
595 if (_networking
&& Company::GetNumItems() >= _settings_client
.network
.max_companies
) return false;
597 /* count number of competitors */
599 for (const Company
*c
: Company::Iterate()) {
603 if (n
< (uint
)_settings_game
.difficulty
.max_no_competitors
) {
604 /* Send a command to all clients to start up a new AI.
605 * Works fine for Multiplayer and Singleplayer */
606 return DoCommandP(0, CCA_NEW_AI
| INVALID_COMPANY
<< 16, 0, CMD_COMPANY_CTRL
);
612 /** Initialize the pool of companies. */
613 void InitializeCompanies()
615 _cur_company_tick_index
= 0;
619 * May company \a cbig buy company \a csmall?
620 * @param cbig Company buying \a csmall.
621 * @param csmall Company getting bought.
622 * @return Return \c true if it is allowed.
624 bool MayCompanyTakeOver(CompanyID cbig
, CompanyID csmall
)
626 const Company
*c1
= Company::Get(cbig
);
627 const Company
*c2
= Company::Get(csmall
);
629 /* Do the combined vehicle counts stay within the limits? */
630 return c1
->group_all
[VEH_TRAIN
].num_vehicle
+ c2
->group_all
[VEH_TRAIN
].num_vehicle
<= _settings_game
.vehicle
.max_trains
&&
631 c1
->group_all
[VEH_ROAD
].num_vehicle
+ c2
->group_all
[VEH_ROAD
].num_vehicle
<= _settings_game
.vehicle
.max_roadveh
&&
632 c1
->group_all
[VEH_SHIP
].num_vehicle
+ c2
->group_all
[VEH_SHIP
].num_vehicle
<= _settings_game
.vehicle
.max_ships
&&
633 c1
->group_all
[VEH_AIRCRAFT
].num_vehicle
+ c2
->group_all
[VEH_AIRCRAFT
].num_vehicle
<= _settings_game
.vehicle
.max_aircraft
;
637 * Handle the bankruptcy take over of a company.
638 * Companies going bankrupt will ask the other companies in order of their
639 * performance rating, so better performing companies get the 'do you want to
640 * merge with Y' question earlier. The question will then stay till either the
641 * company has gone bankrupt or got merged with a company.
643 * @param c the company that is going bankrupt.
645 static void HandleBankruptcyTakeover(Company
*c
)
647 /* Amount of time out for each company to take over a company;
648 * Timeout is a quarter (3 months of 30 days) divided over the
649 * number of companies. The minimum number of days in a quarter
650 * is 90: 31 in January, 28 in February and 31 in March.
651 * Note that the company going bankrupt can't buy itself. */
652 static const int TAKE_OVER_TIMEOUT
= 3 * 30 * DAY_TICKS
/ (MAX_COMPANIES
- 1);
654 assert(c
->bankrupt_asked
!= 0);
656 /* We're currently asking some company to buy 'us' */
657 if (c
->bankrupt_timeout
!= 0) {
658 c
->bankrupt_timeout
-= MAX_COMPANIES
;
659 if (c
->bankrupt_timeout
> 0) return;
660 c
->bankrupt_timeout
= 0;
665 /* Did we ask everyone for bankruptcy? If so, bail out. */
666 if (c
->bankrupt_asked
== MAX_UVALUE(CompanyMask
)) return;
668 Company
*best
= nullptr;
669 int32 best_performance
= -1;
671 /* Ask the company with the highest performance history first */
672 for (Company
*c2
: Company::Iterate()) {
673 if (c2
->bankrupt_asked
== 0 && // Don't ask companies going bankrupt themselves
674 !HasBit(c
->bankrupt_asked
, c2
->index
) &&
675 best_performance
< c2
->old_economy
[1].performance_history
&&
676 MayCompanyTakeOver(c2
->index
, c
->index
)) {
677 best_performance
= c2
->old_economy
[1].performance_history
;
682 /* Asked all companies? */
683 if (best_performance
== -1) {
684 c
->bankrupt_asked
= MAX_UVALUE(CompanyMask
);
688 SetBit(c
->bankrupt_asked
, best
->index
);
690 c
->bankrupt_timeout
= TAKE_OVER_TIMEOUT
;
692 AI::NewEvent(best
->index
, new ScriptEventCompanyAskMerger(c
->index
, ClampToI32(c
->bankrupt_value
)));
693 } else if (IsInteractiveCompany(best
->index
)) {
694 ShowBuyCompanyDialog(c
->index
);
698 /** Called every tick for updating some company info. */
699 void OnTick_Companies()
701 if (_game_mode
== GM_EDITOR
) return;
703 Company
*c
= Company::GetIfValid(_cur_company_tick_index
);
705 if (c
->name_1
!= 0) GenerateCompanyName(c
);
706 if (c
->bankrupt_asked
!= 0) HandleBankruptcyTakeover(c
);
709 if (_next_competitor_start
== 0) {
710 /* AI::GetStartNextTime() can return 0. */
711 _next_competitor_start
= std::max(1, AI::GetStartNextTime() * DAY_TICKS
);
714 if (_game_mode
!= GM_MENU
&& AI::CanStartNew() && --_next_competitor_start
== 0) {
715 /* Allow multiple AIs to possibly start in the same tick. */
717 if (!MaybeStartNewCompany()) break;
719 /* In networking mode, we can only send a command to start but it
720 * didn't execute yet, so we cannot loop. */
721 if (_networking
) break;
722 } while (AI::GetStartNextTime() == 0);
725 _cur_company_tick_index
= (_cur_company_tick_index
+ 1) % MAX_COMPANIES
;
729 * A year has passed, update the economic data of all companies, and perhaps show the
730 * financial overview window of the local company.
732 void CompaniesYearlyLoop()
734 /* Copy statistics */
735 for (Company
*c
: Company::Iterate()) {
736 memmove(&c
->yearly_expenses
[1], &c
->yearly_expenses
[0], sizeof(c
->yearly_expenses
) - sizeof(c
->yearly_expenses
[0]));
737 memset(&c
->yearly_expenses
[0], 0, sizeof(c
->yearly_expenses
[0]));
738 SetWindowDirty(WC_FINANCES
, c
->index
);
741 if (_settings_client
.gui
.show_finances
&& _local_company
!= COMPANY_SPECTATOR
) {
742 ShowCompanyFinances(_local_company
);
743 Company
*c
= Company::Get(_local_company
);
744 if (c
->num_valid_stat_ent
> 5 && c
->old_economy
[0].performance_history
< c
->old_economy
[4].performance_history
) {
745 if (_settings_client
.sound
.new_year
) SndPlayFx(SND_01_BAD_YEAR
);
747 if (_settings_client
.sound
.new_year
) SndPlayFx(SND_00_GOOD_YEAR
);
753 * Fill the CompanyNewsInformation struct with the required data.
754 * @param c the current company.
755 * @param other the other company (use \c nullptr if not relevant).
757 CompanyNewsInformation::CompanyNewsInformation(const Company
*c
, const Company
*other
)
759 SetDParam(0, c
->index
);
760 this->company_name
= GetString(STR_COMPANY_NAME
);
762 if (other
!= nullptr) {
763 SetDParam(0, other
->index
);
764 this->other_company_name
= GetString(STR_COMPANY_NAME
);
768 SetDParam(0, c
->index
);
769 this->president_name
= GetString(STR_PRESIDENT_NAME_MANAGER
);
771 this->colour
= c
->colour
;
772 this->face
= c
->face
;
777 * Called whenever company related information changes in order to notify admins.
778 * @param company The company data changed of.
780 void CompanyAdminUpdate(const Company
*company
)
782 if (_network_server
) NetworkAdminCompanyUpdate(company
);
786 * Called whenever a company is removed in order to notify admins.
787 * @param company_id The company that was removed.
788 * @param reason The reason the company was removed.
790 void CompanyAdminRemove(CompanyID company_id
, CompanyRemoveReason reason
)
792 if (_network_server
) NetworkAdminCompanyRemove(company_id
, (AdminCompanyRemoveReason
)reason
);
796 * Control the companies: add, delete, etc.
798 * @param flags operation to perform
799 * @param p1 various functionality
800 * - bits 0..15: CompanyCtrlAction
801 * - bits 16..23: CompanyID
802 * - bits 24..31: CompanyRemoveReason (with CCA_DELETE)
805 * @return the cost of this operation or an error
807 CommandCost
CmdCompanyCtrl(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const std::string
&text
)
809 InvalidateWindowData(WC_COMPANY_LEAGUE
, 0, 0);
810 CompanyID company_id
= (CompanyID
)GB(p1
, 16, 8);
812 switch ((CompanyCtrlAction
)GB(p1
, 0, 16)) {
813 case CCA_NEW
: { // Create a new company
814 /* This command is only executed in a multiplayer game */
815 if (!_networking
) return CMD_ERROR
;
817 /* Has the network client a correct ClientIndex? */
818 if (!(flags
& DC_EXEC
)) return CommandCost();
820 ClientID client_id
= (ClientID
)p2
;
821 NetworkClientInfo
*ci
= NetworkClientInfo::GetByClientID(client_id
);
823 /* Delete multiplayer progress bar */
824 CloseWindowById(WC_NETWORK_STATUS_WINDOW
, WN_NETWORK_STATUS_WINDOW_JOIN
);
826 Company
*c
= DoStartupNewCompany(false);
828 /* A new company could not be created, revert to being a spectator */
830 /* We check for "ci != nullptr" as a client could have left by
831 * the time we execute this command. */
832 if (_network_server
&& ci
!= nullptr) {
833 ci
->client_playas
= COMPANY_SPECTATOR
;
834 NetworkUpdateClientInfo(ci
->client_id
);
839 /* This is the client (or non-dedicated server) who wants a new company */
840 if (client_id
== _network_own_client_id
) {
841 assert(_local_company
== COMPANY_SPECTATOR
);
842 SetLocalCompany(c
->index
);
843 if (!_settings_client
.network
.default_company_pass
.empty()) {
844 NetworkChangeCompanyPassword(_local_company
, _settings_client
.network
.default_company_pass
);
847 /* Now that we have a new company, broadcast our company settings to
848 * all clients so everything is in sync */
849 SyncCompanySettings();
851 MarkWholeScreenDirty();
854 NetworkServerNewCompany(c
, ci
);
858 case CCA_NEW_AI
: { // Make a new AI company
859 if (company_id
!= INVALID_COMPANY
&& company_id
>= MAX_COMPANIES
) return CMD_ERROR
;
861 /* For network games, company deletion is delayed. */
862 if (!_networking
&& company_id
!= INVALID_COMPANY
&& Company::IsValidID(company_id
)) return CMD_ERROR
;
864 if (!(flags
& DC_EXEC
)) return CommandCost();
866 /* For network game, just assume deletion happened. */
867 assert(company_id
== INVALID_COMPANY
|| !Company::IsValidID(company_id
));
869 Company
*c
= DoStartupNewCompany(true, company_id
);
870 if (c
!= nullptr) NetworkServerNewCompany(c
, nullptr);
874 case CCA_DELETE
: { // Delete a company
875 CompanyRemoveReason reason
= (CompanyRemoveReason
)GB(p1
, 24, 8);
876 if (reason
>= CRR_END
) return CMD_ERROR
;
878 /* We can't delete the last existing company in singleplayer mode. */
879 if (!_networking
&& Company::GetNumItems() == 1) return CMD_ERROR
;
881 Company
*c
= Company::GetIfValid(company_id
);
882 if (c
== nullptr) return CMD_ERROR
;
884 if (!(flags
& DC_EXEC
)) return CommandCost();
886 /* Delete any open window of the company */
887 CloseCompanyWindows(c
->index
);
888 CompanyNewsInformation
*cni
= new CompanyNewsInformation(c
);
890 /* Show the bankrupt news */
891 SetDParam(0, STR_NEWS_COMPANY_BANKRUPT_TITLE
);
892 SetDParam(1, STR_NEWS_COMPANY_BANKRUPT_DESCRIPTION
);
893 SetDParamStr(2, cni
->company_name
);
894 AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT
, cni
);
896 /* Remove the company */
897 ChangeOwnershipOfCompanyItems(c
->index
, INVALID_OWNER
);
898 if (c
->is_ai
) AI::Stop(c
->index
);
900 CompanyID c_index
= c
->index
;
902 AI::BroadcastNewEvent(new ScriptEventCompanyBankrupt(c_index
));
903 Game::NewEvent(new ScriptEventCompanyBankrupt(c_index
));
904 CompanyAdminRemove(c_index
, (CompanyRemoveReason
)reason
);
906 if (StoryPage::GetNumItems() == 0 || Goal::GetNumItems() == 0) InvalidateWindowData(WC_MAIN_TOOLBAR
, 0);
907 InvalidateWindowData(WC_CLIENT_LIST
, 0);
912 default: return CMD_ERROR
;
915 InvalidateWindowClassesData(WC_GAME_OPTIONS
);
916 InvalidateWindowClassesData(WC_AI_SETTINGS
);
917 InvalidateWindowClassesData(WC_AI_LIST
);
919 return CommandCost();
923 * Change the company manager's face.
925 * @param flags operation to perform
927 * @param p2 face bitmasked
929 * @return the cost of this operation or an error
931 CommandCost
CmdSetCompanyManagerFace(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const std::string
&text
)
933 CompanyManagerFace cmf
= (CompanyManagerFace
)p2
;
935 if (!IsValidCompanyManagerFace(cmf
)) return CMD_ERROR
;
937 if (flags
& DC_EXEC
) {
938 Company::Get(_current_company
)->face
= cmf
;
939 MarkWholeScreenDirty();
941 return CommandCost();
945 * Change the company's company-colour
947 * @param flags operation to perform
948 * @param p1 bitstuffed:
949 * p1 bits 0-7 scheme to set
950 * p1 bit 8 set first/second colour
951 * @param p2 new colour for vehicles, property, etc.
953 * @return the cost of this operation or an error
955 CommandCost
CmdSetCompanyColour(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const std::string
&text
)
957 Colours colour
= Extract
<Colours
, 0, 8>(p2
);
958 LiveryScheme scheme
= Extract
<LiveryScheme
, 0, 8>(p1
);
959 bool second
= HasBit(p1
, 8);
961 if (scheme
>= LS_END
|| (colour
>= COLOUR_END
&& colour
!= INVALID_COLOUR
)) return CMD_ERROR
;
963 /* Default scheme can't be reset to invalid. */
964 if (scheme
== LS_DEFAULT
&& colour
== INVALID_COLOUR
) return CMD_ERROR
;
966 Company
*c
= Company::Get(_current_company
);
968 /* Ensure no two companies have the same primary colour */
969 if (scheme
== LS_DEFAULT
&& !second
) {
970 for (const Company
*cc
: Company::Iterate()) {
971 if (cc
!= c
&& cc
->colour
== colour
) return CMD_ERROR
;
975 if (flags
& DC_EXEC
) {
977 if (scheme
!= LS_DEFAULT
) SB(c
->livery
[scheme
].in_use
, 0, 1, colour
!= INVALID_COLOUR
);
978 if (colour
== INVALID_COLOUR
) colour
= (Colours
)c
->livery
[LS_DEFAULT
].colour1
;
979 c
->livery
[scheme
].colour1
= colour
;
981 /* If setting the first colour of the default scheme, adjust the
982 * original and cached company colours too. */
983 if (scheme
== LS_DEFAULT
) {
984 for (int i
= 1; i
< LS_END
; i
++) {
985 if (!HasBit(c
->livery
[i
].in_use
, 0)) c
->livery
[i
].colour1
= colour
;
987 _company_colours
[_current_company
] = colour
;
989 CompanyAdminUpdate(c
);
992 if (scheme
!= LS_DEFAULT
) SB(c
->livery
[scheme
].in_use
, 1, 1, colour
!= INVALID_COLOUR
);
993 if (colour
== INVALID_COLOUR
) colour
= (Colours
)c
->livery
[LS_DEFAULT
].colour2
;
994 c
->livery
[scheme
].colour2
= colour
;
996 if (scheme
== LS_DEFAULT
) {
997 for (int i
= 1; i
< LS_END
; i
++) {
998 if (!HasBit(c
->livery
[i
].in_use
, 1)) c
->livery
[i
].colour2
= colour
;
1003 if (c
->livery
[scheme
].in_use
!= 0) {
1004 /* If enabling a scheme, set the default scheme to be in use too */
1005 c
->livery
[LS_DEFAULT
].in_use
= 1;
1007 /* Else loop through all schemes to see if any are left enabled.
1008 * If not, disable the default scheme too. */
1009 c
->livery
[LS_DEFAULT
].in_use
= 0;
1010 for (scheme
= LS_DEFAULT
; scheme
< LS_END
; scheme
++) {
1011 if (c
->livery
[scheme
].in_use
!= 0) {
1012 c
->livery
[LS_DEFAULT
].in_use
= 1;
1018 ResetVehicleColourMap();
1019 MarkWholeScreenDirty();
1021 /* All graph related to companies use the company colour. */
1022 InvalidateWindowData(WC_INCOME_GRAPH
, 0);
1023 InvalidateWindowData(WC_OPERATING_PROFIT
, 0);
1024 InvalidateWindowData(WC_DELIVERED_CARGO
, 0);
1025 InvalidateWindowData(WC_PERFORMANCE_HISTORY
, 0);
1026 InvalidateWindowData(WC_COMPANY_VALUE
, 0);
1027 InvalidateWindowData(WC_LINKGRAPH_LEGEND
, 0);
1028 /* The smallmap owner view also stores the company colours. */
1030 InvalidateWindowData(WC_SMALLMAP
, 0, 1);
1032 /* Company colour data is indirectly cached. */
1033 for (Vehicle
*v
: Vehicle::Iterate()) {
1034 if (v
->owner
== _current_company
) v
->InvalidateNewGRFCache();
1037 extern void UpdateObjectColours(const Company
*c
);
1038 UpdateObjectColours(c
);
1040 return CommandCost();
1044 * Is the given name in use as name of a company?
1045 * @param name Name to search.
1046 * @return \c true if the name us unique (that is, not in use), else \c false.
1048 static bool IsUniqueCompanyName(const std::string
&name
)
1050 for (const Company
*c
: Company::Iterate()) {
1051 if (!c
->name
.empty() && c
->name
== name
) return false;
1058 * Change the name of the company.
1059 * @param tile unused
1060 * @param flags operation to perform
1063 * @param text the new name or an empty string when resetting to the default
1064 * @return the cost of this operation or an error
1066 CommandCost
CmdRenameCompany(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const std::string
&text
)
1068 bool reset
= text
.empty();
1071 if (Utf8StringLength(text
) >= MAX_LENGTH_COMPANY_NAME_CHARS
) return CMD_ERROR
;
1072 if (!IsUniqueCompanyName(text
)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE
);
1075 if (flags
& DC_EXEC
) {
1076 Company
*c
= Company::Get(_current_company
);
1082 MarkWholeScreenDirty();
1083 CompanyAdminUpdate(c
);
1086 return CommandCost();
1090 * Is the given name in use as president name of a company?
1091 * @param name Name to search.
1092 * @return \c true if the name us unique (that is, not in use), else \c false.
1094 static bool IsUniquePresidentName(const std::string
&name
)
1096 for (const Company
*c
: Company::Iterate()) {
1097 if (!c
->president_name
.empty() && c
->president_name
== name
) return false;
1104 * Change the name of the president.
1105 * @param tile unused
1106 * @param flags operation to perform
1109 * @param text the new name or an empty string when resetting to the default
1110 * @return the cost of this operation or an error
1112 CommandCost
CmdRenamePresident(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const std::string
&text
)
1114 bool reset
= text
.empty();
1117 if (Utf8StringLength(text
) >= MAX_LENGTH_PRESIDENT_NAME_CHARS
) return CMD_ERROR
;
1118 if (!IsUniquePresidentName(text
)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE
);
1121 if (flags
& DC_EXEC
) {
1122 Company
*c
= Company::Get(_current_company
);
1125 c
->president_name
.clear();
1127 c
->president_name
= text
;
1129 if (c
->name_1
== STR_SV_UNNAMED
&& c
->name
.empty()) {
1130 DoCommand(0, 0, 0, DC_EXEC
, CMD_RENAME_COMPANY
, text
+ " Transport");
1134 MarkWholeScreenDirty();
1135 CompanyAdminUpdate(c
);
1138 return CommandCost();
1142 * Get the service interval for the given company and vehicle type.
1143 * @param c The company, or nullptr for client-default settings.
1144 * @param type The vehicle type to get the interval for.
1145 * @return The service interval.
1147 int CompanyServiceInterval(const Company
*c
, VehicleType type
)
1149 const VehicleDefaultSettings
*vds
= (c
== nullptr) ? &_settings_client
.company
.vehicle
: &c
->settings
.vehicle
;
1151 default: NOT_REACHED();
1152 case VEH_TRAIN
: return vds
->servint_trains
;
1153 case VEH_ROAD
: return vds
->servint_roadveh
;
1154 case VEH_AIRCRAFT
: return vds
->servint_aircraft
;
1155 case VEH_SHIP
: return vds
->servint_ships
;
1160 * Get total sum of all owned road bits.
1161 * @return Combined total road road bits.
1163 uint32
CompanyInfrastructure::GetRoadTotal() const
1166 for (RoadType rt
= ROADTYPE_BEGIN
; rt
!= ROADTYPE_END
; rt
++) {
1167 if (RoadTypeIsRoad(rt
)) total
+= this->road
[rt
];
1173 * Get total sum of all owned tram bits.
1174 * @return Combined total of tram road bits.
1176 uint32
CompanyInfrastructure::GetTramTotal() const
1179 for (RoadType rt
= ROADTYPE_BEGIN
; rt
!= ROADTYPE_END
; rt
++) {
1180 if (RoadTypeIsTram(rt
)) total
+= this->road
[rt
];
1186 * Transfer funds (money) from one company to another.
1187 * To prevent abuse in multiplayer games you can only send money to other
1188 * companies if you have paid off your loan (either explicitly, or implicitly
1189 * given the fact that you have more money than loan).
1190 * @param tile unused
1191 * @param flags operation to perform
1192 * @param p1 the amount of money to transfer; max 20.000.000
1193 * @param p2 the company to transfer the money to
1194 * @param text unused
1195 * @return the cost of this operation or an error
1197 CommandCost
CmdGiveMoney(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const std::string
&text
)
1199 if (!_settings_game
.economy
.give_money
) return CMD_ERROR
;
1201 const Company
*c
= Company::Get(_current_company
);
1202 CommandCost
amount(EXPENSES_OTHER
, std::min
<Money
>(p1
, 20000000LL));
1203 CompanyID dest_company
= (CompanyID
)p2
;
1205 /* You can only transfer funds that is in excess of your loan */
1206 if (c
->money
- c
->current_loan
< amount
.GetCost() || amount
.GetCost() < 0) return_cmd_error(STR_ERROR_INSUFFICIENT_FUNDS
);
1207 if (!Company::IsValidID(dest_company
)) return CMD_ERROR
;
1209 if (flags
& DC_EXEC
) {
1210 /* Add money to company */
1211 Backup
<CompanyID
> cur_company(_current_company
, dest_company
, FILE_LINE
);
1212 SubtractMoneyFromCompany(CommandCost(EXPENSES_OTHER
, -amount
.GetCost()));
1213 cur_company
.Restore();
1216 SetDParam(0, dest_company
);
1217 std::string dest_company_name
= GetString(STR_COMPANY_NAME
);
1219 SetDParam(0, _current_company
);
1220 std::string from_company_name
= GetString(STR_COMPANY_NAME
);
1222 NetworkTextMessage(NETWORK_ACTION_GIVE_MONEY
, GetDrawStringCompanyColour(_current_company
), false, from_company_name
, dest_company_name
, amount
.GetCost());
1226 /* Subtract money from local-company */