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 "ai/ai_instance.hpp"
24 #include "ai/ai_config.hpp"
25 #include "company_manager_face.h"
26 #include "window_func.h"
27 #include "strings_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 "company_cmd.h"
39 #include "timer/timer.h"
40 #include "timer/timer_game_economy.h"
41 #include "timer/timer_game_tick.h"
43 #include "widgets/statusbar_widget.h"
45 #include "table/strings.h"
47 #include "safeguards.h"
49 void ClearEnginesHiddenFlagOfCompany(CompanyID cid
);
50 void UpdateObjectColours(const Company
*c
);
52 CompanyID _local_company
; ///< Company controlled by the human player at this client. Can also be #COMPANY_SPECTATOR.
53 CompanyID _current_company
; ///< Company currently doing an action.
54 Colours _company_colours
[MAX_COMPANIES
]; ///< NOSAVE: can be determined from company structs.
55 CompanyManagerFace _company_manager_face
; ///< for company manager face storage in openttd.cfg
56 uint _cur_company_tick_index
; ///< used to generate a name for one company that doesn't have a name yet per tick
58 CompanyPool
_company_pool("Company"); ///< Pool of companies.
59 INSTANTIATE_POOL_METHODS(Company
)
63 * @param name_1 Name of the company.
64 * @param is_ai A computer program is running for this company.
66 Company::Company(uint16_t name_1
, bool is_ai
)
68 this->name_1
= name_1
;
69 this->location_of_HQ
= INVALID_TILE
;
71 this->terraform_limit
= (uint32_t)_settings_game
.construction
.terraform_frame_burst
<< 16;
72 this->clear_limit
= (uint32_t)_settings_game
.construction
.clear_frame_burst
<< 16;
73 this->tree_limit
= (uint32_t)_settings_game
.construction
.tree_frame_burst
<< 16;
74 this->build_object_limit
= (uint32_t)_settings_game
.construction
.build_object_frame_burst
<< 16;
76 InvalidateWindowData(WC_PERFORMANCE_DETAIL
, 0, INVALID_COMPANY
);
82 if (CleaningPool()) return;
84 CloseCompanyWindows(this->index
);
88 * Invalidating some stuff after removing item from the pool.
89 * @param index index of deleted item
91 void Company::PostDestructor(size_t index
)
93 InvalidateWindowData(WC_GRAPH_LEGEND
, 0, (int)index
);
94 InvalidateWindowData(WC_PERFORMANCE_DETAIL
, 0, (int)index
);
95 InvalidateWindowData(WC_COMPANY_LEAGUE
, 0, 0);
96 InvalidateWindowData(WC_LINKGRAPH_LEGEND
, 0);
97 /* If the currently shown error message has this company in it, then close it. */
98 InvalidateWindowData(WC_ERRMSG
, 0);
102 * Calculate the max allowed loan for this company.
103 * @return the max loan amount.
105 Money
Company::GetMaxLoan() const
107 if (this->max_loan
== COMPANY_MAX_LOAN_DEFAULT
) return _economy
.max_loan
;
108 return this->max_loan
;
112 * Sets the local company and updates the settings that are set on a
113 * per-company basis to reflect the core's state in the GUI.
114 * @param new_company the new company
115 * @pre Company::IsValidID(new_company) || new_company == COMPANY_SPECTATOR || new_company == OWNER_NONE
117 void SetLocalCompany(CompanyID new_company
)
119 /* company could also be COMPANY_SPECTATOR or OWNER_NONE */
120 assert(Company::IsValidID(new_company
) || new_company
== COMPANY_SPECTATOR
|| new_company
== OWNER_NONE
);
122 /* If actually changing to another company, several windows need closing */
123 bool switching_company
= _local_company
!= new_company
;
125 /* Delete the chat window, if you were team chatting. */
126 if (switching_company
) InvalidateWindowData(WC_SEND_NETWORK_MSG
, DESTTYPE_TEAM
, _local_company
);
128 assert(IsLocalCompany());
130 _current_company
= _local_company
= new_company
;
132 if (switching_company
) {
133 InvalidateWindowClassesData(WC_COMPANY
);
134 /* Delete any construction windows... */
135 CloseConstructionWindows();
138 /* ... and redraw the whole screen. */
139 MarkWholeScreenDirty();
140 InvalidateWindowClassesData(WC_SIGN_LIST
, -1);
141 InvalidateWindowClassesData(WC_GOALS_LIST
);
145 * Get the colour for DrawString-subroutines which matches the colour of the company.
146 * @param company Company to get the colour of.
147 * @return Colour of \a company.
149 TextColour
GetDrawStringCompanyColour(CompanyID company
)
151 if (!Company::IsValidID(company
)) return (TextColour
)GetColourGradient(COLOUR_WHITE
, SHADE_NORMAL
) | TC_IS_PALETTE_COLOUR
;
152 return (TextColour
)GetColourGradient(_company_colours
[company
], SHADE_NORMAL
) | TC_IS_PALETTE_COLOUR
;
156 * Draw the icon of a company.
157 * @param c Company that needs its icon drawn.
158 * @param x Horizontal coordinate of the icon.
159 * @param y Vertical coordinate of the icon.
161 void DrawCompanyIcon(CompanyID c
, int x
, int y
)
163 DrawSprite(SPR_COMPANY_ICON
, COMPANY_SPRITE_COLOUR(c
), x
, y
);
167 * Checks whether a company manager's face is a valid encoding.
168 * Unused bits are not enforced to be 0.
169 * @param cmf the fact to check
170 * @return true if and only if the face is valid
172 static bool IsValidCompanyManagerFace(CompanyManagerFace cmf
)
174 if (!AreCompanyManagerFaceBitsValid(cmf
, CMFV_GEN_ETHN
, GE_WM
)) return false;
176 GenderEthnicity ge
= (GenderEthnicity
)GetCompanyManagerFaceBits(cmf
, CMFV_GEN_ETHN
, GE_WM
);
177 bool has_moustache
= !HasBit(ge
, GENDER_FEMALE
) && GetCompanyManagerFaceBits(cmf
, CMFV_HAS_MOUSTACHE
, ge
) != 0;
178 bool has_tie_earring
= !HasBit(ge
, GENDER_FEMALE
) || GetCompanyManagerFaceBits(cmf
, CMFV_HAS_TIE_EARRING
, ge
) != 0;
179 bool has_glasses
= GetCompanyManagerFaceBits(cmf
, CMFV_HAS_GLASSES
, ge
) != 0;
181 if (!AreCompanyManagerFaceBitsValid(cmf
, CMFV_EYE_COLOUR
, ge
)) return false;
182 for (CompanyManagerFaceVariable cmfv
= CMFV_CHEEKS
; cmfv
< CMFV_END
; cmfv
++) {
184 case CMFV_MOUSTACHE
: if (!has_moustache
) continue; break;
186 case CMFV_NOSE
: if (has_moustache
) continue; break;
187 case CMFV_TIE_EARRING
: if (!has_tie_earring
) continue; break;
188 case CMFV_GLASSES
: if (!has_glasses
) continue; break;
191 if (!AreCompanyManagerFaceBitsValid(cmf
, cmfv
, ge
)) return false;
198 * Refresh all windows owned by a company.
199 * @param company Company that changed, and needs its windows refreshed.
201 void InvalidateCompanyWindows(const Company
*company
)
203 CompanyID cid
= company
->index
;
205 if (cid
== _local_company
) SetWindowWidgetDirty(WC_STATUS_BAR
, 0, WID_S_RIGHT
);
206 SetWindowDirty(WC_FINANCES
, cid
);
210 * Get the amount of money that a company has available, or INT64_MAX
211 * if there is no such valid company.
213 * @param company Company to check
214 * @return The available money of the company or INT64_MAX
216 Money
GetAvailableMoney(CompanyID company
)
218 if (_settings_game
.difficulty
.infinite_money
) return INT64_MAX
;
219 if (!Company::IsValidID(company
)) return INT64_MAX
;
220 return Company::Get(company
)->money
;
224 * This functions returns the money which can be used to execute a command.
225 * This is either the money of the current company, or INT64_MAX if infinite money
226 * is enabled or there is no such a company "at the moment" like the server itself.
228 * @return The available money of the current company or INT64_MAX
230 Money
GetAvailableMoneyForCommand()
232 return GetAvailableMoney(_current_company
);
236 * Verify whether the company can pay the bill.
237 * @param[in,out] cost Money to pay, is changed to an error if the company does not have enough money.
238 * @return Function returns \c true if the company has enough money or infinite money is enabled,
239 * else it returns \c false.
241 bool CheckCompanyHasMoney(CommandCost
&cost
)
243 if (cost
.GetCost() <= 0) return true;
244 if (_settings_game
.difficulty
.infinite_money
) return true;
246 const Company
*c
= Company::GetIfValid(_current_company
);
247 if (c
!= nullptr && cost
.GetCost() > c
->money
) {
248 SetDParam(0, cost
.GetCost());
249 cost
.MakeError(STR_ERROR_NOT_ENOUGH_CASH_REQUIRES_CURRENCY
);
256 * Deduct costs of a command from the money of a company.
257 * @param c Company to pay the bill.
258 * @param cost Money to pay.
260 static void SubtractMoneyFromAnyCompany(Company
*c
, const CommandCost
&cost
)
262 if (cost
.GetCost() == 0) return;
263 assert(cost
.GetExpensesType() != INVALID_EXPENSES
);
265 c
->money
-= cost
.GetCost();
266 c
->yearly_expenses
[0][cost
.GetExpensesType()] += cost
.GetCost();
268 if (HasBit(1 << EXPENSES_TRAIN_REVENUE
|
269 1 << EXPENSES_ROADVEH_REVENUE
|
270 1 << EXPENSES_AIRCRAFT_REVENUE
|
271 1 << EXPENSES_SHIP_REVENUE
, cost
.GetExpensesType())) {
272 c
->cur_economy
.income
-= cost
.GetCost();
273 } else if (HasBit(1 << EXPENSES_TRAIN_RUN
|
274 1 << EXPENSES_ROADVEH_RUN
|
275 1 << EXPENSES_AIRCRAFT_RUN
|
276 1 << EXPENSES_SHIP_RUN
|
277 1 << EXPENSES_PROPERTY
|
278 1 << EXPENSES_LOAN_INTEREST
, cost
.GetExpensesType())) {
279 c
->cur_economy
.expenses
-= cost
.GetCost();
282 InvalidateCompanyWindows(c
);
286 * Subtract money from the #_current_company, if the company is valid.
287 * @param cost Money to pay.
289 void SubtractMoneyFromCompany(const CommandCost
&cost
)
291 Company
*c
= Company::GetIfValid(_current_company
);
292 if (c
!= nullptr) SubtractMoneyFromAnyCompany(c
, cost
);
296 * Subtract money from a company, including the money fraction.
297 * @param company Company paying the bill.
298 * @param cst Cost of a command.
300 void SubtractMoneyFromCompanyFract(CompanyID company
, const CommandCost
&cst
)
302 Company
*c
= Company::Get(company
);
303 uint8_t m
= c
->money_fraction
;
304 Money cost
= cst
.GetCost();
306 c
->money_fraction
= m
- (uint8_t)cost
;
308 if (c
->money_fraction
> m
) cost
++;
309 if (cost
!= 0) SubtractMoneyFromAnyCompany(c
, CommandCost(cst
.GetExpensesType(), cost
));
312 static constexpr void UpdateLandscapingLimit(uint32_t &limit
, uint64_t per_64k_frames
, uint64_t burst
)
314 limit
= static_cast<uint32_t>(std::min
<uint64_t>(limit
+ per_64k_frames
, burst
<< 16));
317 /** Update the landscaping limits per company. */
318 void UpdateLandscapingLimits()
320 for (Company
*c
: Company::Iterate()) {
321 UpdateLandscapingLimit(c
->terraform_limit
, _settings_game
.construction
.terraform_per_64k_frames
, _settings_game
.construction
.terraform_frame_burst
);
322 UpdateLandscapingLimit(c
->clear_limit
, _settings_game
.construction
.clear_per_64k_frames
, _settings_game
.construction
.clear_frame_burst
);
323 UpdateLandscapingLimit(c
->tree_limit
, _settings_game
.construction
.tree_per_64k_frames
, _settings_game
.construction
.tree_frame_burst
);
324 UpdateLandscapingLimit(c
->build_object_limit
, _settings_game
.construction
.build_object_per_64k_frames
, _settings_game
.construction
.build_object_frame_burst
);
329 * Set the right DParams for STR_ERROR_OWNED_BY.
330 * @param owner the owner to get the name of.
331 * @param tile optional tile to get the right town.
332 * @pre if tile == 0, then owner can't be OWNER_TOWN.
334 void SetDParamsForOwnedBy(Owner owner
, TileIndex tile
)
336 SetDParam(OWNED_BY_OWNER_IN_PARAMETERS_OFFSET
, owner
);
338 if (owner
!= OWNER_TOWN
) {
339 if (!Company::IsValidID(owner
)) {
340 SetDParam(0, STR_COMPANY_SOMEONE
);
342 SetDParam(0, STR_COMPANY_NAME
);
347 const Town
*t
= ClosestTownFromTile(tile
, UINT_MAX
);
349 SetDParam(0, STR_TOWN_NAME
);
350 SetDParam(1, t
->index
);
356 * Check whether the current owner owns something.
357 * If that isn't the case an appropriate error will be given.
358 * @param owner the owner of the thing to check.
359 * @param tile optional tile to get the right town.
360 * @pre if tile == 0 then the owner can't be OWNER_TOWN.
361 * @return A succeeded command iff it's owned by the current company, else a failed command.
363 CommandCost
CheckOwnership(Owner owner
, TileIndex tile
)
365 assert(owner
< OWNER_END
);
366 assert(owner
!= OWNER_TOWN
|| tile
!= 0);
368 if (owner
== _current_company
) return CommandCost();
370 SetDParamsForOwnedBy(owner
, tile
);
371 return_cmd_error(STR_ERROR_OWNED_BY
);
375 * Check whether the current owner owns the stuff on
376 * the given tile. If that isn't the case an
377 * appropriate error will be given.
378 * @param tile the tile to check.
379 * @return A succeeded command iff it's owned by the current company, else a failed command.
381 CommandCost
CheckTileOwnership(TileIndex tile
)
383 Owner owner
= GetTileOwner(tile
);
385 assert(owner
< OWNER_END
);
387 if (owner
== _current_company
) return CommandCost();
389 /* no need to get the name of the owner unless we're the local company (saves some time) */
390 if (IsLocalCompany()) SetDParamsForOwnedBy(owner
, tile
);
391 return_cmd_error(STR_ERROR_OWNED_BY
);
395 * Generate the name of a company from the last build coordinate.
396 * @param c Company to give a name.
398 static void GenerateCompanyName(Company
*c
)
400 if (c
->name_1
!= STR_SV_UNNAMED
) return;
401 if (c
->last_build_coordinate
== 0) return;
403 Town
*t
= ClosestTownFromTile(c
->last_build_coordinate
, UINT_MAX
);
408 if (t
->name
.empty() && IsInsideMM(t
->townnametype
, SPECSTR_TOWNNAME_START
, SPECSTR_TOWNNAME_LAST
+ 1)) {
409 str
= t
->townnametype
- SPECSTR_TOWNNAME_START
+ SPECSTR_COMPANY_NAME_START
;
410 strp
= t
->townnameparts
;
413 /* No companies must have this name already */
414 for (const Company
*cc
: Company::Iterate()) {
415 if (cc
->name_1
== str
&& cc
->name_2
== strp
) goto bad_town_name
;
419 name
= GetString(str
);
420 if (Utf8StringLength(name
) >= MAX_LENGTH_COMPANY_NAME_CHARS
) goto bad_town_name
;
426 MarkWholeScreenDirty();
429 CompanyNewsInformation
*cni
= new CompanyNewsInformation(c
);
430 SetDParam(0, STR_NEWS_COMPANY_LAUNCH_TITLE
);
431 SetDParam(1, STR_NEWS_COMPANY_LAUNCH_DESCRIPTION
);
432 SetDParamStr(2, cni
->company_name
);
433 SetDParam(3, t
->index
);
434 AddNewsItem(STR_MESSAGE_NEWS_FORMAT
, NT_COMPANY_INFO
, NF_COMPANY
, NR_TILE
, c
->last_build_coordinate
.base(), NR_NONE
, UINT32_MAX
, cni
);
440 if (c
->president_name_1
== SPECSTR_PRESIDENT_NAME
) {
441 str
= SPECSTR_ANDCO_NAME
;
442 strp
= c
->president_name_2
;
445 str
= SPECSTR_ANDCO_NAME
;
451 /** Sorting weights for the company colours. */
452 static const uint8_t _colour_sort
[COLOUR_END
] = {2, 2, 3, 2, 3, 2, 3, 2, 3, 2, 2, 2, 3, 1, 1, 1};
453 /** Similar colours, so we can try to prevent same coloured companies. */
454 static const Colours _similar_colour
[COLOUR_END
][2] = {
455 { COLOUR_BLUE
, COLOUR_LIGHT_BLUE
}, // COLOUR_DARK_BLUE
456 { COLOUR_GREEN
, COLOUR_DARK_GREEN
}, // COLOUR_PALE_GREEN
457 { INVALID_COLOUR
, INVALID_COLOUR
}, // COLOUR_PINK
458 { COLOUR_ORANGE
, INVALID_COLOUR
}, // COLOUR_YELLOW
459 { INVALID_COLOUR
, INVALID_COLOUR
}, // COLOUR_RED
460 { COLOUR_DARK_BLUE
, COLOUR_BLUE
}, // COLOUR_LIGHT_BLUE
461 { COLOUR_PALE_GREEN
, COLOUR_DARK_GREEN
}, // COLOUR_GREEN
462 { COLOUR_PALE_GREEN
, COLOUR_GREEN
}, // COLOUR_DARK_GREEN
463 { COLOUR_DARK_BLUE
, COLOUR_LIGHT_BLUE
}, // COLOUR_BLUE
464 { COLOUR_BROWN
, COLOUR_ORANGE
}, // COLOUR_CREAM
465 { COLOUR_PURPLE
, INVALID_COLOUR
}, // COLOUR_MAUVE
466 { COLOUR_MAUVE
, INVALID_COLOUR
}, // COLOUR_PURPLE
467 { COLOUR_YELLOW
, COLOUR_CREAM
}, // COLOUR_ORANGE
468 { COLOUR_CREAM
, INVALID_COLOUR
}, // COLOUR_BROWN
469 { COLOUR_WHITE
, INVALID_COLOUR
}, // COLOUR_GREY
470 { COLOUR_GREY
, INVALID_COLOUR
}, // COLOUR_WHITE
474 * Generate a company colour.
475 * @return Generated company colour.
477 static Colours
GenerateCompanyColour()
479 Colours colours
[COLOUR_END
];
481 /* Initialize array */
482 for (uint i
= 0; i
< COLOUR_END
; i
++) colours
[i
] = static_cast<Colours
>(i
);
484 /* And randomize it */
485 for (uint i
= 0; i
< 100; i
++) {
487 Swap(colours
[GB(r
, 0, 4)], colours
[GB(r
, 4, 4)]);
490 /* Bubble sort it according to the values in table 1 */
491 for (uint i
= 0; i
< COLOUR_END
; i
++) {
492 for (uint j
= 1; j
< COLOUR_END
; j
++) {
493 if (_colour_sort
[colours
[j
- 1]] < _colour_sort
[colours
[j
]]) {
494 Swap(colours
[j
- 1], colours
[j
]);
499 /* Move the colours that look similar to each company's colour to the side */
500 for (const Company
*c
: Company::Iterate()) {
501 Colours pcolour
= c
->colour
;
503 for (uint i
= 0; i
< COLOUR_END
; i
++) {
504 if (colours
[i
] == pcolour
) {
505 colours
[i
] = INVALID_COLOUR
;
510 for (uint j
= 0; j
< 2; j
++) {
511 Colours similar
= _similar_colour
[pcolour
][j
];
512 if (similar
== INVALID_COLOUR
) break;
514 for (uint i
= 1; i
< COLOUR_END
; i
++) {
515 if (colours
[i
- 1] == similar
) Swap(colours
[i
- 1], colours
[i
]);
520 /* Return the first available colour */
521 for (uint i
= 0; i
< COLOUR_END
; i
++) {
522 if (colours
[i
] != INVALID_COLOUR
) return colours
[i
];
529 * Generate a random president name of a company.
530 * @param c Company that needs a new president name.
532 static void GeneratePresidentName(Company
*c
)
536 c
->president_name_2
= Random();
537 c
->president_name_1
= SPECSTR_PRESIDENT_NAME
;
539 /* Reserve space for extra unicode character. We need to do this to be able
540 * to detect too long president name. */
541 SetDParam(0, c
->index
);
542 std::string name
= GetString(STR_PRESIDENT_NAME
);
543 if (Utf8StringLength(name
) >= MAX_LENGTH_PRESIDENT_NAME_CHARS
) continue;
545 for (const Company
*cc
: Company::Iterate()) {
547 SetDParam(0, cc
->index
);
548 std::string other_name
= GetString(STR_PRESIDENT_NAME
);
549 if (name
== other_name
) goto restart
;
557 * Reset the livery schemes to the company's primary colour.
558 * This is used on loading games without livery information and on new company start up.
559 * @param c Company to reset.
561 void ResetCompanyLivery(Company
*c
)
563 for (LiveryScheme scheme
= LS_BEGIN
; scheme
< LS_END
; scheme
++) {
564 c
->livery
[scheme
].in_use
= 0;
565 c
->livery
[scheme
].colour1
= c
->colour
;
566 c
->livery
[scheme
].colour2
= c
->colour
;
569 for (Group
*g
: Group::Iterate()) {
570 if (g
->owner
== c
->index
) {
571 g
->livery
.in_use
= 0;
572 g
->livery
.colour1
= c
->colour
;
573 g
->livery
.colour2
= c
->colour
;
579 * Create a new company and sets all company variables default values
581 * @param is_ai is an AI company?
582 * @param company CompanyID to use for the new company
583 * @return the company struct
585 Company
*DoStartupNewCompany(bool is_ai
, CompanyID company
= INVALID_COMPANY
)
587 if (!Company::CanAllocateItem()) return nullptr;
589 /* we have to generate colour before this company is valid */
590 Colours colour
= GenerateCompanyColour();
593 if (company
== INVALID_COMPANY
) {
594 c
= new Company(STR_SV_UNNAMED
, is_ai
);
596 if (Company::IsValidID(company
)) return nullptr;
597 c
= new (company
) Company(STR_SV_UNNAMED
, is_ai
);
602 ResetCompanyLivery(c
);
603 _company_colours
[c
->index
] = c
->colour
;
605 /* Scale the initial loan based on the inflation rounded down to the loan interval. The maximum loan has already been inflation adjusted. */
606 c
->money
= c
->current_loan
= std::min
<int64_t>((INITIAL_LOAN
* _economy
.inflation_prices
>> 16) / LOAN_INTERVAL
* LOAN_INTERVAL
, _economy
.max_loan
);
608 c
->avail_railtypes
= GetCompanyRailTypes(c
->index
);
609 c
->avail_roadtypes
= GetCompanyRoadTypes(c
->index
);
610 c
->inaugurated_year
= TimerGameEconomy::year
;
611 c
->inaugurated_year_calendar
= TimerGameCalendar::year
;
613 /* If starting a player company in singleplayer and a favorite company manager face is selected, choose it. Otherwise, use a random face.
614 * In a network game, we'll choose the favorite face later in CmdCompanyCtrl to sync it to all clients. */
615 if (_company_manager_face
!= 0 && !is_ai
&& !_networking
) {
616 c
->face
= _company_manager_face
;
618 RandomCompanyManagerFaceBits(c
->face
, (GenderEthnicity
)Random(), false, _random
);
621 SetDefaultCompanySettings(c
->index
);
622 ClearEnginesHiddenFlagOfCompany(c
->index
);
624 GeneratePresidentName(c
);
626 SetWindowDirty(WC_GRAPH_LEGEND
, 0);
627 InvalidateWindowData(WC_CLIENT_LIST
, 0);
628 InvalidateWindowData(WC_LINKGRAPH_LEGEND
, 0);
630 InvalidateWindowData(WC_SMALLMAP
, 0, 1);
632 if (is_ai
&& (!_networking
|| _network_server
)) AI::StartNew(c
->index
);
634 AI::BroadcastNewEvent(new ScriptEventCompanyNew(c
->index
), c
->index
);
635 Game::NewEvent(new ScriptEventCompanyNew(c
->index
));
640 /** Start a new competitor company if possible. */
641 TimeoutTimer
<TimerGameTick
> _new_competitor_timeout({ TimerGameTick::Priority::COMPETITOR_TIMEOUT
, 0 }, []() {
642 if (_game_mode
== GM_MENU
|| !AI::CanStartNew()) return;
643 if (_networking
&& Company::GetNumItems() >= _settings_client
.network
.max_companies
) return;
645 /* count number of competitors */
647 for (const Company
*c
: Company::Iterate()) {
651 if (n
>= _settings_game
.difficulty
.max_no_competitors
) return;
653 /* Send a command to all clients to start up a new AI.
654 * Works fine for Multiplayer and Singleplayer */
655 Command
<CMD_COMPANY_CTRL
>::Post(CCA_NEW_AI
, INVALID_COMPANY
, CRR_NONE
, INVALID_CLIENT_ID
);
658 /** Start of a new game. */
659 void StartupCompanies()
661 /* Ensure the timeout is aborted, so it doesn't fire based on information of the last game. */
662 _new_competitor_timeout
.Abort();
665 /** Initialize the pool of companies. */
666 void InitializeCompanies()
668 _cur_company_tick_index
= 0;
672 * Can company \a cbig buy company \a csmall without exceeding vehicle limits?
673 * @param cbig Company buying \a csmall.
674 * @param csmall Company getting bought.
675 * @return Return \c true if it is allowed.
677 bool CheckTakeoverVehicleLimit(CompanyID cbig
, CompanyID csmall
)
679 const Company
*c1
= Company::Get(cbig
);
680 const Company
*c2
= Company::Get(csmall
);
682 /* Do the combined vehicle counts stay within the limits? */
683 return c1
->group_all
[VEH_TRAIN
].num_vehicle
+ c2
->group_all
[VEH_TRAIN
].num_vehicle
<= _settings_game
.vehicle
.max_trains
&&
684 c1
->group_all
[VEH_ROAD
].num_vehicle
+ c2
->group_all
[VEH_ROAD
].num_vehicle
<= _settings_game
.vehicle
.max_roadveh
&&
685 c1
->group_all
[VEH_SHIP
].num_vehicle
+ c2
->group_all
[VEH_SHIP
].num_vehicle
<= _settings_game
.vehicle
.max_ships
&&
686 c1
->group_all
[VEH_AIRCRAFT
].num_vehicle
+ c2
->group_all
[VEH_AIRCRAFT
].num_vehicle
<= _settings_game
.vehicle
.max_aircraft
;
690 * Handle the bankruptcy take over of a company.
691 * Companies going bankrupt will ask the other companies in order of their
692 * performance rating, so better performing companies get the 'do you want to
693 * merge with Y' question earlier. The question will then stay till either the
694 * company has gone bankrupt or got merged with a company.
696 * @param c the company that is going bankrupt.
698 static void HandleBankruptcyTakeover(Company
*c
)
700 /* Amount of time out for each company to take over a company;
701 * Timeout is a quarter (3 months of 30 days) divided over the
702 * number of companies. The minimum number of days in a quarter
703 * is 90: 31 in January, 28 in February and 31 in March.
704 * Note that the company going bankrupt can't buy itself. */
705 static const int TAKE_OVER_TIMEOUT
= 3 * 30 * Ticks::DAY_TICKS
/ (MAX_COMPANIES
- 1);
707 assert(c
->bankrupt_asked
!= 0);
709 /* We're currently asking some company to buy 'us' */
710 if (c
->bankrupt_timeout
!= 0) {
711 c
->bankrupt_timeout
-= MAX_COMPANIES
;
712 if (c
->bankrupt_timeout
> 0) return;
713 c
->bankrupt_timeout
= 0;
718 /* Did we ask everyone for bankruptcy? If so, bail out. */
719 if (c
->bankrupt_asked
== MAX_UVALUE(CompanyMask
)) return;
721 Company
*best
= nullptr;
722 int32_t best_performance
= -1;
724 /* Ask the company with the highest performance history first */
725 for (Company
*c2
: Company::Iterate()) {
726 if (c2
->bankrupt_asked
== 0 && // Don't ask companies going bankrupt themselves
727 !HasBit(c
->bankrupt_asked
, c2
->index
) &&
728 best_performance
< c2
->old_economy
[1].performance_history
&&
729 CheckTakeoverVehicleLimit(c2
->index
, c
->index
)) {
730 best_performance
= c2
->old_economy
[1].performance_history
;
735 /* Asked all companies? */
736 if (best_performance
== -1) {
737 c
->bankrupt_asked
= MAX_UVALUE(CompanyMask
);
741 SetBit(c
->bankrupt_asked
, best
->index
);
743 c
->bankrupt_timeout
= TAKE_OVER_TIMEOUT
;
745 AI::NewEvent(best
->index
, new ScriptEventCompanyAskMerger(c
->index
, c
->bankrupt_value
));
746 if (IsInteractiveCompany(best
->index
)) {
747 ShowBuyCompanyDialog(c
->index
, false);
751 /** Called every tick for updating some company info. */
752 void OnTick_Companies()
754 if (_game_mode
== GM_EDITOR
) return;
756 Company
*c
= Company::GetIfValid(_cur_company_tick_index
);
758 if (c
->name_1
!= 0) GenerateCompanyName(c
);
759 if (c
->bankrupt_asked
!= 0) HandleBankruptcyTakeover(c
);
762 if (_new_competitor_timeout
.HasFired() && _game_mode
!= GM_MENU
&& AI::CanStartNew()) {
763 int32_t timeout
= _settings_game
.difficulty
.competitors_interval
* 60 * Ticks::TICKS_PER_SECOND
;
764 /* If the interval is zero, start as many competitors as needed then check every ~10 minutes if a company went bankrupt and needs replacing. */
766 /* count number of competitors */
768 for (const Company
*cc
: Company::Iterate()) {
772 for (auto i
= 0; i
< _settings_game
.difficulty
.max_no_competitors
; i
++) {
773 if (_networking
&& Company::GetNumItems() >= _settings_client
.network
.max_companies
) break;
774 if (n
++ >= _settings_game
.difficulty
.max_no_competitors
) break;
775 Command
<CMD_COMPANY_CTRL
>::Post(CCA_NEW_AI
, INVALID_COMPANY
, CRR_NONE
, INVALID_CLIENT_ID
);
777 timeout
= 10 * 60 * Ticks::TICKS_PER_SECOND
;
779 /* Randomize a bit when the AI is actually going to start; ranges from 87.5% .. 112.5% of indicated value. */
780 timeout
+= ScriptObject::GetRandomizer(OWNER_NONE
).Next(timeout
/ 4) - timeout
/ 8;
782 _new_competitor_timeout
.Reset({ TimerGameTick::Priority::COMPETITOR_TIMEOUT
, static_cast<uint
>(std::max(1, timeout
)) });
785 _cur_company_tick_index
= (_cur_company_tick_index
+ 1) % MAX_COMPANIES
;
789 * A year has passed, update the economic data of all companies, and perhaps show the
790 * financial overview window of the local company.
792 static IntervalTimer
<TimerGameEconomy
> _economy_companies_yearly({TimerGameEconomy::YEAR
, TimerGameEconomy::Priority::COMPANY
}, [](auto)
794 /* Copy statistics */
795 for (Company
*c
: Company::Iterate()) {
796 /* Move expenses to previous years. */
797 std::rotate(std::rbegin(c
->yearly_expenses
), std::rbegin(c
->yearly_expenses
) + 1, std::rend(c
->yearly_expenses
));
798 c
->yearly_expenses
[0] = {};
799 SetWindowDirty(WC_FINANCES
, c
->index
);
802 if (_settings_client
.gui
.show_finances
&& _local_company
!= COMPANY_SPECTATOR
) {
803 ShowCompanyFinances(_local_company
);
804 Company
*c
= Company::Get(_local_company
);
805 if (c
->num_valid_stat_ent
> 5 && c
->old_economy
[0].performance_history
< c
->old_economy
[4].performance_history
) {
806 if (_settings_client
.sound
.new_year
) SndPlayFx(SND_01_BAD_YEAR
);
808 if (_settings_client
.sound
.new_year
) SndPlayFx(SND_00_GOOD_YEAR
);
814 * Fill the CompanyNewsInformation struct with the required data.
815 * @param c the current company.
816 * @param other the other company (use \c nullptr if not relevant).
818 CompanyNewsInformation::CompanyNewsInformation(const Company
*c
, const Company
*other
)
820 SetDParam(0, c
->index
);
821 this->company_name
= GetString(STR_COMPANY_NAME
);
823 if (other
!= nullptr) {
824 SetDParam(0, other
->index
);
825 this->other_company_name
= GetString(STR_COMPANY_NAME
);
829 SetDParam(0, c
->index
);
830 this->president_name
= GetString(STR_PRESIDENT_NAME_MANAGER
);
832 this->colour
= c
->colour
;
833 this->face
= c
->face
;
838 * Called whenever company related information changes in order to notify admins.
839 * @param company The company data changed of.
841 void CompanyAdminUpdate(const Company
*company
)
843 if (_network_server
) NetworkAdminCompanyUpdate(company
);
847 * Called whenever a company is removed in order to notify admins.
848 * @param company_id The company that was removed.
849 * @param reason The reason the company was removed.
851 void CompanyAdminRemove(CompanyID company_id
, CompanyRemoveReason reason
)
853 if (_network_server
) NetworkAdminCompanyRemove(company_id
, (AdminCompanyRemoveReason
)reason
);
857 * Control the companies: add, delete, etc.
858 * @param flags operation to perform
859 * @param cca action to perform
860 * @param company_id company to perform the action on
861 * @param client_id ClientID
862 * @return the cost of this operation or an error
864 CommandCost
CmdCompanyCtrl(DoCommandFlag flags
, CompanyCtrlAction cca
, CompanyID company_id
, CompanyRemoveReason reason
, ClientID client_id
)
866 InvalidateWindowData(WC_COMPANY_LEAGUE
, 0, 0);
869 case CCA_NEW
: { // Create a new company
870 /* This command is only executed in a multiplayer game */
871 if (!_networking
) return CMD_ERROR
;
873 /* Has the network client a correct ClientIndex? */
874 if (!(flags
& DC_EXEC
)) return CommandCost();
876 NetworkClientInfo
*ci
= NetworkClientInfo::GetByClientID(client_id
);
878 /* Delete multiplayer progress bar */
879 CloseWindowById(WC_NETWORK_STATUS_WINDOW
, WN_NETWORK_STATUS_WINDOW_JOIN
);
881 Company
*c
= DoStartupNewCompany(false);
883 /* A new company could not be created, revert to being a spectator */
885 /* We check for "ci != nullptr" as a client could have left by
886 * the time we execute this command. */
887 if (_network_server
&& ci
!= nullptr) {
888 ci
->client_playas
= COMPANY_SPECTATOR
;
889 NetworkUpdateClientInfo(ci
->client_id
);
894 NetworkAdminCompanyNew(c
);
895 NetworkServerNewCompany(c
, ci
);
897 /* This is the client (or non-dedicated server) who wants a new company */
898 if (client_id
== _network_own_client_id
) {
899 assert(_local_company
== COMPANY_SPECTATOR
);
900 SetLocalCompany(c
->index
);
903 * If a favorite company manager face is selected, choose it. Otherwise, use a random face.
904 * Because this needs to be synchronised over the network, only the client knows
905 * its configuration and we are currently in the execution of a command, we have
906 * to circumvent the normal ::Post logic for commands and just send the command.
908 if (_company_manager_face
!= 0) Command
<CMD_SET_COMPANY_MANAGER_FACE
>::SendNet(STR_NULL
, c
->index
, _company_manager_face
);
910 /* Now that we have a new company, broadcast our company settings to
911 * all clients so everything is in sync */
912 SyncCompanySettings();
914 MarkWholeScreenDirty();
919 case CCA_NEW_AI
: { // Make a new AI company
920 if (company_id
!= INVALID_COMPANY
&& company_id
>= MAX_COMPANIES
) return CMD_ERROR
;
922 /* For network games, company deletion is delayed. */
923 if (!_networking
&& company_id
!= INVALID_COMPANY
&& Company::IsValidID(company_id
)) return CMD_ERROR
;
925 if (!(flags
& DC_EXEC
)) return CommandCost();
927 /* For network game, just assume deletion happened. */
928 assert(company_id
== INVALID_COMPANY
|| !Company::IsValidID(company_id
));
930 Company
*c
= DoStartupNewCompany(true, company_id
);
932 NetworkAdminCompanyNew(c
);
933 NetworkServerNewCompany(c
, nullptr);
938 case CCA_DELETE
: { // Delete a company
939 if (reason
>= CRR_END
) return CMD_ERROR
;
941 /* We can't delete the last existing company in singleplayer mode. */
942 if (!_networking
&& Company::GetNumItems() == 1) return CMD_ERROR
;
944 Company
*c
= Company::GetIfValid(company_id
);
945 if (c
== nullptr) return CMD_ERROR
;
947 if (!(flags
& DC_EXEC
)) return CommandCost();
949 CompanyNewsInformation
*cni
= new CompanyNewsInformation(c
);
951 /* Show the bankrupt news */
952 SetDParam(0, STR_NEWS_COMPANY_BANKRUPT_TITLE
);
953 SetDParam(1, STR_NEWS_COMPANY_BANKRUPT_DESCRIPTION
);
954 SetDParamStr(2, cni
->company_name
);
955 AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT
, cni
);
957 /* Remove the company */
958 ChangeOwnershipOfCompanyItems(c
->index
, INVALID_OWNER
);
959 if (c
->is_ai
) AI::Stop(c
->index
);
961 CompanyID c_index
= c
->index
;
963 AI::BroadcastNewEvent(new ScriptEventCompanyBankrupt(c_index
));
964 Game::NewEvent(new ScriptEventCompanyBankrupt(c_index
));
965 CompanyAdminRemove(c_index
, (CompanyRemoveReason
)reason
);
967 if (StoryPage::GetNumItems() == 0 || Goal::GetNumItems() == 0) InvalidateWindowData(WC_MAIN_TOOLBAR
, 0);
968 InvalidateWindowData(WC_CLIENT_LIST
, 0);
973 default: return CMD_ERROR
;
976 InvalidateWindowClassesData(WC_GAME_OPTIONS
);
977 InvalidateWindowClassesData(WC_SCRIPT_SETTINGS
);
978 InvalidateWindowClassesData(WC_SCRIPT_LIST
);
980 return CommandCost();
983 static bool ExecuteAllowListCtrlAction(CompanyAllowListCtrlAction action
, Company
*c
, const std::string
&public_key
)
987 return c
->allow_list
.Add(public_key
);
990 return c
->allow_list
.Remove(public_key
);
998 * Add or remove the given public key to the allow list of this company.
999 * @param flags Operation to perform.
1000 * @param action The action to perform.
1001 * @param public_key The public key of the client to add or remove.
1002 * @return The cost of this operation or an error.
1004 CommandCost
CmdCompanyAllowListCtrl(DoCommandFlag flags
, CompanyAllowListCtrlAction action
, const std::string
&public_key
)
1006 Company
*c
= Company::GetIfValid(_current_company
);
1007 if (c
== nullptr) return CMD_ERROR
;
1009 /* The public key length includes the '\0'. */
1010 if (public_key
.size() != NETWORK_PUBLIC_KEY_LENGTH
- 1) return CMD_ERROR
;
1021 if (flags
& DC_EXEC
) {
1022 if (ExecuteAllowListCtrlAction(action
, c
, public_key
)) {
1023 InvalidateWindowData(WC_CLIENT_LIST
, 0);
1024 SetWindowDirty(WC_COMPANY
, _current_company
);
1028 return CommandCost();
1032 * Change the company manager's face.
1033 * @param flags operation to perform
1034 * @param cmf face bitmasked
1035 * @return the cost of this operation or an error
1037 CommandCost
CmdSetCompanyManagerFace(DoCommandFlag flags
, CompanyManagerFace cmf
)
1039 if (!IsValidCompanyManagerFace(cmf
)) return CMD_ERROR
;
1041 if (flags
& DC_EXEC
) {
1042 Company::Get(_current_company
)->face
= cmf
;
1043 MarkWholeScreenDirty();
1045 return CommandCost();
1049 * Update liveries for a company. This is called when the LS_DEFAULT scheme is changed, to update schemes with colours
1051 * @param c Company to update.
1053 void UpdateCompanyLiveries(Company
*c
)
1055 for (int i
= 1; i
< LS_END
; i
++) {
1056 if (!HasBit(c
->livery
[i
].in_use
, 0)) c
->livery
[i
].colour1
= c
->livery
[LS_DEFAULT
].colour1
;
1057 if (!HasBit(c
->livery
[i
].in_use
, 1)) c
->livery
[i
].colour2
= c
->livery
[LS_DEFAULT
].colour2
;
1059 UpdateCompanyGroupLiveries(c
);
1063 * Change the company's company-colour
1064 * @param flags operation to perform
1065 * @param scheme scheme to set
1066 * @param primary set first/second colour
1067 * @param colour new colour for vehicles, property, etc.
1068 * @return the cost of this operation or an error
1070 CommandCost
CmdSetCompanyColour(DoCommandFlag flags
, LiveryScheme scheme
, bool primary
, Colours colour
)
1072 if (scheme
>= LS_END
|| (colour
>= COLOUR_END
&& colour
!= INVALID_COLOUR
)) return CMD_ERROR
;
1074 /* Default scheme can't be reset to invalid. */
1075 if (scheme
== LS_DEFAULT
&& colour
== INVALID_COLOUR
) return CMD_ERROR
;
1077 Company
*c
= Company::Get(_current_company
);
1079 /* Ensure no two companies have the same primary colour */
1080 if (scheme
== LS_DEFAULT
&& primary
) {
1081 for (const Company
*cc
: Company::Iterate()) {
1082 if (cc
!= c
&& cc
->colour
== colour
) return CMD_ERROR
;
1086 if (flags
& DC_EXEC
) {
1088 if (scheme
!= LS_DEFAULT
) AssignBit(c
->livery
[scheme
].in_use
, 0, colour
!= INVALID_COLOUR
);
1089 if (colour
== INVALID_COLOUR
) colour
= c
->livery
[LS_DEFAULT
].colour1
;
1090 c
->livery
[scheme
].colour1
= colour
;
1092 /* If setting the first colour of the default scheme, adjust the
1093 * original and cached company colours too. */
1094 if (scheme
== LS_DEFAULT
) {
1095 UpdateCompanyLiveries(c
);
1096 _company_colours
[_current_company
] = colour
;
1098 CompanyAdminUpdate(c
);
1101 if (scheme
!= LS_DEFAULT
) AssignBit(c
->livery
[scheme
].in_use
, 1, colour
!= INVALID_COLOUR
);
1102 if (colour
== INVALID_COLOUR
) colour
= c
->livery
[LS_DEFAULT
].colour2
;
1103 c
->livery
[scheme
].colour2
= colour
;
1105 if (scheme
== LS_DEFAULT
) {
1106 UpdateCompanyLiveries(c
);
1110 if (c
->livery
[scheme
].in_use
!= 0) {
1111 /* If enabling a scheme, set the default scheme to be in use too */
1112 c
->livery
[LS_DEFAULT
].in_use
= 1;
1114 /* Else loop through all schemes to see if any are left enabled.
1115 * If not, disable the default scheme too. */
1116 c
->livery
[LS_DEFAULT
].in_use
= 0;
1117 for (scheme
= LS_DEFAULT
; scheme
< LS_END
; scheme
++) {
1118 if (c
->livery
[scheme
].in_use
!= 0) {
1119 c
->livery
[LS_DEFAULT
].in_use
= 1;
1125 ResetVehicleColourMap();
1126 MarkWholeScreenDirty();
1128 /* All graph related to companies use the company colour. */
1129 InvalidateWindowData(WC_INCOME_GRAPH
, 0);
1130 InvalidateWindowData(WC_OPERATING_PROFIT
, 0);
1131 InvalidateWindowData(WC_DELIVERED_CARGO
, 0);
1132 InvalidateWindowData(WC_PERFORMANCE_HISTORY
, 0);
1133 InvalidateWindowData(WC_COMPANY_VALUE
, 0);
1134 InvalidateWindowData(WC_LINKGRAPH_LEGEND
, 0);
1135 /* The smallmap owner view also stores the company colours. */
1137 InvalidateWindowData(WC_SMALLMAP
, 0, 1);
1139 /* Company colour data is indirectly cached. */
1140 for (Vehicle
*v
: Vehicle::Iterate()) {
1141 if (v
->owner
== _current_company
) v
->InvalidateNewGRFCache();
1144 UpdateObjectColours(c
);
1146 return CommandCost();
1150 * Is the given name in use as name of a company?
1151 * @param name Name to search.
1152 * @return \c true if the name us unique (that is, not in use), else \c false.
1154 static bool IsUniqueCompanyName(const std::string
&name
)
1156 for (const Company
*c
: Company::Iterate()) {
1157 if (!c
->name
.empty() && c
->name
== name
) return false;
1164 * Change the name of the company.
1165 * @param flags operation to perform
1166 * @param text the new name or an empty string when resetting to the default
1167 * @return the cost of this operation or an error
1169 CommandCost
CmdRenameCompany(DoCommandFlag flags
, const std::string
&text
)
1171 bool reset
= text
.empty();
1174 if (Utf8StringLength(text
) >= MAX_LENGTH_COMPANY_NAME_CHARS
) return CMD_ERROR
;
1175 if (!IsUniqueCompanyName(text
)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE
);
1178 if (flags
& DC_EXEC
) {
1179 Company
*c
= Company::Get(_current_company
);
1185 MarkWholeScreenDirty();
1186 CompanyAdminUpdate(c
);
1189 return CommandCost();
1193 * Is the given name in use as president name of a company?
1194 * @param name Name to search.
1195 * @return \c true if the name us unique (that is, not in use), else \c false.
1197 static bool IsUniquePresidentName(const std::string
&name
)
1199 for (const Company
*c
: Company::Iterate()) {
1200 if (!c
->president_name
.empty() && c
->president_name
== name
) return false;
1207 * Change the name of the president.
1208 * @param flags operation to perform
1209 * @param text the new name or an empty string when resetting to the default
1210 * @return the cost of this operation or an error
1212 CommandCost
CmdRenamePresident(DoCommandFlag flags
, const std::string
&text
)
1214 bool reset
= text
.empty();
1217 if (Utf8StringLength(text
) >= MAX_LENGTH_PRESIDENT_NAME_CHARS
) return CMD_ERROR
;
1218 if (!IsUniquePresidentName(text
)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE
);
1221 if (flags
& DC_EXEC
) {
1222 Company
*c
= Company::Get(_current_company
);
1225 c
->president_name
.clear();
1227 c
->president_name
= text
;
1229 if (c
->name_1
== STR_SV_UNNAMED
&& c
->name
.empty()) {
1230 Command
<CMD_RENAME_COMPANY
>::Do(DC_EXEC
, text
+ " Transport");
1234 InvalidateWindowClassesData(WC_COMPANY
, 1);
1235 MarkWholeScreenDirty();
1236 CompanyAdminUpdate(c
);
1239 return CommandCost();
1243 * Get the service interval for the given company and vehicle type.
1244 * @param c The company, or nullptr for client-default settings.
1245 * @param type The vehicle type to get the interval for.
1246 * @return The service interval.
1248 int CompanyServiceInterval(const Company
*c
, VehicleType type
)
1250 const VehicleDefaultSettings
*vds
= (c
== nullptr) ? &_settings_client
.company
.vehicle
: &c
->settings
.vehicle
;
1252 default: NOT_REACHED();
1253 case VEH_TRAIN
: return vds
->servint_trains
;
1254 case VEH_ROAD
: return vds
->servint_roadveh
;
1255 case VEH_AIRCRAFT
: return vds
->servint_aircraft
;
1256 case VEH_SHIP
: return vds
->servint_ships
;
1261 * Get total sum of all owned road bits.
1262 * @return Combined total road road bits.
1264 uint32_t CompanyInfrastructure::GetRoadTotal() const
1267 for (RoadType rt
= ROADTYPE_BEGIN
; rt
!= ROADTYPE_END
; rt
++) {
1268 if (RoadTypeIsRoad(rt
)) total
+= this->road
[rt
];
1274 * Get total sum of all owned tram bits.
1275 * @return Combined total of tram road bits.
1277 uint32_t CompanyInfrastructure::GetTramTotal() const
1280 for (RoadType rt
= ROADTYPE_BEGIN
; rt
!= ROADTYPE_END
; rt
++) {
1281 if (RoadTypeIsTram(rt
)) total
+= this->road
[rt
];
1287 * Transfer funds (money) from one company to another.
1288 * To prevent abuse in multiplayer games you can only send money to other
1289 * companies if you have paid off your loan (either explicitly, or implicitly
1290 * given the fact that you have more money than loan).
1291 * @param flags operation to perform
1292 * @param money the amount of money to transfer; max 20.000.000
1293 * @param dest_company the company to transfer the money to
1294 * @return the cost of this operation or an error
1296 CommandCost
CmdGiveMoney(DoCommandFlag flags
, Money money
, CompanyID dest_company
)
1298 if (!_settings_game
.economy
.give_money
) return CMD_ERROR
;
1300 const Company
*c
= Company::Get(_current_company
);
1301 CommandCost
amount(EXPENSES_OTHER
, std::min
<Money
>(money
, 20000000LL));
1303 /* You can only transfer funds that is in excess of your loan */
1304 if (c
->money
- c
->current_loan
< amount
.GetCost() || amount
.GetCost() < 0) return_cmd_error(STR_ERROR_INSUFFICIENT_FUNDS
);
1305 if (!Company::IsValidID(dest_company
)) return CMD_ERROR
;
1307 if (flags
& DC_EXEC
) {
1308 /* Add money to company */
1309 Backup
<CompanyID
> cur_company(_current_company
, dest_company
);
1310 SubtractMoneyFromCompany(CommandCost(EXPENSES_OTHER
, -amount
.GetCost()));
1311 cur_company
.Restore();
1314 SetDParam(0, dest_company
);
1315 std::string dest_company_name
= GetString(STR_COMPANY_NAME
);
1317 SetDParam(0, _current_company
);
1318 std::string from_company_name
= GetString(STR_COMPANY_NAME
);
1320 NetworkTextMessage(NETWORK_ACTION_GIVE_MONEY
, GetDrawStringCompanyColour(_current_company
), false, from_company_name
, dest_company_name
, amount
.GetCost());
1324 /* Subtract money from local-company */
1329 * Get the index of the first available company. It attempts,
1330 * from first to last, and as soon as the attempt succeeds,
1331 * to get the index of the company:
1332 * 1st - get the first existing human company.
1333 * 2nd - get the first non-existing company.
1334 * 3rd - get COMPANY_FIRST.
1335 * @return the index of the first available company.
1337 CompanyID
GetFirstPlayableCompanyID()
1339 for (Company
*c
: Company::Iterate()) {
1340 if (Company::IsHumanID(c
->index
)) {
1345 if (Company::CanAllocateItem()) {
1346 for (CompanyID c
= COMPANY_FIRST
; c
< MAX_COMPANIES
; c
++) {
1347 if (!Company::IsValidID(c
)) {
1353 return COMPANY_FIRST
;