engine.cpp

Go to the documentation of this file.
00001 /* $Id: engine.cpp 25560 2013-07-04 21:20:05Z rubidium $ */
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_func.h"
00014 #include "command_func.h"
00015 #include "news_func.h"
00016 #include "aircraft.h"
00017 #include "newgrf.h"
00018 #include "newgrf_engine.h"
00019 #include "strings_func.h"
00020 #include "core/random_func.hpp"
00021 #include "window_func.h"
00022 #include "date_func.h"
00023 #include "autoreplace_gui.h"
00024 #include "string_func.h"
00025 #include "ai/ai.hpp"
00026 #include "core/pool_func.hpp"
00027 #include "engine_gui.h"
00028 #include "engine_func.h"
00029 #include "engine_base.h"
00030 #include "company_base.h"
00031 #include "vehicle_func.h"
00032 #include "articulated_vehicles.h"
00033 #include "error.h"
00034 
00035 #include "table/strings.h"
00036 #include "table/engines.h"
00037 
00038 EnginePool _engine_pool("Engine");
00039 INSTANTIATE_POOL_METHODS(Engine)
00040 
00041 EngineOverrideManager _engine_mngr;
00042 
00047 static Year _year_engine_aging_stops;
00048 
00052 static uint16 _introduced_railtypes;
00053 
00055 const uint8 _engine_counts[4] = {
00056   lengthof(_orig_rail_vehicle_info),
00057   lengthof(_orig_road_vehicle_info),
00058   lengthof(_orig_ship_vehicle_info),
00059   lengthof(_orig_aircraft_vehicle_info),
00060 };
00061 
00063 const uint8 _engine_offsets[4] = {
00064   0,
00065   lengthof(_orig_rail_vehicle_info),
00066   lengthof(_orig_rail_vehicle_info) + lengthof(_orig_road_vehicle_info),
00067   lengthof(_orig_rail_vehicle_info) + lengthof(_orig_road_vehicle_info) + lengthof(_orig_ship_vehicle_info),
00068 };
00069 
00070 assert_compile(lengthof(_orig_rail_vehicle_info) + lengthof(_orig_road_vehicle_info) + lengthof(_orig_ship_vehicle_info) + lengthof(_orig_aircraft_vehicle_info) == lengthof(_orig_engine_info));
00071 
00072 const uint EngineOverrideManager::NUM_DEFAULT_ENGINES = _engine_counts[VEH_TRAIN] + _engine_counts[VEH_ROAD] + _engine_counts[VEH_SHIP] + _engine_counts[VEH_AIRCRAFT];
00073 
00074 Engine::Engine() :
00075   name(NULL),
00076   overrides_count(0),
00077   overrides(NULL)
00078 {
00079 }
00080 
00081 Engine::Engine(VehicleType type, EngineID base)
00082 {
00083   this->type = type;
00084   this->grf_prop.local_id = base;
00085   this->list_position = base;
00086 
00087   /* Check if this base engine is within the original engine data range */
00088   if (base >= _engine_counts[type]) {
00089     /* Set model life to maximum to make wagons available */
00090     this->info.base_life = 0xFF;
00091     /* Set road vehicle tractive effort to the default value */
00092     if (type == VEH_ROAD) this->u.road.tractive_effort = 0x4C;
00093     /* Aircraft must have CT_INVALID as default, as there is no property */
00094     if (type == VEH_AIRCRAFT) this->info.cargo_type = CT_INVALID;
00095     /* Set visual effect to the default value */
00096     switch (type) {
00097       case VEH_TRAIN: this->u.rail.visual_effect = VE_DEFAULT; break;
00098       case VEH_ROAD:  this->u.road.visual_effect = VE_DEFAULT; break;
00099       case VEH_SHIP:  this->u.ship.visual_effect = VE_DEFAULT; break;
00100       default: break; // The aircraft, disasters and especially visual effects have no NewGRF configured visual effects
00101     }
00102     /* Set cargo aging period to the default value. */
00103     this->info.cargo_age_period = CARGO_AGING_TICKS;
00104     return;
00105   }
00106 
00107   /* Copy the original engine info for this slot */
00108   this->info = _orig_engine_info[_engine_offsets[type] + base];
00109 
00110   /* Copy the original engine data for this slot */
00111   switch (type) {
00112     default: NOT_REACHED();
00113 
00114     case VEH_TRAIN:
00115       this->u.rail = _orig_rail_vehicle_info[base];
00116       this->original_image_index = this->u.rail.image_index;
00117       this->info.string_id = STR_VEHICLE_NAME_TRAIN_ENGINE_RAIL_KIRBY_PAUL_TANK_STEAM + base;
00118 
00119       /* Set the default model life of original wagons to "infinite" */
00120       if (this->u.rail.railveh_type == RAILVEH_WAGON) this->info.base_life = 0xFF;
00121 
00122       break;
00123 
00124     case VEH_ROAD:
00125       this->u.road = _orig_road_vehicle_info[base];
00126       this->original_image_index = this->u.road.image_index;
00127       this->info.string_id = STR_VEHICLE_NAME_ROAD_VEHICLE_MPS_REGAL_BUS + base;
00128       break;
00129 
00130     case VEH_SHIP:
00131       this->u.ship = _orig_ship_vehicle_info[base];
00132       this->original_image_index = this->u.ship.image_index;
00133       this->info.string_id = STR_VEHICLE_NAME_SHIP_MPS_OIL_TANKER + base;
00134       break;
00135 
00136     case VEH_AIRCRAFT:
00137       this->u.air = _orig_aircraft_vehicle_info[base];
00138       this->original_image_index = this->u.air.image_index;
00139       this->info.string_id = STR_VEHICLE_NAME_AIRCRAFT_SAMPSON_U52 + base;
00140       break;
00141   }
00142 }
00143 
00144 Engine::~Engine()
00145 {
00146   UnloadWagonOverrides(this);
00147   free(this->name);
00148 }
00149 
00154 bool Engine::IsEnabled() const
00155 {
00156   return this->info.string_id != STR_NEWGRF_INVALID_ENGINE && HasBit(this->info.climates, _settings_game.game_creation.landscape);
00157 }
00158 
00164 uint32 Engine::GetGRFID() const
00165 {
00166   const GRFFile *file = this->GetGRF();
00167   return file == NULL ? 0 : file->grfid;
00168 }
00169 
00175 bool Engine::CanCarryCargo() const
00176 {
00177   /* For engines that can appear in a consist (i.e. rail vehicles and (articulated) road vehicles), a capacity
00178    * of zero is a special case, to define the vehicle to not carry anything. The default cargotype is still used
00179    * for livery selection etc.
00180    * Note: Only the property is tested. A capacity callback returning 0 does not have the same effect.
00181    */
00182   switch (this->type) {
00183     case VEH_TRAIN:
00184       if (this->u.rail.capacity == 0) return false;
00185       break;
00186 
00187     case VEH_ROAD:
00188       if (this->u.road.capacity == 0) return false;
00189       break;
00190 
00191     case VEH_SHIP:
00192     case VEH_AIRCRAFT:
00193       break;
00194 
00195     default: NOT_REACHED();
00196   }
00197   return this->GetDefaultCargoType() != CT_INVALID;
00198 }
00199 
00200 
00208 uint Engine::DetermineCapacity(const Vehicle *v, uint16 *mail_capacity) const
00209 {
00210   assert(v == NULL || this->index == v->engine_type);
00211   if (mail_capacity != NULL) *mail_capacity = 0;
00212 
00213   if (!this->CanCarryCargo()) return 0;
00214 
00215   bool new_multipliers = HasBit(this->info.misc_flags, EF_NO_DEFAULT_CARGO_MULTIPLIER);
00216   CargoID default_cargo = this->GetDefaultCargoType();
00217   CargoID cargo_type = (v != NULL) ? v->cargo_type : default_cargo;
00218 
00219   if (mail_capacity != NULL && this->type == VEH_AIRCRAFT && IsCargoInClass(cargo_type, CC_PASSENGERS)) {
00220     *mail_capacity = GetEngineProperty(this->index, PROP_AIRCRAFT_MAIL_CAPACITY, this->u.air.mail_capacity, v);
00221   }
00222 
00223   /* Check the refit capacity callback if we are not in the default configuration, or if we are using the new multiplier algorithm. */
00224   if (HasBit(this->info.callback_mask, CBM_VEHICLE_REFIT_CAPACITY) &&
00225       (new_multipliers || default_cargo != cargo_type || (v != NULL && v->cargo_subtype != 0))) {
00226     uint16 callback = GetVehicleCallback(CBID_VEHICLE_REFIT_CAPACITY, 0, 0, this->index, v);
00227     if (callback != CALLBACK_FAILED) return callback;
00228   }
00229 
00230   /* Get capacity according to property resp. CB */
00231   uint capacity;
00232   uint extra_mail_cap = 0;
00233   switch (this->type) {
00234     case VEH_TRAIN:
00235       capacity = GetEngineProperty(this->index, PROP_TRAIN_CARGO_CAPACITY,        this->u.rail.capacity, v);
00236 
00237       /* In purchase list add the capacity of the second head. Always use the plain property for this. */
00238       if (v == NULL && this->u.rail.railveh_type == RAILVEH_MULTIHEAD) capacity += this->u.rail.capacity;
00239       break;
00240 
00241     case VEH_ROAD:
00242       capacity = GetEngineProperty(this->index, PROP_ROADVEH_CARGO_CAPACITY,      this->u.road.capacity, v);
00243       break;
00244 
00245     case VEH_SHIP:
00246       capacity = GetEngineProperty(this->index, PROP_SHIP_CARGO_CAPACITY,         this->u.ship.capacity, v);
00247       break;
00248 
00249     case VEH_AIRCRAFT:
00250       capacity = GetEngineProperty(this->index, PROP_AIRCRAFT_PASSENGER_CAPACITY, this->u.air.passenger_capacity, v);
00251       if (!IsCargoInClass(cargo_type, CC_PASSENGERS)) {
00252         extra_mail_cap = GetEngineProperty(this->index, PROP_AIRCRAFT_MAIL_CAPACITY, this->u.air.mail_capacity, v);
00253       }
00254       if (!new_multipliers && cargo_type == CT_MAIL) return capacity + extra_mail_cap;
00255       default_cargo = CT_PASSENGERS; // Always use 'passengers' wrt. cargo multipliers
00256       break;
00257 
00258     default: NOT_REACHED();
00259   }
00260 
00261   if (!new_multipliers) {
00262     /* Use the passenger multiplier for mail as well */
00263     capacity += extra_mail_cap;
00264     extra_mail_cap = 0;
00265   }
00266 
00267   /* Apply multipliers depending on cargo- and vehicletype. */
00268   if (new_multipliers || (this->type != VEH_SHIP && default_cargo != cargo_type)) {
00269     uint16 default_multiplier = new_multipliers ? 0x100 : CargoSpec::Get(default_cargo)->multiplier;
00270     uint16 cargo_multiplier = CargoSpec::Get(cargo_type)->multiplier;
00271     capacity *= cargo_multiplier;
00272     if (extra_mail_cap > 0) {
00273       uint mail_multiplier = CargoSpec::Get(CT_MAIL)->multiplier;
00274       capacity += (default_multiplier * extra_mail_cap * cargo_multiplier + mail_multiplier / 2) / mail_multiplier;
00275     }
00276     capacity = (capacity + default_multiplier / 2) / default_multiplier;
00277   }
00278 
00279   return capacity;
00280 }
00281 
00286 Money Engine::GetRunningCost() const
00287 {
00288   Price base_price;
00289   uint cost_factor;
00290   switch (this->type) {
00291     case VEH_ROAD:
00292       base_price = this->u.road.running_cost_class;
00293       if (base_price == INVALID_PRICE) return 0;
00294       cost_factor = GetEngineProperty(this->index, PROP_ROADVEH_RUNNING_COST_FACTOR, this->u.road.running_cost);
00295       break;
00296 
00297     case VEH_TRAIN:
00298       base_price = this->u.rail.running_cost_class;
00299       if (base_price == INVALID_PRICE) return 0;
00300       cost_factor = GetEngineProperty(this->index, PROP_TRAIN_RUNNING_COST_FACTOR, this->u.rail.running_cost);
00301       break;
00302 
00303     case VEH_SHIP:
00304       base_price = PR_RUNNING_SHIP;
00305       cost_factor = GetEngineProperty(this->index, PROP_SHIP_RUNNING_COST_FACTOR, this->u.ship.running_cost);
00306       break;
00307 
00308     case VEH_AIRCRAFT:
00309       base_price = PR_RUNNING_AIRCRAFT;
00310       cost_factor = GetEngineProperty(this->index, PROP_AIRCRAFT_RUNNING_COST_FACTOR, this->u.air.running_cost);
00311       break;
00312 
00313     default: NOT_REACHED();
00314   }
00315 
00316   return GetPrice(base_price, cost_factor, this->GetGRF(), -8);
00317 }
00318 
00323 Money Engine::GetCost() const
00324 {
00325   Price base_price;
00326   uint cost_factor;
00327   switch (this->type) {
00328     case VEH_ROAD:
00329       base_price = PR_BUILD_VEHICLE_ROAD;
00330       cost_factor = GetEngineProperty(this->index, PROP_ROADVEH_COST_FACTOR, this->u.road.cost_factor);
00331       break;
00332 
00333     case VEH_TRAIN:
00334       if (this->u.rail.railveh_type == RAILVEH_WAGON) {
00335         base_price = PR_BUILD_VEHICLE_WAGON;
00336         cost_factor = GetEngineProperty(this->index, PROP_TRAIN_COST_FACTOR, this->u.rail.cost_factor);
00337       } else {
00338         base_price = PR_BUILD_VEHICLE_TRAIN;
00339         cost_factor = GetEngineProperty(this->index, PROP_TRAIN_COST_FACTOR, this->u.rail.cost_factor);
00340       }
00341       break;
00342 
00343     case VEH_SHIP:
00344       base_price = PR_BUILD_VEHICLE_SHIP;
00345       cost_factor = GetEngineProperty(this->index, PROP_SHIP_COST_FACTOR, this->u.ship.cost_factor);
00346       break;
00347 
00348     case VEH_AIRCRAFT:
00349       base_price = PR_BUILD_VEHICLE_AIRCRAFT;
00350       cost_factor = GetEngineProperty(this->index, PROP_AIRCRAFT_COST_FACTOR, this->u.air.cost_factor);
00351       break;
00352 
00353     default: NOT_REACHED();
00354   }
00355 
00356   return GetPrice(base_price, cost_factor, this->GetGRF(), -8);
00357 }
00358 
00363 uint Engine::GetDisplayMaxSpeed() const
00364 {
00365   switch (this->type) {
00366     case VEH_TRAIN:
00367       return GetEngineProperty(this->index, PROP_TRAIN_SPEED, this->u.rail.max_speed);
00368 
00369     case VEH_ROAD: {
00370       uint max_speed = GetEngineProperty(this->index, PROP_ROADVEH_SPEED, 0);
00371       return (max_speed != 0) ? max_speed * 2 : this->u.road.max_speed / 2;
00372     }
00373 
00374     case VEH_SHIP:
00375       return GetEngineProperty(this->index, PROP_SHIP_SPEED, this->u.ship.max_speed) / 2;
00376 
00377     case VEH_AIRCRAFT: {
00378       uint max_speed = GetEngineProperty(this->index, PROP_AIRCRAFT_SPEED, 0);
00379       if (max_speed != 0) {
00380         return (max_speed * 128) / 10;
00381       }
00382       return this->u.air.max_speed;
00383     }
00384 
00385     default: NOT_REACHED();
00386   }
00387 }
00388 
00395 uint Engine::GetPower() const
00396 {
00397   /* Only trains and road vehicles have 'power'. */
00398   switch (this->type) {
00399     case VEH_TRAIN:
00400       return GetEngineProperty(this->index, PROP_TRAIN_POWER, this->u.rail.power);
00401     case VEH_ROAD:
00402       return GetEngineProperty(this->index, PROP_ROADVEH_POWER, this->u.road.power) * 10;
00403 
00404     default: NOT_REACHED();
00405   }
00406 }
00407 
00413 uint Engine::GetDisplayWeight() const
00414 {
00415   /* Only trains and road vehicles have 'weight'. */
00416   switch (this->type) {
00417     case VEH_TRAIN:
00418       return GetEngineProperty(this->index, PROP_TRAIN_WEIGHT, this->u.rail.weight) << (this->u.rail.railveh_type == RAILVEH_MULTIHEAD ? 1 : 0);
00419     case VEH_ROAD:
00420       return GetEngineProperty(this->index, PROP_ROADVEH_WEIGHT, this->u.road.weight) / 4;
00421 
00422     default: NOT_REACHED();
00423   }
00424 }
00425 
00431 uint Engine::GetDisplayMaxTractiveEffort() const
00432 {
00433   /* Only trains and road vehicles have 'tractive effort'. */
00434   switch (this->type) {
00435     case VEH_TRAIN:
00436       return (10 * this->GetDisplayWeight() * GetEngineProperty(this->index, PROP_TRAIN_TRACTIVE_EFFORT, this->u.rail.tractive_effort)) / 256;
00437     case VEH_ROAD:
00438       return (10 * this->GetDisplayWeight() * GetEngineProperty(this->index, PROP_ROADVEH_TRACTIVE_EFFORT, this->u.road.tractive_effort)) / 256;
00439 
00440     default: NOT_REACHED();
00441   }
00442 }
00443 
00448 Date Engine::GetLifeLengthInDays() const
00449 {
00450   /* Assume leap years; this gives the player a bit more than the given amount of years, but never less. */
00451   return (this->info.lifelength + _settings_game.vehicle.extend_vehicle_life) * DAYS_IN_LEAP_YEAR;
00452 }
00453 
00458 uint16 Engine::GetRange() const
00459 {
00460   switch (this->type) {
00461     case VEH_AIRCRAFT:
00462       return GetEngineProperty(this->index, PROP_AIRCRAFT_RANGE, this->u.air.max_range);
00463 
00464     default: NOT_REACHED();
00465   }
00466 }
00467 
00471 void EngineOverrideManager::ResetToDefaultMapping()
00472 {
00473   this->Clear();
00474   for (VehicleType type = VEH_TRAIN; type <= VEH_AIRCRAFT; type++) {
00475     for (uint internal_id = 0; internal_id < _engine_counts[type]; internal_id++) {
00476       EngineIDMapping *eid = this->Append();
00477       eid->type            = type;
00478       eid->grfid           = INVALID_GRFID;
00479       eid->internal_id     = internal_id;
00480       eid->substitute_id   = internal_id;
00481     }
00482   }
00483 }
00484 
00494 EngineID EngineOverrideManager::GetID(VehicleType type, uint16 grf_local_id, uint32 grfid)
00495 {
00496   const EngineIDMapping *end = this->End();
00497   EngineID index = 0;
00498   for (const EngineIDMapping *eid = this->Begin(); eid != end; eid++, index++) {
00499     if (eid->type == type && eid->grfid == grfid && eid->internal_id == grf_local_id) {
00500       return index;
00501     }
00502   }
00503   return INVALID_ENGINE;
00504 }
00505 
00511 bool EngineOverrideManager::ResetToCurrentNewGRFConfig()
00512 {
00513   const Vehicle *v;
00514   FOR_ALL_VEHICLES(v) {
00515     if (IsCompanyBuildableVehicleType(v)) return false;
00516   }
00517 
00518   /* Reset the engines, they will get new EngineIDs */
00519   _engine_mngr.ResetToDefaultMapping();
00520   ReloadNewGRFData();
00521 
00522   return true;
00523 }
00524 
00528 void SetupEngines()
00529 {
00530   DeleteWindowByClass(WC_ENGINE_PREVIEW);
00531   _engine_pool.CleanPool();
00532 
00533   assert(_engine_mngr.Length() >= _engine_mngr.NUM_DEFAULT_ENGINES);
00534   const EngineIDMapping *end = _engine_mngr.End();
00535   uint index = 0;
00536   for (const EngineIDMapping *eid = _engine_mngr.Begin(); eid != end; eid++, index++) {
00537     /* Assert is safe; there won't be more than 256 original vehicles
00538      * in any case, and we just cleaned the pool. */
00539     assert(Engine::CanAllocateItem());
00540     const Engine *e = new Engine(eid->type, eid->internal_id);
00541     assert(e->index == index);
00542   }
00543 
00544   _introduced_railtypes = 0;
00545 }
00546 
00550 static void CheckRailIntroduction()
00551 {
00552   /* All railtypes have been introduced. */
00553   if (_introduced_railtypes == UINT16_MAX || Company::GetPoolSize() == 0) return;
00554 
00555   /* We need to find the railtypes that are known to all companies. */
00556   RailTypes rts = (RailTypes)UINT16_MAX;
00557 
00558   /* We are at, or past the introduction date of the rail. */
00559   Company *c;
00560   FOR_ALL_COMPANIES(c) {
00561     c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes, _date);
00562     rts &= c->avail_railtypes;
00563   }
00564 
00565   _introduced_railtypes |= rts;
00566 }
00567 
00568 void ShowEnginePreviewWindow(EngineID engine);
00569 
00575 static bool IsWagon(EngineID index)
00576 {
00577   const Engine *e = Engine::Get(index);
00578   return e->type == VEH_TRAIN && e->u.rail.railveh_type == RAILVEH_WAGON;
00579 }
00580 
00585 static void CalcEngineReliability(Engine *e)
00586 {
00587   uint age = e->age;
00588 
00589   /* Check for early retirement */
00590   if (e->company_avail != 0 && !_settings_game.vehicle.never_expire_vehicles && e->info.base_life != 0xFF) {
00591     int retire_early = e->info.retire_early;
00592     uint retire_early_max_age = max(0, e->duration_phase_1 + e->duration_phase_2 - retire_early * 12);
00593     if (retire_early != 0 && age >= retire_early_max_age) {
00594       /* Early retirement is enabled and we're past the date... */
00595       e->company_avail = 0;
00596       AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
00597     }
00598   }
00599 
00600   if (age < e->duration_phase_1) {
00601     uint start = e->reliability_start;
00602     e->reliability = age * (e->reliability_max - start) / e->duration_phase_1 + start;
00603   } else if ((age -= e->duration_phase_1) < e->duration_phase_2 || _settings_game.vehicle.never_expire_vehicles || e->info.base_life == 0xFF) {
00604     /* We are at the peak of this engines life. It will have max reliability.
00605      * This is also true if the engines never expire. They will not go bad over time */
00606     e->reliability = e->reliability_max;
00607   } else if ((age -= e->duration_phase_2) < e->duration_phase_3) {
00608     uint max = e->reliability_max;
00609     e->reliability = (int)age * (int)(e->reliability_final - max) / e->duration_phase_3 + max;
00610   } else {
00611     /* time's up for this engine.
00612      * We will now completely retire this design */
00613     e->company_avail = 0;
00614     e->reliability = e->reliability_final;
00615     /* Kick this engine out of the lists */
00616     AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
00617   }
00618   SetWindowClassesDirty(WC_BUILD_VEHICLE); // Update to show the new reliability
00619   SetWindowClassesDirty(WC_REPLACE_VEHICLE);
00620 }
00621 
00623 void SetYearEngineAgingStops()
00624 {
00625   /* Determine last engine aging year, default to 2050 as previously. */
00626   _year_engine_aging_stops = 2050;
00627 
00628   const Engine *e;
00629   FOR_ALL_ENGINES(e) {
00630     const EngineInfo *ei = &e->info;
00631 
00632     /* Exclude certain engines */
00633     if (!HasBit(ei->climates, _settings_game.game_creation.landscape)) continue;
00634     if (e->type == VEH_TRAIN && e->u.rail.railveh_type == RAILVEH_WAGON) continue;
00635 
00636     /* Base year ending date on half the model life */
00637     YearMonthDay ymd;
00638     ConvertDateToYMD(ei->base_intro + (ei->lifelength * DAYS_IN_LEAP_YEAR) / 2, &ymd);
00639 
00640     _year_engine_aging_stops = max(_year_engine_aging_stops, ymd.year);
00641   }
00642 }
00643 
00649 void StartupOneEngine(Engine *e, Date aging_date)
00650 {
00651   const EngineInfo *ei = &e->info;
00652 
00653   e->age = 0;
00654   e->flags = 0;
00655   e->company_avail = 0;
00656 
00657   /* Don't randomise the start-date in the first two years after gamestart to ensure availability
00658    * of engines in early starting games.
00659    * Note: TTDP uses fixed 1922 */
00660   uint32 r = Random();
00661   e->intro_date = ei->base_intro <= ConvertYMDToDate(_settings_game.game_creation.starting_year + 2, 0, 1) ? ei->base_intro : (Date)GB(r, 0, 9) + ei->base_intro;
00662   if (e->intro_date <= _date) {
00663     e->age = (aging_date - e->intro_date) >> 5;
00664     e->company_avail = (CompanyMask)-1;
00665     e->flags |= ENGINE_AVAILABLE;
00666   }
00667 
00668   e->reliability_start = GB(r, 16, 14) + 0x7AE0;
00669   r = Random();
00670   e->reliability_max   = GB(r,  0, 14) + 0xBFFF;
00671   e->reliability_final = GB(r, 16, 14) + 0x3FFF;
00672 
00673   r = Random();
00674   e->duration_phase_1 = GB(r, 0, 5) + 7;
00675   e->duration_phase_2 = GB(r, 5, 4) + ei->base_life * 12 - 96;
00676   e->duration_phase_3 = GB(r, 9, 7) + 120;
00677 
00678   e->reliability_spd_dec = ei->decay_speed << 2;
00679 
00680   CalcEngineReliability(e);
00681 
00682   /* prevent certain engines from ever appearing. */
00683   if (!HasBit(ei->climates, _settings_game.game_creation.landscape)) {
00684     e->flags |= ENGINE_AVAILABLE;
00685     e->company_avail = 0;
00686   }
00687 }
00688 
00693 void StartupEngines()
00694 {
00695   Engine *e;
00696   /* Aging of vehicles stops, so account for that when starting late */
00697   const Date aging_date = min(_date, ConvertYMDToDate(_year_engine_aging_stops, 0, 1));
00698 
00699   FOR_ALL_ENGINES(e) {
00700     StartupOneEngine(e, aging_date);
00701   }
00702 
00703   /* Update the bitmasks for the vehicle lists */
00704   Company *c;
00705   FOR_ALL_COMPANIES(c) {
00706     c->avail_railtypes = GetCompanyRailtypes(c->index);
00707     c->avail_roadtypes = GetCompanyRoadtypes(c->index);
00708   }
00709 
00710   /* Rail types that are invalid or never introduced are marked as
00711    * being introduced upon start. That way we can easily check whether
00712    * there is any date related introduction that is still going to
00713    * happen somewhere in the future. */
00714   for (RailType rt = RAILTYPE_BEGIN; rt != RAILTYPE_END; rt++) {
00715     const RailtypeInfo *rti = GetRailTypeInfo(rt);
00716     if (rti->label != 0 && IsInsideMM(rti->introduction_date, 0, MAX_DAY)) continue;
00717 
00718     SetBit(_introduced_railtypes, rt);
00719   }
00720 
00721   CheckRailIntroduction();
00722 
00723   /* Invalidate any open purchase lists */
00724   InvalidateWindowClassesData(WC_BUILD_VEHICLE);
00725 }
00726 
00732 static void AcceptEnginePreview(EngineID eid, CompanyID company)
00733 {
00734   Engine *e = Engine::Get(eid);
00735   Company *c = Company::Get(company);
00736 
00737   SetBit(e->company_avail, company);
00738   if (e->type == VEH_TRAIN) {
00739     assert(e->u.rail.railtype < RAILTYPE_END);
00740     c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes | GetRailTypeInfo(e->u.rail.railtype)->introduces_railtypes, _date);
00741   } else if (e->type == VEH_ROAD) {
00742     SetBit(c->avail_roadtypes, HasBit(e->info.misc_flags, EF_ROAD_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD);
00743   }
00744 
00745   e->preview_company = INVALID_COMPANY;
00746   e->preview_asked = (CompanyMask)-1;
00747   if (company == _local_company) {
00748     AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
00749   }
00750 
00751   /* Update the toolbar. */
00752   if (e->type == VEH_ROAD) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_ROAD);
00753   if (e->type == VEH_SHIP) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_WATER);
00754 
00755   /* Notify preview window, that it might want to close.
00756    * Note: We cannot directly close the window.
00757    *       In singleplayer this function is called from the preview window, so
00758    *       we have to use the GUI-scope scheduling of InvalidateWindowData.
00759    */
00760   InvalidateWindowData(WC_ENGINE_PREVIEW, eid);
00761 }
00762 
00768 static CompanyID GetPreviewCompany(Engine *e)
00769 {
00770   CompanyID best_company = INVALID_COMPANY;
00771 
00772   /* For trains the cargomask has no useful meaning, since you can attach other wagons */
00773   uint32 cargomask = e->type != VEH_TRAIN ? GetUnionOfArticulatedRefitMasks(e->index, true) : (uint32)-1;
00774 
00775   int32 best_hist = -1;
00776   const Company *c;
00777   FOR_ALL_COMPANIES(c) {
00778     if (c->block_preview == 0 && !HasBit(e->preview_asked, c->index) &&
00779         c->old_economy[0].performance_history > best_hist) {
00780 
00781       /* Check whether the company uses similar vehicles */
00782       Vehicle *v;
00783       FOR_ALL_VEHICLES(v) {
00784         if (v->owner != c->index || v->type != e->type) continue;
00785         if (!v->GetEngine()->CanCarryCargo() || !HasBit(cargomask, v->cargo_type)) continue;
00786 
00787         best_hist = c->old_economy[0].performance_history;
00788         best_company = c->index;
00789         break;
00790       }
00791     }
00792   }
00793 
00794   return best_company;
00795 }
00796 
00804 static bool IsVehicleTypeDisabled(VehicleType type, bool ai)
00805 {
00806   switch (type) {
00807     case VEH_TRAIN:    return _settings_game.vehicle.max_trains == 0   || (ai && _settings_game.ai.ai_disable_veh_train);
00808     case VEH_ROAD:     return _settings_game.vehicle.max_roadveh == 0  || (ai && _settings_game.ai.ai_disable_veh_roadveh);
00809     case VEH_SHIP:     return _settings_game.vehicle.max_ships == 0    || (ai && _settings_game.ai.ai_disable_veh_ship);
00810     case VEH_AIRCRAFT: return _settings_game.vehicle.max_aircraft == 0 || (ai && _settings_game.ai.ai_disable_veh_aircraft);
00811 
00812     default: NOT_REACHED();
00813   }
00814 }
00815 
00817 void EnginesDailyLoop()
00818 {
00819   CheckRailIntroduction();
00820 
00821   if (_cur_year >= _year_engine_aging_stops) return;
00822 
00823   Engine *e;
00824   FOR_ALL_ENGINES(e) {
00825     EngineID i = e->index;
00826     if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) {
00827       if (e->preview_company != INVALID_COMPANY) {
00828         if (!--e->preview_wait) {
00829           DeleteWindowById(WC_ENGINE_PREVIEW, i);
00830           e->preview_company = INVALID_COMPANY;
00831         }
00832       } else if (CountBits(e->preview_asked) < MAX_COMPANIES) {
00833         e->preview_company = GetPreviewCompany(e);
00834 
00835         if (e->preview_company == INVALID_COMPANY) {
00836           e->preview_asked = (CompanyMask)-1;
00837           continue;
00838         }
00839 
00840         SetBit(e->preview_asked, e->preview_company);
00841         e->preview_wait = 20;
00842         /* AIs are intentionally not skipped for preview even if they cannot build a certain
00843          * vehicle type. This is done to not give poor performing human companies an "unfair"
00844          * boost that they wouldn't have gotten against other human companies. The check on
00845          * the line below is just to make AIs not notice that they have a preview if they
00846          * cannot build the vehicle. */
00847         if (!IsVehicleTypeDisabled(e->type, true)) AI::NewEvent(e->preview_company, new ScriptEventEnginePreview(i));
00848         if (IsInteractiveCompany(e->preview_company)) ShowEnginePreviewWindow(i);
00849       }
00850     }
00851   }
00852 }
00853 
00864 CommandCost CmdWantEnginePreview(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00865 {
00866   Engine *e = Engine::GetIfValid(p1);
00867   if (e == NULL || e->preview_company != _current_company) return CMD_ERROR;
00868 
00869   if (flags & DC_EXEC) AcceptEnginePreview(p1, _current_company);
00870 
00871   return CommandCost();
00872 }
00873 
00879 static void NewVehicleAvailable(Engine *e)
00880 {
00881   Vehicle *v;
00882   Company *c;
00883   EngineID index = e->index;
00884 
00885   /* In case the company didn't build the vehicle during the intro period,
00886    * prevent that company from getting future intro periods for a while. */
00887   if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) {
00888     FOR_ALL_COMPANIES(c) {
00889       uint block_preview = c->block_preview;
00890 
00891       if (!HasBit(e->company_avail, c->index)) continue;
00892 
00893       /* We assume the user did NOT build it.. prove me wrong ;) */
00894       c->block_preview = 20;
00895 
00896       FOR_ALL_VEHICLES(v) {
00897         if (v->type == VEH_TRAIN || v->type == VEH_ROAD || v->type == VEH_SHIP ||
00898             (v->type == VEH_AIRCRAFT && Aircraft::From(v)->IsNormalAircraft())) {
00899           if (v->owner == c->index && v->engine_type == index) {
00900             /* The user did prove me wrong, so restore old value */
00901             c->block_preview = block_preview;
00902             break;
00903           }
00904         }
00905       }
00906     }
00907   }
00908 
00909   e->flags = (e->flags & ~ENGINE_EXCLUSIVE_PREVIEW) | ENGINE_AVAILABLE;
00910   AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
00911 
00912   /* Now available for all companies */
00913   e->company_avail = (CompanyMask)-1;
00914 
00915   /* Do not introduce new rail wagons */
00916   if (IsWagon(index)) return;
00917 
00918   if (e->type == VEH_TRAIN) {
00919     /* maybe make another rail type available */
00920     RailType railtype = e->u.rail.railtype;
00921     assert(railtype < RAILTYPE_END);
00922     FOR_ALL_COMPANIES(c) c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes | GetRailTypeInfo(e->u.rail.railtype)->introduces_railtypes, _date);
00923   } else if (e->type == VEH_ROAD) {
00924     /* maybe make another road type available */
00925     FOR_ALL_COMPANIES(c) SetBit(c->avail_roadtypes, HasBit(e->info.misc_flags, EF_ROAD_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD);
00926   }
00927 
00928   /* Only broadcast event if AIs are able to build this vehicle type. */
00929   if (!IsVehicleTypeDisabled(e->type, true)) AI::BroadcastNewEvent(new ScriptEventEngineAvailable(index));
00930 
00931   /* Only provide the "New Vehicle available" news paper entry, if engine can be built. */
00932   if (!IsVehicleTypeDisabled(e->type, false)) {
00933     SetDParam(0, GetEngineCategoryName(index));
00934     SetDParam(1, index);
00935     AddNewsItem(STR_NEWS_NEW_VEHICLE_NOW_AVAILABLE_WITH_TYPE, NT_NEW_VEHICLES, NF_VEHICLE, NR_ENGINE, index);
00936   }
00937 
00938   /* Update the toolbar. */
00939   if (e->type == VEH_ROAD) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_ROAD);
00940   if (e->type == VEH_SHIP) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_WATER);
00941 
00942   /* Close pending preview windows */
00943   DeleteWindowById(WC_ENGINE_PREVIEW, index);
00944 }
00945 
00947 void EnginesMonthlyLoop()
00948 {
00949   if (_cur_year < _year_engine_aging_stops) {
00950     Engine *e;
00951     FOR_ALL_ENGINES(e) {
00952       /* Age the vehicle */
00953       if ((e->flags & ENGINE_AVAILABLE) && e->age != MAX_DAY) {
00954         e->age++;
00955         CalcEngineReliability(e);
00956       }
00957 
00958       /* Do not introduce invalid engines */
00959       if (!e->IsEnabled()) continue;
00960 
00961       if (!(e->flags & ENGINE_AVAILABLE) && _date >= (e->intro_date + DAYS_IN_YEAR)) {
00962         /* Introduce it to all companies */
00963         NewVehicleAvailable(e);
00964       } else if (!(e->flags & (ENGINE_AVAILABLE | ENGINE_EXCLUSIVE_PREVIEW)) && _date >= e->intro_date) {
00965         /* Introduction date has passed...
00966          * Check if it is allowed to build this vehicle type at all
00967          * based on the current game settings. If not, it does not
00968          * make sense to show the preview dialog to any company. */
00969         if (IsVehicleTypeDisabled(e->type, false)) continue;
00970 
00971         /* Do not introduce new rail wagons */
00972         if (IsWagon(e->index)) continue;
00973 
00974         /* Show preview dialog to one of the companies. */
00975         e->flags |= ENGINE_EXCLUSIVE_PREVIEW;
00976         e->preview_company = INVALID_COMPANY;
00977         e->preview_asked = 0;
00978       }
00979     }
00980 
00981     InvalidateWindowClassesData(WC_BUILD_VEHICLE); // rebuild the purchase list (esp. when sorted by reliability)
00982   }
00983 }
00984 
00990 static bool IsUniqueEngineName(const char *name)
00991 {
00992   const Engine *e;
00993 
00994   FOR_ALL_ENGINES(e) {
00995     if (e->name != NULL && strcmp(e->name, name) == 0) return false;
00996   }
00997 
00998   return true;
00999 }
01000 
01010 CommandCost CmdRenameEngine(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01011 {
01012   Engine *e = Engine::GetIfValid(p1);
01013   if (e == NULL) return CMD_ERROR;
01014 
01015   bool reset = StrEmpty(text);
01016 
01017   if (!reset) {
01018     if (Utf8StringLength(text) >= MAX_LENGTH_ENGINE_NAME_CHARS) return CMD_ERROR;
01019     if (!IsUniqueEngineName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
01020   }
01021 
01022   if (flags & DC_EXEC) {
01023     free(e->name);
01024 
01025     if (reset) {
01026       e->name = NULL;
01027     } else {
01028       e->name = strdup(text);
01029     }
01030 
01031     MarkWholeScreenDirty();
01032   }
01033 
01034   return CommandCost();
01035 }
01036 
01037 
01046 bool IsEngineBuildable(EngineID engine, VehicleType type, CompanyID company)
01047 {
01048   const Engine *e = Engine::GetIfValid(engine);
01049 
01050   /* check if it's an engine that is in the engine array */
01051   if (e == NULL) return false;
01052 
01053   /* check if it's an engine of specified type */
01054   if (e->type != type) return false;
01055 
01056   /* check if it's available ... */
01057   if (company == OWNER_DEITY) {
01058     /* ... for any company (preview does not count) */
01059     if (!(e->flags & ENGINE_AVAILABLE) || e->company_avail == 0) return false;
01060   } else {
01061     /* ... for this company */
01062     if (!HasBit(e->company_avail, company)) return false;
01063   }
01064 
01065   if (!e->IsEnabled()) return false;
01066 
01067   if (type == VEH_TRAIN && company != OWNER_DEITY) {
01068     /* Check if the rail type is available to this company */
01069     const Company *c = Company::Get(company);
01070     if (((GetRailTypeInfo(e->u.rail.railtype))->compatible_railtypes & c->avail_railtypes) == 0) return false;
01071   }
01072 
01073   return true;
01074 }
01075 
01082 bool IsEngineRefittable(EngineID engine)
01083 {
01084   const Engine *e = Engine::GetIfValid(engine);
01085 
01086   /* check if it's an engine that is in the engine array */
01087   if (e == NULL) return false;
01088 
01089   if (!e->CanCarryCargo()) return false;
01090 
01091   const EngineInfo *ei = &e->info;
01092   if (ei->refit_mask == 0) return false;
01093 
01094   /* Are there suffixes?
01095    * Note: This does not mean the suffixes are actually available for every consist at any time. */
01096   if (HasBit(ei->callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) return true;
01097 
01098   /* Is there any cargo except the default cargo? */
01099   CargoID default_cargo = e->GetDefaultCargoType();
01100   return default_cargo != CT_INVALID && ei->refit_mask != 1U << default_cargo;
01101 }
01102 
01106 void CheckEngines()
01107 {
01108   const Engine *e;
01109   Date min_date = INT32_MAX;
01110 
01111   FOR_ALL_ENGINES(e) {
01112     if (!e->IsEnabled()) continue;
01113 
01114     /* We have an available engine... yay! */
01115     if (e->flags & ENGINE_AVAILABLE && e->company_avail != 0) return;
01116 
01117     /* Okay, try to find the earliest date. */
01118     min_date = min(min_date, e->info.base_intro);
01119   }
01120 
01121   SetDParam(0, min_date);
01122   ShowErrorMessage(STR_ERROR_NO_VEHICLES_AVAILABLE, STR_ERROR_NO_VEHICLES_AVAILABLE_EXPLANATION, WL_WARNING);
01123 }