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 "engine_base.h"
00014 #include "company_base.h"
00015 #include "company_func.h"
00016 #include "company_gui.h"
00017 #include "town.h"
00018 #include "news_func.h"
00019 #include "cmd_helper.h"
00020 #include "command_func.h"
00021 #include "network/network.h"
00022 #include "network/network_func.h"
00023 #include "network/network_base.h"
00024 #include "network/network_admin.h"
00025 #include "ai/ai.hpp"
00026 #include "company_manager_face.h"
00027 #include "window_func.h"
00028 #include "strings_func.h"
00029 #include "date_func.h"
00030 #include "sound_func.h"
00031 #include "rail.h"
00032 #include "core/pool_func.hpp"
00033 #include "settings_func.h"
00034 #include "vehicle_base.h"
00035 #include "vehicle_func.h"
00036 #include "sprite.h"
00037 #include "smallmap_gui.h"
00038 
00039 #include "table/strings.h"
00040 
00041 CompanyByte _local_company;   
00042 CompanyByte _current_company; 
00043 Colours _company_colours[MAX_COMPANIES];  
00044 CompanyManagerFace _company_manager_face; 
00045 uint _next_competitor_start;              
00046 uint _cur_company_tick_index;             
00047 
00048 CompanyPool _company_pool("Company"); 
00049 INSTANTIATE_POOL_METHODS(Company)
00050 
00051 
00056 Company::Company(uint16 name_1, bool is_ai)
00057 {
00058   this->name_1 = name_1;
00059   this->location_of_HQ = INVALID_TILE;
00060   this->is_ai = is_ai;
00061   this->terraform_limit = _settings_game.construction.terraform_frame_burst << 16;
00062   this->clear_limit     = _settings_game.construction.clear_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 }
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   }
00265 }
00266 
00273 void GetNameOfOwner(Owner owner, TileIndex tile)
00274 {
00275   SetDParam(2, owner);
00276 
00277   if (owner != OWNER_TOWN) {
00278     if (!Company::IsValidID(owner)) {
00279       SetDParam(0, STR_COMPANY_SOMEONE);
00280     } else {
00281       SetDParam(0, STR_COMPANY_NAME);
00282       SetDParam(1, owner);
00283     }
00284   } else {
00285     assert(tile != 0);
00286     const Town *t = ClosestTownFromTile(tile, UINT_MAX);
00287 
00288     SetDParam(0, STR_TOWN_NAME);
00289     SetDParam(1, t->index);
00290   }
00291 }
00292 
00293 
00302 CommandCost CheckOwnership(Owner owner, TileIndex tile)
00303 {
00304   assert(owner < OWNER_END);
00305   assert(owner != OWNER_TOWN || tile != 0);
00306 
00307   if (owner == _current_company) return CommandCost();
00308 
00309   GetNameOfOwner(owner, tile);
00310   return_cmd_error(STR_ERROR_OWNED_BY);
00311 }
00312 
00320 CommandCost CheckTileOwnership(TileIndex tile)
00321 {
00322   Owner owner = GetTileOwner(tile);
00323 
00324   assert(owner < OWNER_END);
00325 
00326   if (owner == _current_company) return CommandCost();
00327 
00328   /* no need to get the name of the owner unless we're the local company (saves some time) */
00329   if (IsLocalCompany()) GetNameOfOwner(owner, tile);
00330   return_cmd_error(STR_ERROR_OWNED_BY);
00331 }
00332 
00337 static void GenerateCompanyName(Company *c)
00338 {
00339   /* Reserve space for extra unicode character. We need to do this to be able
00340    * to detect too long company name. */
00341   char buffer[(MAX_LENGTH_COMPANY_NAME_CHARS + 1) * MAX_CHAR_LENGTH];
00342 
00343   if (c->name_1 != STR_SV_UNNAMED) return;
00344   if (c->last_build_coordinate == 0) return;
00345 
00346   Town *t = ClosestTownFromTile(c->last_build_coordinate, UINT_MAX);
00347 
00348   StringID str;
00349   uint32 strp;
00350   if (t->name == NULL && IsInsideMM(t->townnametype, SPECSTR_TOWNNAME_START, SPECSTR_TOWNNAME_LAST + 1)) {
00351     str = t->townnametype - SPECSTR_TOWNNAME_START + SPECSTR_COMPANY_NAME_START;
00352     strp = t->townnameparts;
00353 
00354 verify_name:;
00355     /* No companies must have this name already */
00356     Company *cc;
00357     FOR_ALL_COMPANIES(cc) {
00358       if (cc->name_1 == str && cc->name_2 == strp) goto bad_town_name;
00359     }
00360 
00361     GetString(buffer, str, lastof(buffer));
00362     if (Utf8StringLength(buffer) >= MAX_LENGTH_COMPANY_NAME_CHARS) goto bad_town_name;
00363 
00364 set_name:;
00365     c->name_1 = str;
00366     c->name_2 = strp;
00367 
00368     MarkWholeScreenDirty();
00369 
00370     if (c->is_ai) {
00371       CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
00372       cni->FillData(c);
00373       SetDParam(0, STR_NEWS_COMPANY_LAUNCH_TITLE);
00374       SetDParam(1, STR_NEWS_COMPANY_LAUNCH_DESCRIPTION);
00375       SetDParamStr(2, cni->company_name);
00376       SetDParam(3, t->index);
00377       AddNewsItem(STR_MESSAGE_NEWS_FORMAT, NS_COMPANY_NEW, NR_TILE, c->last_build_coordinate, NR_NONE, UINT32_MAX, cni);
00378     }
00379     return;
00380   }
00381 bad_town_name:;
00382 
00383   if (c->president_name_1 == SPECSTR_PRESIDENT_NAME) {
00384     str = SPECSTR_ANDCO_NAME;
00385     strp = c->president_name_2;
00386     goto set_name;
00387   } else {
00388     str = SPECSTR_ANDCO_NAME;
00389     strp = Random();
00390     goto verify_name;
00391   }
00392 }
00393 
00395 static const byte _colour_sort[COLOUR_END] = {2, 2, 3, 2, 3, 2, 3, 2, 3, 2, 2, 2, 3, 1, 1, 1};
00397 static const Colours _similar_colour[COLOUR_END][2] = {
00398   { COLOUR_BLUE,       COLOUR_LIGHT_BLUE }, // COLOUR_DARK_BLUE
00399   { COLOUR_GREEN,      COLOUR_DARK_GREEN }, // COLOUR_PALE_GREEN
00400   { INVALID_COLOUR,    INVALID_COLOUR    }, // COLOUR_PINK
00401   { COLOUR_ORANGE,     INVALID_COLOUR    }, // COLOUR_YELLOW
00402   { INVALID_COLOUR,    INVALID_COLOUR    }, // COLOUR_RED
00403   { COLOUR_DARK_BLUE,  COLOUR_BLUE       }, // COLOUR_LIGHT_BLUE
00404   { COLOUR_PALE_GREEN, COLOUR_DARK_GREEN }, // COLOUR_GREEN
00405   { COLOUR_PALE_GREEN, COLOUR_GREEN      }, // COLOUR_DARK_GREEN
00406   { COLOUR_DARK_BLUE,  COLOUR_LIGHT_BLUE }, // COLOUR_BLUE
00407   { COLOUR_BROWN,      COLOUR_ORANGE     }, // COLOUR_CREAM
00408   { COLOUR_PURPLE,     INVALID_COLOUR    }, // COLOUR_MAUVE
00409   { COLOUR_MAUVE,      INVALID_COLOUR    }, // COLOUR_PURPLE
00410   { COLOUR_YELLOW,     COLOUR_CREAM      }, // COLOUR_ORANGE
00411   { COLOUR_CREAM,      INVALID_COLOUR    }, // COLOUR_BROWN
00412   { COLOUR_WHITE,      INVALID_COLOUR    }, // COLOUR_GREY
00413   { COLOUR_GREY,       INVALID_COLOUR    }, // COLOUR_WHITE
00414 };
00415 
00420 static Colours GenerateCompanyColour()
00421 {
00422   Colours colours[COLOUR_END];
00423 
00424   /* Initialize array */
00425   for (uint i = 0; i < COLOUR_END; i++) colours[i] = (Colours)i;
00426 
00427   /* And randomize it */
00428   for (uint i = 0; i < 100; i++) {
00429     uint r = Random();
00430     Swap(colours[GB(r, 0, 4)], colours[GB(r, 4, 4)]);
00431   }
00432 
00433   /* Bubble sort it according to the values in table 1 */
00434   for (uint i = 0; i < COLOUR_END; i++) {
00435     for (uint j = 1; j < COLOUR_END; j++) {
00436       if (_colour_sort[colours[j - 1]] < _colour_sort[colours[j]]) {
00437         Swap(colours[j - 1], colours[j]);
00438       }
00439     }
00440   }
00441 
00442   /* Move the colours that look similar to each company's colour to the side */
00443   Company *c;
00444   FOR_ALL_COMPANIES(c) {
00445     Colours pcolour = (Colours)c->colour;
00446 
00447     for (uint i = 0; i < COLOUR_END; i++) {
00448       if (colours[i] == pcolour) {
00449         colours[i] = INVALID_COLOUR;
00450         break;
00451       }
00452     }
00453 
00454     for (uint j = 0; j < 2; j++) {
00455       Colours similar = _similar_colour[pcolour][j];
00456       if (similar == INVALID_COLOUR) break;
00457 
00458       for (uint i = 1; i < COLOUR_END; i++) {
00459         if (colours[i - 1] == similar) Swap(colours[i - 1], colours[i]);
00460       }
00461     }
00462   }
00463 
00464   /* Return the first available colour */
00465   for (uint i = 0; i < COLOUR_END; i++) {
00466     if (colours[i] != INVALID_COLOUR) return colours[i];
00467   }
00468 
00469   NOT_REACHED();
00470 }
00471 
00476 static void GeneratePresidentName(Company *c)
00477 {
00478   for (;;) {
00479 restart:;
00480     c->president_name_2 = Random();
00481     c->president_name_1 = SPECSTR_PRESIDENT_NAME;
00482 
00483     /* Reserve space for extra unicode character. We need to do this to be able
00484      * to detect too long president name. */
00485     char buffer[(MAX_LENGTH_PRESIDENT_NAME_CHARS + 1) * MAX_CHAR_LENGTH];
00486     SetDParam(0, c->index);
00487     GetString(buffer, STR_PRESIDENT_NAME, lastof(buffer));
00488     if (Utf8StringLength(buffer) >= MAX_LENGTH_PRESIDENT_NAME_CHARS) continue;
00489 
00490     Company *cc;
00491     FOR_ALL_COMPANIES(cc) {
00492       if (c != cc) {
00493         /* Reserve extra space so even overlength president names can be compared. */
00494         char buffer2[(MAX_LENGTH_PRESIDENT_NAME_CHARS + 1) * MAX_CHAR_LENGTH];
00495         SetDParam(0, cc->index);
00496         GetString(buffer2, STR_PRESIDENT_NAME, lastof(buffer2));
00497         if (strcmp(buffer2, buffer) == 0) goto restart;
00498       }
00499     }
00500     return;
00501   }
00502 }
00503 
00509 void ResetCompanyLivery(Company *c)
00510 {
00511   for (LiveryScheme scheme = LS_BEGIN; scheme < LS_END; scheme++) {
00512     c->livery[scheme].in_use  = false;
00513     c->livery[scheme].colour1 = c->colour;
00514     c->livery[scheme].colour2 = c->colour;
00515   }
00516 }
00517 
00525 Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY)
00526 {
00527   if (!Company::CanAllocateItem()) return NULL;
00528 
00529   /* we have to generate colour before this company is valid */
00530   Colours colour = GenerateCompanyColour();
00531 
00532   Company *c;
00533   if (company == INVALID_COMPANY) {
00534     c = new Company(STR_SV_UNNAMED, is_ai);
00535   } else {
00536     if (Company::IsValidID(company)) return NULL;
00537     c = new (company) Company(STR_SV_UNNAMED, is_ai);
00538   }
00539 
00540   c->colour = colour;
00541 
00542   ResetCompanyLivery(c);
00543   _company_colours[c->index] = (Colours)c->colour;
00544 
00545   c->money = c->current_loan = (100000ll * _economy.inflation_prices >> 16) / 50000 * 50000;
00546 
00547   c->share_owners[0] = c->share_owners[1] = c->share_owners[2] = c->share_owners[3] = INVALID_OWNER;
00548 
00549   c->avail_railtypes = GetCompanyRailtypes(c->index);
00550   c->avail_roadtypes = GetCompanyRoadtypes(c->index);
00551   c->inaugurated_year = _cur_year;
00552   RandomCompanyManagerFaceBits(c->face, (GenderEthnicity)Random(), false); // create a random company manager face
00553 
00554   SetDefaultCompanySettings(c->index);
00555 
00556   GeneratePresidentName(c);
00557 
00558   SetWindowDirty(WC_GRAPH_LEGEND, 0);
00559   SetWindowClassesDirty(WC_CLIENT_LIST_POPUP);
00560   SetWindowDirty(WC_CLIENT_LIST, 0);
00561   InvalidateWindowData(WC_LINKGRAPH_LEGEND, 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 
00569   return c;
00570 }
00571 
00573 void StartupCompanies()
00574 {
00575   _next_competitor_start = 0;
00576 }
00577 
00579 static void MaybeStartNewCompany()
00580 {
00581 #ifdef ENABLE_NETWORK
00582   if (_networking && Company::GetNumItems() >= _settings_client.network.max_companies) return;
00583 #endif /* ENABLE_NETWORK */
00584 
00585   Company *c;
00586 
00587   /* count number of competitors */
00588   uint n = 0;
00589   FOR_ALL_COMPANIES(c) {
00590     if (c->is_ai) n++;
00591   }
00592 
00593   if (n < (uint)_settings_game.difficulty.max_no_competitors) {
00594     /* Send a command to all clients to start up a new AI.
00595      * Works fine for Multiplayer and Singleplayer */
00596     DoCommandP(0, 1 | INVALID_COMPANY << 16, 0, CMD_COMPANY_CTRL);
00597   }
00598 }
00599 
00601 void InitializeCompanies()
00602 {
00603   _cur_company_tick_index = 0;
00604 }
00605 
00612 bool MayCompanyTakeOver(CompanyID cbig, CompanyID csmall)
00613 {
00614   const Company *c1 = Company::Get(cbig);
00615   const Company *c2 = Company::Get(csmall);
00616 
00617   /* Do the combined vehicle counts stay within the limits? */
00618   return c1->group_all[VEH_TRAIN].num_vehicle + c2->group_all[VEH_TRAIN].num_vehicle <= _settings_game.vehicle.max_trains &&
00619     c1->group_all[VEH_ROAD].num_vehicle     + c2->group_all[VEH_ROAD].num_vehicle     <= _settings_game.vehicle.max_roadveh &&
00620     c1->group_all[VEH_SHIP].num_vehicle     + c2->group_all[VEH_SHIP].num_vehicle     <= _settings_game.vehicle.max_ships &&
00621     c1->group_all[VEH_AIRCRAFT].num_vehicle + c2->group_all[VEH_AIRCRAFT].num_vehicle <= _settings_game.vehicle.max_aircraft;
00622 }
00623 
00633 static void HandleBankruptcyTakeover(Company *c)
00634 {
00635   /* Amount of time out for each company to take over a company;
00636    * Timeout is a quarter (3 months of 30 days) divided over the
00637    * number of companies. The minimum number of days in a quarter
00638    * is 90: 31 in January, 28 in February and 31 in March.
00639    * Note that the company going bankrupt can't buy itself. */
00640   static const int TAKE_OVER_TIMEOUT = 3 * 30 * DAY_TICKS / (MAX_COMPANIES - 1);
00641 
00642   assert(c->bankrupt_asked != 0);
00643 
00644   /* We're currently asking some company to buy 'us' */
00645   if (c->bankrupt_timeout != 0) {
00646     c->bankrupt_timeout -= MAX_COMPANIES;
00647     if (c->bankrupt_timeout > 0) return;
00648     c->bankrupt_timeout = 0;
00649 
00650     return;
00651   }
00652 
00653   /* Did we ask everyone for bankruptcy? If so, bail out. */
00654   if (c->bankrupt_asked == MAX_UVALUE(CompanyMask)) return;
00655 
00656   Company *c2, *best = NULL;
00657   int32 best_performance = -1;
00658 
00659   /* Ask the company with the highest performance history first */
00660   FOR_ALL_COMPANIES(c2) {
00661     if (c2->bankrupt_asked == 0 && // Don't ask companies going bankrupt themselves
00662         !HasBit(c->bankrupt_asked, c2->index) &&
00663         best_performance < c2->old_economy[1].performance_history &&
00664         MayCompanyTakeOver(c2->index, c->index)) {
00665       best_performance = c2->old_economy[1].performance_history;
00666       best = c2;
00667     }
00668   }
00669 
00670   /* Asked all companies? */
00671   if (best_performance == -1) {
00672     c->bankrupt_asked = MAX_UVALUE(CompanyMask);
00673     return;
00674   }
00675 
00676   SetBit(c->bankrupt_asked, best->index);
00677 
00678   c->bankrupt_timeout = TAKE_OVER_TIMEOUT;
00679   if (best->is_ai) {
00680     AI::NewEvent(best->index, new ScriptEventCompanyAskMerger(c->index, ClampToI32(c->bankrupt_value)));
00681   } else if (IsInteractiveCompany(best->index)) {
00682     ShowBuyCompanyDialog(c->index);
00683   }
00684 }
00685 
00687 void OnTick_Companies()
00688 {
00689   if (_game_mode == GM_EDITOR) return;
00690 
00691   Company *c = Company::GetIfValid(_cur_company_tick_index);
00692   if (c != NULL) {
00693     if (c->name_1 != 0) GenerateCompanyName(c);
00694     if (c->bankrupt_asked != 0) HandleBankruptcyTakeover(c);
00695   }
00696 
00697   if (_next_competitor_start == 0) {
00698     _next_competitor_start = AI::GetStartNextTime() * DAY_TICKS;
00699   }
00700 
00701   if (AI::CanStartNew() && _game_mode != GM_MENU && --_next_competitor_start == 0) {
00702     MaybeStartNewCompany();
00703   }
00704 
00705   _cur_company_tick_index = (_cur_company_tick_index + 1) % MAX_COMPANIES;
00706 }
00707 
00712 void CompaniesYearlyLoop()
00713 {
00714   Company *c;
00715 
00716   /* Copy statistics */
00717   FOR_ALL_COMPANIES(c) {
00718     memmove(&c->yearly_expenses[1], &c->yearly_expenses[0], sizeof(c->yearly_expenses) - sizeof(c->yearly_expenses[0]));
00719     memset(&c->yearly_expenses[0], 0, sizeof(c->yearly_expenses[0]));
00720     SetWindowDirty(WC_FINANCES, c->index);
00721   }
00722 
00723   if (_settings_client.gui.show_finances && _local_company != COMPANY_SPECTATOR) {
00724     ShowCompanyFinances(_local_company);
00725     c = Company::Get(_local_company);
00726     if (c->num_valid_stat_ent > 5 && c->old_economy[0].performance_history < c->old_economy[4].performance_history) {
00727       SndPlayFx(SND_01_BAD_YEAR);
00728     } else {
00729       SndPlayFx(SND_00_GOOD_YEAR);
00730     }
00731   }
00732 }
00733 
00739 void CompanyNewsInformation::FillData(const Company *c, const Company *other)
00740 {
00741   SetDParam(0, c->index);
00742   GetString(this->company_name, STR_COMPANY_NAME, lastof(this->company_name));
00743 
00744   if (other == NULL) {
00745     *this->other_company_name = '\0';
00746   } else {
00747     SetDParam(0, other->index);
00748     GetString(this->other_company_name, STR_COMPANY_NAME, lastof(this->other_company_name));
00749     c = other;
00750   }
00751 
00752   SetDParam(0, c->index);
00753   GetString(this->president_name, STR_PRESIDENT_NAME_MANAGER, lastof(this->president_name));
00754 
00755   this->colour = c->colour;
00756   this->face = c->face;
00757 
00758 }
00759 
00764 void CompanyAdminUpdate(const Company *company)
00765 {
00766 #ifdef ENABLE_NETWORK
00767   if (_network_server) NetworkAdminCompanyUpdate(company);
00768 #endif /* ENABLE_NETWORK */
00769 }
00770 
00776 void CompanyAdminRemove(CompanyID company_id, CompanyRemoveReason reason)
00777 {
00778 #ifdef ENABLE_NETWORK
00779   if (_network_server) NetworkAdminCompanyRemove(company_id, (AdminCompanyRemoveReason)reason);
00780 #endif /* ENABLE_NETWORK */
00781 }
00782 
00797 CommandCost CmdCompanyCtrl(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00798 {
00799   InvalidateWindowData(WC_COMPANY_LEAGUE, 0, 0);
00800   CompanyID company_id = (CompanyID)GB(p1, 16, 8);
00801 #ifdef ENABLE_NETWORK
00802   ClientID client_id = (ClientID)p2;
00803 #endif /* ENABLE_NETWORK */
00804 
00805   switch (GB(p1, 0, 16)) {
00806     case 0: { // Create a new company
00807       /* This command is only executed in a multiplayer game */
00808       if (!_networking) return CMD_ERROR;
00809 
00810 #ifdef ENABLE_NETWORK
00811       /* Has the network client a correct ClientIndex? */
00812       if (!(flags & DC_EXEC)) return CommandCost();
00813       NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
00814       if (ci == NULL) return CommandCost();
00815 
00816       /* Delete multiplayer progress bar */
00817       DeleteWindowById(WC_NETWORK_STATUS_WINDOW, 0);
00818 
00819       Company *c = DoStartupNewCompany(false);
00820 
00821       /* A new company could not be created, revert to being a spectator */
00822       if (c == NULL) {
00823         if (_network_server) {
00824           ci->client_playas = COMPANY_SPECTATOR;
00825           NetworkUpdateClientInfo(ci->client_id);
00826         }
00827         break;
00828       }
00829 
00830       /* This is the client (or non-dedicated server) who wants a new company */
00831       if (client_id == _network_own_client_id) {
00832         assert(_local_company == COMPANY_SPECTATOR);
00833         SetLocalCompany(c->index);
00834         if (!StrEmpty(_settings_client.network.default_company_pass)) {
00835           NetworkChangeCompanyPassword(_local_company, _settings_client.network.default_company_pass);
00836         }
00837 
00838         /* Now that we have a new company, broadcast our company settings to
00839          * all clients so everything is in sync */
00840         SyncCompanySettings();
00841 
00842         MarkWholeScreenDirty();
00843       }
00844 
00845       if (_network_server) {
00846         ci->client_playas = c->index;
00847         NetworkUpdateClientInfo(ci->client_id);
00848 
00849         if (Company::IsValidID(ci->client_playas)) {
00850           _network_company_states[c->index].months_empty = 0;
00851           _network_company_states[c->index].password[0] = '\0';
00852           NetworkServerUpdateCompanyPassworded(ci->client_playas, false);
00853 
00854           /* XXX - When a client joins, we automatically set its name to the
00855            * client's name (for some reason). As it stands now only the server
00856            * knows the client's name, so it needs to send out a "broadcast" to
00857            * do this. To achieve this we send a network command. However, it
00858            * uses _local_company to execute the command as.  To prevent abuse
00859            * (eg. only yourself can change your name/company), we 'cheat' by
00860            * impersonation _local_company as the server. Not the best solution;
00861            * but it works.
00862            * TODO: Perhaps this could be improved by when the client is ready
00863            * with joining to let it send itself the command, and not the server?
00864            * For example in network_client.c:534? */
00865           NetworkSendCommand(0, 0, 0, CMD_RENAME_PRESIDENT, NULL, ci->client_name, ci->client_playas);
00866         }
00867 
00868         /* Announce new company on network. */
00869         NetworkAdminCompanyInfo(c, true);
00870         NetworkServerSendChat(NETWORK_ACTION_COMPANY_NEW, DESTTYPE_BROADCAST, 0, "", ci->client_id, ci->client_playas + 1);
00871       }
00872 #endif /* ENABLE_NETWORK */
00873       break;
00874     }
00875 
00876     case 1: // Make a new AI company
00877       if (!(flags & DC_EXEC)) return CommandCost();
00878 
00879       if (company_id != INVALID_COMPANY && (company_id >= MAX_COMPANIES || Company::IsValidID(company_id))) return CMD_ERROR;
00880       DoStartupNewCompany(true, company_id);
00881       break;
00882 
00883     case 2: { // Delete a company
00884       CompanyRemoveReason reason = (CompanyRemoveReason)GB(p2, 0, 2);
00885       if (reason >= CRR_END) return CMD_ERROR;
00886 
00887       Company *c = Company::GetIfValid(company_id);
00888       if (c == NULL) return CMD_ERROR;
00889 
00890       if (!(flags & DC_EXEC)) return CommandCost();
00891 
00892       /* Delete any open window of the company */
00893       DeleteCompanyWindows(c->index);
00894       CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
00895       cni->FillData(c);
00896 
00897       /* Show the bankrupt news */
00898       SetDParam(0, STR_NEWS_COMPANY_BANKRUPT_TITLE);
00899       SetDParam(1, STR_NEWS_COMPANY_BANKRUPT_DESCRIPTION);
00900       SetDParamStr(2, cni->company_name);
00901       AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, NS_COMPANY_BANKRUPT, cni);
00902 
00903       /* Remove the company */
00904       ChangeOwnershipOfCompanyItems(c->index, INVALID_OWNER);
00905       if (c->is_ai) AI::Stop(c->index);
00906 
00907       CompanyID c_index = c->index;
00908       delete c;
00909       AI::BroadcastNewEvent(new ScriptEventCompanyBankrupt(c_index));
00910       CompanyAdminRemove(c_index, (CompanyRemoveReason)reason);
00911       break;
00912     }
00913 
00914     default: return CMD_ERROR;
00915   }
00916 
00917   InvalidateWindowClassesData(WC_GAME_OPTIONS);
00918   InvalidateWindowClassesData(WC_AI_SETTINGS);
00919   InvalidateWindowClassesData(WC_AI_LIST);
00920 
00921   return CommandCost();
00922 }
00923 
00933 CommandCost CmdSetCompanyManagerFace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00934 {
00935   CompanyManagerFace cmf = (CompanyManagerFace)p2;
00936 
00937   if (!IsValidCompanyManagerFace(cmf)) return CMD_ERROR;
00938 
00939   if (flags & DC_EXEC) {
00940     Company::Get(_current_company)->face = cmf;
00941     MarkWholeScreenDirty();
00942   }
00943   return CommandCost();
00944 }
00945 
00957 CommandCost CmdSetCompanyColour(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00958 {
00959   Colours colour = Extract<Colours, 0, 4>(p2);
00960   LiveryScheme scheme = Extract<LiveryScheme, 0, 8>(p1);
00961   byte state = GB(p1, 8, 2);
00962 
00963   if (scheme >= LS_END || state >= 3 || colour == INVALID_COLOUR) return CMD_ERROR;
00964 
00965   Company *c = Company::Get(_current_company);
00966 
00967   /* Ensure no two companies have the same primary colour */
00968   if (scheme == LS_DEFAULT && state == 0) {
00969     const Company *cc;
00970     FOR_ALL_COMPANIES(cc) {
00971       if (cc != c && cc->colour == colour) return CMD_ERROR;
00972     }
00973   }
00974 
00975   if (flags & DC_EXEC) {
00976     switch (state) {
00977       case 0:
00978         c->livery[scheme].colour1 = colour;
00979 
00980         /* If setting the first colour of the default scheme, adjust the
00981          * original and cached company colours too. */
00982         if (scheme == LS_DEFAULT) {
00983           _company_colours[_current_company] = colour;
00984           c->colour = colour;
00985           CompanyAdminUpdate(c);
00986         }
00987         break;
00988 
00989       case 1:
00990         c->livery[scheme].colour2 = colour;
00991         break;
00992 
00993       case 2:
00994         c->livery[scheme].in_use = colour != 0;
00995 
00996         /* Now handle setting the default scheme's in_use flag.
00997          * This is different to the other schemes, as it signifies if any
00998          * scheme is active at all. If this flag is not set, then no
00999          * processing of vehicle types occurs at all, and only the default
01000          * colours will be used. */
01001 
01002         /* If enabling a scheme, set the default scheme to be in use too */
01003         if (colour != 0) {
01004           c->livery[LS_DEFAULT].in_use = true;
01005           break;
01006         }
01007 
01008         /* Else loop through all schemes to see if any are left enabled.
01009          * If not, disable the default scheme too. */
01010         c->livery[LS_DEFAULT].in_use = false;
01011         for (scheme = LS_DEFAULT; scheme < LS_END; scheme++) {
01012           if (c->livery[scheme].in_use) {
01013             c->livery[LS_DEFAULT].in_use = true;
01014             break;
01015           }
01016         }
01017         break;
01018 
01019       default:
01020         break;
01021     }
01022     ResetVehicleColourMap();
01023     MarkWholeScreenDirty();
01024 
01025     /* All graph related to companies use the company colour. */
01026     InvalidateWindowData(WC_INCOME_GRAPH, 0);
01027     InvalidateWindowData(WC_OPERATING_PROFIT, 0);
01028     InvalidateWindowData(WC_DELIVERED_CARGO, 0);
01029     InvalidateWindowData(WC_PERFORMANCE_HISTORY, 0);
01030     InvalidateWindowData(WC_COMPANY_VALUE, 0);
01031     InvalidateWindowData(WC_LINKGRAPH_LEGEND, 0);
01032     /* The smallmap owner view also stores the company colours. */
01033     BuildOwnerLegend();
01034     InvalidateWindowData(WC_SMALLMAP, 0, 1);
01035 
01036     /* Company colour data is indirectly cached. */
01037     Vehicle *v;
01038     FOR_ALL_VEHICLES(v) {
01039       if (v->owner == _current_company) v->InvalidateNewGRFCache();
01040     }
01041 
01042     extern void UpdateObjectColours(const Company *c);
01043     UpdateObjectColours(c);
01044   }
01045   return CommandCost();
01046 }
01047 
01053 static bool IsUniqueCompanyName(const char *name)
01054 {
01055   const Company *c;
01056 
01057   FOR_ALL_COMPANIES(c) {
01058     if (c->name != NULL && strcmp(c->name, name) == 0) return false;
01059   }
01060 
01061   return true;
01062 }
01063 
01073 CommandCost CmdRenameCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01074 {
01075   bool reset = StrEmpty(text);
01076 
01077   if (!reset) {
01078     if (Utf8StringLength(text) >= MAX_LENGTH_COMPANY_NAME_CHARS) return CMD_ERROR;
01079     if (!IsUniqueCompanyName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
01080   }
01081 
01082   if (flags & DC_EXEC) {
01083     Company *c = Company::Get(_current_company);
01084     free(c->name);
01085     c->name = reset ? NULL : strdup(text);
01086     MarkWholeScreenDirty();
01087     CompanyAdminUpdate(c);
01088   }
01089 
01090   return CommandCost();
01091 }
01092 
01098 static bool IsUniquePresidentName(const char *name)
01099 {
01100   const Company *c;
01101 
01102   FOR_ALL_COMPANIES(c) {
01103     if (c->president_name != NULL && strcmp(c->president_name, name) == 0) return false;
01104   }
01105 
01106   return true;
01107 }
01108 
01118 CommandCost CmdRenamePresident(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01119 {
01120   bool reset = StrEmpty(text);
01121 
01122   if (!reset) {
01123     if (Utf8StringLength(text) >= MAX_LENGTH_PRESIDENT_NAME_CHARS) return CMD_ERROR;
01124     if (!IsUniquePresidentName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
01125   }
01126 
01127   if (flags & DC_EXEC) {
01128     Company *c = Company::Get(_current_company);
01129     free(c->president_name);
01130 
01131     if (reset) {
01132       c->president_name = NULL;
01133     } else {
01134       c->president_name = strdup(text);
01135 
01136       if (c->name_1 == STR_SV_UNNAMED && c->name == NULL) {
01137         char buf[80];
01138 
01139         snprintf(buf, lengthof(buf), "%s Transport", text);
01140         DoCommand(0, 0, 0, DC_EXEC, CMD_RENAME_COMPANY, buf);
01141       }
01142     }
01143 
01144     MarkWholeScreenDirty();
01145     CompanyAdminUpdate(c);
01146   }
01147 
01148   return CommandCost();
01149 }