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"
39 #include "company_cmd.h"
41 #include "table/strings.h"
43 #include "safeguards.h"
45 void ClearEnginesHiddenFlagOfCompany(CompanyID cid
);
47 CompanyID _local_company
; ///< Company controlled by the human player at this client. Can also be #COMPANY_SPECTATOR.
48 CompanyID _current_company
; ///< Company currently doing an action.
49 Colours _company_colours
[MAX_COMPANIES
]; ///< NOSAVE: can be determined from company structs.
50 CompanyManagerFace _company_manager_face
; ///< for company manager face storage in openttd.cfg
51 uint _next_competitor_start
; ///< the number of ticks before the next AI is started
52 uint _cur_company_tick_index
; ///< used to generate a name for one company that doesn't have a name yet per tick
54 CompanyPool
_company_pool("Company"); ///< Pool of companies.
55 INSTANTIATE_POOL_METHODS(Company
)
59 * @param name_1 Name of the company.
60 * @param is_ai A computer program is running for this company.
62 Company::Company(uint16 name_1
, bool is_ai
)
64 this->name_1
= name_1
;
65 this->location_of_HQ
= INVALID_TILE
;
67 this->terraform_limit
= (uint32
)_settings_game
.construction
.terraform_frame_burst
<< 16;
68 this->clear_limit
= (uint32
)_settings_game
.construction
.clear_frame_burst
<< 16;
69 this->tree_limit
= (uint32
)_settings_game
.construction
.tree_frame_burst
<< 16;
71 for (uint j
= 0; j
< 4; j
++) this->share_owners
[j
] = INVALID_OWNER
;
72 InvalidateWindowData(WC_PERFORMANCE_DETAIL
, 0, INVALID_COMPANY
);
78 if (CleaningPool()) return;
80 CloseCompanyWindows(this->index
);
84 * Invalidating some stuff after removing item from the pool.
85 * @param index index of deleted item
87 void Company::PostDestructor(size_t index
)
89 InvalidateWindowData(WC_GRAPH_LEGEND
, 0, (int)index
);
90 InvalidateWindowData(WC_PERFORMANCE_DETAIL
, 0, (int)index
);
91 InvalidateWindowData(WC_COMPANY_LEAGUE
, 0, 0);
92 InvalidateWindowData(WC_LINKGRAPH_LEGEND
, 0);
93 /* If the currently shown error message has this company in it, then close it. */
94 InvalidateWindowData(WC_ERRMSG
, 0);
98 * Sets the local company and updates the settings that are set on a
99 * per-company basis to reflect the core's state in the GUI.
100 * @param new_company the new company
101 * @pre Company::IsValidID(new_company) || new_company == COMPANY_SPECTATOR || new_company == OWNER_NONE
103 void SetLocalCompany(CompanyID new_company
)
105 /* company could also be COMPANY_SPECTATOR or OWNER_NONE */
106 assert(Company::IsValidID(new_company
) || new_company
== COMPANY_SPECTATOR
|| new_company
== OWNER_NONE
);
108 /* If actually changing to another company, several windows need closing */
109 bool switching_company
= _local_company
!= new_company
;
111 /* Delete the chat window, if you were team chatting. */
112 if (switching_company
) InvalidateWindowData(WC_SEND_NETWORK_MSG
, DESTTYPE_TEAM
, _local_company
);
114 assert(IsLocalCompany());
116 _current_company
= _local_company
= new_company
;
118 /* Delete any construction windows... */
119 if (switching_company
) CloseConstructionWindows();
121 /* ... and redraw the whole screen. */
122 MarkWholeScreenDirty();
123 InvalidateWindowClassesData(WC_SIGN_LIST
, -1);
124 InvalidateWindowClassesData(WC_GOALS_LIST
);
128 * Get the colour for DrawString-subroutines which matches the colour of the company.
129 * @param company Company to get the colour of.
130 * @return Colour of \a company.
132 TextColour
GetDrawStringCompanyColour(CompanyID company
)
134 if (!Company::IsValidID(company
)) return (TextColour
)_colour_gradient
[COLOUR_WHITE
][4] | TC_IS_PALETTE_COLOUR
;
135 return (TextColour
)_colour_gradient
[_company_colours
[company
]][4] | TC_IS_PALETTE_COLOUR
;
139 * Draw the icon of a company.
140 * @param c Company that needs its icon drawn.
141 * @param x Horizontal coordinate of the icon.
142 * @param y Vertical coordinate of the icon.
144 void DrawCompanyIcon(CompanyID c
, int x
, int y
)
146 DrawSprite(SPR_COMPANY_ICON
, COMPANY_SPRITE_COLOUR(c
), x
, y
);
150 * Checks whether a company manager's face is a valid encoding.
151 * Unused bits are not enforced to be 0.
152 * @param cmf the fact to check
153 * @return true if and only if the face is valid
155 static bool IsValidCompanyManagerFace(CompanyManagerFace cmf
)
157 if (!AreCompanyManagerFaceBitsValid(cmf
, CMFV_GEN_ETHN
, GE_WM
)) return false;
159 GenderEthnicity ge
= (GenderEthnicity
)GetCompanyManagerFaceBits(cmf
, CMFV_GEN_ETHN
, GE_WM
);
160 bool has_moustache
= !HasBit(ge
, GENDER_FEMALE
) && GetCompanyManagerFaceBits(cmf
, CMFV_HAS_MOUSTACHE
, ge
) != 0;
161 bool has_tie_earring
= !HasBit(ge
, GENDER_FEMALE
) || GetCompanyManagerFaceBits(cmf
, CMFV_HAS_TIE_EARRING
, ge
) != 0;
162 bool has_glasses
= GetCompanyManagerFaceBits(cmf
, CMFV_HAS_GLASSES
, ge
) != 0;
164 if (!AreCompanyManagerFaceBitsValid(cmf
, CMFV_EYE_COLOUR
, ge
)) return false;
165 for (CompanyManagerFaceVariable cmfv
= CMFV_CHEEKS
; cmfv
< CMFV_END
; cmfv
++) {
167 case CMFV_MOUSTACHE
: if (!has_moustache
) continue; break;
169 case CMFV_NOSE
: if (has_moustache
) continue; break;
170 case CMFV_TIE_EARRING
: if (!has_tie_earring
) continue; break;
171 case CMFV_GLASSES
: if (!has_glasses
) continue; break;
174 if (!AreCompanyManagerFaceBitsValid(cmf
, cmfv
, ge
)) return false;
181 * Refresh all windows owned by a company.
182 * @param company Company that changed, and needs its windows refreshed.
184 void InvalidateCompanyWindows(const Company
*company
)
186 CompanyID cid
= company
->index
;
188 if (cid
== _local_company
) SetWindowWidgetDirty(WC_STATUS_BAR
, 0, WID_S_RIGHT
);
189 SetWindowDirty(WC_FINANCES
, cid
);
193 * Verify whether the company can pay the bill.
194 * @param[in,out] cost Money to pay, is changed to an error if the company does not have enough money.
195 * @return Function returns \c true if the company has enough money, else it returns \c false.
197 bool CheckCompanyHasMoney(CommandCost
&cost
)
199 if (cost
.GetCost() > 0) {
200 const Company
*c
= Company::GetIfValid(_current_company
);
201 if (c
!= nullptr && cost
.GetCost() > c
->money
) {
202 SetDParam(0, cost
.GetCost());
203 cost
.MakeError(STR_ERROR_NOT_ENOUGH_CASH_REQUIRES_CURRENCY
);
211 * Deduct costs of a command from the money of a company.
212 * @param c Company to pay the bill.
213 * @param cost Money to pay.
215 static void SubtractMoneyFromAnyCompany(Company
*c
, const CommandCost
&cost
)
217 if (cost
.GetCost() == 0) return;
218 assert(cost
.GetExpensesType() != INVALID_EXPENSES
);
220 c
->money
-= cost
.GetCost();
221 c
->yearly_expenses
[0][cost
.GetExpensesType()] += cost
.GetCost();
223 if (HasBit(1 << EXPENSES_TRAIN_INC
|
224 1 << EXPENSES_ROADVEH_INC
|
225 1 << EXPENSES_AIRCRAFT_INC
|
226 1 << EXPENSES_SHIP_INC
, cost
.GetExpensesType())) {
227 c
->cur_economy
.income
-= cost
.GetCost();
228 } else if (HasBit(1 << EXPENSES_TRAIN_RUN
|
229 1 << EXPENSES_ROADVEH_RUN
|
230 1 << EXPENSES_AIRCRAFT_RUN
|
231 1 << EXPENSES_SHIP_RUN
|
232 1 << EXPENSES_PROPERTY
|
233 1 << EXPENSES_LOAN_INT
, cost
.GetExpensesType())) {
234 c
->cur_economy
.expenses
-= cost
.GetCost();
237 InvalidateCompanyWindows(c
);
241 * Subtract money from the #_current_company, if the company is valid.
242 * @param cost Money to pay.
244 void SubtractMoneyFromCompany(const CommandCost
&cost
)
246 Company
*c
= Company::GetIfValid(_current_company
);
247 if (c
!= nullptr) SubtractMoneyFromAnyCompany(c
, cost
);
251 * Subtract money from a company, including the money fraction.
252 * @param company Company paying the bill.
253 * @param cst Cost of a command.
255 void SubtractMoneyFromCompanyFract(CompanyID company
, const CommandCost
&cst
)
257 Company
*c
= Company::Get(company
);
258 byte m
= c
->money_fraction
;
259 Money cost
= cst
.GetCost();
261 c
->money_fraction
= m
- (byte
)cost
;
263 if (c
->money_fraction
> m
) cost
++;
264 if (cost
!= 0) SubtractMoneyFromAnyCompany(c
, CommandCost(cst
.GetExpensesType(), cost
));
267 /** Update the landscaping limits per company. */
268 void UpdateLandscapingLimits()
270 for (Company
*c
: Company::Iterate()) {
271 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);
272 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);
273 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);
278 * Set the right DParams to get the name of an owner.
279 * @param owner the owner to get the name of.
280 * @param tile optional tile to get the right town.
281 * @pre if tile == 0, then owner can't be OWNER_TOWN.
283 void GetNameOfOwner(Owner owner
, TileIndex tile
)
287 if (owner
!= OWNER_TOWN
) {
288 if (!Company::IsValidID(owner
)) {
289 SetDParam(0, STR_COMPANY_SOMEONE
);
291 SetDParam(0, STR_COMPANY_NAME
);
296 const Town
*t
= ClosestTownFromTile(tile
, UINT_MAX
);
298 SetDParam(0, STR_TOWN_NAME
);
299 SetDParam(1, t
->index
);
305 * Check whether the current owner owns something.
306 * If that isn't the case an appropriate error will be given.
307 * @param owner the owner of the thing to check.
308 * @param tile optional tile to get the right town.
309 * @pre if tile == 0 then the owner can't be OWNER_TOWN.
310 * @return A succeeded command iff it's owned by the current company, else a failed command.
312 CommandCost
CheckOwnership(Owner owner
, TileIndex tile
)
314 assert(owner
< OWNER_END
);
315 assert(owner
!= OWNER_TOWN
|| tile
!= 0);
317 if (owner
== _current_company
) return CommandCost();
319 GetNameOfOwner(owner
, tile
);
320 return_cmd_error(STR_ERROR_OWNED_BY
);
324 * Check whether the current owner owns the stuff on
325 * the given tile. If that isn't the case an
326 * appropriate error will be given.
327 * @param tile the tile to check.
328 * @return A succeeded command iff it's owned by the current company, else a failed command.
330 CommandCost
CheckTileOwnership(TileIndex tile
)
332 Owner owner
= GetTileOwner(tile
);
334 assert(owner
< OWNER_END
);
336 if (owner
== _current_company
) return CommandCost();
338 /* no need to get the name of the owner unless we're the local company (saves some time) */
339 if (IsLocalCompany()) GetNameOfOwner(owner
, tile
);
340 return_cmd_error(STR_ERROR_OWNED_BY
);
344 * Generate the name of a company from the last build coordinate.
345 * @param c Company to give a name.
347 static void GenerateCompanyName(Company
*c
)
349 /* Reserve space for extra unicode character. We need to do this to be able
350 * to detect too long company name. */
351 char buffer
[(MAX_LENGTH_COMPANY_NAME_CHARS
+ 1) * MAX_CHAR_LENGTH
];
353 if (c
->name_1
!= STR_SV_UNNAMED
) return;
354 if (c
->last_build_coordinate
== 0) return;
356 Town
*t
= ClosestTownFromTile(c
->last_build_coordinate
, UINT_MAX
);
360 if (t
->name
.empty() && IsInsideMM(t
->townnametype
, SPECSTR_TOWNNAME_START
, SPECSTR_TOWNNAME_LAST
+ 1)) {
361 str
= t
->townnametype
- SPECSTR_TOWNNAME_START
+ SPECSTR_COMPANY_NAME_START
;
362 strp
= t
->townnameparts
;
365 /* No companies must have this name already */
366 for (const Company
*cc
: Company::Iterate()) {
367 if (cc
->name_1
== str
&& cc
->name_2
== strp
) goto bad_town_name
;
370 GetString(buffer
, str
, lastof(buffer
));
371 if (Utf8StringLength(buffer
) >= MAX_LENGTH_COMPANY_NAME_CHARS
) goto bad_town_name
;
377 MarkWholeScreenDirty();
380 CompanyNewsInformation
*cni
= new CompanyNewsInformation(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
);
391 if (c
->president_name_1
== SPECSTR_PRESIDENT_NAME
) {
392 str
= SPECSTR_ANDCO_NAME
;
393 strp
= c
->president_name_2
;
396 str
= SPECSTR_ANDCO_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
++) {
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
;
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
];
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
)
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()) {
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
;
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();
547 if (company
== INVALID_COMPANY
) {
548 c
= new Company(STR_SV_UNNAMED
, is_ai
);
550 if (Company::IsValidID(company
)) return nullptr;
551 c
= new (company
) Company(STR_SV_UNNAMED
, is_ai
);
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 InvalidateWindowData(WC_CLIENT_LIST
, 0);
575 InvalidateWindowData(WC_LINKGRAPH_LEGEND
, 0);
577 InvalidateWindowData(WC_SMALLMAP
, 0, 1);
579 if (is_ai
&& (!_networking
|| _network_server
)) AI::StartNew(c
->index
);
581 AI::BroadcastNewEvent(new ScriptEventCompanyNew(c
->index
), c
->index
);
582 Game::NewEvent(new ScriptEventCompanyNew(c
->index
));
587 /** Start the next competitor now. */
588 void StartupCompanies()
590 _next_competitor_start
= 0;
593 /** Start a new competitor company if possible. */
594 static bool MaybeStartNewCompany()
596 if (_networking
&& Company::GetNumItems() >= _settings_client
.network
.max_companies
) return false;
598 /* count number of competitors */
600 for (const Company
*c
: Company::Iterate()) {
604 if (n
< (uint
)_settings_game
.difficulty
.max_no_competitors
) {
605 /* Send a command to all clients to start up a new AI.
606 * Works fine for Multiplayer and Singleplayer */
607 return Command
<CMD_COMPANY_CTRL
>::Post(CCA_NEW_AI
, INVALID_COMPANY
, CRR_NONE
, INVALID_CLIENT_ID
);
613 /** Initialize the pool of companies. */
614 void InitializeCompanies()
616 _cur_company_tick_index
= 0;
620 * May company \a cbig buy company \a csmall?
621 * @param cbig Company buying \a csmall.
622 * @param csmall Company getting bought.
623 * @return Return \c true if it is allowed.
625 bool MayCompanyTakeOver(CompanyID cbig
, CompanyID csmall
)
627 const Company
*c1
= Company::Get(cbig
);
628 const Company
*c2
= Company::Get(csmall
);
630 /* Do the combined vehicle counts stay within the limits? */
631 return c1
->group_all
[VEH_TRAIN
].num_vehicle
+ c2
->group_all
[VEH_TRAIN
].num_vehicle
<= _settings_game
.vehicle
.max_trains
&&
632 c1
->group_all
[VEH_ROAD
].num_vehicle
+ c2
->group_all
[VEH_ROAD
].num_vehicle
<= _settings_game
.vehicle
.max_roadveh
&&
633 c1
->group_all
[VEH_SHIP
].num_vehicle
+ c2
->group_all
[VEH_SHIP
].num_vehicle
<= _settings_game
.vehicle
.max_ships
&&
634 c1
->group_all
[VEH_AIRCRAFT
].num_vehicle
+ c2
->group_all
[VEH_AIRCRAFT
].num_vehicle
<= _settings_game
.vehicle
.max_aircraft
;
638 * Handle the bankruptcy take over of a company.
639 * Companies going bankrupt will ask the other companies in order of their
640 * performance rating, so better performing companies get the 'do you want to
641 * merge with Y' question earlier. The question will then stay till either the
642 * company has gone bankrupt or got merged with a company.
644 * @param c the company that is going bankrupt.
646 static void HandleBankruptcyTakeover(Company
*c
)
648 /* Amount of time out for each company to take over a company;
649 * Timeout is a quarter (3 months of 30 days) divided over the
650 * number of companies. The minimum number of days in a quarter
651 * is 90: 31 in January, 28 in February and 31 in March.
652 * Note that the company going bankrupt can't buy itself. */
653 static const int TAKE_OVER_TIMEOUT
= 3 * 30 * DAY_TICKS
/ (MAX_COMPANIES
- 1);
655 assert(c
->bankrupt_asked
!= 0);
657 /* We're currently asking some company to buy 'us' */
658 if (c
->bankrupt_timeout
!= 0) {
659 c
->bankrupt_timeout
-= MAX_COMPANIES
;
660 if (c
->bankrupt_timeout
> 0) return;
661 c
->bankrupt_timeout
= 0;
666 /* Did we ask everyone for bankruptcy? If so, bail out. */
667 if (c
->bankrupt_asked
== MAX_UVALUE(CompanyMask
)) return;
669 Company
*best
= nullptr;
670 int32 best_performance
= -1;
672 /* Ask the company with the highest performance history first */
673 for (Company
*c2
: Company::Iterate()) {
674 if (c2
->bankrupt_asked
== 0 && // Don't ask companies going bankrupt themselves
675 !HasBit(c
->bankrupt_asked
, c2
->index
) &&
676 best_performance
< c2
->old_economy
[1].performance_history
&&
677 MayCompanyTakeOver(c2
->index
, c
->index
)) {
678 best_performance
= c2
->old_economy
[1].performance_history
;
683 /* Asked all companies? */
684 if (best_performance
== -1) {
685 c
->bankrupt_asked
= MAX_UVALUE(CompanyMask
);
689 SetBit(c
->bankrupt_asked
, best
->index
);
691 c
->bankrupt_timeout
= TAKE_OVER_TIMEOUT
;
693 AI::NewEvent(best
->index
, new ScriptEventCompanyAskMerger(c
->index
, ClampToI32(c
->bankrupt_value
)));
694 } else if (IsInteractiveCompany(best
->index
)) {
695 ShowBuyCompanyDialog(c
->index
);
699 /** Called every tick for updating some company info. */
700 void OnTick_Companies()
702 if (_game_mode
== GM_EDITOR
) return;
704 Company
*c
= Company::GetIfValid(_cur_company_tick_index
);
706 if (c
->name_1
!= 0) GenerateCompanyName(c
);
707 if (c
->bankrupt_asked
!= 0) HandleBankruptcyTakeover(c
);
710 if (_next_competitor_start
== 0) {
711 /* AI::GetStartNextTime() can return 0. */
712 _next_competitor_start
= std::max(1, AI::GetStartNextTime() * DAY_TICKS
);
715 if (_game_mode
!= GM_MENU
&& AI::CanStartNew() && --_next_competitor_start
== 0) {
716 /* Allow multiple AIs to possibly start in the same tick. */
718 if (!MaybeStartNewCompany()) break;
720 /* In networking mode, we can only send a command to start but it
721 * didn't execute yet, so we cannot loop. */
722 if (_networking
) break;
723 } while (AI::GetStartNextTime() == 0);
726 _cur_company_tick_index
= (_cur_company_tick_index
+ 1) % MAX_COMPANIES
;
730 * A year has passed, update the economic data of all companies, and perhaps show the
731 * financial overview window of the local company.
733 void CompaniesYearlyLoop()
735 /* Copy statistics */
736 for (Company
*c
: Company::Iterate()) {
737 memmove(&c
->yearly_expenses
[1], &c
->yearly_expenses
[0], sizeof(c
->yearly_expenses
) - sizeof(c
->yearly_expenses
[0]));
738 memset(&c
->yearly_expenses
[0], 0, sizeof(c
->yearly_expenses
[0]));
739 SetWindowDirty(WC_FINANCES
, c
->index
);
742 if (_settings_client
.gui
.show_finances
&& _local_company
!= COMPANY_SPECTATOR
) {
743 ShowCompanyFinances(_local_company
);
744 Company
*c
= Company::Get(_local_company
);
745 if (c
->num_valid_stat_ent
> 5 && c
->old_economy
[0].performance_history
< c
->old_economy
[4].performance_history
) {
746 if (_settings_client
.sound
.new_year
) SndPlayFx(SND_01_BAD_YEAR
);
748 if (_settings_client
.sound
.new_year
) SndPlayFx(SND_00_GOOD_YEAR
);
754 * Fill the CompanyNewsInformation struct with the required data.
755 * @param c the current company.
756 * @param other the other company (use \c nullptr if not relevant).
758 CompanyNewsInformation::CompanyNewsInformation(const Company
*c
, const Company
*other
)
760 SetDParam(0, c
->index
);
761 this->company_name
= GetString(STR_COMPANY_NAME
);
763 if (other
!= nullptr) {
764 SetDParam(0, other
->index
);
765 this->other_company_name
= GetString(STR_COMPANY_NAME
);
769 SetDParam(0, c
->index
);
770 this->president_name
= GetString(STR_PRESIDENT_NAME_MANAGER
);
772 this->colour
= c
->colour
;
773 this->face
= c
->face
;
778 * Called whenever company related information changes in order to notify admins.
779 * @param company The company data changed of.
781 void CompanyAdminUpdate(const Company
*company
)
783 if (_network_server
) NetworkAdminCompanyUpdate(company
);
787 * Called whenever a company is removed in order to notify admins.
788 * @param company_id The company that was removed.
789 * @param reason The reason the company was removed.
791 void CompanyAdminRemove(CompanyID company_id
, CompanyRemoveReason reason
)
793 if (_network_server
) NetworkAdminCompanyRemove(company_id
, (AdminCompanyRemoveReason
)reason
);
797 * Control the companies: add, delete, etc.
798 * @param flags operation to perform
799 * @param cca action to perform
800 * @param company_id company to perform the action on
801 * @param client_id ClientID
802 * @return the cost of this operation or an error
804 CommandCost
CmdCompanyCtrl(DoCommandFlag flags
, CompanyCtrlAction cca
, CompanyID company_id
, CompanyRemoveReason reason
, ClientID client_id
)
806 InvalidateWindowData(WC_COMPANY_LEAGUE
, 0, 0);
809 case CCA_NEW
: { // Create a new company
810 /* This command is only executed in a multiplayer game */
811 if (!_networking
) return CMD_ERROR
;
813 /* Has the network client a correct ClientIndex? */
814 if (!(flags
& DC_EXEC
)) return CommandCost();
816 NetworkClientInfo
*ci
= NetworkClientInfo::GetByClientID(client_id
);
818 /* Delete multiplayer progress bar */
819 CloseWindowById(WC_NETWORK_STATUS_WINDOW
, WN_NETWORK_STATUS_WINDOW_JOIN
);
821 Company
*c
= DoStartupNewCompany(false);
823 /* A new company could not be created, revert to being a spectator */
825 /* We check for "ci != nullptr" as a client could have left by
826 * the time we execute this command. */
827 if (_network_server
&& ci
!= nullptr) {
828 ci
->client_playas
= COMPANY_SPECTATOR
;
829 NetworkUpdateClientInfo(ci
->client_id
);
834 /* This is the client (or non-dedicated server) who wants a new company */
835 if (client_id
== _network_own_client_id
) {
836 assert(_local_company
== COMPANY_SPECTATOR
);
837 SetLocalCompany(c
->index
);
838 if (!_settings_client
.network
.default_company_pass
.empty()) {
839 NetworkChangeCompanyPassword(_local_company
, _settings_client
.network
.default_company_pass
);
842 /* Now that we have a new company, broadcast our company settings to
843 * all clients so everything is in sync */
844 SyncCompanySettings();
846 MarkWholeScreenDirty();
849 NetworkServerNewCompany(c
, ci
);
853 case CCA_NEW_AI
: { // Make a new AI company
854 if (company_id
!= INVALID_COMPANY
&& company_id
>= MAX_COMPANIES
) return CMD_ERROR
;
856 /* For network games, company deletion is delayed. */
857 if (!_networking
&& company_id
!= INVALID_COMPANY
&& Company::IsValidID(company_id
)) return CMD_ERROR
;
859 if (!(flags
& DC_EXEC
)) return CommandCost();
861 /* For network game, just assume deletion happened. */
862 assert(company_id
== INVALID_COMPANY
|| !Company::IsValidID(company_id
));
864 Company
*c
= DoStartupNewCompany(true, company_id
);
865 if (c
!= nullptr) NetworkServerNewCompany(c
, nullptr);
869 case CCA_DELETE
: { // Delete a company
870 if (reason
>= CRR_END
) return CMD_ERROR
;
872 /* We can't delete the last existing company in singleplayer mode. */
873 if (!_networking
&& Company::GetNumItems() == 1) return CMD_ERROR
;
875 Company
*c
= Company::GetIfValid(company_id
);
876 if (c
== nullptr) return CMD_ERROR
;
878 if (!(flags
& DC_EXEC
)) return CommandCost();
880 /* Delete any open window of the company */
881 CloseCompanyWindows(c
->index
);
882 CompanyNewsInformation
*cni
= new CompanyNewsInformation(c
);
884 /* Show the bankrupt news */
885 SetDParam(0, STR_NEWS_COMPANY_BANKRUPT_TITLE
);
886 SetDParam(1, STR_NEWS_COMPANY_BANKRUPT_DESCRIPTION
);
887 SetDParamStr(2, cni
->company_name
);
888 AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT
, cni
);
890 /* Remove the company */
891 ChangeOwnershipOfCompanyItems(c
->index
, INVALID_OWNER
);
892 if (c
->is_ai
) AI::Stop(c
->index
);
894 CompanyID c_index
= c
->index
;
896 AI::BroadcastNewEvent(new ScriptEventCompanyBankrupt(c_index
));
897 Game::NewEvent(new ScriptEventCompanyBankrupt(c_index
));
898 CompanyAdminRemove(c_index
, (CompanyRemoveReason
)reason
);
900 if (StoryPage::GetNumItems() == 0 || Goal::GetNumItems() == 0) InvalidateWindowData(WC_MAIN_TOOLBAR
, 0);
901 InvalidateWindowData(WC_CLIENT_LIST
, 0);
906 default: return CMD_ERROR
;
909 InvalidateWindowClassesData(WC_GAME_OPTIONS
);
910 InvalidateWindowClassesData(WC_AI_SETTINGS
);
911 InvalidateWindowClassesData(WC_AI_LIST
);
913 return CommandCost();
917 * Change the company manager's face.
918 * @param flags operation to perform
921 * @param p2 face bitmasked
923 * @return the cost of this operation or an error
925 CommandCost
CmdSetCompanyManagerFace(DoCommandFlag flags
, TileIndex tile
, uint32 p1
, uint32 p2
, const std::string
&text
)
927 CompanyManagerFace cmf
= (CompanyManagerFace
)p2
;
929 if (!IsValidCompanyManagerFace(cmf
)) return CMD_ERROR
;
931 if (flags
& DC_EXEC
) {
932 Company::Get(_current_company
)->face
= cmf
;
933 MarkWholeScreenDirty();
935 return CommandCost();
939 * Change the company's company-colour
940 * @param flags operation to perform
942 * @param p1 bitstuffed:
943 * p1 bits 0-7 scheme to set
944 * p1 bit 8 set first/second colour
945 * @param p2 new colour for vehicles, property, etc.
947 * @return the cost of this operation or an error
949 CommandCost
CmdSetCompanyColour(DoCommandFlag flags
, TileIndex tile
, uint32 p1
, uint32 p2
, const std::string
&text
)
951 Colours colour
= Extract
<Colours
, 0, 8>(p2
);
952 LiveryScheme scheme
= Extract
<LiveryScheme
, 0, 8>(p1
);
953 bool second
= HasBit(p1
, 8);
955 if (scheme
>= LS_END
|| (colour
>= COLOUR_END
&& colour
!= INVALID_COLOUR
)) return CMD_ERROR
;
957 /* Default scheme can't be reset to invalid. */
958 if (scheme
== LS_DEFAULT
&& colour
== INVALID_COLOUR
) return CMD_ERROR
;
960 Company
*c
= Company::Get(_current_company
);
962 /* Ensure no two companies have the same primary colour */
963 if (scheme
== LS_DEFAULT
&& !second
) {
964 for (const Company
*cc
: Company::Iterate()) {
965 if (cc
!= c
&& cc
->colour
== colour
) return CMD_ERROR
;
969 if (flags
& DC_EXEC
) {
971 if (scheme
!= LS_DEFAULT
) SB(c
->livery
[scheme
].in_use
, 0, 1, colour
!= INVALID_COLOUR
);
972 if (colour
== INVALID_COLOUR
) colour
= (Colours
)c
->livery
[LS_DEFAULT
].colour1
;
973 c
->livery
[scheme
].colour1
= colour
;
975 /* If setting the first colour of the default scheme, adjust the
976 * original and cached company colours too. */
977 if (scheme
== LS_DEFAULT
) {
978 for (int i
= 1; i
< LS_END
; i
++) {
979 if (!HasBit(c
->livery
[i
].in_use
, 0)) c
->livery
[i
].colour1
= colour
;
981 _company_colours
[_current_company
] = colour
;
983 CompanyAdminUpdate(c
);
986 if (scheme
!= LS_DEFAULT
) SB(c
->livery
[scheme
].in_use
, 1, 1, colour
!= INVALID_COLOUR
);
987 if (colour
== INVALID_COLOUR
) colour
= (Colours
)c
->livery
[LS_DEFAULT
].colour2
;
988 c
->livery
[scheme
].colour2
= colour
;
990 if (scheme
== LS_DEFAULT
) {
991 for (int i
= 1; i
< LS_END
; i
++) {
992 if (!HasBit(c
->livery
[i
].in_use
, 1)) c
->livery
[i
].colour2
= colour
;
997 if (c
->livery
[scheme
].in_use
!= 0) {
998 /* If enabling a scheme, set the default scheme to be in use too */
999 c
->livery
[LS_DEFAULT
].in_use
= 1;
1001 /* Else loop through all schemes to see if any are left enabled.
1002 * If not, disable the default scheme too. */
1003 c
->livery
[LS_DEFAULT
].in_use
= 0;
1004 for (scheme
= LS_DEFAULT
; scheme
< LS_END
; scheme
++) {
1005 if (c
->livery
[scheme
].in_use
!= 0) {
1006 c
->livery
[LS_DEFAULT
].in_use
= 1;
1012 ResetVehicleColourMap();
1013 MarkWholeScreenDirty();
1015 /* All graph related to companies use the company colour. */
1016 InvalidateWindowData(WC_INCOME_GRAPH
, 0);
1017 InvalidateWindowData(WC_OPERATING_PROFIT
, 0);
1018 InvalidateWindowData(WC_DELIVERED_CARGO
, 0);
1019 InvalidateWindowData(WC_PERFORMANCE_HISTORY
, 0);
1020 InvalidateWindowData(WC_COMPANY_VALUE
, 0);
1021 InvalidateWindowData(WC_LINKGRAPH_LEGEND
, 0);
1022 /* The smallmap owner view also stores the company colours. */
1024 InvalidateWindowData(WC_SMALLMAP
, 0, 1);
1026 /* Company colour data is indirectly cached. */
1027 for (Vehicle
*v
: Vehicle::Iterate()) {
1028 if (v
->owner
== _current_company
) v
->InvalidateNewGRFCache();
1031 extern void UpdateObjectColours(const Company
*c
);
1032 UpdateObjectColours(c
);
1034 return CommandCost();
1038 * Is the given name in use as name of a company?
1039 * @param name Name to search.
1040 * @return \c true if the name us unique (that is, not in use), else \c false.
1042 static bool IsUniqueCompanyName(const std::string
&name
)
1044 for (const Company
*c
: Company::Iterate()) {
1045 if (!c
->name
.empty() && c
->name
== name
) return false;
1052 * Change the name of the company.
1053 * @param flags operation to perform
1054 * @param tile unused
1057 * @param text the new name or an empty string when resetting to the default
1058 * @return the cost of this operation or an error
1060 CommandCost
CmdRenameCompany(DoCommandFlag flags
, TileIndex tile
, uint32 p1
, uint32 p2
, const std::string
&text
)
1062 bool reset
= text
.empty();
1065 if (Utf8StringLength(text
) >= MAX_LENGTH_COMPANY_NAME_CHARS
) return CMD_ERROR
;
1066 if (!IsUniqueCompanyName(text
)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE
);
1069 if (flags
& DC_EXEC
) {
1070 Company
*c
= Company::Get(_current_company
);
1076 MarkWholeScreenDirty();
1077 CompanyAdminUpdate(c
);
1080 return CommandCost();
1084 * Is the given name in use as president name of a company?
1085 * @param name Name to search.
1086 * @return \c true if the name us unique (that is, not in use), else \c false.
1088 static bool IsUniquePresidentName(const std::string
&name
)
1090 for (const Company
*c
: Company::Iterate()) {
1091 if (!c
->president_name
.empty() && c
->president_name
== name
) return false;
1098 * Change the name of the president.
1099 * @param flags operation to perform
1100 * @param tile unused
1103 * @param text the new name or an empty string when resetting to the default
1104 * @return the cost of this operation or an error
1106 CommandCost
CmdRenamePresident(DoCommandFlag flags
, TileIndex tile
, uint32 p1
, uint32 p2
, const std::string
&text
)
1108 bool reset
= text
.empty();
1111 if (Utf8StringLength(text
) >= MAX_LENGTH_PRESIDENT_NAME_CHARS
) return CMD_ERROR
;
1112 if (!IsUniquePresidentName(text
)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE
);
1115 if (flags
& DC_EXEC
) {
1116 Company
*c
= Company::Get(_current_company
);
1119 c
->president_name
.clear();
1121 c
->president_name
= text
;
1123 if (c
->name_1
== STR_SV_UNNAMED
&& c
->name
.empty()) {
1124 Command
<CMD_RENAME_COMPANY
>::Do(DC_EXEC
, 0, 0, 0, text
+ " Transport");
1128 MarkWholeScreenDirty();
1129 CompanyAdminUpdate(c
);
1132 return CommandCost();
1136 * Get the service interval for the given company and vehicle type.
1137 * @param c The company, or nullptr for client-default settings.
1138 * @param type The vehicle type to get the interval for.
1139 * @return The service interval.
1141 int CompanyServiceInterval(const Company
*c
, VehicleType type
)
1143 const VehicleDefaultSettings
*vds
= (c
== nullptr) ? &_settings_client
.company
.vehicle
: &c
->settings
.vehicle
;
1145 default: NOT_REACHED();
1146 case VEH_TRAIN
: return vds
->servint_trains
;
1147 case VEH_ROAD
: return vds
->servint_roadveh
;
1148 case VEH_AIRCRAFT
: return vds
->servint_aircraft
;
1149 case VEH_SHIP
: return vds
->servint_ships
;
1154 * Get total sum of all owned road bits.
1155 * @return Combined total road road bits.
1157 uint32
CompanyInfrastructure::GetRoadTotal() const
1160 for (RoadType rt
= ROADTYPE_BEGIN
; rt
!= ROADTYPE_END
; rt
++) {
1161 if (RoadTypeIsRoad(rt
)) total
+= this->road
[rt
];
1167 * Get total sum of all owned tram bits.
1168 * @return Combined total of tram road bits.
1170 uint32
CompanyInfrastructure::GetTramTotal() const
1173 for (RoadType rt
= ROADTYPE_BEGIN
; rt
!= ROADTYPE_END
; rt
++) {
1174 if (RoadTypeIsTram(rt
)) total
+= this->road
[rt
];
1180 * Transfer funds (money) from one company to another.
1181 * To prevent abuse in multiplayer games you can only send money to other
1182 * companies if you have paid off your loan (either explicitly, or implicitly
1183 * given the fact that you have more money than loan).
1184 * @param flags operation to perform
1185 * @param tile unused
1186 * @param p1 the amount of money to transfer; max 20.000.000
1187 * @param p2 the company to transfer the money to
1188 * @param text unused
1189 * @return the cost of this operation or an error
1191 CommandCost
CmdGiveMoney(DoCommandFlag flags
, TileIndex tile
, uint32 p1
, uint32 p2
, const std::string
&text
)
1193 if (!_settings_game
.economy
.give_money
) return CMD_ERROR
;
1195 const Company
*c
= Company::Get(_current_company
);
1196 CommandCost
amount(EXPENSES_OTHER
, std::min
<Money
>(p1
, 20000000LL));
1197 CompanyID dest_company
= (CompanyID
)p2
;
1199 /* You can only transfer funds that is in excess of your loan */
1200 if (c
->money
- c
->current_loan
< amount
.GetCost() || amount
.GetCost() < 0) return_cmd_error(STR_ERROR_INSUFFICIENT_FUNDS
);
1201 if (!Company::IsValidID(dest_company
)) return CMD_ERROR
;
1203 if (flags
& DC_EXEC
) {
1204 /* Add money to company */
1205 Backup
<CompanyID
> cur_company(_current_company
, dest_company
, FILE_LINE
);
1206 SubtractMoneyFromCompany(CommandCost(EXPENSES_OTHER
, -amount
.GetCost()));
1207 cur_company
.Restore();
1210 SetDParam(0, dest_company
);
1211 std::string dest_company_name
= GetString(STR_COMPANY_NAME
);
1213 SetDParam(0, _current_company
);
1214 std::string from_company_name
= GetString(STR_COMPANY_NAME
);
1216 NetworkTextMessage(NETWORK_ACTION_GIVE_MONEY
, GetDrawStringCompanyColour(_current_company
), false, from_company_name
, dest_company_name
, amount
.GetCost());
1220 /* Subtract money from local-company */