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 "command_func.h"
18 #include "network/network.h"
19 #include "network/network_func.h"
20 #include "network/network_base.h"
21 #include "network/network_admin.h"
23 #include "company_manager_face.h"
24 #include "window_func.h"
25 #include "strings_func.h"
26 #include "date_func.h"
27 #include "sound_func.h"
29 #include "core/pool_func.hpp"
30 #include "settings_func.h"
31 #include "vehicle_base.h"
32 #include "vehicle_func.h"
33 #include "smallmap_gui.h"
34 #include "game/game.hpp"
35 #include "goal_base.h"
36 #include "story_base.h"
37 #include "widgets/statusbar_widget.h"
38 #include "company_cmd.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 std::fill(this->share_owners
.begin(), this->share_owners
.end(), 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_REVENUE
|
223 1 << EXPENSES_ROADVEH_REVENUE
|
224 1 << EXPENSES_AIRCRAFT_REVENUE
|
225 1 << EXPENSES_SHIP_REVENUE
, 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_INTEREST
, 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 std::fill(c
->share_owners
.begin(), c
->share_owners
.end(), INVALID_OWNER
);
562 c
->avail_railtypes
= GetCompanyRailtypes(c
->index
);
563 c
->avail_roadtypes
= GetCompanyRoadTypes(c
->index
);
564 c
->inaugurated_year
= _cur_year
;
566 /* If starting a player company in singleplayer and a favorite company manager face is selected, choose it. Otherwise, use a random face.
567 * In a network game, we'll choose the favorite face later in CmdCompanyCtrl to sync it to all clients, but we choose it here for the first (host) company. */
568 if (_company_manager_face
!= 0 && !is_ai
) {
569 c
->face
= _company_manager_face
;
571 RandomCompanyManagerFaceBits(c
->face
, (GenderEthnicity
)Random(), false, false);
574 SetDefaultCompanySettings(c
->index
);
575 ClearEnginesHiddenFlagOfCompany(c
->index
);
577 GeneratePresidentName(c
);
579 SetWindowDirty(WC_GRAPH_LEGEND
, 0);
580 InvalidateWindowData(WC_CLIENT_LIST
, 0);
581 InvalidateWindowData(WC_LINKGRAPH_LEGEND
, 0);
583 InvalidateWindowData(WC_SMALLMAP
, 0, 1);
585 if (is_ai
&& (!_networking
|| _network_server
)) AI::StartNew(c
->index
);
587 AI::BroadcastNewEvent(new ScriptEventCompanyNew(c
->index
), c
->index
);
588 Game::NewEvent(new ScriptEventCompanyNew(c
->index
));
593 /** Start the next competitor now. */
594 void StartupCompanies()
596 _next_competitor_start
= 0;
599 /** Start a new competitor company if possible. */
600 static bool MaybeStartNewCompany()
602 if (_networking
&& Company::GetNumItems() >= _settings_client
.network
.max_companies
) return false;
604 /* count number of competitors */
606 for (const Company
*c
: Company::Iterate()) {
610 if (n
< (uint
)_settings_game
.difficulty
.max_no_competitors
) {
611 /* Send a command to all clients to start up a new AI.
612 * Works fine for Multiplayer and Singleplayer */
613 return Command
<CMD_COMPANY_CTRL
>::Post(CCA_NEW_AI
, INVALID_COMPANY
, CRR_NONE
, INVALID_CLIENT_ID
);
619 /** Initialize the pool of companies. */
620 void InitializeCompanies()
622 _cur_company_tick_index
= 0;
626 * May company \a cbig buy company \a csmall?
627 * @param cbig Company buying \a csmall.
628 * @param csmall Company getting bought.
629 * @return Return \c true if it is allowed.
631 bool MayCompanyTakeOver(CompanyID cbig
, CompanyID csmall
)
633 const Company
*c1
= Company::Get(cbig
);
634 const Company
*c2
= Company::Get(csmall
);
636 /* Do the combined vehicle counts stay within the limits? */
637 return c1
->group_all
[VEH_TRAIN
].num_vehicle
+ c2
->group_all
[VEH_TRAIN
].num_vehicle
<= _settings_game
.vehicle
.max_trains
&&
638 c1
->group_all
[VEH_ROAD
].num_vehicle
+ c2
->group_all
[VEH_ROAD
].num_vehicle
<= _settings_game
.vehicle
.max_roadveh
&&
639 c1
->group_all
[VEH_SHIP
].num_vehicle
+ c2
->group_all
[VEH_SHIP
].num_vehicle
<= _settings_game
.vehicle
.max_ships
&&
640 c1
->group_all
[VEH_AIRCRAFT
].num_vehicle
+ c2
->group_all
[VEH_AIRCRAFT
].num_vehicle
<= _settings_game
.vehicle
.max_aircraft
;
644 * Handle the bankruptcy take over of a company.
645 * Companies going bankrupt will ask the other companies in order of their
646 * performance rating, so better performing companies get the 'do you want to
647 * merge with Y' question earlier. The question will then stay till either the
648 * company has gone bankrupt or got merged with a company.
650 * @param c the company that is going bankrupt.
652 static void HandleBankruptcyTakeover(Company
*c
)
654 /* Amount of time out for each company to take over a company;
655 * Timeout is a quarter (3 months of 30 days) divided over the
656 * number of companies. The minimum number of days in a quarter
657 * is 90: 31 in January, 28 in February and 31 in March.
658 * Note that the company going bankrupt can't buy itself. */
659 static const int TAKE_OVER_TIMEOUT
= 3 * 30 * DAY_TICKS
/ (MAX_COMPANIES
- 1);
661 assert(c
->bankrupt_asked
!= 0);
663 /* We're currently asking some company to buy 'us' */
664 if (c
->bankrupt_timeout
!= 0) {
665 c
->bankrupt_timeout
-= MAX_COMPANIES
;
666 if (c
->bankrupt_timeout
> 0) return;
667 c
->bankrupt_timeout
= 0;
672 /* Did we ask everyone for bankruptcy? If so, bail out. */
673 if (c
->bankrupt_asked
== MAX_UVALUE(CompanyMask
)) return;
675 Company
*best
= nullptr;
676 int32 best_performance
= -1;
678 /* Ask the company with the highest performance history first */
679 for (Company
*c2
: Company::Iterate()) {
680 if (c2
->bankrupt_asked
== 0 && // Don't ask companies going bankrupt themselves
681 !HasBit(c
->bankrupt_asked
, c2
->index
) &&
682 best_performance
< c2
->old_economy
[1].performance_history
&&
683 MayCompanyTakeOver(c2
->index
, c
->index
)) {
684 best_performance
= c2
->old_economy
[1].performance_history
;
689 /* Asked all companies? */
690 if (best_performance
== -1) {
691 c
->bankrupt_asked
= MAX_UVALUE(CompanyMask
);
695 SetBit(c
->bankrupt_asked
, best
->index
);
697 c
->bankrupt_timeout
= TAKE_OVER_TIMEOUT
;
699 AI::NewEvent(best
->index
, new ScriptEventCompanyAskMerger(c
->index
, ClampToI32(c
->bankrupt_value
)));
700 } else if (IsInteractiveCompany(best
->index
)) {
701 ShowBuyCompanyDialog(c
->index
);
705 /** Called every tick for updating some company info. */
706 void OnTick_Companies()
708 if (_game_mode
== GM_EDITOR
) return;
710 Company
*c
= Company::GetIfValid(_cur_company_tick_index
);
712 if (c
->name_1
!= 0) GenerateCompanyName(c
);
713 if (c
->bankrupt_asked
!= 0) HandleBankruptcyTakeover(c
);
716 if (_next_competitor_start
== 0) {
717 /* AI::GetStartNextTime() can return 0. */
718 _next_competitor_start
= std::max(1, AI::GetStartNextTime() * DAY_TICKS
);
721 if (_game_mode
!= GM_MENU
&& AI::CanStartNew() && --_next_competitor_start
== 0) {
722 /* Allow multiple AIs to possibly start in the same tick. */
724 if (!MaybeStartNewCompany()) break;
726 /* In networking mode, we can only send a command to start but it
727 * didn't execute yet, so we cannot loop. */
728 if (_networking
) break;
729 } while (AI::GetStartNextTime() == 0);
732 _cur_company_tick_index
= (_cur_company_tick_index
+ 1) % MAX_COMPANIES
;
736 * A year has passed, update the economic data of all companies, and perhaps show the
737 * financial overview window of the local company.
739 void CompaniesYearlyLoop()
741 /* Copy statistics */
742 for (Company
*c
: Company::Iterate()) {
743 memmove(&c
->yearly_expenses
[1], &c
->yearly_expenses
[0], sizeof(c
->yearly_expenses
) - sizeof(c
->yearly_expenses
[0]));
744 memset(&c
->yearly_expenses
[0], 0, sizeof(c
->yearly_expenses
[0]));
745 SetWindowDirty(WC_FINANCES
, c
->index
);
748 if (_settings_client
.gui
.show_finances
&& _local_company
!= COMPANY_SPECTATOR
) {
749 ShowCompanyFinances(_local_company
);
750 Company
*c
= Company::Get(_local_company
);
751 if (c
->num_valid_stat_ent
> 5 && c
->old_economy
[0].performance_history
< c
->old_economy
[4].performance_history
) {
752 if (_settings_client
.sound
.new_year
) SndPlayFx(SND_01_BAD_YEAR
);
754 if (_settings_client
.sound
.new_year
) SndPlayFx(SND_00_GOOD_YEAR
);
760 * Fill the CompanyNewsInformation struct with the required data.
761 * @param c the current company.
762 * @param other the other company (use \c nullptr if not relevant).
764 CompanyNewsInformation::CompanyNewsInformation(const Company
*c
, const Company
*other
)
766 SetDParam(0, c
->index
);
767 this->company_name
= GetString(STR_COMPANY_NAME
);
769 if (other
!= nullptr) {
770 SetDParam(0, other
->index
);
771 this->other_company_name
= GetString(STR_COMPANY_NAME
);
775 SetDParam(0, c
->index
);
776 this->president_name
= GetString(STR_PRESIDENT_NAME_MANAGER
);
778 this->colour
= c
->colour
;
779 this->face
= c
->face
;
784 * Called whenever company related information changes in order to notify admins.
785 * @param company The company data changed of.
787 void CompanyAdminUpdate(const Company
*company
)
789 if (_network_server
) NetworkAdminCompanyUpdate(company
);
793 * Called whenever a company is removed in order to notify admins.
794 * @param company_id The company that was removed.
795 * @param reason The reason the company was removed.
797 void CompanyAdminRemove(CompanyID company_id
, CompanyRemoveReason reason
)
799 if (_network_server
) NetworkAdminCompanyRemove(company_id
, (AdminCompanyRemoveReason
)reason
);
803 * Control the companies: add, delete, etc.
804 * @param flags operation to perform
805 * @param cca action to perform
806 * @param company_id company to perform the action on
807 * @param client_id ClientID
808 * @return the cost of this operation or an error
810 CommandCost
CmdCompanyCtrl(DoCommandFlag flags
, CompanyCtrlAction cca
, CompanyID company_id
, CompanyRemoveReason reason
, ClientID client_id
)
812 InvalidateWindowData(WC_COMPANY_LEAGUE
, 0, 0);
815 case CCA_NEW
: { // Create a new company
816 /* This command is only executed in a multiplayer game */
817 if (!_networking
) return CMD_ERROR
;
819 /* Has the network client a correct ClientIndex? */
820 if (!(flags
& DC_EXEC
)) return CommandCost();
822 NetworkClientInfo
*ci
= NetworkClientInfo::GetByClientID(client_id
);
824 /* Delete multiplayer progress bar */
825 CloseWindowById(WC_NETWORK_STATUS_WINDOW
, WN_NETWORK_STATUS_WINDOW_JOIN
);
827 Company
*c
= DoStartupNewCompany(false);
829 /* A new company could not be created, revert to being a spectator */
831 /* We check for "ci != nullptr" as a client could have left by
832 * the time we execute this command. */
833 if (_network_server
&& ci
!= nullptr) {
834 ci
->client_playas
= COMPANY_SPECTATOR
;
835 NetworkUpdateClientInfo(ci
->client_id
);
840 /* This is the client (or non-dedicated server) who wants a new company */
841 if (client_id
== _network_own_client_id
) {
842 assert(_local_company
== COMPANY_SPECTATOR
);
843 SetLocalCompany(c
->index
);
844 if (!_settings_client
.network
.default_company_pass
.empty()) {
845 NetworkChangeCompanyPassword(_local_company
, _settings_client
.network
.default_company_pass
);
848 /* In network games, we need to try setting the company manager face here to sync it to all clients.
849 * If a favorite company manager face is selected, choose it. Otherwise, use a random face. */
850 if (_company_manager_face
!= 0) Command
<CMD_SET_COMPANY_MANAGER_FACE
>::SendNet(STR_NULL
, c
->index
, _company_manager_face
);
852 /* Now that we have a new company, broadcast our company settings to
853 * all clients so everything is in sync */
854 SyncCompanySettings();
856 MarkWholeScreenDirty();
859 NetworkServerNewCompany(c
, ci
);
863 case CCA_NEW_AI
: { // Make a new AI company
864 if (company_id
!= INVALID_COMPANY
&& company_id
>= MAX_COMPANIES
) return CMD_ERROR
;
866 /* For network games, company deletion is delayed. */
867 if (!_networking
&& company_id
!= INVALID_COMPANY
&& Company::IsValidID(company_id
)) return CMD_ERROR
;
869 if (!(flags
& DC_EXEC
)) return CommandCost();
871 /* For network game, just assume deletion happened. */
872 assert(company_id
== INVALID_COMPANY
|| !Company::IsValidID(company_id
));
874 Company
*c
= DoStartupNewCompany(true, company_id
);
875 if (c
!= nullptr) NetworkServerNewCompany(c
, nullptr);
879 case CCA_DELETE
: { // Delete a company
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 CloseCompanyWindows(c
->index
);
892 CompanyNewsInformation
*cni
= new CompanyNewsInformation(c
);
894 /* Show the bankrupt news */
895 SetDParam(0, STR_NEWS_COMPANY_BANKRUPT_TITLE
);
896 SetDParam(1, STR_NEWS_COMPANY_BANKRUPT_DESCRIPTION
);
897 SetDParamStr(2, cni
->company_name
);
898 AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT
, cni
);
900 /* Remove the company */
901 ChangeOwnershipOfCompanyItems(c
->index
, INVALID_OWNER
);
902 if (c
->is_ai
) AI::Stop(c
->index
);
904 CompanyID c_index
= c
->index
;
906 AI::BroadcastNewEvent(new ScriptEventCompanyBankrupt(c_index
));
907 Game::NewEvent(new ScriptEventCompanyBankrupt(c_index
));
908 CompanyAdminRemove(c_index
, (CompanyRemoveReason
)reason
);
910 if (StoryPage::GetNumItems() == 0 || Goal::GetNumItems() == 0) InvalidateWindowData(WC_MAIN_TOOLBAR
, 0);
911 InvalidateWindowData(WC_CLIENT_LIST
, 0);
916 default: return CMD_ERROR
;
919 InvalidateWindowClassesData(WC_GAME_OPTIONS
);
920 InvalidateWindowClassesData(WC_AI_SETTINGS
);
921 InvalidateWindowClassesData(WC_AI_LIST
);
923 return CommandCost();
927 * Change the company manager's face.
928 * @param flags operation to perform
929 * @param cmf face bitmasked
930 * @return the cost of this operation or an error
932 CommandCost
CmdSetCompanyManagerFace(DoCommandFlag flags
, CompanyManagerFace cmf
)
934 if (!IsValidCompanyManagerFace(cmf
)) return CMD_ERROR
;
936 if (flags
& DC_EXEC
) {
937 Company::Get(_current_company
)->face
= cmf
;
938 MarkWholeScreenDirty();
940 return CommandCost();
944 * Change the company's company-colour
945 * @param flags operation to perform
946 * @param scheme scheme to set
947 * @param primary set first/second colour
948 * @param colour new colour for vehicles, property, etc.
949 * @return the cost of this operation or an error
951 CommandCost
CmdSetCompanyColour(DoCommandFlag flags
, LiveryScheme scheme
, bool primary
, Colours colour
)
953 if (scheme
>= LS_END
|| (colour
>= COLOUR_END
&& colour
!= INVALID_COLOUR
)) return CMD_ERROR
;
955 /* Default scheme can't be reset to invalid. */
956 if (scheme
== LS_DEFAULT
&& colour
== INVALID_COLOUR
) return CMD_ERROR
;
958 Company
*c
= Company::Get(_current_company
);
960 /* Ensure no two companies have the same primary colour */
961 if (scheme
== LS_DEFAULT
&& primary
) {
962 for (const Company
*cc
: Company::Iterate()) {
963 if (cc
!= c
&& cc
->colour
== colour
) return CMD_ERROR
;
967 if (flags
& DC_EXEC
) {
969 if (scheme
!= LS_DEFAULT
) SB(c
->livery
[scheme
].in_use
, 0, 1, colour
!= INVALID_COLOUR
);
970 if (colour
== INVALID_COLOUR
) colour
= (Colours
)c
->livery
[LS_DEFAULT
].colour1
;
971 c
->livery
[scheme
].colour1
= colour
;
973 /* If setting the first colour of the default scheme, adjust the
974 * original and cached company colours too. */
975 if (scheme
== LS_DEFAULT
) {
976 for (int i
= 1; i
< LS_END
; i
++) {
977 if (!HasBit(c
->livery
[i
].in_use
, 0)) c
->livery
[i
].colour1
= colour
;
979 _company_colours
[_current_company
] = colour
;
981 CompanyAdminUpdate(c
);
984 if (scheme
!= LS_DEFAULT
) SB(c
->livery
[scheme
].in_use
, 1, 1, colour
!= INVALID_COLOUR
);
985 if (colour
== INVALID_COLOUR
) colour
= (Colours
)c
->livery
[LS_DEFAULT
].colour2
;
986 c
->livery
[scheme
].colour2
= colour
;
988 if (scheme
== LS_DEFAULT
) {
989 for (int i
= 1; i
< LS_END
; i
++) {
990 if (!HasBit(c
->livery
[i
].in_use
, 1)) c
->livery
[i
].colour2
= colour
;
995 if (c
->livery
[scheme
].in_use
!= 0) {
996 /* If enabling a scheme, set the default scheme to be in use too */
997 c
->livery
[LS_DEFAULT
].in_use
= 1;
999 /* Else loop through all schemes to see if any are left enabled.
1000 * If not, disable the default scheme too. */
1001 c
->livery
[LS_DEFAULT
].in_use
= 0;
1002 for (scheme
= LS_DEFAULT
; scheme
< LS_END
; scheme
++) {
1003 if (c
->livery
[scheme
].in_use
!= 0) {
1004 c
->livery
[LS_DEFAULT
].in_use
= 1;
1010 ResetVehicleColourMap();
1011 MarkWholeScreenDirty();
1013 /* All graph related to companies use the company colour. */
1014 InvalidateWindowData(WC_INCOME_GRAPH
, 0);
1015 InvalidateWindowData(WC_OPERATING_PROFIT
, 0);
1016 InvalidateWindowData(WC_DELIVERED_CARGO
, 0);
1017 InvalidateWindowData(WC_PERFORMANCE_HISTORY
, 0);
1018 InvalidateWindowData(WC_COMPANY_VALUE
, 0);
1019 InvalidateWindowData(WC_LINKGRAPH_LEGEND
, 0);
1020 /* The smallmap owner view also stores the company colours. */
1022 InvalidateWindowData(WC_SMALLMAP
, 0, 1);
1024 /* Company colour data is indirectly cached. */
1025 for (Vehicle
*v
: Vehicle::Iterate()) {
1026 if (v
->owner
== _current_company
) v
->InvalidateNewGRFCache();
1029 extern void UpdateObjectColours(const Company
*c
);
1030 UpdateObjectColours(c
);
1032 return CommandCost();
1036 * Is the given name in use as name of a company?
1037 * @param name Name to search.
1038 * @return \c true if the name us unique (that is, not in use), else \c false.
1040 static bool IsUniqueCompanyName(const std::string
&name
)
1042 for (const Company
*c
: Company::Iterate()) {
1043 if (!c
->name
.empty() && c
->name
== name
) return false;
1050 * Change the name of the company.
1051 * @param flags operation to perform
1052 * @param text the new name or an empty string when resetting to the default
1053 * @return the cost of this operation or an error
1055 CommandCost
CmdRenameCompany(DoCommandFlag flags
, const std::string
&text
)
1057 bool reset
= text
.empty();
1060 if (Utf8StringLength(text
) >= MAX_LENGTH_COMPANY_NAME_CHARS
) return CMD_ERROR
;
1061 if (!IsUniqueCompanyName(text
)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE
);
1064 if (flags
& DC_EXEC
) {
1065 Company
*c
= Company::Get(_current_company
);
1071 MarkWholeScreenDirty();
1072 CompanyAdminUpdate(c
);
1075 return CommandCost();
1079 * Is the given name in use as president name of a company?
1080 * @param name Name to search.
1081 * @return \c true if the name us unique (that is, not in use), else \c false.
1083 static bool IsUniquePresidentName(const std::string
&name
)
1085 for (const Company
*c
: Company::Iterate()) {
1086 if (!c
->president_name
.empty() && c
->president_name
== name
) return false;
1093 * Change the name of the president.
1094 * @param flags operation to perform
1095 * @param text the new name or an empty string when resetting to the default
1096 * @return the cost of this operation or an error
1098 CommandCost
CmdRenamePresident(DoCommandFlag flags
, const std::string
&text
)
1100 bool reset
= text
.empty();
1103 if (Utf8StringLength(text
) >= MAX_LENGTH_PRESIDENT_NAME_CHARS
) return CMD_ERROR
;
1104 if (!IsUniquePresidentName(text
)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE
);
1107 if (flags
& DC_EXEC
) {
1108 Company
*c
= Company::Get(_current_company
);
1111 c
->president_name
.clear();
1113 c
->president_name
= text
;
1115 if (c
->name_1
== STR_SV_UNNAMED
&& c
->name
.empty()) {
1116 Command
<CMD_RENAME_COMPANY
>::Do(DC_EXEC
, text
+ " Transport");
1120 MarkWholeScreenDirty();
1121 CompanyAdminUpdate(c
);
1124 return CommandCost();
1128 * Get the service interval for the given company and vehicle type.
1129 * @param c The company, or nullptr for client-default settings.
1130 * @param type The vehicle type to get the interval for.
1131 * @return The service interval.
1133 int CompanyServiceInterval(const Company
*c
, VehicleType type
)
1135 const VehicleDefaultSettings
*vds
= (c
== nullptr) ? &_settings_client
.company
.vehicle
: &c
->settings
.vehicle
;
1137 default: NOT_REACHED();
1138 case VEH_TRAIN
: return vds
->servint_trains
;
1139 case VEH_ROAD
: return vds
->servint_roadveh
;
1140 case VEH_AIRCRAFT
: return vds
->servint_aircraft
;
1141 case VEH_SHIP
: return vds
->servint_ships
;
1146 * Get total sum of all owned road bits.
1147 * @return Combined total road road bits.
1149 uint32
CompanyInfrastructure::GetRoadTotal() const
1152 for (RoadType rt
= ROADTYPE_BEGIN
; rt
!= ROADTYPE_END
; rt
++) {
1153 if (RoadTypeIsRoad(rt
)) total
+= this->road
[rt
];
1159 * Get total sum of all owned tram bits.
1160 * @return Combined total of tram road bits.
1162 uint32
CompanyInfrastructure::GetTramTotal() const
1165 for (RoadType rt
= ROADTYPE_BEGIN
; rt
!= ROADTYPE_END
; rt
++) {
1166 if (RoadTypeIsTram(rt
)) total
+= this->road
[rt
];
1172 * Transfer funds (money) from one company to another.
1173 * To prevent abuse in multiplayer games you can only send money to other
1174 * companies if you have paid off your loan (either explicitly, or implicitly
1175 * given the fact that you have more money than loan).
1176 * @param flags operation to perform
1177 * @param money the amount of money to transfer; max 20.000.000
1178 * @param dest_company the company to transfer the money to
1179 * @return the cost of this operation or an error
1181 CommandCost
CmdGiveMoney(DoCommandFlag flags
, uint32 money
, CompanyID dest_company
)
1183 if (!_settings_game
.economy
.give_money
) return CMD_ERROR
;
1185 const Company
*c
= Company::Get(_current_company
);
1186 CommandCost
amount(EXPENSES_OTHER
, std::min
<Money
>(money
, 20000000LL));
1188 /* You can only transfer funds that is in excess of your loan */
1189 if (c
->money
- c
->current_loan
< amount
.GetCost() || amount
.GetCost() < 0) return_cmd_error(STR_ERROR_INSUFFICIENT_FUNDS
);
1190 if (!Company::IsValidID(dest_company
)) return CMD_ERROR
;
1192 if (flags
& DC_EXEC
) {
1193 /* Add money to company */
1194 Backup
<CompanyID
> cur_company(_current_company
, dest_company
, FILE_LINE
);
1195 SubtractMoneyFromCompany(CommandCost(EXPENSES_OTHER
, -amount
.GetCost()));
1196 cur_company
.Restore();
1199 SetDParam(0, dest_company
);
1200 std::string dest_company_name
= GetString(STR_COMPANY_NAME
);
1202 SetDParam(0, _current_company
);
1203 std::string from_company_name
= GetString(STR_COMPANY_NAME
);
1205 NetworkTextMessage(NETWORK_ACTION_GIVE_MONEY
, GetDrawStringCompanyColour(_current_company
), false, from_company_name
, dest_company_name
, amount
.GetCost());
1209 /* Subtract money from local-company */
1214 * Get the index of the first available company. It attempts,
1215 * from first to last, and as soon as the attempt succeeds,
1216 * to get the index of the company:
1217 * 1st - get the first existing human company.
1218 * 2nd - get the first non-existing company.
1219 * 3rd - get COMPANY_FIRST.
1220 * @return the index of the first available company.
1222 CompanyID
GetFirstPlayableCompanyID()
1224 for (Company
*c
: Company::Iterate()) {
1225 if (Company::IsHumanID(c
->index
)) {
1230 if (Company::CanAllocateItem()) {
1231 for (CompanyID c
= COMPANY_FIRST
; c
< MAX_COMPANIES
; c
++) {
1232 if (!Company::IsValidID(c
)) {
1238 return COMPANY_FIRST
;