# company_cmd.cpp

Go to the documentation of this file.

    00001 /* $Id$ */
    00002
    00003 /*
    00004  * This file is part of OpenTTD.
    00005  * 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.
    00006  * 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.
    00007  * 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/>.
    00008  */
    00009
    00012 #include "stdafx.h"
    00013 #include "company_base.h"
    00014 #include "company_func.h"
    00015 #include "company_gui.h"
    00016 #include "town.h"
    00017 #include "news_func.h"
    00018 #include "cmd_helper.h"
    00019 #include "command_func.h"
    00020 #include "network/network.h"
    00021 #include "network/network_func.h"
    00022 #include "network/network_base.h"
    00023 #include "network/network_admin.h"
    00024 #include "ai/ai.hpp"
    00025 #include "company_manager_face.h"
    00026 #include "window_func.h"
    00027 #include "strings_func.h"
    00028 #include "date_func.h"
    00029 #include "sound_func.h"
    00030 #include "rail.h"
    00031 #include "core/pool_func.hpp"
    00032 #include "settings_func.h"
    00033 #include "vehicle_base.h"
    00034 #include "vehicle_func.h"
    00035 #include "smallmap_gui.h"
    00036 #include "game/game.hpp"
    00037
    00038 #include "table/strings.h"
    00039
    00040 CompanyByte _local_company;
    00041 CompanyByte _current_company;
    00042 Colours _company_colours[MAX_COMPANIES];
    00043 CompanyManagerFace _company_manager_face;
    00044 uint _next_competitor_start;
    00045 uint _cur_company_tick_index;
    00046
    00047 CompanyPool _company_pool("Company");
    00048 INSTANTIATE_POOL_METHODS(Company)
    00049
    00050
    00055 Company::Company(uint16 name_1, bool is_ai)
    00056 {
    00057   this->name_1 = name_1;
    00058   this->location_of_HQ = INVALID_TILE;
    00059   this->is_ai = is_ai;
    00060   this->terraform_limit = _settings_game.construction.terraform_frame_burst << 16;
    00061   this->clear_limit     = _settings_game.construction.clear_frame_burst << 16;
    00062   this->tree_limit      = _settings_game.construction.tree_frame_burst << 16;
    00063
    00064   for (uint j = 0; j < 4; j++) this->share_owners[j] = COMPANY_SPECTATOR;
    00065   InvalidateWindowData(WC_PERFORMANCE_DETAIL, 0, INVALID_COMPANY);
    00066 }
    00067
    00069 Company::~Company()
    00070 {
    00071   if (CleaningPool()) return;
    00072
    00073   DeleteCompanyWindows(this->index);
    00074 }
    00075
    00080 void Company::PostDestructor(size_t index)
    00081 {
    00082   InvalidateWindowData(WC_GRAPH_LEGEND, 0, (int)index);
    00083   InvalidateWindowData(WC_PERFORMANCE_DETAIL, 0, (int)index);
    00084   InvalidateWindowData(WC_COMPANY_LEAGUE, 0, 0);
    00085   InvalidateWindowData(WC_LINKGRAPH_LEGEND, 0);
    00086   /* If the currently shown error message has this company in it, then close it. */
    00087   InvalidateWindowData(WC_ERRMSG, 0);
    00088 }
    00089
    00096 void SetLocalCompany(CompanyID new_company)
    00097 {
    00098   /* company could also be COMPANY_SPECTATOR or OWNER_NONE */
    00099   assert(Company::IsValidID(new_company) || new_company == COMPANY_SPECTATOR || new_company == OWNER_NONE);
    00100
    00101 #ifdef ENABLE_NETWORK
    00102   /* Delete the chat window, if you were team chatting. */
    00103   InvalidateWindowData(WC_SEND_NETWORK_MSG, DESTTYPE_TEAM, _local_company);
    00104 #endif
    00105
    00106   assert(IsLocalCompany());
    00107
    00108   _current_company = _local_company = new_company;
    00109
    00110   /* Delete any construction windows... */
    00111   DeleteConstructionWindows();
    00112
    00113   /* ... and redraw the whole screen. */
    00114   MarkWholeScreenDirty();
    00115   InvalidateWindowClassesData(WC_SIGN_LIST, -1);
    00116 }
    00117
    00123 TextColour GetDrawStringCompanyColour(CompanyID company)
    00124 {
    00125   if (!Company::IsValidID(company)) return (TextColour)_colour_gradient[COLOUR_WHITE][4] | TC_IS_PALETTE_COLOUR;
    00126   return (TextColour)_colour_gradient[_company_colours[company]][4] | TC_IS_PALETTE_COLOUR;
    00127 }
    00128
    00135 void DrawCompanyIcon(CompanyID c, int x, int y)
    00136 {
    00137   DrawSprite(SPR_COMPANY_ICON, COMPANY_SPRITE_COLOUR(c), x, y);
    00138 }
    00139
    00146 static bool IsValidCompanyManagerFace(CompanyManagerFace cmf)
    00147 {
    00148   if (!AreCompanyManagerFaceBitsValid(cmf, CMFV_GEN_ETHN, GE_WM)) return false;
    00149
    00150   GenderEthnicity ge   = (GenderEthnicity)GetCompanyManagerFaceBits(cmf, CMFV_GEN_ETHN, GE_WM);
    00151   bool has_moustache   = !HasBit(ge, GENDER_FEMALE) && GetCompanyManagerFaceBits(cmf, CMFV_HAS_MOUSTACHE,   ge) != 0;
    00152   bool has_tie_earring = !HasBit(ge, GENDER_FEMALE) || GetCompanyManagerFaceBits(cmf, CMFV_HAS_TIE_EARRING, ge) != 0;
    00153   bool has_glasses     = GetCompanyManagerFaceBits(cmf, CMFV_HAS_GLASSES, ge) != 0;
    00154
    00155   if (!AreCompanyManagerFaceBitsValid(cmf, CMFV_EYE_COLOUR, ge)) return false;
    00156   for (CompanyManagerFaceVariable cmfv = CMFV_CHEEKS; cmfv < CMFV_END; cmfv++) {
    00157     switch (cmfv) {
    00158       case CMFV_MOUSTACHE:   if (!has_moustache)   continue; break;
    00159       case CMFV_LIPS:        // FALL THROUGH
    00160       case CMFV_NOSE:        if (has_moustache)    continue; break;
    00161       case CMFV_TIE_EARRING: if (!has_tie_earring) continue; break;
    00162       case CMFV_GLASSES:     if (!has_glasses)     continue; break;
    00163       default: break;
    00164     }
    00165     if (!AreCompanyManagerFaceBitsValid(cmf, cmfv, ge)) return false;
    00166   }
    00167
    00168   return true;
    00169 }
    00170
    00175 void InvalidateCompanyWindows(const Company *company)
    00176 {
    00177   CompanyID cid = company->index;
    00178
    00179   if (cid == _local_company) SetWindowDirty(WC_STATUS_BAR, 0);
    00180   SetWindowDirty(WC_FINANCES, cid);
    00181 }
    00182
    00188 bool CheckCompanyHasMoney(CommandCost &cost)
    00189 {
    00190   if (cost.GetCost() > 0) {
    00191     const Company *c = Company::GetIfValid(_current_company);
    00192     if (c != NULL && cost.GetCost() > c->money) {
    00193       SetDParam(0, cost.GetCost());
    00194       cost.MakeError(STR_ERROR_NOT_ENOUGH_CASH_REQUIRES_CURRENCY);
    00195       return false;
    00196     }
    00197   }
    00198   return true;
    00199 }
    00200
    00206 static void SubtractMoneyFromAnyCompany(Company *c, CommandCost cost)
    00207 {
    00208   if (cost.GetCost() == 0) return;
    00209   assert(cost.GetExpensesType() != INVALID_EXPENSES);
    00210
    00211   c->money -= cost.GetCost();
    00212   c->yearly_expenses[0][cost.GetExpensesType()] += cost.GetCost();
    00213
    00214   if (HasBit(1 << EXPENSES_TRAIN_INC    |
    00215              1 << EXPENSES_ROADVEH_INC  |
    00216              1 << EXPENSES_AIRCRAFT_INC |
    00217              1 << EXPENSES_SHIP_INC, cost.GetExpensesType())) {
    00218     c->cur_economy.income -= cost.GetCost();
    00219   } else if (HasBit(1 << EXPENSES_TRAIN_RUN    |
    00220                     1 << EXPENSES_ROADVEH_RUN  |
    00221                     1 << EXPENSES_AIRCRAFT_RUN |
    00222                     1 << EXPENSES_SHIP_RUN     |
    00223                     1 << EXPENSES_PROPERTY     |
    00224                     1 << EXPENSES_LOAN_INT, cost.GetExpensesType())) {
    00225     c->cur_economy.expenses -= cost.GetCost();
    00226   }
    00227
    00228   InvalidateCompanyWindows(c);
    00229 }
    00230
    00235 void SubtractMoneyFromCompany(CommandCost cost)
    00236 {
    00237   Company *c = Company::GetIfValid(_current_company);
    00238   if (c != NULL) SubtractMoneyFromAnyCompany(c, cost);
    00239 }
    00240
    00246 void SubtractMoneyFromCompanyFract(CompanyID company, CommandCost cst)
    00247 {
    00248   Company *c = Company::Get(company);
    00249   byte m = c->money_fraction;
    00250   Money cost = cst.GetCost();
    00251
    00252   c->money_fraction = m - (byte)cost;
    00253   cost >>= 8;
    00254   if (c->money_fraction > m) cost++;
    00255   if (cost != 0) SubtractMoneyFromAnyCompany(c, CommandCost(cst.GetExpensesType(), cost));
    00256 }
    00257
    00259 void UpdateLandscapingLimits()
    00260 {
    00261   Company *c;
    00262   FOR_ALL_COMPANIES(c) {
    00263     c->terraform_limit = min(c->terraform_limit + _settings_game.construction.terraform_per_64k_frames, (uint32)_settings_game.construction.terraform_frame_burst << 16);
    00264     c->clear_limit     = min(c->clear_limit     + _settings_game.construction.clear_per_64k_frames,     (uint32)_settings_game.construction.clear_frame_burst << 16);
    00265     c->tree_limit      = min(c->tree_limit      + _settings_game.construction.tree_per_64k_frames,      (uint32)_settings_game.construction.tree_frame_burst << 16);
    00266   }
    00267 }
    00268
    00275 void GetNameOfOwner(Owner owner, TileIndex tile)
    00276 {
    00277   SetDParam(2, owner);
    00278
    00279   if (owner != OWNER_TOWN) {
    00280     if (!Company::IsValidID(owner)) {
    00281       SetDParam(0, STR_COMPANY_SOMEONE);
    00282     } else {
    00283       SetDParam(0, STR_COMPANY_NAME);
    00284       SetDParam(1, owner);
    00285     }
    00286   } else {
    00287     assert(tile != 0);
    00288     const Town *t = ClosestTownFromTile(tile, UINT_MAX);
    00289
    00290     SetDParam(0, STR_TOWN_NAME);
    00291     SetDParam(1, t->index);
    00292   }
    00293 }
    00294
    00295
    00304 CommandCost CheckOwnership(Owner owner, TileIndex tile)
    00305 {
    00306   assert(owner < OWNER_END);
    00307   assert(owner != OWNER_TOWN || tile != 0);
    00308
    00309   if (owner == _current_company) return CommandCost();
    00310
    00311   GetNameOfOwner(owner, tile);
    00312   return_cmd_error(STR_ERROR_OWNED_BY);
    00313 }
    00314
    00322 CommandCost CheckTileOwnership(TileIndex tile)
    00323 {
    00324   Owner owner = GetTileOwner(tile);
    00325
    00326   assert(owner < OWNER_END);
    00327
    00328   if (owner == _current_company) return CommandCost();
    00329
    00330   /* no need to get the name of the owner unless we're the local company (saves some time) */
    00331   if (IsLocalCompany()) GetNameOfOwner(owner, tile);
    00332   return_cmd_error(STR_ERROR_OWNED_BY);
    00333 }
    00334
    00339 static void GenerateCompanyName(Company *c)
    00340 {
    00341   /* Reserve space for extra unicode character. We need to do this to be able
    00342    * to detect too long company name. */
    00343   char buffer[(MAX_LENGTH_COMPANY_NAME_CHARS + 1) * MAX_CHAR_LENGTH];
    00344
    00345   if (c->name_1 != STR_SV_UNNAMED) return;
    00346   if (c->last_build_coordinate == 0) return;
    00347
    00348   Town *t = ClosestTownFromTile(c->last_build_coordinate, UINT_MAX);
    00349
    00350   StringID str;
    00351   uint32 strp;
    00352   if (t->name == NULL && IsInsideMM(t->townnametype, SPECSTR_TOWNNAME_START, SPECSTR_TOWNNAME_LAST + 1)) {
    00353     str = t->townnametype - SPECSTR_TOWNNAME_START + SPECSTR_COMPANY_NAME_START;
    00354     strp = t->townnameparts;
    00355
    00356 verify_name:;
    00357     /* No companies must have this name already */
    00358     Company *cc;
    00359     FOR_ALL_COMPANIES(cc) {
    00360       if (cc->name_1 == str && cc->name_2 == strp) goto bad_town_name;
    00361     }
    00362
    00363     GetString(buffer, str, lastof(buffer));
    00364     if (Utf8StringLength(buffer) >= MAX_LENGTH_COMPANY_NAME_CHARS) goto bad_town_name;
    00365
    00366 set_name:;
    00367     c->name_1 = str;
    00368     c->name_2 = strp;
    00369
    00370     MarkWholeScreenDirty();
    00371
    00372     if (c->is_ai) {
    00373       CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
    00374       cni->FillData(c);
    00375       SetDParam(0, STR_NEWS_COMPANY_LAUNCH_TITLE);
    00376       SetDParam(1, STR_NEWS_COMPANY_LAUNCH_DESCRIPTION);
    00377       SetDParamStr(2, cni->company_name);
    00378       SetDParam(3, t->index);
    00379       AddNewsItem(STR_MESSAGE_NEWS_FORMAT, NT_COMPANY_INFO, NF_COMPANY, NR_TILE, c->last_build_coordinate, NR_NONE, UINT32_MAX, cni);
    00380     }
    00381     return;
    00382   }
    00383 bad_town_name:;
    00384
    00385   if (c->president_name_1 == SPECSTR_PRESIDENT_NAME) {
    00386     str = SPECSTR_ANDCO_NAME;
    00387     strp = c->president_name_2;
    00388     goto set_name;
    00389   } else {
    00390     str = SPECSTR_ANDCO_NAME;
    00391     strp = Random();
    00392     goto verify_name;
    00393   }
    00394 }
    00395
    00397 static const byte _colour_sort[COLOUR_END] = {2, 2, 3, 2, 3, 2, 3, 2, 3, 2, 2, 2, 3, 1, 1, 1};
    00399 static const Colours _similar_colour[COLOUR_END][2] = {
    00400   { COLOUR_BLUE,       COLOUR_LIGHT_BLUE }, // COLOUR_DARK_BLUE
    00401   { COLOUR_GREEN,      COLOUR_DARK_GREEN }, // COLOUR_PALE_GREEN
    00402   { INVALID_COLOUR,    INVALID_COLOUR    }, // COLOUR_PINK
    00403   { COLOUR_ORANGE,     INVALID_COLOUR    }, // COLOUR_YELLOW
    00404   { INVALID_COLOUR,    INVALID_COLOUR    }, // COLOUR_RED
    00405   { COLOUR_DARK_BLUE,  COLOUR_BLUE       }, // COLOUR_LIGHT_BLUE
    00406   { COLOUR_PALE_GREEN, COLOUR_DARK_GREEN }, // COLOUR_GREEN
    00407   { COLOUR_PALE_GREEN, COLOUR_GREEN      }, // COLOUR_DARK_GREEN
    00408   { COLOUR_DARK_BLUE,  COLOUR_LIGHT_BLUE }, // COLOUR_BLUE
    00409   { COLOUR_BROWN,      COLOUR_ORANGE     }, // COLOUR_CREAM
    00410   { COLOUR_PURPLE,     INVALID_COLOUR    }, // COLOUR_MAUVE
    00411   { COLOUR_MAUVE,      INVALID_COLOUR    }, // COLOUR_PURPLE
    00412   { COLOUR_YELLOW,     COLOUR_CREAM      }, // COLOUR_ORANGE
    00413   { COLOUR_CREAM,      INVALID_COLOUR    }, // COLOUR_BROWN
    00414   { COLOUR_WHITE,      INVALID_COLOUR    }, // COLOUR_GREY
    00415   { COLOUR_GREY,       INVALID_COLOUR    }, // COLOUR_WHITE
    00416 };
    00417
    00422 static Colours GenerateCompanyColour()
    00423 {
    00424   Colours colours[COLOUR_END];
    00425
    00426   /* Initialize array */
    00427   for (uint i = 0; i < COLOUR_END; i++) colours[i] = (Colours)i;
    00428
    00429   /* And randomize it */
    00430   for (uint i = 0; i < 100; i++) {
    00431     uint r = Random();
    00432     Swap(colours[GB(r, 0, 4)], colours[GB(r, 4, 4)]);
    00433   }
    00434
    00435   /* Bubble sort it according to the values in table 1 */
    00436   for (uint i = 0; i < COLOUR_END; i++) {
    00437     for (uint j = 1; j < COLOUR_END; j++) {
    00438       if (_colour_sort[colours[j - 1]] < _colour_sort[colours[j]]) {
    00439         Swap(colours[j - 1], colours[j]);
    00440       }
    00441     }
    00442   }
    00443
    00444   /* Move the colours that look similar to each company's colour to the side */
    00445   Company *c;
    00446   FOR_ALL_COMPANIES(c) {
    00447     Colours pcolour = (Colours)c->colour;
    00448
    00449     for (uint i = 0; i < COLOUR_END; i++) {
    00450       if (colours[i] == pcolour) {
    00451         colours[i] = INVALID_COLOUR;
    00452         break;
    00453       }
    00454     }
    00455
    00456     for (uint j = 0; j < 2; j++) {
    00457       Colours similar = _similar_colour[pcolour][j];
    00458       if (similar == INVALID_COLOUR) break;
    00459
    00460       for (uint i = 1; i < COLOUR_END; i++) {
    00461         if (colours[i - 1] == similar) Swap(colours[i - 1], colours[i]);
    00462       }
    00463     }
    00464   }
    00465
    00466   /* Return the first available colour */
    00467   for (uint i = 0; i < COLOUR_END; i++) {
    00468     if (colours[i] != INVALID_COLOUR) return colours[i];
    00469   }
    00470
    00471   NOT_REACHED();
    00472 }
    00473
    00478 static void GeneratePresidentName(Company *c)
    00479 {
    00480   for (;;) {
    00481 restart:;
    00482     c->president_name_2 = Random();
    00483     c->president_name_1 = SPECSTR_PRESIDENT_NAME;
    00484
    00485     /* Reserve space for extra unicode character. We need to do this to be able
    00486      * to detect too long president name. */
    00487     char buffer[(MAX_LENGTH_PRESIDENT_NAME_CHARS + 1) * MAX_CHAR_LENGTH];
    00488     SetDParam(0, c->index);
    00489     GetString(buffer, STR_PRESIDENT_NAME, lastof(buffer));
    00490     if (Utf8StringLength(buffer) >= MAX_LENGTH_PRESIDENT_NAME_CHARS) continue;
    00491
    00492     Company *cc;
    00493     FOR_ALL_COMPANIES(cc) {
    00494       if (c != cc) {
    00495         /* Reserve extra space so even overlength president names can be compared. */
    00496         char buffer2[(MAX_LENGTH_PRESIDENT_NAME_CHARS + 1) * MAX_CHAR_LENGTH];
    00497         SetDParam(0, cc->index);
    00498         GetString(buffer2, STR_PRESIDENT_NAME, lastof(buffer2));
    00499         if (strcmp(buffer2, buffer) == 0) goto restart;
    00500       }
    00501     }
    00502     return;
    00503   }
    00504 }
    00505
    00511 void ResetCompanyLivery(Company *c)
    00512 {
    00513   for (LiveryScheme scheme = LS_BEGIN; scheme < LS_END; scheme++) {
    00514     c->livery[scheme].in_use  = false;
    00515     c->livery[scheme].colour1 = c->colour;
    00516     c->livery[scheme].colour2 = c->colour;
    00517   }
    00518 }
    00519
    00527 Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY)
    00528 {
    00529   if (!Company::CanAllocateItem()) return NULL;
    00530
    00531   /* we have to generate colour before this company is valid */
    00532   Colours colour = GenerateCompanyColour();
    00533
    00534   Company *c;
    00535   if (company == INVALID_COMPANY) {
    00536     c = new Company(STR_SV_UNNAMED, is_ai);
    00537   } else {
    00538     if (Company::IsValidID(company)) return NULL;
    00539     c = new (company) Company(STR_SV_UNNAMED, is_ai);
    00540   }
    00541
    00542   c->colour = colour;
    00543
    00544   ResetCompanyLivery(c);
    00545   _company_colours[c->index] = (Colours)c->colour;
    00546
    00547   c->money = c->current_loan = (100000ll * _economy.inflation_prices >> 16) / 50000 * 50000;
    00548
    00549   c->share_owners[0] = c->share_owners[1] = c->share_owners[2] = c->share_owners[3] = INVALID_OWNER;
    00550
    00551   c->avail_railtypes = GetCompanyRailtypes(c->index);
    00552   c->avail_roadtypes = GetCompanyRoadtypes(c->index);
    00553   c->inaugurated_year = _cur_year;
    00554   RandomCompanyManagerFaceBits(c->face, (GenderEthnicity)Random(), false); // create a random company manager face
    00555
    00556   SetDefaultCompanySettings(c->index);
    00557
    00558   GeneratePresidentName(c);
    00559
    00560   SetWindowDirty(WC_GRAPH_LEGEND, 0);
    00561   SetWindowClassesDirty(WC_CLIENT_LIST_POPUP);
    00562   SetWindowDirty(WC_CLIENT_LIST, 0);
    00563   InvalidateWindowData(WC_LINKGRAPH_LEGEND, 0);
    00564   BuildOwnerLegend();
    00565   InvalidateWindowData(WC_SMALLMAP, 0, 1);
    00566
    00567   if (is_ai && (!_networking || _network_server)) AI::StartNew(c->index);
    00568
    00569   AI::BroadcastNewEvent(new ScriptEventCompanyNew(c->index), c->index);
    00570   Game::NewEvent(new ScriptEventCompanyNew(c->index));
    00571
    00572   return c;
    00573 }
    00574
    00576 void StartupCompanies()
    00577 {
    00578   _next_competitor_start = 0;
    00579 }
    00580
    00582 static void MaybeStartNewCompany()
    00583 {
    00584 #ifdef ENABLE_NETWORK
    00585   if (_networking && Company::GetNumItems() >= _settings_client.network.max_companies) return;
    00586 #endif /* ENABLE_NETWORK */
    00587
    00588   Company *c;
    00589
    00590   /* count number of competitors */
    00591   uint n = 0;
    00592   FOR_ALL_COMPANIES(c) {
    00593     if (c->is_ai) n++;
    00594   }
    00595
    00596   if (n < (uint)_settings_game.difficulty.max_no_competitors) {
    00597     /* Send a command to all clients to start up a new AI.
    00598      * Works fine for Multiplayer and Singleplayer */
    00599     DoCommandP(0, 1 | INVALID_COMPANY << 16, 0, CMD_COMPANY_CTRL);
    00600   }
    00601 }
    00602
    00604 void InitializeCompanies()
    00605 {
    00606   _cur_company_tick_index = 0;
    00607 }
    00608
    00615 bool MayCompanyTakeOver(CompanyID cbig, CompanyID csmall)
    00616 {
    00617   const Company *c1 = Company::Get(cbig);
    00618   const Company *c2 = Company::Get(csmall);
    00619
    00620   /* Do the combined vehicle counts stay within the limits? */
    00621   return c1->group_all[VEH_TRAIN].num_vehicle + c2->group_all[VEH_TRAIN].num_vehicle <= _settings_game.vehicle.max_trains &&
    00622     c1->group_all[VEH_ROAD].num_vehicle     + c2->group_all[VEH_ROAD].num_vehicle     <= _settings_game.vehicle.max_roadveh &&
    00623     c1->group_all[VEH_SHIP].num_vehicle     + c2->group_all[VEH_SHIP].num_vehicle     <= _settings_game.vehicle.max_ships &&
    00624     c1->group_all[VEH_AIRCRAFT].num_vehicle + c2->group_all[VEH_AIRCRAFT].num_vehicle <= _settings_game.vehicle.max_aircraft;
    00625 }
    00626
    00636 static void HandleBankruptcyTakeover(Company *c)
    00637 {
    00638   /* Amount of time out for each company to take over a company;
    00639    * Timeout is a quarter (3 months of 30 days) divided over the
    00640    * number of companies. The minimum number of days in a quarter
    00641    * is 90: 31 in January, 28 in February and 31 in March.
    00642    * Note that the company going bankrupt can't buy itself. */
    00643   static const int TAKE_OVER_TIMEOUT = 3 * 30 * DAY_TICKS / (MAX_COMPANIES - 1);
    00644
    00645   assert(c->bankrupt_asked != 0);
    00646
    00647   /* We're currently asking some company to buy 'us' */
    00648   if (c->bankrupt_timeout != 0) {
    00649     c->bankrupt_timeout -= MAX_COMPANIES;
    00650     if (c->bankrupt_timeout > 0) return;
    00651     c->bankrupt_timeout = 0;
    00652
    00653     return;
    00654   }
    00655
    00656   /* Did we ask everyone for bankruptcy? If so, bail out. */
    00657   if (c->bankrupt_asked == MAX_UVALUE(CompanyMask)) return;
    00658
    00659   Company *c2, *best = NULL;
    00660   int32 best_performance = -1;
    00661
    00662   /* Ask the company with the highest performance history first */
    00663   FOR_ALL_COMPANIES(c2) {
    00664     if (c2->bankrupt_asked == 0 && // Don't ask companies going bankrupt themselves
    00665         !HasBit(c->bankrupt_asked, c2->index) &&
    00666         best_performance < c2->old_economy[1].performance_history &&
    00667         MayCompanyTakeOver(c2->index, c->index)) {
    00668       best_performance = c2->old_economy[1].performance_history;
    00669       best = c2;
    00670     }
    00671   }
    00672
    00673   /* Asked all companies? */
    00674   if (best_performance == -1) {
    00675     c->bankrupt_asked = MAX_UVALUE(CompanyMask);
    00676     return;
    00677   }
    00678
    00679   SetBit(c->bankrupt_asked, best->index);
    00680
    00681   c->bankrupt_timeout = TAKE_OVER_TIMEOUT;
    00682   if (best->is_ai) {
    00683     AI::NewEvent(best->index, new ScriptEventCompanyAskMerger(c->index, ClampToI32(c->bankrupt_value)));
    00684   } else if (IsInteractiveCompany(best->index)) {
    00685     ShowBuyCompanyDialog(c->index);
    00686   }
    00687 }
    00688
    00690 void OnTick_Companies()
    00691 {
    00692   if (_game_mode == GM_EDITOR) return;
    00693
    00694   Company *c = Company::GetIfValid(_cur_company_tick_index);
    00695   if (c != NULL) {
    00696     if (c->name_1 != 0) GenerateCompanyName(c);
    00697     if (c->bankrupt_asked != 0) HandleBankruptcyTakeover(c);
    00698   }
    00699
    00700   if (_next_competitor_start == 0) {
    00701     _next_competitor_start = AI::GetStartNextTime() * DAY_TICKS;
    00702   }
    00703
    00704   if (AI::CanStartNew() && _game_mode != GM_MENU && --_next_competitor_start == 0) {
    00705     MaybeStartNewCompany();
    00706   }
    00707
    00708   _cur_company_tick_index = (_cur_company_tick_index + 1) % MAX_COMPANIES;
    00709 }
    00710
    00715 void CompaniesYearlyLoop()
    00716 {
    00717   Company *c;
    00718
    00719   /* Copy statistics */
    00720   FOR_ALL_COMPANIES(c) {
    00721     memmove(&c->yearly_expenses[1], &c->yearly_expenses[0], sizeof(c->yearly_expenses) - sizeof(c->yearly_expenses[0]));
    00722     memset(&c->yearly_expenses[0], 0, sizeof(c->yearly_expenses[0]));
    00723     SetWindowDirty(WC_FINANCES, c->index);
    00724   }
    00725
    00726   if (_settings_client.gui.show_finances && _local_company != COMPANY_SPECTATOR) {
    00727     ShowCompanyFinances(_local_company);
    00728     c = Company::Get(_local_company);
    00729     if (c->num_valid_stat_ent > 5 && c->old_economy[0].performance_history < c->old_economy[4].performance_history) {
    00730       if (_settings_client.sound.new_year) SndPlayFx(SND_01_BAD_YEAR);
    00731     } else {
    00732       if (_settings_client.sound.new_year) SndPlayFx(SND_00_GOOD_YEAR);
    00733     }
    00734   }
    00735 }
    00736
    00742 void CompanyNewsInformation::FillData(const Company *c, const Company *other)
    00743 {
    00744   SetDParam(0, c->index);
    00745   GetString(this->company_name, STR_COMPANY_NAME, lastof(this->company_name));
    00746
    00747   if (other == NULL) {
    00748     *this->other_company_name = '\0';
    00749   } else {
    00750     SetDParam(0, other->index);
    00751     GetString(this->other_company_name, STR_COMPANY_NAME, lastof(this->other_company_name));
    00752     c = other;
    00753   }
    00754
    00755   SetDParam(0, c->index);
    00756   GetString(this->president_name, STR_PRESIDENT_NAME_MANAGER, lastof(this->president_name));
    00757
    00758   this->colour = c->colour;
    00759   this->face = c->face;
    00760
    00761 }
    00762
    00767 void CompanyAdminUpdate(const Company *company)
    00768 {
    00769 #ifdef ENABLE_NETWORK
    00770   if (_network_server) NetworkAdminCompanyUpdate(company);
    00771 #endif /* ENABLE_NETWORK */
    00772 }
    00773
    00779 void CompanyAdminRemove(CompanyID company_id, CompanyRemoveReason reason)
    00780 {
    00781 #ifdef ENABLE_NETWORK
    00782   if (_network_server) NetworkAdminCompanyRemove(company_id, (AdminCompanyRemoveReason)reason);
    00783 #endif /* ENABLE_NETWORK */
    00784 }
    00785
    00800 CommandCost CmdCompanyCtrl(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00801 {
    00802   InvalidateWindowData(WC_COMPANY_LEAGUE, 0, 0);
    00803   CompanyID company_id = (CompanyID)GB(p1, 16, 8);
    00804 #ifdef ENABLE_NETWORK
    00805   ClientID client_id = (ClientID)p2;
    00806 #endif /* ENABLE_NETWORK */
    00807
    00808   switch (GB(p1, 0, 16)) {
    00809     case 0: { // Create a new company
    00810       /* This command is only executed in a multiplayer game */
    00811       if (!_networking) return CMD_ERROR;
    00812
    00813 #ifdef ENABLE_NETWORK
    00814       /* Has the network client a correct ClientIndex? */
    00815       if (!(flags & DC_EXEC)) return CommandCost();
    00816       NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
    00817 #ifndef DEBUG_DUMP_COMMANDS
    00818       /* When replaying the client ID is not a valid client; there
    00819        * are actually no clients at all. However, the company has to
    00820        * be created, otherwise we cannot rerun the game properly.
    00821        * So only allow a NULL client info in that case. */
    00822       if (ci == NULL) return CommandCost();
    00823 #endif /* NOT DEBUG_DUMP_COMMANDS */
    00824
    00825       /* Delete multiplayer progress bar */
    00826       DeleteWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
    00827
    00828       Company *c = DoStartupNewCompany(false);
    00829
    00830       /* A new company could not be created, revert to being a spectator */
    00831       if (c == NULL) {
    00832         if (_network_server) {
    00833           ci->client_playas = COMPANY_SPECTATOR;
    00834           NetworkUpdateClientInfo(ci->client_id);
    00835         }
    00836         break;
    00837       }
    00838
    00839       /* This is the client (or non-dedicated server) who wants a new company */
    00840       if (client_id == _network_own_client_id) {
    00841         assert(_local_company == COMPANY_SPECTATOR);
    00842         SetLocalCompany(c->index);
    00843         if (!StrEmpty(_settings_client.network.default_company_pass)) {
    00844           NetworkChangeCompanyPassword(_local_company, _settings_client.network.default_company_pass);
    00845         }
    00846
    00847         /* Now that we have a new company, broadcast our company settings to
    00848          * all clients so everything is in sync */
    00849         SyncCompanySettings();
    00850
    00851         MarkWholeScreenDirty();
    00852       }
    00853
    00854       if (_network_server) {
    00855         if (ci != NULL) {
    00856           /* ci is only NULL when replaying.
    00857            * When replaying no client is actually in need of an update. */
    00858           ci->client_playas = c->index;
    00859           NetworkUpdateClientInfo(ci->client_id);
    00860         }
    00861
    00862         if (Company::IsValidID(c->index)) {
    00863           _network_company_states[c->index].months_empty = 0;
    00864           _network_company_states[c->index].password[0] = '\0';
    00865           NetworkServerUpdateCompanyPassworded(c->index, false);
    00866
    00867           /* XXX - When a client joins, we automatically set its name to the
    00868            * client's name (for some reason). As it stands now only the server
    00869            * knows the client's name, so it needs to send out a "broadcast" to
    00870            * do this. To achieve this we send a network command. However, it
    00871            * uses _local_company to execute the command as.  To prevent abuse
    00872            * (eg. only yourself can change your name/company), we 'cheat' by
    00873            * impersonation _local_company as the server. Not the best solution;
    00874            * but it works.
    00875            * TODO: Perhaps this could be improved by when the client is ready
    00876            * with joining to let it send itself the command, and not the server?
    00877            * For example in network_client.c:534? */
    00878           if (ci != NULL) {
    00879             /* ci is only NULL when replaying.
    00880              * When replaying, the command to rename the president will
    00881              * automatically be ran, so this is not even needed to get
    00882              * the exact same state. */
    00883             NetworkSendCommand(0, 0, 0, CMD_RENAME_PRESIDENT, NULL, ci->client_name, c->index);
    00884           }
    00885         }
    00886
    00887         /* Announce new company on network. */
    00888         NetworkAdminCompanyInfo(c, true);
    00889
    00890         if (ci != NULL) {
    00891           /* ci is only NULL when replaying.
    00892            * When replaying, the message that someone started a new company
    00893            * is not interesting at all. */
    00894           NetworkServerSendChat(NETWORK_ACTION_COMPANY_NEW, DESTTYPE_BROADCAST, 0, "", ci->client_id, c->index + 1);
    00895         }
    00896       }
    00897 #endif /* ENABLE_NETWORK */
    00898       break;
    00899     }
    00900
    00901     case 1: // Make a new AI company
    00902       if (!(flags & DC_EXEC)) return CommandCost();
    00903
    00904       if (company_id != INVALID_COMPANY && (company_id >= MAX_COMPANIES || Company::IsValidID(company_id))) return CMD_ERROR;
    00905       DoStartupNewCompany(true, company_id);
    00906       break;
    00907
    00908     case 2: { // Delete a company
    00909       CompanyRemoveReason reason = (CompanyRemoveReason)GB(p2, 0, 2);
    00910       if (reason >= CRR_END) return CMD_ERROR;
    00911
    00912       Company *c = Company::GetIfValid(company_id);
    00913       if (c == NULL) return CMD_ERROR;
    00914
    00915       if (!(flags & DC_EXEC)) return CommandCost();
    00916
    00917       /* Delete any open window of the company */
    00918       DeleteCompanyWindows(c->index);
    00919       CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
    00920       cni->FillData(c);
    00921
    00922       /* Show the bankrupt news */
    00923       SetDParam(0, STR_NEWS_COMPANY_BANKRUPT_TITLE);
    00924       SetDParam(1, STR_NEWS_COMPANY_BANKRUPT_DESCRIPTION);
    00925       SetDParamStr(2, cni->company_name);
    00926       AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, cni);
    00927
    00928       /* Remove the company */
    00929       ChangeOwnershipOfCompanyItems(c->index, INVALID_OWNER);
    00930       if (c->is_ai) AI::Stop(c->index);
    00931
    00932       CompanyID c_index = c->index;
    00933       delete c;
    00934       AI::BroadcastNewEvent(new ScriptEventCompanyBankrupt(c_index));
    00935       Game::NewEvent(new ScriptEventCompanyBankrupt(c_index));
    00936       CompanyAdminRemove(c_index, (CompanyRemoveReason)reason);
    00937       break;
    00938     }
    00939
    00940     default: return CMD_ERROR;
    00941   }
    00942
    00943   InvalidateWindowClassesData(WC_GAME_OPTIONS);
    00944   InvalidateWindowClassesData(WC_AI_SETTINGS);
    00945   InvalidateWindowClassesData(WC_AI_LIST);
    00946
    00947   return CommandCost();
    00948 }
    00949
    00959 CommandCost CmdSetCompanyManagerFace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00960 {
    00961   CompanyManagerFace cmf = (CompanyManagerFace)p2;
    00962
    00963   if (!IsValidCompanyManagerFace(cmf)) return CMD_ERROR;
    00964
    00965   if (flags & DC_EXEC) {
    00966     Company::Get(_current_company)->face = cmf;
    00967     MarkWholeScreenDirty();
    00968   }
    00969   return CommandCost();
    00970 }
    00971
    00983 CommandCost CmdSetCompanyColour(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00984 {
    00985   Colours colour = Extract<Colours, 0, 4>(p2);
    00986   LiveryScheme scheme = Extract<LiveryScheme, 0, 8>(p1);
    00987   byte state = GB(p1, 8, 2);
    00988
    00989   if (scheme >= LS_END || state >= 3 || colour == INVALID_COLOUR) return CMD_ERROR;
    00990
    00991   Company *c = Company::Get(_current_company);
    00992
    00993   /* Ensure no two companies have the same primary colour */
    00994   if (scheme == LS_DEFAULT && state == 0) {
    00995     const Company *cc;
    00996     FOR_ALL_COMPANIES(cc) {
    00997       if (cc != c && cc->colour == colour) return CMD_ERROR;
    00998     }
    00999   }
    01000
    01001   if (flags & DC_EXEC) {
    01002     switch (state) {
    01003       case 0:
    01004         c->livery[scheme].colour1 = colour;
    01005
    01006         /* If setting the first colour of the default scheme, adjust the
    01007          * original and cached company colours too. */
    01008         if (scheme == LS_DEFAULT) {
    01009           _company_colours[_current_company] = colour;
    01010           c->colour = colour;
    01011           CompanyAdminUpdate(c);
    01012         }
    01013         break;
    01014
    01015       case 1:
    01016         c->livery[scheme].colour2 = colour;
    01017         break;
    01018
    01019       case 2:
    01020         c->livery[scheme].in_use = colour != 0;
    01021
    01022         /* Now handle setting the default scheme's in_use flag.
    01023          * This is different to the other schemes, as it signifies if any
    01024          * scheme is active at all. If this flag is not set, then no
    01025          * processing of vehicle types occurs at all, and only the default
    01026          * colours will be used. */
    01027
    01028         /* If enabling a scheme, set the default scheme to be in use too */
    01029         if (colour != 0) {
    01030           c->livery[LS_DEFAULT].in_use = true;
    01031           break;
    01032         }
    01033
    01034         /* Else loop through all schemes to see if any are left enabled.
    01035          * If not, disable the default scheme too. */
    01036         c->livery[LS_DEFAULT].in_use = false;
    01037         for (scheme = LS_DEFAULT; scheme < LS_END; scheme++) {
    01038           if (c->livery[scheme].in_use) {
    01039             c->livery[LS_DEFAULT].in_use = true;
    01040             break;
    01041           }
    01042         }
    01043         break;
    01044
    01045       default:
    01046         break;
    01047     }
    01048     ResetVehicleColourMap();
    01049     MarkWholeScreenDirty();
    01050
    01051     /* All graph related to companies use the company colour. */
    01052     InvalidateWindowData(WC_INCOME_GRAPH, 0);
    01053     InvalidateWindowData(WC_OPERATING_PROFIT, 0);
    01054     InvalidateWindowData(WC_DELIVERED_CARGO, 0);
    01055     InvalidateWindowData(WC_PERFORMANCE_HISTORY, 0);
    01056     InvalidateWindowData(WC_COMPANY_VALUE, 0);
    01057     InvalidateWindowData(WC_LINKGRAPH_LEGEND, 0);
    01058     /* The smallmap owner view also stores the company colours. */
    01059     BuildOwnerLegend();
    01060     InvalidateWindowData(WC_SMALLMAP, 0, 1);
    01061
    01062     /* Company colour data is indirectly cached. */
    01063     Vehicle *v;
    01064     FOR_ALL_VEHICLES(v) {
    01065       if (v->owner == _current_company) v->InvalidateNewGRFCache();
    01066     }
    01067
    01068     extern void UpdateObjectColours(const Company *c);
    01069     UpdateObjectColours(c);
    01070   }
    01071   return CommandCost();
    01072 }
    01073
    01079 static bool IsUniqueCompanyName(const char *name)
    01080 {
    01081   const Company *c;
    01082
    01083   FOR_ALL_COMPANIES(c) {
    01084     if (c->name != NULL && strcmp(c->name, name) == 0) return false;
    01085   }
    01086
    01087   return true;
    01088 }
    01089
    01099 CommandCost CmdRenameCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    01100 {
    01101   bool reset = StrEmpty(text);
    01102
    01103   if (!reset) {
    01104     if (Utf8StringLength(text) >= MAX_LENGTH_COMPANY_NAME_CHARS) return CMD_ERROR;
    01105     if (!IsUniqueCompanyName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
    01106   }
    01107
    01108   if (flags & DC_EXEC) {
    01109     Company *c = Company::Get(_current_company);
    01110     free(c->name);
    01111     c->name = reset ? NULL : strdup(text);
    01112     MarkWholeScreenDirty();
    01113     CompanyAdminUpdate(c);
    01114   }
    01115
    01116   return CommandCost();
    01117 }
    01118
    01124 static bool IsUniquePresidentName(const char *name)
    01125 {
    01126   const Company *c;
    01127
    01128   FOR_ALL_COMPANIES(c) {
    01129     if (c->president_name != NULL && strcmp(c->president_name, name) == 0) return false;
    01130   }
    01131
    01132   return true;
    01133 }
    01134
    01144 CommandCost CmdRenamePresident(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    01145 {
    01146   bool reset = StrEmpty(text);
    01147
    01148   if (!reset) {
    01149     if (Utf8StringLength(text) >= MAX_LENGTH_PRESIDENT_NAME_CHARS) return CMD_ERROR;
    01150     if (!IsUniquePresidentName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
    01151   }
    01152
    01153   if (flags & DC_EXEC) {
    01154     Company *c = Company::Get(_current_company);
    01155     free(c->president_name);
    01156
    01157     if (reset) {
    01158       c->president_name = NULL;
    01159     } else {
    01160       c->president_name = strdup(text);
    01161
    01162       if (c->name_1 == STR_SV_UNNAMED && c->name == NULL) {
    01163         char buf[80];
    01164
    01165         snprintf(buf, lengthof(buf), "%s Transport", text);
    01166         DoCommand(0, 0, 0, DC_EXEC, CMD_RENAME_COMPANY, buf);
    01167       }
    01168     }
    01169
    01170     MarkWholeScreenDirty();
    01171     CompanyAdminUpdate(c);
    01172   }
    01173
    01174   return CommandCost();
    01175 }
    01176
    01183 int CompanyServiceInterval(const Company *c, VehicleType type)
    01184 {
    01185   const VehicleDefaultSettings *vds = (c == NULL) ? &_settings_client.company.vehicle : &c->settings.vehicle;
    01186   switch (type) {
    01187     default: NOT_REACHED();
    01188     case VEH_TRAIN:    return vds->servint_trains;
    01189     case VEH_ROAD:     return vds->servint_roadveh;
    01190     case VEH_AIRCRAFT: return vds->servint_aircraft;
    01191     case VEH_SHIP:     return vds->servint_ships;
    01192   }
    01193 }