47#include "table/strings.h"
110 if (this->
max_loan == COMPANY_MAX_LOAN_DEFAULT)
return _economy.max_loan;
135 if (switching_company) {
149 ResetVehicleColourMap();
197 if (!vars[var].IsValid(cmf))
return false;
212 CompanyID cid = company->index;
269 if (cost.
GetCost() <= 0)
return true;
274 cost.
MakeError(STR_ERROR_NOT_ENOUGH_CASH_REQUIRES_CURRENCY);
290 if (cost.
GetCost() == 0)
return;
341static constexpr void UpdateLandscapingLimit(uint32_t &limit, uint64_t per_64k_frames, uint64_t burst)
343 limit =
static_cast<uint32_t
>(std::min<uint64_t>(limit + per_64k_frames, burst << 16));
350 UpdateLandscapingLimit(c->terraform_limit,
_settings_game.construction.terraform_per_64k_frames,
_settings_game.construction.terraform_frame_burst);
351 UpdateLandscapingLimit(c->clear_limit,
_settings_game.construction.clear_per_64k_frames,
_settings_game.construction.clear_frame_burst);
353 UpdateLandscapingLimit(c->build_object_limit,
_settings_game.construction.build_object_per_64k_frames,
_settings_game.construction.build_object_frame_burst);
369 return {STR_TOWN_NAME, t->index};
373 return {STR_COMPANY_SOMEONE, std::monostate{}};
376 return {STR_COMPANY_NAME, owner};
421 if (c->
name_1 != STR_SV_UNNAMED)
return;
436 if (cc->name_1 == str && cc->name_2 == strp)
goto bad_town_name;
451 auto cni = std::make_unique<CompanyNewsInformation>(STR_NEWS_COMPANY_LAUNCH_TITLE, c);
473static const EnumClassIndexContainer<std::array<uint8_t,
to_underlying(
Colours::End)>,
Colours>
_colour_sort{2, 2, 3, 2, 3, 2, 3, 2, 3, 2, 2, 2, 3, 1, 1, 1};
505 for (uint i = 0; i < 100; i++) {
507 std::swap(colours[
GB(r, 0, 4)], colours[
GB(r, 4, 4)]);
511 std::ranges::stable_sort(colours, {}, [](
auto &i) {
return _colour_sort[i]; });
516 std::erase(colours, c->colour);
519 auto it = std::ranges::find(colours, similar);
520 if (it != colours.end()) std::rotate(it, it + 1, colours.end());
525 return colours.at(0);
541 std::string name =
GetString(STR_PRESIDENT_NAME, c->index);
546 std::string other_name =
GetString(STR_PRESIDENT_NAME, cc->index);
547 if (name == other_name)
goto restart;
561 for (
LiveryScheme scheme = LS_BEGIN; scheme < LS_END; scheme++) {
562 c->livery[scheme].in_use.Reset();
563 c->livery[scheme].colour1 = c->
colour;
564 c->livery[scheme].colour2 = c->
colour;
568 if (g->owner == c->index) {
569 g->livery.in_use.Reset();
570 g->livery.colour1 = c->
colour;
571 g->livery.colour2 = c->
colour;
591 if (company == CompanyID::Invalid()) {
613 bool randomise_face =
true;
616 if (cmf.has_value()) {
617 randomise_face =
false;
618 c->
face = std::move(*cmf);
708 static const int TAKE_OVER_TIMEOUT = 3 * 30 *
Ticks::DAY_TICKS / (MAX_COMPANIES - 1);
725 int32_t best_performance = -1;
729 if (c2->bankrupt_asked.None() &&
731 best_performance < c2->old_economy[1].performance_history &&
733 best_performance = c2->old_economy[1].performance_history;
739 if (best_performance == -1) {
748 AI::NewEvent(best->index,
new ScriptEventCompanyAskMerger(c->index, c->bankrupt_value));
757 if (_game_mode == GM_EDITOR)
return;
772 if (cc->is_ai) num_ais++;
776 for (
auto i = 0; i <
_settings_game.difficulty.max_no_competitors; i++) {
778 if (num_ais++ >=
_settings_game.difficulty.max_no_competitors)
break;
784 timeout += ScriptObject::GetRandomizer(
OWNER_NONE).Next(timeout / 4) - timeout / 8;
801 std::rotate(std::rbegin(c->yearly_expenses), std::rbegin(c->yearly_expenses) + 1, std::rend(c->yearly_expenses));
802 c->yearly_expenses[0].fill(0);
827 if (other !=
nullptr) {
914 if (cmf.has_value()) {
915 Command<Commands::SetCompanyManagerFace>::SendNet(STR_NULL, c->index, cmf->style, cmf->bits);
929 if (company_id != CompanyID::Invalid() && company_id >= MAX_COMPANIES)
return CMD_ERROR;
959 auto cni = std::make_unique<CompanyNewsInformation>(STR_NEWS_COMPANY_BANKRUPT_TITLE, c);
961 AddCompanyNewsItem(std::move(headline), std::move(cni));
967 CompanyID c_index = c->index;
1034 if (public_key.size() != 0)
return CMD_ERROR;
1042 if (ExecuteAllowListCtrlAction(action, c, public_key)) {
1080 for (
int i = 1; i < LS_END; i++) {
1081 if (!c->livery[i].in_use.Test(
Livery::Flag::Primary)) c->livery[i].colour1 = c->livery[LS_DEFAULT].colour1;
1105 if (scheme == LS_DEFAULT && primary) {
1115 c->livery[scheme].colour1 = colour;
1119 if (scheme == LS_DEFAULT) {
1128 c->livery[scheme].colour2 = colour;
1130 if (scheme == LS_DEFAULT) {
1135 if (c->livery[scheme].in_use.Any({Livery::Flag::Primary, Livery::Flag::Secondary})) {
1142 for (scheme = LS_DEFAULT; scheme < LS_END; scheme++) {
1143 if (c->livery[scheme].in_use.Any({Livery::Flag::Primary, Livery::Flag::Secondary})) {
1150 ResetVehicleColourMap();
1182 if (!c->
name.empty() && c->
name == name)
return false;
1196 bool reset = text.empty();
1215 std::string new_name =
GetString(STR_COMPANY_NAME, c->index);
1217 Game::NewEvent(
new ScriptEventCompanyRenamed(c->index, new_name));
1245 bool reset = text.empty();
1260 if (c->
name_1 == STR_SV_UNNAMED && c->
name.empty()) {
1269 std::string new_name =
GetString(STR_PRESIDENT_NAME, c->index);
1271 Game::NewEvent(
new ScriptEventPresidentRenamed(c->index, new_name));
1287 default: NOT_REACHED();
1304 total += this->
road[rt];
1335 std::string dest_company_name =
GetString(STR_COMPANY_NAME, dest_company);
1364 for (CompanyID c = CompanyID::Begin(); c < MAX_COMPANIES; ++c) {
1371 return CompanyID::Begin();
1391 return static_cast<uint
>(std::size(
_faces));
1412 auto it = std::ranges::find(
_faces, label, &FaceSpec::label);
1413 if (it == std::end(
_faces))
return std::nullopt;
1415 return static_cast<uint
>(std::distance(std::begin(
_faces), it));
1426 if (spec ==
nullptr)
return {};
1427 return spec->GetFaceVars();
1439 assert(spec !=
nullptr);
1469 vars[var].SetBits(face, vars[var].GetBits(cmf));
1483 return fmt::format(
"{}:{}", cmf.
style_label, masked_face_bits);
1493 if (str.empty())
return std::nullopt;
1502 if (!bits.has_value() || consumer.
AnyBytesLeft())
return std::nullopt;
1506 if (!style.has_value())
return std::nullopt;
1513 if (!bits.has_value())
return std::nullopt;
Base functions for all AIs.
AIConfig stores the configuration settings of every AI.
The AIInstance tracks an AI.
Class for backupping variables and making sure they are restored later.
static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
static void BroadcastNewEvent(ScriptEvent *event, CompanyID skip_company=CompanyID::Invalid())
Broadcast a new event to all active AIs.
static bool CanStartNew()
Is it possible to start a new AI company?
static void StartNew(CompanyID company)
Start a new AI company.
static void Stop(CompanyID company)
Stop a company to be controlled by an AI.
static void NewEvent(CompanyID company, ScriptEvent *event)
Queue a new event for an AI.
constexpr bool All(const Timpl &other) const
Test if all of the values are set.
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
constexpr Timpl & Set()
Set all bits.
constexpr bool Any(const Timpl &other) const
Test if any of the given values are set.
Common return value for all commands.
ExpensesType GetExpensesType() const
The expense type of the cost.
void MakeError(StringID message)
Makes this CommandCost behave like an error command.
Money GetCost() const
The costs as made up to this moment.
void SetEncodedMessage(EncodedString &&message)
Set the encoded message string.
void SetErrorOwner(Owner owner)
Set the 'owner' (the originator) of this error message.
Container for an encoded string, created by GetEncodedString.
A sort-of mixin that implements 'at(pos)' and 'operator[](pos)' only for a specific enum class.
static void NewEvent(class ScriptEvent *event)
Queue a new event for the game script.
An interval timer will fire every interval, and will continue to fire until it is deleted.
bool Add(std::string_view key)
Add the given key to the authorized keys, when it is not already contained.
bool Remove(std::string_view key)
Remove the given key from the authorized keys, when it is exists.
Parse data from a string / buffer.
std::optional< T > TryReadIntegerBase(int base, bool clamp=false)
Try to read and parse an integer in number 'base', and then advance the reader.
std::string_view ReadUntilChar(char c, SeparatorUsage sep)
Read data until the first occurrence of 8-bit char 'c', and advance reader.
size_type FindChar(char c) const
Find first occurrence of 8-bit char 'c'.
@ SKIP_ONE_SEPARATOR
Read and discard one separator, do not include it in the result.
bool AnyBytesLeft() const noexcept
Check whether any bytes left to read.
static constexpr size_type npos
Special value for "end of data".
static constexpr TimerGameTick::Ticks DAY_TICKS
1 day is 74 ticks; TimerGameCalendar::date_fract used to be uint16_t and incremented by 885.
static constexpr TimerGameTick::Ticks TICKS_PER_SECOND
Estimation of how many ticks fit in a single second.
A timeout timer will fire once after the interval.
static Year year
Current year, starting at 0.
static Year year
Current year, starting at 0.
@ CompetitorTimeout
Considering starting a new competitor/AI.
A sort-of mixin that implements 'at(pos)' and 'operator[](pos)' only for a specific type.
Functions related to commands.
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
@ Execute
execute the given command
Definition of stuff that is very close to a company, like the company struct itself.
uint _cur_company_tick_index
used to generate a name for one company that doesn't have a name yet per tick
void ClearEnginesHiddenFlagOfCompany(CompanyID cid)
Clear the 'hidden' flag for all engines of a new company.
void UpdateObjectColours(const Company *c)
Updates the colour of the object whenever a company changes.
std::optional< CompanyManagerFace > ParseCompanyManagerFaceCode(std::string_view str)
Parse a face code into a company manager face.
static void GenerateCompanyName(Company *c)
Generate the name of a company from the last build coordinate.
static const IntervalTimer< TimerGameEconomy > _economy_companies_yearly({TimerGameEconomy::Trigger::Year, TimerGameEconomy::Priority::Company}, [](auto) { for(Company *c :Company::Iterate()) { std::rotate(std::rbegin(c->yearly_expenses), std::rbegin(c->yearly_expenses)+1, std::rend(c->yearly_expenses));c->yearly_expenses[0].fill(0);InvalidateWindowData(WC_FINANCES, c->index);} if(_settings_client.gui.show_finances &&_local_company !=COMPANY_SPECTATOR) { ShowCompanyFinances(_local_company);Company *c=Company::Get(_local_company);if(c->num_valid_stat_ent > 5 &&c->old_economy[0].performance_history< c->old_economy[4].performance_history) { if(_settings_client.sound.new_year) SndPlayFx(SND_01_BAD_YEAR);} else { if(_settings_client.sound.new_year) SndPlayFx(SND_00_GOOD_YEAR);} } })
A year has passed, update the economic data of all companies, and perhaps show the financial overview...
static bool IsValidCompanyManagerFace(CompanyManagerFace cmf)
Checks whether a company manager's face is a valid encoding.
const FaceSpec * GetCompanyManagerFaceSpec(uint style_index)
Get the definition of a company manager face style.
void OnTick_Companies()
Called every tick for updating some company info.
std::array< StringParameter, 2 > GetParamsForOwnedBy(Owner owner, TileIndex tile)
Get the right StringParameters for STR_ERROR_OWNED_BY.
FaceVars GetCompanyManagerFaceVars(uint style)
Get the face variables for a face style.
TimeoutTimer< TimerGameTick > _new_competitor_timeout({ TimerGameTick::Priority::CompetitorTimeout, 0 }, []() { if(_game_mode==GM_MENU||!AI::CanStartNew()) return;if(_networking &&Company::GetNumItems() >=_settings_client.network.max_companies) return;if(_settings_game.difficulty.competitors_interval==0) return;uint8_t n=0;for(const Company *c :Company::Iterate()) { if(c->is_ai) n++;} if(n >=_settings_game.difficulty.max_no_competitors) return;Command< Commands::CompanyControl >::Post(CompanyCtrlAction::NewAI, CompanyID::Invalid(), CompanyRemoveReason::None, INVALID_CLIENT_ID);})
Start a new competitor company if possible.
CommandCost CmdCompanyAllowListCtrl(DoCommandFlags flags, CompanyAllowListCtrlAction action, const std::string &public_key)
Add or remove the given public key to the allow list of this company.
void RandomiseCompanyManagerFace(CompanyManagerFace &cmf, Randomizer &randomizer)
Completely randomise a company manager face, including style.
void ResetFaces()
Reset company manager face styles to default.
Company * DoStartupNewCompany(bool is_ai, CompanyID company=CompanyID::Invalid())
Create a new company and sets all company variables default values.
void DrawCompanyIcon(CompanyID c, int x, int y)
Draw the icon of a company.
uint32_t MaskCompanyManagerFaceBits(const CompanyManagerFace &cmf, FaceVars vars)
Mask company manager face bits to ensure they are all within range.
static const std::initializer_list< Colours > _similar_colour[to_underlying(Colours::End)]
Similar colours, so we can try to prevent same coloured companies.
std::string _company_manager_face
for company manager face storage in openttd.cfg
static Colours GenerateCompanyColour()
Generate a company colour.
static void GeneratePresidentName(Company *c)
Generate a random president name of a company.
TypedIndexContainer< std::array< Colours, MAX_COMPANIES >, CompanyID > _company_colours
NOSAVE: can be determined from company structs.
void ResetCompanyLivery(Company *c)
Reset the livery schemes to the company's primary colour.
void UpdateCompanyLiveries(Company *c)
Update liveries for a company.
CommandCost CheckTileOwnership(TileIndex tile)
Check whether the current owner owns the stuff on the given tile.
CommandCost CmdSetCompanyColour(DoCommandFlags flags, LiveryScheme scheme, bool primary, Colours colour)
Change the company's company-colour.
CommandCost CmdCompanyCtrl(DoCommandFlags flags, CompanyCtrlAction cca, CompanyID company_id, CompanyRemoveReason reason, ClientID client_id)
Control the companies: add, delete, etc.
static std::vector< FaceSpec > _faces
All company manager face styles.
void InvalidateCompanyWindows(const Company *company)
Mark all finance windows owned by a company as needing a refresh.
int CompanyServiceInterval(const Company *c, VehicleType type)
Get the service interval for the given company and vehicle type.
PaletteID GetCompanyPalette(CompanyID company)
Get the palette for recolouring with a company colour.
void SetCompanyManagerFaceStyle(CompanyManagerFace &cmf, uint style)
Set a company face style.
bool CheckCompanyHasMoney(CommandCost &cost)
Verify whether the company can pay the bill.
static const EnumClassIndexContainer< std::array< uint8_t, to_underlying(Colours::End)>, Colours > _colour_sort
Sorting weights for the company colours.
static void SubtractMoneyFromCompany(Company *c, const CommandCost &cost)
Deduct costs of a command from the money of a company.
CompanyID GetFirstPlayableCompanyID()
Get the index of the first available company.
static CompanyMask _dirty_company_finances
Bitmask of company finances that should be marked dirty.
TextColour GetDrawStringCompanyColour(CompanyID company)
Get the colour for DrawString-subroutines which matches the colour of the company.
CommandCost CmdSetCompanyManagerFace(DoCommandFlags flags, uint style, uint32_t bits)
Change the company manager's face.
Money GetAvailableMoneyForCommand()
This functions returns the money which can be used to execute a command.
void CompanyAdminUpdate(const Company *company)
Called whenever company related information changes in order to notify admins.
std::optional< uint > FindCompanyManagerFaceLabel(std::string_view label)
Find a company manager face style by label.
CommandCost CheckOwnership(Owner owner, TileIndex tile)
Check whether the current owner owns something.
void CompanyAdminRemove(CompanyID company_id, CompanyRemoveReason reason)
Called whenever a company is removed in order to notify admins.
CommandCost CmdRenamePresident(DoCommandFlags flags, const std::string &text)
Change the name of the president.
CompanyPool _company_pool("Company")
Pool of companies.
uint GetNumCompanyManagerFaceStyles()
Get the number of company manager face styles.
std::string FormatCompanyManagerFaceCode(const CompanyManagerFace &cmf)
Get a face code representation of a company manager face.
Money GetAvailableMoney(CompanyID company)
Get the amount of money that a company has available, or INT64_MAX if there is no such valid company.
void UpdateLandscapingLimits()
Update the landscaping limits per company.
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
void InitializeCompanies()
Initialize the pool of companies.
void StartupCompanies()
Start of a new game.
bool CheckTakeoverVehicleLimit(CompanyID cbig, CompanyID csmall)
Can company cbig buy company csmall without exceeding vehicle limits?
static bool IsUniqueCompanyName(const std::string &name)
Is the given name in use as name of a company?
void SetLocalCompany(CompanyID new_company)
Sets the local company and updates the settings that are set on a per-company basis to reflect the co...
static bool IsUniquePresidentName(const std::string &name)
Is the given name in use as president name of a company?
CompanyID _current_company
Company currently doing an action.
CommandCost CmdGiveMoney(DoCommandFlags flags, Money money, CompanyID dest_company)
Transfer funds (money) from one company to another.
static void HandleBankruptcyTakeover(Company *c)
Handle the bankruptcy take over of a company.
CommandCost CmdRenameCompany(DoCommandFlags flags, const std::string &text)
Change the name of the company.
void SubtractMoneyFromCompanyFract(CompanyID company, const CommandCost &cst)
Subtract money from a company, including the money fraction.
static const IntervalTimer< TimerWindow > invalidate_company_windows_interval(std::chrono::milliseconds(1), [](auto) { for(CompanyID cid :_dirty_company_finances) { if(cid==_local_company) SetWindowWidgetDirty(WC_STATUS_BAR, 0, WID_S_RIGHT);Window *w=FindWindowById(WC_FINANCES, cid);if(w !=nullptr) { w->SetWidgetDirty(WID_CF_EXPS_PRICE3);w->SetWidgetDirty(WID_CF_OWN_VALUE);w->SetWidgetDirty(WID_CF_LOAN_VALUE);w->SetWidgetDirty(WID_CF_BALANCE_VALUE);w->SetWidgetDirty(WID_CF_MAXLOAN_VALUE);} SetWindowWidgetDirty(WC_COMPANY, cid, WID_C_DESC_COMPANY_VALUE);} _dirty_company_finances.Reset();})
Refresh all company finance windows previously marked dirty.
Command definitions related to companies.
This file contains all definitions for default company faces.
static FaceSpec _original_faces[]
Original face styles.
Functions related to companies.
bool IsInteractiveCompany(CompanyID company)
Is the user representing company?
void ChangeOwnershipOfCompanyItems(Owner old_owner, Owner new_owner)
Change the ownership of all the items of a company.
void ShowBuyCompanyDialog(CompanyID company, bool hostile_takeover)
Show the query to buy another company.
bool IsLocalCompany()
Is the current company the local company?
void ShowCompanyFinances(CompanyID company)
Open the finances window of a company.
GUI Functions related to companies.
void CloseCompanyWindows(CompanyID company)
Close all windows of a company.
Functionality related to the company manager's face.
void RandomiseCompanyManagerFaceBits(CompanyManagerFace &cmf, FaceVars vars, Randomizer &randomizer)
Make a random new face without changing the face style.
uint64_t GetActiveFaceVars(const CompanyManagerFace &cmf, FaceVars vars)
Get a bitmask of currently active face variables.
void ScaleAllCompanyManagerFaceBits(CompanyManagerFace &cmf, FaceVars vars)
Scales all company manager's face bits to the correct scope.
static const uint MAX_LENGTH_PRESIDENT_NAME_CHARS
The maximum length of a president name in characters including '\0'.
static const uint MAX_LENGTH_COMPANY_NAME_CHARS
The maximum length of a company name in characters including '\0'.
CompanyCtrlAction
The action to do with Commands::CompanyControl.
@ New
Create a new company.
@ NewAI
Create a new AI company.
@ Delete
Delete a company.
static constexpr CompanyID COMPANY_SPECTATOR
The client is spectating.
static constexpr Owner OWNER_END
Last + 1 owner.
CompanyAllowListCtrlAction
The action to do with Commands::CompanyAllowListControl.
@ RemoveKey
Remove a public key.
@ AddKey
Create a public key.
@ AllowListed
Allow only listed keys to join the company.
@ AllowAny
Allow joining the company without a key.
static constexpr Owner OWNER_TOWN
A town owns the tile, or a town is expanding.
static constexpr Owner OWNER_NONE
The tile has no ownership.
static constexpr Owner INVALID_OWNER
An invalid owner.
CompanyRemoveReason
The reason why the company was removed.
@ None
Dummy reason for actions that don't need one.
static const uint NETWORK_PUBLIC_KEY_LENGTH
The maximum length of the hexadecimal encoded public keys, in bytes including '\0'.
@ EXPENSES_ROADVEH_RUN
Running costs road vehicles.
@ EXPENSES_TRAIN_RUN
Running costs trains.
@ EXPENSES_AIRCRAFT_REVENUE
Revenue from aircraft.
@ EXPENSES_AIRCRAFT_RUN
Running costs aircraft.
@ EXPENSES_ROADVEH_REVENUE
Revenue from road vehicles.
@ EXPENSES_PROPERTY
Property costs.
@ EXPENSES_OTHER
Other expenses.
@ EXPENSES_SHIP_REVENUE
Revenue from ships.
@ EXPENSES_LOAN_INTEREST
Interest payments over the loan.
@ EXPENSES_TRAIN_REVENUE
Revenue from trains.
@ EXPENSES_SHIP_RUN
Running costs ships.
@ INVALID_EXPENSES
Invalid expense type.
static const int LOAN_INTERVAL
The "steps" in loan size, in British Pounds!
static const int64_t INITIAL_LOAN
The size of loan for a new company, in British Pounds!
constexpr std::underlying_type_t< enum_type > to_underlying(enum_type e)
Implementation of std::to_underlying (from C++23).
Base functions for all Games.
void DrawSprite(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub, ZoomLevel zoom)
Draw a sprite, not in a viewport.
uint32_t PaletteID
The number of the palette.
Colours
One of 16 base colours used for companies and windows/widgets.
@ End
End-of-array marker.
TextColour
Colour of the strings, see _string_colourmap in table/string_colours.h or docs/ottd-colourtext-palett...
void UpdateCompanyGroupLiveries(const Company *c)
Update group liveries for a company.
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
LiveryScheme
List of different livery schemes.
constexpr bool IsInsideMM(const size_t x, const size_t min, const size_t max) noexcept
Checks if a value is in an interval.
bool _networking
are we in networking mode?
bool _network_server
network-server is active
void NetworkTextMessage(NetworkAction action, TextColour colour, bool self_send, std::string_view name, std::string_view str, StringParameter &&data)
Writes a text-message to the console and the chat box.
ClientID _network_own_client_id
Our client identifier.
Basic functions/variables used all over the place.
void NetworkAdminCompanyUpdate(const Company *company)
Notify the admin network of company updates.
void NetworkAdminCompanyNew(const Company *company)
Notify the admin network of a new company.
void NetworkAdminCompanyRemove(CompanyID company_id, AdminCompanyRemoveReason bcrr)
Notify the admin network of a company to be removed (including the reason why).
Server part of the admin network protocol.
Base core network types and some helper functions to access them.
Network functions used by other parts of OpenTTD.
void NetworkServerNewCompany(const Company *company, NetworkClientInfo *ci)
Perform all the server specific administration of a new company.
void NetworkUpdateClientInfo(ClientID client_id)
Send updated client info of a particular client.
@ GiveMoney
A company was given money.
@ Team
Send message/notice to everyone playing the same company (Team).
ClientID
'Unique' identifier to be given to clients
@ INVALID_CLIENT_ID
Client is not part of anything.
Functions related to news.
void AddNewsItem(EncodedString &&headline, NewsType type, NewsStyle style, NewsFlags flags, NewsReference ref1={}, NewsReference ref2={}, std::unique_ptr< NewsAllocatedData > &&data=nullptr, AdviceType advice_type=AdviceType::Invalid)
Add a new newsitem to be shown.
@ CompanyInfo
Company info (new companies, bankruptcy messages).
@ Company
Company news item. (Newspaper with face).
PixelColour GetColourGradient(Colours colour, ColourShade shade)
Get colour gradient palette index.
Some methods of Pool are placed here in order to reduce compilation time and binary size.
#define INSTANTIATE_POOL_METHODS(name)
Force instantiation of pool methods so we don't get linker errors.
RailTypes GetCompanyRailTypes(CompanyID company, bool introduces)
Get the rail types the given company can build.
void SetDefaultRailGui()
Set the initial (default) railtype to use.
Randomizer _random
Random used in the game state calculations.
RoadTypes GetCompanyRoadTypes(CompanyID company, bool introduces)
Get the road types the given company can build.
RoadTypes GetMaskForRoadTramType(RoadTramType rtt)
Get the mask for road types of the given RoadTramType.
RoadType
The different roadtypes we support.
RoadTramType
The different types of road type.
A number of safeguards to prevent using unsafe methods.
void SyncCompanySettings()
Sync all company settings in a multiplayer game.
void SetDefaultCompanySettings(CompanyID cid)
Set the company settings for a new company to their default values.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
ClientSettings _settings_client
The current settings for this game.
Functions related to setting/changing the settings.
void BuildOwnerLegend()
Completes the array for the owned property legend.
Functions related to sound.
@ SND_01_BAD_YEAR
40 == 0x28 New year: performance declined
@ SND_00_GOOD_YEAR
39 == 0x27 New year: performance improved
static PaletteID GetColourPalette(Colours colour)
Get recolour palette for a colour.
Definition of base types and functions in a cross-platform compatible way.
size_t Utf8StringLength(std::string_view str)
Get the length of an UTF-8 encoded string in number of characters and thus not the number of bytes th...
static std::optional< T > ParseInteger(std::string_view arg, int base=10, bool clamp=false)
Change a string into its number representation.
EncodedString GetEncodedStringWithArgs(StringID str, std::span< const StringParameter > params)
Encode a string with its parameters into an encoded string.
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
std::string GetString(StringID string)
Resolve the given StringID into a std::string with formatting but no parameters.
Functions related to OTTD's strings.
uint32_t StringID
Numeric value that represents a string, independent of the selected language.
static constexpr StringID SPECSTR_COMPANY_NAME_START
Special strings for company names on the form "TownName transport".
static constexpr StringID SPECSTR_ANDCO_NAME
Special string for Surname & Co company names.
static constexpr StringID SPECSTR_PRESIDENT_NAME
Special string for the president's name.
static constexpr StringID SPECSTR_TOWNNAME_START
Special strings for town names.
Money income
The amount of income.
Money expenses
The amount of expenses.
uint32_t GetRoadTramTotal(RoadTramType rtt) const
Get total sum of all owned road bits.
std::array< uint32_t, ROADTYPE_END > road
Count of company owned track bits for each road type.
uint32_t bits
Company manager face bits, meaning is dependent on style.
uint style
Company manager face style.
std::string style_label
Face style label.
uint32_t clear_limit
Amount of tiles we can (still) clear (times 65536).
CompanyMask bankrupt_asked
which companies were asked about buying it?
std::string president_name
Name of the president if the user changed it.
int16_t bankrupt_timeout
If bigger than 0, amount of time to wait for an answer on an offer to buy this company.
CompanySettings settings
settings specific for each company
NetworkAuthorizedKeys allow_list
Public keys of clients that are allowed to join this company.
bool allow_any
Set if anyone is allowed to join this company.
uint32_t build_object_limit
Amount of tiles we can (still) build objects on (times 65536). Also applies to buying land and placin...
uint32_t name_2
Parameter of name_1.
uint8_t money_fraction
Fraction of money of the company, too small to represent in money.
bool is_ai
If true, the company is (also) controlled by the computer (a NoAI program).
uint32_t president_name_2
Parameter of president_name_1.
StringID name_1
Name of the company if the user did not change it.
Money current_loan
Amount of money borrowed from the bank.
TimerGameCalendar::Year inaugurated_year_calendar
Calendar year of starting the company. Used to display proper Inauguration year while in wallclock mo...
uint32_t terraform_limit
Amount of tileheights we can (still) terraform (times 65536).
TimerGameEconomy::Year inaugurated_year
Economy year of starting the company.
CompanyEconomyEntry cur_economy
Economic data of the company of this quarter.
Colours colour
Company colour.
uint32_t tree_limit
Amount of trees we can (still) plant (times 65536).
std::array< CompanyEconomyEntry, MAX_HISTORY_QUARTERS > old_economy
Economic data of the company of the last MAX_HISTORY_QUARTERS quarters.
CompanyManagerFace face
Face description of the president.
Money max_loan
Max allowed amount of the loan or COMPANY_MAX_LOAN_DEFAULT.
std::array< Expenses, 3 > yearly_expenses
Expenses of the company for the last three years.
TileIndex last_build_coordinate
Coordinate of the last build thing by this company.
StringID president_name_1
Name of the president if the user did not change it.
std::string name
Name of the company if the user changed it.
Money money
Money owned by the company.
uint8_t num_valid_stat_ent
Number of valid statistical entries in old_economy.
VehicleDefaultSettings vehicle
default settings for vehicles
Money GetMaxLoan() const
Calculate the max allowed loan for this company.
static bool IsHumanID(auto index)
Is this company a company not controlled by a NoAI program?
std::array< GroupStatistics, VEH_COMPANY_END > group_all
NOSAVE: Statistics for the ALL_GROUP group.
RoadTypes avail_roadtypes
Road types available to this company.
~Company()
Close the associated company windows.
RailTypes avail_railtypes
Rail types available to this company.
static void PostDestructor(size_t index)
Invalidating some stuff after removing item from the pool.
Company(CompanyID index, StringID name_1={}, bool is_ai=false)
Constructor.
@ Primary
Primary colour is set.
@ Secondary
Secondary colour is set.
Container for all information known about a client.
static NetworkClientInfo * GetByClientID(ClientID client_id)
Return the CI given it's client-identifier.
CompanyID client_playas
As which company is this client playing (CompanyID).
ClientID client_id
Client identifier (same as ClientState->client_id).
PoolItem(CompanyID index)
static Pool::IterateWrapper< Company > Iterate(size_t from=0)
static T * CreateAtIndex(CompanyID index, Targs &&... args)
static Company * Get(auto index)
static size_t GetNumItems()
static bool CanAllocateItem(size_t n=1)
static bool IsValidID(auto index)
static T * Create(Targs &&... args)
static bool CleaningPool()
static Company * GetIfValid(auto index)
Structure to encapsulate the pseudo random number generators.
uint32_t Next()
Generate the next pseudo random number.
Iterable ensemble of each set bit in a value.
std::string name
Custom town name. If empty, the town was not renamed and uses the generated name.
uint32_t townnameparts
Custom town name. If empty, the town was not renamed and uses the generated name.
uint16_t townnametype
Custom town name. If empty, the town was not renamed and uses the generated name.
Default settings for vehicles.
uint16_t servint_aircraft
service interval for aircraft
uint16_t servint_roadveh
service interval for road vehicles
uint16_t servint_ships
service interval for ships
uint16_t servint_trains
service interval for trains
Data structure for an opened window.
void SetWidgetDirty(WidgetID widget_index) const
Invalidate a widget, i.e.
AdminCompanyRemoveReason
Reasons for removing a company - communicated to admins.
Owner GetTileOwner(Tile tile)
Returns the owner of a tile.
StrongType::Typedef< uint32_t, struct TileIndexTag, StrongType::Compare, StrongType::Integer, StrongType::Compatible< int32_t >, StrongType::Compatible< int64_t > > TileIndex
The index/ID of a Tile.
Definition of Interval and OneShot timers.
Definition of the game-economy-timer.
Definition of the tick-based game-timer.
Definition of the Window system.
Town * ClosestTownFromTile(TileIndex tile, uint threshold)
Return the town closest (in distance or ownership) to a given tile, within a given threshold.
Base class for all vehicles.
Functions related to vehicles.
VehicleType
Available vehicle types.
@ VEH_ROAD
Road vehicle type.
@ VEH_AIRCRAFT
Aircraft vehicle type.
@ VEH_SHIP
Ship vehicle type.
@ VEH_TRAIN
Train vehicle type.
void CloseConstructionWindows()
Close all windows that are used for construction of vehicle etc.
void CloseWindowById(WindowClass cls, WindowNumber number, bool force, int data)
Close a window by its class and window number (if it is open).
void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
Mark window data of the window of a given class and specific window number as invalid (in need of re-...
Window * FindWindowById(WindowClass cls, WindowNumber number)
Find a window by its class and window number.
void SetWindowWidgetDirty(WindowClass cls, WindowNumber number, WidgetID widget_index)
Mark a particular widget in a particular window as dirty (in need of repainting).
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting).
void InvalidateWindowClassesData(WindowClass cls, int data, bool gui_scope)
Mark window data of all windows of a given class as invalid (in need of re-computing) Note that by de...
Window functions not directly related to making/drawing windows.
@ WN_NETWORK_STATUS_WINDOW_JOIN
Network join status.
@ WC_PERFORMANCE_HISTORY
Performance history graph; Window numbers:
@ WC_COMPANY_LEAGUE
Company league window; Window numbers:
@ WC_SIGN_LIST
Sign list; Window numbers:
@ WC_PERFORMANCE_DETAIL
Performance detail window; Window numbers:
@ WC_COMPANY_COLOUR
Company colour selection; Window numbers:
@ WC_GRAPH_LEGEND
Legend for graphs; Window numbers:
@ WC_LINKGRAPH_LEGEND
Linkgraph legend; Window numbers:
@ WC_STATUS_BAR
Statusbar (at the bottom of your screen); Window numbers:
@ WC_SEND_NETWORK_MSG
Chatbox; Window numbers:
@ WC_ERRMSG
Error message; Window numbers:
@ WC_SCRIPT_SETTINGS
Script settings; Window numbers:
@ WC_SCRIPT_LIST
Scripts list; Window numbers:
@ WC_GOALS_LIST
Goals list; Window numbers:
@ WC_OPERATING_PROFIT
Operating profit graph; Window numbers:
@ WC_CLIENT_LIST
Client list; Window numbers:
@ WC_GAME_OPTIONS
Game options window; Window numbers:
@ WC_FINANCES
Finances of a company; Window numbers:
@ WC_INCOME_GRAPH
Income graph; Window numbers:
@ WC_SMALLMAP
Small map; Window numbers:
@ WC_DELIVERED_CARGO
Delivered cargo graph; Window numbers:
@ WC_COMPANY_VALUE
Company value graph; Window numbers:
@ WC_MAIN_TOOLBAR
Main toolbar (the long bar at the top); Window numbers:
@ WC_COMPANY
Company view; Window numbers:
@ WC_NETWORK_STATUS_WINDOW
Network status window; Window numbers:
@ WC_VEHICLE_VIEW
Vehicle view; Window numbers: