company_cmd.cpp

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