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"
39 #include "table/strings.h"
41 #include "safeguards.h"
43 void ClearEnginesHiddenFlagOfCompany(CompanyID cid
);
45 CompanyID _local_company
; ///< Company controlled by the human player at this client. Can also be #COMPANY_SPECTATOR.
46 CompanyID _current_company
; ///< Company currently doing an action.
47 Colours _company_colours
[MAX_COMPANIES
]; ///< NOSAVE: can be determined from company structs.
48 CompanyManagerFace _company_manager_face
; ///< for company manager face storage in openttd.cfg
49 uint _next_competitor_start
; ///< the number of ticks before the next AI is started
50 uint _cur_company_tick_index
; ///< used to generate a name for one company that doesn't have a name yet per tick
52 CompanyPool
_company_pool("Company"); ///< Pool of companies.
53 INSTANTIATE_POOL_METHODS(Company
)
57 * @param name_1 Name of the company.
58 * @param is_ai A computer program is running for this company.
60 Company::Company(uint16 name_1
, bool is_ai
)
62 this->name_1
= name_1
;
63 this->location_of_HQ
= INVALID_TILE
;
65 this->terraform_limit
= _settings_game
.construction
.terraform_frame_burst
<< 16;
66 this->clear_limit
= _settings_game
.construction
.clear_frame_burst
<< 16;
67 this->tree_limit
= _settings_game
.construction
.tree_frame_burst
<< 16;
69 for (uint j
= 0; j
< 4; j
++) this->share_owners
[j
] = COMPANY_SPECTATOR
;
70 InvalidateWindowData(WC_PERFORMANCE_DETAIL
, 0, INVALID_COMPANY
);
76 if (CleaningPool()) return;
78 DeleteCompanyWindows(this->index
);
82 * Invalidating some stuff after removing item from the pool.
83 * @param index index of deleted item
85 void Company::PostDestructor(size_t index
)
87 InvalidateWindowData(WC_GRAPH_LEGEND
, 0, (int)index
);
88 InvalidateWindowData(WC_PERFORMANCE_DETAIL
, 0, (int)index
);
89 InvalidateWindowData(WC_COMPANY_LEAGUE
, 0, 0);
90 InvalidateWindowData(WC_LINKGRAPH_LEGEND
, 0);
91 /* If the currently shown error message has this company in it, then close it. */
92 InvalidateWindowData(WC_ERRMSG
, 0);
96 * Sets the local company and updates the settings that are set on a
97 * per-company basis to reflect the core's state in the GUI.
98 * @param new_company the new company
99 * @pre Company::IsValidID(new_company) || new_company == COMPANY_SPECTATOR || new_company == OWNER_NONE
101 void SetLocalCompany(CompanyID new_company
)
103 /* company could also be COMPANY_SPECTATOR or OWNER_NONE */
104 assert(Company::IsValidID(new_company
) || new_company
== COMPANY_SPECTATOR
|| new_company
== OWNER_NONE
);
106 /* If actually changing to another company, several windows need closing */
107 bool switching_company
= _local_company
!= new_company
;
109 /* Delete the chat window, if you were team chatting. */
110 if (switching_company
) InvalidateWindowData(WC_SEND_NETWORK_MSG
, DESTTYPE_TEAM
, _local_company
);
112 assert(IsLocalCompany());
114 _current_company
= _local_company
= new_company
;
116 /* Delete any construction windows... */
117 if (switching_company
) DeleteConstructionWindows();
119 /* ... and redraw the whole screen. */
120 MarkWholeScreenDirty();
121 InvalidateWindowClassesData(WC_SIGN_LIST
, -1);
125 * Get the colour for DrawString-subroutines which matches the colour of the company.
126 * @param company Company to get the colour of.
127 * @return Colour of \a company.
129 TextColour
GetDrawStringCompanyColour(CompanyID company
)
131 if (!Company::IsValidID(company
)) return (TextColour
)_colour_gradient
[COLOUR_WHITE
][4] | TC_IS_PALETTE_COLOUR
;
132 return (TextColour
)_colour_gradient
[_company_colours
[company
]][4] | TC_IS_PALETTE_COLOUR
;
136 * Draw the icon of a company.
137 * @param c Company that needs its icon drawn.
138 * @param x Horizontal coordinate of the icon.
139 * @param y Vertical coordinate of the icon.
141 void DrawCompanyIcon(CompanyID c
, int x
, int y
)
143 DrawSprite(SPR_COMPANY_ICON
, COMPANY_SPRITE_COLOUR(c
), x
, y
);
147 * Checks whether a company manager's face is a valid encoding.
148 * Unused bits are not enforced to be 0.
149 * @param cmf the fact to check
150 * @return true if and only if the face is valid
152 static bool IsValidCompanyManagerFace(CompanyManagerFace cmf
)
154 if (!AreCompanyManagerFaceBitsValid(cmf
, CMFV_GEN_ETHN
, GE_WM
)) return false;
156 GenderEthnicity ge
= (GenderEthnicity
)GetCompanyManagerFaceBits(cmf
, CMFV_GEN_ETHN
, GE_WM
);
157 bool has_moustache
= !HasBit(ge
, GENDER_FEMALE
) && GetCompanyManagerFaceBits(cmf
, CMFV_HAS_MOUSTACHE
, ge
) != 0;
158 bool has_tie_earring
= !HasBit(ge
, GENDER_FEMALE
) || GetCompanyManagerFaceBits(cmf
, CMFV_HAS_TIE_EARRING
, ge
) != 0;
159 bool has_glasses
= GetCompanyManagerFaceBits(cmf
, CMFV_HAS_GLASSES
, ge
) != 0;
161 if (!AreCompanyManagerFaceBitsValid(cmf
, CMFV_EYE_COLOUR
, ge
)) return false;
162 for (CompanyManagerFaceVariable cmfv
= CMFV_CHEEKS
; cmfv
< CMFV_END
; cmfv
++) {
164 case CMFV_MOUSTACHE
: if (!has_moustache
) continue; break;
166 case CMFV_NOSE
: if (has_moustache
) continue; break;
167 case CMFV_TIE_EARRING
: if (!has_tie_earring
) continue; break;
168 case CMFV_GLASSES
: if (!has_glasses
) continue; break;
171 if (!AreCompanyManagerFaceBitsValid(cmf
, cmfv
, ge
)) return false;
178 * Refresh all windows owned by a company.
179 * @param company Company that changed, and needs its windows refreshed.
181 void InvalidateCompanyWindows(const Company
*company
)
183 CompanyID cid
= company
->index
;
185 if (cid
== _local_company
) SetWindowDirty(WC_STATUS_BAR
, 0);
186 SetWindowDirty(WC_FINANCES
, cid
);
190 * Verify whether the company can pay the bill.
191 * @param[in,out] cost Money to pay, is changed to an error if the company does not have enough money.
192 * @return Function returns \c true if the company has enough money, else it returns \c false.
194 bool CheckCompanyHasMoney(CommandCost
&cost
)
196 if (cost
.GetCost() > 0) {
197 const Company
*c
= Company::GetIfValid(_current_company
);
198 if (c
!= nullptr && cost
.GetCost() > c
->money
) {
199 SetDParam(0, cost
.GetCost());
200 cost
.MakeError(STR_ERROR_NOT_ENOUGH_CASH_REQUIRES_CURRENCY
);
208 * Deduct costs of a command from the money of a company.
209 * @param c Company to pay the bill.
210 * @param cost Money to pay.
212 static void SubtractMoneyFromAnyCompany(Company
*c
, const CommandCost
&cost
)
214 if (cost
.GetCost() == 0) return;
215 assert(cost
.GetExpensesType() != INVALID_EXPENSES
);
217 c
->money
-= cost
.GetCost();
218 c
->yearly_expenses
[0][cost
.GetExpensesType()] += cost
.GetCost();
220 if (HasBit(1 << EXPENSES_TRAIN_INC
|
221 1 << EXPENSES_ROADVEH_INC
|
222 1 << EXPENSES_AIRCRAFT_INC
|
223 1 << EXPENSES_SHIP_INC
, cost
.GetExpensesType())) {
224 c
->cur_economy
.income
-= cost
.GetCost();
225 } else if (HasBit(1 << EXPENSES_TRAIN_RUN
|
226 1 << EXPENSES_ROADVEH_RUN
|
227 1 << EXPENSES_AIRCRAFT_RUN
|
228 1 << EXPENSES_SHIP_RUN
|
229 1 << EXPENSES_PROPERTY
|
230 1 << EXPENSES_LOAN_INT
, cost
.GetExpensesType())) {
231 c
->cur_economy
.expenses
-= cost
.GetCost();
234 InvalidateCompanyWindows(c
);
238 * Subtract money from the #_current_company, if the company is valid.
239 * @param cost Money to pay.
241 void SubtractMoneyFromCompany(const CommandCost
&cost
)
243 Company
*c
= Company::GetIfValid(_current_company
);
244 if (c
!= nullptr) SubtractMoneyFromAnyCompany(c
, cost
);
248 * Subtract money from a company, including the money fraction.
249 * @param company Company paying the bill.
250 * @param cst Cost of a command.
252 void SubtractMoneyFromCompanyFract(CompanyID company
, const CommandCost
&cst
)
254 Company
*c
= Company::Get(company
);
255 byte m
= c
->money_fraction
;
256 Money cost
= cst
.GetCost();
258 c
->money_fraction
= m
- (byte
)cost
;
260 if (c
->money_fraction
> m
) cost
++;
261 if (cost
!= 0) SubtractMoneyFromAnyCompany(c
, CommandCost(cst
.GetExpensesType(), cost
));
264 /** Update the landscaping limits per company. */
265 void UpdateLandscapingLimits()
267 for (Company
*c
: Company::Iterate()) {
268 c
->terraform_limit
= std::min
<uint32
>(c
->terraform_limit
+ _settings_game
.construction
.terraform_per_64k_frames
, _settings_game
.construction
.terraform_frame_burst
<< 16);
269 c
->clear_limit
= std::min
<uint32
>(c
->clear_limit
+ _settings_game
.construction
.clear_per_64k_frames
, _settings_game
.construction
.clear_frame_burst
<< 16);
270 c
->tree_limit
= std::min
<uint32
>(c
->tree_limit
+ _settings_game
.construction
.tree_per_64k_frames
, _settings_game
.construction
.tree_frame_burst
<< 16);
275 * Set the right DParams to get the name of an owner.
276 * @param owner the owner to get the name of.
277 * @param tile optional tile to get the right town.
278 * @pre if tile == 0, then owner can't be OWNER_TOWN.
280 void GetNameOfOwner(Owner owner
, TileIndex tile
)
284 if (owner
!= OWNER_TOWN
) {
285 if (!Company::IsValidID(owner
)) {
286 SetDParam(0, STR_COMPANY_SOMEONE
);
288 SetDParam(0, STR_COMPANY_NAME
);
293 const Town
*t
= ClosestTownFromTile(tile
, UINT_MAX
);
295 SetDParam(0, STR_TOWN_NAME
);
296 SetDParam(1, t
->index
);
302 * Check whether the current owner owns something.
303 * If that isn't the case an appropriate error will be given.
304 * @param owner the owner of the thing to check.
305 * @param tile optional tile to get the right town.
306 * @pre if tile == 0 then the owner can't be OWNER_TOWN.
307 * @return A succeeded command iff it's owned by the current company, else a failed command.
309 CommandCost
CheckOwnership(Owner owner
, TileIndex tile
)
311 assert(owner
< OWNER_END
);
312 assert(owner
!= OWNER_TOWN
|| tile
!= 0);
314 if (owner
== _current_company
) return CommandCost();
316 GetNameOfOwner(owner
, tile
);
317 return_cmd_error(STR_ERROR_OWNED_BY
);
321 * Check whether the current owner owns the stuff on
322 * the given tile. If that isn't the case an
323 * appropriate error will be given.
324 * @param tile the tile to check.
325 * @return A succeeded command iff it's owned by the current company, else a failed command.
327 CommandCost
CheckTileOwnership(TileIndex tile
)
329 Owner owner
= GetTileOwner(tile
);
331 assert(owner
< OWNER_END
);
333 if (owner
== _current_company
) return CommandCost();
335 /* no need to get the name of the owner unless we're the local company (saves some time) */
336 if (IsLocalCompany()) GetNameOfOwner(owner
, tile
);
337 return_cmd_error(STR_ERROR_OWNED_BY
);
341 * Generate the name of a company from the last build coordinate.
342 * @param c Company to give a name.
344 static void GenerateCompanyName(Company
*c
)
346 /* Reserve space for extra unicode character. We need to do this to be able
347 * to detect too long company name. */
348 char buffer
[(MAX_LENGTH_COMPANY_NAME_CHARS
+ 1) * MAX_CHAR_LENGTH
];
350 if (c
->name_1
!= STR_SV_UNNAMED
) return;
351 if (c
->last_build_coordinate
== 0) return;
353 Town
*t
= ClosestTownFromTile(c
->last_build_coordinate
, UINT_MAX
);
357 if (t
->name
.empty() && IsInsideMM(t
->townnametype
, SPECSTR_TOWNNAME_START
, SPECSTR_TOWNNAME_LAST
+ 1)) {
358 str
= t
->townnametype
- SPECSTR_TOWNNAME_START
+ SPECSTR_COMPANY_NAME_START
;
359 strp
= t
->townnameparts
;
362 /* No companies must have this name already */
363 for (const Company
*cc
: Company::Iterate()) {
364 if (cc
->name_1
== str
&& cc
->name_2
== strp
) goto bad_town_name
;
367 GetString(buffer
, str
, lastof(buffer
));
368 if (Utf8StringLength(buffer
) >= MAX_LENGTH_COMPANY_NAME_CHARS
) goto bad_town_name
;
374 MarkWholeScreenDirty();
377 CompanyNewsInformation
*cni
= MallocT
<CompanyNewsInformation
>(1);
379 SetDParam(0, STR_NEWS_COMPANY_LAUNCH_TITLE
);
380 SetDParam(1, STR_NEWS_COMPANY_LAUNCH_DESCRIPTION
);
381 SetDParamStr(2, cni
->company_name
);
382 SetDParam(3, t
->index
);
383 AddNewsItem(STR_MESSAGE_NEWS_FORMAT
, NT_COMPANY_INFO
, NF_COMPANY
, NR_TILE
, c
->last_build_coordinate
, NR_NONE
, UINT32_MAX
, cni
);
389 if (c
->president_name_1
== SPECSTR_PRESIDENT_NAME
) {
390 str
= SPECSTR_ANDCO_NAME
;
391 strp
= c
->president_name_2
;
394 str
= SPECSTR_ANDCO_NAME
;
400 /** Sorting weights for the company colours. */
401 static const byte _colour_sort
[COLOUR_END
] = {2, 2, 3, 2, 3, 2, 3, 2, 3, 2, 2, 2, 3, 1, 1, 1};
402 /** Similar colours, so we can try to prevent same coloured companies. */
403 static const Colours _similar_colour
[COLOUR_END
][2] = {
404 { COLOUR_BLUE
, COLOUR_LIGHT_BLUE
}, // COLOUR_DARK_BLUE
405 { COLOUR_GREEN
, COLOUR_DARK_GREEN
}, // COLOUR_PALE_GREEN
406 { INVALID_COLOUR
, INVALID_COLOUR
}, // COLOUR_PINK
407 { COLOUR_ORANGE
, INVALID_COLOUR
}, // COLOUR_YELLOW
408 { INVALID_COLOUR
, INVALID_COLOUR
}, // COLOUR_RED
409 { COLOUR_DARK_BLUE
, COLOUR_BLUE
}, // COLOUR_LIGHT_BLUE
410 { COLOUR_PALE_GREEN
, COLOUR_DARK_GREEN
}, // COLOUR_GREEN
411 { COLOUR_PALE_GREEN
, COLOUR_GREEN
}, // COLOUR_DARK_GREEN
412 { COLOUR_DARK_BLUE
, COLOUR_LIGHT_BLUE
}, // COLOUR_BLUE
413 { COLOUR_BROWN
, COLOUR_ORANGE
}, // COLOUR_CREAM
414 { COLOUR_PURPLE
, INVALID_COLOUR
}, // COLOUR_MAUVE
415 { COLOUR_MAUVE
, INVALID_COLOUR
}, // COLOUR_PURPLE
416 { COLOUR_YELLOW
, COLOUR_CREAM
}, // COLOUR_ORANGE
417 { COLOUR_CREAM
, INVALID_COLOUR
}, // COLOUR_BROWN
418 { COLOUR_WHITE
, INVALID_COLOUR
}, // COLOUR_GREY
419 { COLOUR_GREY
, INVALID_COLOUR
}, // COLOUR_WHITE
423 * Generate a company colour.
424 * @return Generated company colour.
426 static Colours
GenerateCompanyColour()
428 Colours colours
[COLOUR_END
];
430 /* Initialize array */
431 for (uint i
= 0; i
< COLOUR_END
; i
++) colours
[i
] = (Colours
)i
;
433 /* And randomize it */
434 for (uint i
= 0; i
< 100; i
++) {
436 Swap(colours
[GB(r
, 0, 4)], colours
[GB(r
, 4, 4)]);
439 /* Bubble sort it according to the values in table 1 */
440 for (uint i
= 0; i
< COLOUR_END
; i
++) {
441 for (uint j
= 1; j
< COLOUR_END
; j
++) {
442 if (_colour_sort
[colours
[j
- 1]] < _colour_sort
[colours
[j
]]) {
443 Swap(colours
[j
- 1], colours
[j
]);
448 /* Move the colours that look similar to each company's colour to the side */
449 for (const Company
*c
: Company::Iterate()) {
450 Colours pcolour
= (Colours
)c
->colour
;
452 for (uint i
= 0; i
< COLOUR_END
; i
++) {
453 if (colours
[i
] == pcolour
) {
454 colours
[i
] = INVALID_COLOUR
;
459 for (uint j
= 0; j
< 2; j
++) {
460 Colours similar
= _similar_colour
[pcolour
][j
];
461 if (similar
== INVALID_COLOUR
) break;
463 for (uint i
= 1; i
< COLOUR_END
; i
++) {
464 if (colours
[i
- 1] == similar
) Swap(colours
[i
- 1], colours
[i
]);
469 /* Return the first available colour */
470 for (uint i
= 0; i
< COLOUR_END
; i
++) {
471 if (colours
[i
] != INVALID_COLOUR
) return colours
[i
];
478 * Generate a random president name of a company.
479 * @param c Company that needs a new president name.
481 static void GeneratePresidentName(Company
*c
)
485 c
->president_name_2
= Random();
486 c
->president_name_1
= SPECSTR_PRESIDENT_NAME
;
488 /* Reserve space for extra unicode character. We need to do this to be able
489 * to detect too long president name. */
490 char buffer
[(MAX_LENGTH_PRESIDENT_NAME_CHARS
+ 1) * MAX_CHAR_LENGTH
];
491 SetDParam(0, c
->index
);
492 GetString(buffer
, STR_PRESIDENT_NAME
, lastof(buffer
));
493 if (Utf8StringLength(buffer
) >= MAX_LENGTH_PRESIDENT_NAME_CHARS
) continue;
495 for (const Company
*cc
: Company::Iterate()) {
497 /* Reserve extra space so even overlength president names can be compared. */
498 char buffer2
[(MAX_LENGTH_PRESIDENT_NAME_CHARS
+ 1) * MAX_CHAR_LENGTH
];
499 SetDParam(0, cc
->index
);
500 GetString(buffer2
, STR_PRESIDENT_NAME
, lastof(buffer2
));
501 if (strcmp(buffer2
, buffer
) == 0) goto restart
;
509 * Reset the livery schemes to the company's primary colour.
510 * This is used on loading games without livery information and on new company start up.
511 * @param c Company to reset.
513 void ResetCompanyLivery(Company
*c
)
515 for (LiveryScheme scheme
= LS_BEGIN
; scheme
< LS_END
; scheme
++) {
516 c
->livery
[scheme
].in_use
= 0;
517 c
->livery
[scheme
].colour1
= c
->colour
;
518 c
->livery
[scheme
].colour2
= c
->colour
;
521 for (Group
*g
: Group::Iterate()) {
522 if (g
->owner
== c
->index
) {
523 g
->livery
.in_use
= 0;
524 g
->livery
.colour1
= c
->colour
;
525 g
->livery
.colour2
= c
->colour
;
531 * Create a new company and sets all company variables default values
533 * @param is_ai is an AI company?
534 * @param company CompanyID to use for the new company
535 * @return the company struct
537 Company
*DoStartupNewCompany(bool is_ai
, CompanyID company
= INVALID_COMPANY
)
539 if (!Company::CanAllocateItem()) return nullptr;
541 /* we have to generate colour before this company is valid */
542 Colours colour
= GenerateCompanyColour();
545 if (company
== INVALID_COMPANY
) {
546 c
= new Company(STR_SV_UNNAMED
, is_ai
);
548 if (Company::IsValidID(company
)) return nullptr;
549 c
= new (company
) Company(STR_SV_UNNAMED
, is_ai
);
554 ResetCompanyLivery(c
);
555 _company_colours
[c
->index
] = (Colours
)c
->colour
;
557 c
->money
= c
->current_loan
= (std::min
<int64
>(INITIAL_LOAN
, _economy
.max_loan
) * _economy
.inflation_prices
>> 16) / 50000 * 50000;
559 c
->share_owners
[0] = c
->share_owners
[1] = c
->share_owners
[2] = c
->share_owners
[3] = INVALID_OWNER
;
561 c
->avail_railtypes
= GetCompanyRailtypes(c
->index
);
562 c
->avail_roadtypes
= GetCompanyRoadTypes(c
->index
);
563 c
->inaugurated_year
= _cur_year
;
564 RandomCompanyManagerFaceBits(c
->face
, (GenderEthnicity
)Random(), false, false); // create a random company manager face
566 SetDefaultCompanySettings(c
->index
);
567 ClearEnginesHiddenFlagOfCompany(c
->index
);
569 GeneratePresidentName(c
);
571 SetWindowDirty(WC_GRAPH_LEGEND
, 0);
572 SetWindowClassesDirty(WC_CLIENT_LIST_POPUP
);
573 SetWindowDirty(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 void CompanyNewsInformation::FillData(const Company
*c
, const Company
*other
)
759 SetDParam(0, c
->index
);
760 GetString(this->company_name
, STR_COMPANY_NAME
, lastof(this->company_name
));
762 if (other
== nullptr) {
763 *this->other_company_name
= '\0';
765 SetDParam(0, other
->index
);
766 GetString(this->other_company_name
, STR_COMPANY_NAME
, lastof(this->other_company_name
));
770 SetDParam(0, c
->index
);
771 GetString(this->president_name
, STR_PRESIDENT_NAME_MANAGER
, lastof(this->president_name
));
773 this->colour
= c
->colour
;
774 this->face
= c
->face
;
779 * Called whenever company related information changes in order to notify admins.
780 * @param company The company data changed of.
782 void CompanyAdminUpdate(const Company
*company
)
784 if (_network_server
) NetworkAdminCompanyUpdate(company
);
788 * Called whenever a company is removed in order to notify admins.
789 * @param company_id The company that was removed.
790 * @param reason The reason the company was removed.
792 void CompanyAdminRemove(CompanyID company_id
, CompanyRemoveReason reason
)
794 if (_network_server
) NetworkAdminCompanyRemove(company_id
, (AdminCompanyRemoveReason
)reason
);
798 * Control the companies: add, delete, etc.
800 * @param flags operation to perform
801 * @param p1 various functionality
802 * - bits 0..15: CompanyCtrlAction
803 * - bits 16..23: CompanyID
804 * - bits 24..31: CompanyRemoveReason (with CCA_DELETE)
807 * @return the cost of this operation or an error
809 CommandCost
CmdCompanyCtrl(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
811 InvalidateWindowData(WC_COMPANY_LEAGUE
, 0, 0);
812 CompanyID company_id
= (CompanyID
)GB(p1
, 16, 8);
814 switch ((CompanyCtrlAction
)GB(p1
, 0, 16)) {
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 ClientID client_id
= (ClientID
)p2
;
823 NetworkClientInfo
*ci
= NetworkClientInfo::GetByClientID(client_id
);
824 #ifndef DEBUG_DUMP_COMMANDS
825 /* When replaying the client ID is not a valid client; there
826 * are actually no clients at all. However, the company has to
827 * be created, otherwise we cannot rerun the game properly.
828 * So only allow a nullptr client info in that case. */
829 if (ci
== nullptr) return CommandCost();
830 #endif /* NOT DEBUG_DUMP_COMMANDS */
832 /* Delete multiplayer progress bar */
833 DeleteWindowById(WC_NETWORK_STATUS_WINDOW
, WN_NETWORK_STATUS_WINDOW_JOIN
);
835 Company
*c
= DoStartupNewCompany(false);
837 /* A new company could not be created, revert to being a spectator */
839 if (_network_server
) {
840 ci
->client_playas
= COMPANY_SPECTATOR
;
841 NetworkUpdateClientInfo(ci
->client_id
);
846 /* This is the client (or non-dedicated server) who wants a new company */
847 if (client_id
== _network_own_client_id
) {
848 assert(_local_company
== COMPANY_SPECTATOR
);
849 SetLocalCompany(c
->index
);
850 if (!StrEmpty(_settings_client
.network
.default_company_pass
)) {
851 NetworkChangeCompanyPassword(_local_company
, _settings_client
.network
.default_company_pass
);
854 /* Now that we have a new company, broadcast our company settings to
855 * all clients so everything is in sync */
856 SyncCompanySettings();
858 MarkWholeScreenDirty();
861 NetworkServerNewCompany(c
, ci
);
865 case CCA_NEW_AI
: { // Make a new AI company
866 if (company_id
!= INVALID_COMPANY
&& company_id
>= MAX_COMPANIES
) return CMD_ERROR
;
868 /* For network games, company deletion is delayed. */
869 if (!_networking
&& company_id
!= INVALID_COMPANY
&& Company::IsValidID(company_id
)) return CMD_ERROR
;
871 if (!(flags
& DC_EXEC
)) return CommandCost();
873 /* For network game, just assume deletion happened. */
874 assert(company_id
== INVALID_COMPANY
|| !Company::IsValidID(company_id
));
876 Company
*c
= DoStartupNewCompany(true, company_id
);
877 if (c
!= nullptr) NetworkServerNewCompany(c
, nullptr);
881 case CCA_DELETE
: { // Delete a company
882 CompanyRemoveReason reason
= (CompanyRemoveReason
)GB(p1
, 24, 8);
883 if (reason
>= CRR_END
) return CMD_ERROR
;
885 /* We can't delete the last existing company in singleplayer mode. */
886 if (!_networking
&& Company::GetNumItems() == 1) return CMD_ERROR
;
888 Company
*c
= Company::GetIfValid(company_id
);
889 if (c
== nullptr) return CMD_ERROR
;
891 if (!(flags
& DC_EXEC
)) return CommandCost();
893 /* Delete any open window of the company */
894 DeleteCompanyWindows(c
->index
);
895 CompanyNewsInformation
*cni
= MallocT
<CompanyNewsInformation
>(1);
898 /* Show the bankrupt news */
899 SetDParam(0, STR_NEWS_COMPANY_BANKRUPT_TITLE
);
900 SetDParam(1, STR_NEWS_COMPANY_BANKRUPT_DESCRIPTION
);
901 SetDParamStr(2, cni
->company_name
);
902 AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT
, cni
);
904 /* Remove the company */
905 ChangeOwnershipOfCompanyItems(c
->index
, INVALID_OWNER
);
906 if (c
->is_ai
) AI::Stop(c
->index
);
908 CompanyID c_index
= c
->index
;
910 AI::BroadcastNewEvent(new ScriptEventCompanyBankrupt(c_index
));
911 Game::NewEvent(new ScriptEventCompanyBankrupt(c_index
));
912 CompanyAdminRemove(c_index
, (CompanyRemoveReason
)reason
);
914 if (StoryPage::GetNumItems() == 0 || Goal::GetNumItems() == 0) InvalidateWindowData(WC_MAIN_TOOLBAR
, 0);
918 default: return CMD_ERROR
;
921 InvalidateWindowClassesData(WC_GAME_OPTIONS
);
922 InvalidateWindowClassesData(WC_AI_SETTINGS
);
923 InvalidateWindowClassesData(WC_AI_LIST
);
925 return CommandCost();
929 * Change the company manager's face.
931 * @param flags operation to perform
933 * @param p2 face bitmasked
935 * @return the cost of this operation or an error
937 CommandCost
CmdSetCompanyManagerFace(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
939 CompanyManagerFace cmf
= (CompanyManagerFace
)p2
;
941 if (!IsValidCompanyManagerFace(cmf
)) return CMD_ERROR
;
943 if (flags
& DC_EXEC
) {
944 Company::Get(_current_company
)->face
= cmf
;
945 MarkWholeScreenDirty();
947 return CommandCost();
951 * Change the company's company-colour
953 * @param flags operation to perform
954 * @param p1 bitstuffed:
955 * p1 bits 0-7 scheme to set
956 * p1 bit 8 set first/second colour
957 * @param p2 new colour for vehicles, property, etc.
959 * @return the cost of this operation or an error
961 CommandCost
CmdSetCompanyColour(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
963 Colours colour
= Extract
<Colours
, 0, 8>(p2
);
964 LiveryScheme scheme
= Extract
<LiveryScheme
, 0, 8>(p1
);
965 bool second
= HasBit(p1
, 8);
967 if (scheme
>= LS_END
|| (colour
>= COLOUR_END
&& colour
!= INVALID_COLOUR
)) return CMD_ERROR
;
969 /* Default scheme can't be reset to invalid. */
970 if (scheme
== LS_DEFAULT
&& colour
== INVALID_COLOUR
) return CMD_ERROR
;
972 Company
*c
= Company::Get(_current_company
);
974 /* Ensure no two companies have the same primary colour */
975 if (scheme
== LS_DEFAULT
&& !second
) {
976 for (const Company
*cc
: Company::Iterate()) {
977 if (cc
!= c
&& cc
->colour
== colour
) return CMD_ERROR
;
981 if (flags
& DC_EXEC
) {
983 if (scheme
!= LS_DEFAULT
) SB(c
->livery
[scheme
].in_use
, 0, 1, colour
!= INVALID_COLOUR
);
984 if (colour
== INVALID_COLOUR
) colour
= (Colours
)c
->livery
[LS_DEFAULT
].colour1
;
985 c
->livery
[scheme
].colour1
= colour
;
987 /* If setting the first colour of the default scheme, adjust the
988 * original and cached company colours too. */
989 if (scheme
== LS_DEFAULT
) {
990 for (int i
= 1; i
< LS_END
; i
++) {
991 if (!HasBit(c
->livery
[i
].in_use
, 0)) c
->livery
[i
].colour1
= colour
;
993 _company_colours
[_current_company
] = colour
;
995 CompanyAdminUpdate(c
);
998 if (scheme
!= LS_DEFAULT
) SB(c
->livery
[scheme
].in_use
, 1, 1, colour
!= INVALID_COLOUR
);
999 if (colour
== INVALID_COLOUR
) colour
= (Colours
)c
->livery
[LS_DEFAULT
].colour2
;
1000 c
->livery
[scheme
].colour2
= colour
;
1002 if (scheme
== LS_DEFAULT
) {
1003 for (int i
= 1; i
< LS_END
; i
++) {
1004 if (!HasBit(c
->livery
[i
].in_use
, 1)) c
->livery
[i
].colour2
= colour
;
1009 if (c
->livery
[scheme
].in_use
!= 0) {
1010 /* If enabling a scheme, set the default scheme to be in use too */
1011 c
->livery
[LS_DEFAULT
].in_use
= 1;
1013 /* Else loop through all schemes to see if any are left enabled.
1014 * If not, disable the default scheme too. */
1015 c
->livery
[LS_DEFAULT
].in_use
= 0;
1016 for (scheme
= LS_DEFAULT
; scheme
< LS_END
; scheme
++) {
1017 if (c
->livery
[scheme
].in_use
!= 0) {
1018 c
->livery
[LS_DEFAULT
].in_use
= 1;
1024 ResetVehicleColourMap();
1025 MarkWholeScreenDirty();
1027 /* All graph related to companies use the company colour. */
1028 InvalidateWindowData(WC_INCOME_GRAPH
, 0);
1029 InvalidateWindowData(WC_OPERATING_PROFIT
, 0);
1030 InvalidateWindowData(WC_DELIVERED_CARGO
, 0);
1031 InvalidateWindowData(WC_PERFORMANCE_HISTORY
, 0);
1032 InvalidateWindowData(WC_COMPANY_VALUE
, 0);
1033 InvalidateWindowData(WC_LINKGRAPH_LEGEND
, 0);
1034 /* The smallmap owner view also stores the company colours. */
1036 InvalidateWindowData(WC_SMALLMAP
, 0, 1);
1038 /* Company colour data is indirectly cached. */
1039 for (Vehicle
*v
: Vehicle::Iterate()) {
1040 if (v
->owner
== _current_company
) v
->InvalidateNewGRFCache();
1043 extern void UpdateObjectColours(const Company
*c
);
1044 UpdateObjectColours(c
);
1046 return CommandCost();
1050 * Is the given name in use as name of a company?
1051 * @param name Name to search.
1052 * @return \c true if the name us unique (that is, not in use), else \c false.
1054 static bool IsUniqueCompanyName(const char *name
)
1056 for (const Company
*c
: Company::Iterate()) {
1057 if (!c
->name
.empty() && c
->name
== name
) return false;
1064 * Change the name of the company.
1065 * @param tile unused
1066 * @param flags operation to perform
1069 * @param text the new name or an empty string when resetting to the default
1070 * @return the cost of this operation or an error
1072 CommandCost
CmdRenameCompany(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1074 bool reset
= StrEmpty(text
);
1077 if (Utf8StringLength(text
) >= MAX_LENGTH_COMPANY_NAME_CHARS
) return CMD_ERROR
;
1078 if (!IsUniqueCompanyName(text
)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE
);
1081 if (flags
& DC_EXEC
) {
1082 Company
*c
= Company::Get(_current_company
);
1088 MarkWholeScreenDirty();
1089 CompanyAdminUpdate(c
);
1092 return CommandCost();
1096 * Is the given name in use as president name of a company?
1097 * @param name Name to search.
1098 * @return \c true if the name us unique (that is, not in use), else \c false.
1100 static bool IsUniquePresidentName(const char *name
)
1102 for (const Company
*c
: Company::Iterate()) {
1103 if (!c
->president_name
.empty() && c
->president_name
== name
) return false;
1110 * Change the name of the president.
1111 * @param tile unused
1112 * @param flags operation to perform
1115 * @param text the new name or an empty string when resetting to the default
1116 * @return the cost of this operation or an error
1118 CommandCost
CmdRenamePresident(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1120 bool reset
= StrEmpty(text
);
1123 if (Utf8StringLength(text
) >= MAX_LENGTH_PRESIDENT_NAME_CHARS
) return CMD_ERROR
;
1124 if (!IsUniquePresidentName(text
)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE
);
1127 if (flags
& DC_EXEC
) {
1128 Company
*c
= Company::Get(_current_company
);
1131 c
->president_name
.clear();
1133 c
->president_name
= text
;
1135 if (c
->name_1
== STR_SV_UNNAMED
&& c
->name
.empty()) {
1138 seprintf(buf
, lastof(buf
), "%s Transport", text
);
1139 DoCommand(0, 0, 0, DC_EXEC
, CMD_RENAME_COMPANY
, buf
);
1143 MarkWholeScreenDirty();
1144 CompanyAdminUpdate(c
);
1147 return CommandCost();
1151 * Get the service interval for the given company and vehicle type.
1152 * @param c The company, or nullptr for client-default settings.
1153 * @param type The vehicle type to get the interval for.
1154 * @return The service interval.
1156 int CompanyServiceInterval(const Company
*c
, VehicleType type
)
1158 const VehicleDefaultSettings
*vds
= (c
== nullptr) ? &_settings_client
.company
.vehicle
: &c
->settings
.vehicle
;
1160 default: NOT_REACHED();
1161 case VEH_TRAIN
: return vds
->servint_trains
;
1162 case VEH_ROAD
: return vds
->servint_roadveh
;
1163 case VEH_AIRCRAFT
: return vds
->servint_aircraft
;
1164 case VEH_SHIP
: return vds
->servint_ships
;
1169 * Get total sum of all owned road bits.
1170 * @return Combined total road road bits.
1172 uint32
CompanyInfrastructure::GetRoadTotal() const
1175 for (RoadType rt
= ROADTYPE_BEGIN
; rt
!= ROADTYPE_END
; rt
++) {
1176 if (RoadTypeIsRoad(rt
)) total
+= this->road
[rt
];
1182 * Get total sum of all owned tram bits.
1183 * @return Combined total of tram road bits.
1185 uint32
CompanyInfrastructure::GetTramTotal() const
1188 for (RoadType rt
= ROADTYPE_BEGIN
; rt
!= ROADTYPE_END
; rt
++) {
1189 if (RoadTypeIsTram(rt
)) total
+= this->road
[rt
];
1195 * Transfer funds (money) from one company to another.
1196 * To prevent abuse in multiplayer games you can only send money to other
1197 * companies if you have paid off your loan (either explicitly, or implicitly
1198 * given the fact that you have more money than loan).
1199 * @param tile unused
1200 * @param flags operation to perform
1201 * @param p1 the amount of money to transfer; max 20.000.000
1202 * @param p2 the company to transfer the money to
1203 * @param text unused
1204 * @return the cost of this operation or an error
1206 CommandCost
CmdGiveMoney(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1208 if (!_settings_game
.economy
.give_money
) return CMD_ERROR
;
1210 const Company
*c
= Company::Get(_current_company
);
1211 CommandCost
amount(EXPENSES_OTHER
, std::min
<Money
>(p1
, 20000000LL));
1212 CompanyID dest_company
= (CompanyID
)p2
;
1214 /* You can only transfer funds that is in excess of your loan */
1215 if (c
->money
- c
->current_loan
< amount
.GetCost() || amount
.GetCost() < 0) return_cmd_error(STR_ERROR_INSUFFICIENT_FUNDS
);
1216 if (!Company::IsValidID(dest_company
)) return CMD_ERROR
;
1218 if (flags
& DC_EXEC
) {
1219 /* Add money to company */
1220 Backup
<CompanyID
> cur_company(_current_company
, dest_company
, FILE_LINE
);
1221 SubtractMoneyFromCompany(CommandCost(EXPENSES_OTHER
, -amount
.GetCost()));
1222 cur_company
.Restore();
1225 char dest_company_name
[MAX_LENGTH_COMPANY_NAME_CHARS
* MAX_CHAR_LENGTH
];
1226 SetDParam(0, dest_company
);
1227 GetString(dest_company_name
, STR_COMPANY_NAME
, lastof(dest_company_name
));
1229 char from_company_name
[MAX_LENGTH_COMPANY_NAME_CHARS
* MAX_CHAR_LENGTH
];
1230 SetDParam(0, _current_company
);
1231 GetString(from_company_name
, STR_COMPANY_NAME
, lastof(from_company_name
));
1233 NetworkTextMessage(NETWORK_ACTION_GIVE_MONEY
, GetDrawStringCompanyColour(_current_company
), false, from_company_name
, dest_company_name
, amount
.GetCost());
1237 /* Subtract money from local-company */