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