vehicle_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 "roadveh.h"
00014 #include "news_func.h"
00015 #include "airport.h"
00016 #include "cmd_helper.h"
00017 #include "command_func.h"
00018 #include "company_func.h"
00019 #include "train.h"
00020 #include "aircraft.h"
00021 #include "newgrf_text.h"
00022 #include "vehicle_func.h"
00023 #include "string_func.h"
00024 #include "depot_map.h"
00025 #include "vehiclelist.h"
00026 #include "engine_func.h"
00027 #include "articulated_vehicles.h"
00028 #include "autoreplace_gui.h"
00029 #include "group.h"
00030 #include "order_backup.h"
00031 #include "ship.h"
00032 #include "newgrf.h"
00033 #include "company_base.h"
00034 
00035 #include "table/strings.h"
00036 
00037 /* Tables used in vehicle.h to find the right command for a certain vehicle type */
00038 const uint32 _veh_build_proc_table[] = {
00039   CMD_BUILD_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_TRAIN),
00040   CMD_BUILD_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_ROAD_VEHICLE),
00041   CMD_BUILD_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_SHIP),
00042   CMD_BUILD_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_AIRCRAFT),
00043 };
00044 
00045 const uint32 _veh_sell_proc_table[] = {
00046   CMD_SELL_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_SELL_TRAIN),
00047   CMD_SELL_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_SELL_ROAD_VEHICLE),
00048   CMD_SELL_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_SELL_SHIP),
00049   CMD_SELL_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_SELL_AIRCRAFT),
00050 };
00051 
00052 const uint32 _veh_refit_proc_table[] = {
00053   CMD_REFIT_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_REFIT_TRAIN),
00054   CMD_REFIT_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_REFIT_ROAD_VEHICLE),
00055   CMD_REFIT_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_REFIT_SHIP),
00056   CMD_REFIT_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_REFIT_AIRCRAFT),
00057 };
00058 
00059 const uint32 _send_to_depot_proc_table[] = {
00060   CMD_SEND_VEHICLE_TO_DEPOT | CMD_MSG(STR_ERROR_CAN_T_SEND_TRAIN_TO_DEPOT),
00061   CMD_SEND_VEHICLE_TO_DEPOT | CMD_MSG(STR_ERROR_CAN_T_SEND_ROAD_VEHICLE_TO_DEPOT),
00062   CMD_SEND_VEHICLE_TO_DEPOT | CMD_MSG(STR_ERROR_CAN_T_SEND_SHIP_TO_DEPOT),
00063   CMD_SEND_VEHICLE_TO_DEPOT | CMD_MSG(STR_ERROR_CAN_T_SEND_AIRCRAFT_TO_HANGAR),
00064 };
00065 
00066 
00067 CommandCost CmdBuildRailVehicle(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **v);
00068 CommandCost CmdBuildRoadVehicle(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **v);
00069 CommandCost CmdBuildShip       (TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **v);
00070 CommandCost CmdBuildAircraft   (TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **v);
00071 
00083 CommandCost CmdBuildVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00084 {
00085   /* Elementary check for valid location. */
00086   if (!IsDepotTile(tile) || !IsTileOwner(tile, _current_company)) return CMD_ERROR;
00087 
00088   VehicleType type;
00089   switch (GetTileType(tile)) {
00090     case MP_RAILWAY: type = VEH_TRAIN;    break;
00091     case MP_ROAD:    type = VEH_ROAD;     break;
00092     case MP_WATER:   type = VEH_SHIP;     break;
00093     case MP_STATION: type = VEH_AIRCRAFT; break;
00094     default: NOT_REACHED(); // Safe due to IsDepotTile()
00095   }
00096 
00097   /* Validate the engine type. */
00098   EngineID eid = GB(p1, 0, 16);
00099   if (!IsEngineBuildable(eid, type, _current_company)) return_cmd_error(STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE + type);
00100 
00101   const Engine *e = Engine::Get(eid);
00102   CommandCost value(EXPENSES_NEW_VEHICLES, e->GetCost());
00103 
00104   /* Engines without valid cargo should not be available */
00105   if (e->GetDefaultCargoType() == CT_INVALID) return CMD_ERROR;
00106 
00107   /* Check whether the number of vehicles we need to build can be built according to pool space. */
00108   uint num_vehicles;
00109   switch (type) {
00110     case VEH_TRAIN:    num_vehicles = (e->u.rail.railveh_type == RAILVEH_MULTIHEAD ? 2 : 1) + CountArticulatedParts(eid, false); break;
00111     case VEH_ROAD:     num_vehicles = 1 + CountArticulatedParts(eid, false); break;
00112     case VEH_SHIP:     num_vehicles = 1; break;
00113     case VEH_AIRCRAFT: num_vehicles = e->u.air.subtype & AIR_CTOL ? 2 : 3; break;
00114     default: NOT_REACHED(); // Safe due to IsDepotTile()
00115   }
00116   if (!Vehicle::CanAllocateItem(num_vehicles)) return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
00117 
00118   /* Check whether we can allocate a unit number. Autoreplace does not allocate
00119    * an unit number as it will (always) reuse the one of the replaced vehicle
00120    * and (train) wagons don't have an unit number in any scenario. */
00121   UnitID unit_num = (flags & DC_AUTOREPLACE || (type == VEH_TRAIN && e->u.rail.railveh_type == RAILVEH_WAGON)) ? 0 : GetFreeUnitNumber(type);
00122   if (unit_num == UINT16_MAX) return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
00123 
00124   Vehicle *v;
00125   switch (type) {
00126     case VEH_TRAIN:    value.AddCost(CmdBuildRailVehicle(tile, flags, e, GB(p1, 16, 16), &v)); break;
00127     case VEH_ROAD:     value.AddCost(CmdBuildRoadVehicle(tile, flags, e, GB(p1, 16, 16), &v)); break;
00128     case VEH_SHIP:     value.AddCost(CmdBuildShip       (tile, flags, e, GB(p1, 16, 16), &v)); break;
00129     case VEH_AIRCRAFT: value.AddCost(CmdBuildAircraft   (tile, flags, e, GB(p1, 16, 16), &v)); break;
00130     default: NOT_REACHED(); // Safe due to IsDepotTile()
00131   }
00132 
00133   if (value.Succeeded() && flags & DC_EXEC) {
00134     v->unitnumber = unit_num;
00135     v->value      = value.GetCost();
00136 
00137     InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
00138     InvalidateWindowClassesData(GetWindowClassForVehicleType(type), 0);
00139     SetWindowDirty(WC_COMPANY, _current_company);
00140     if (IsLocalCompany()) {
00141       InvalidateAutoreplaceWindow(v->engine_type, v->group_id); // updates the auto replace window (must be called before incrementing num_engines)
00142     }
00143 
00144     GroupStatistics::CountEngine(v, 1);
00145     GroupStatistics::UpdateAutoreplace(_current_company);
00146 
00147     if (v->IsPrimaryVehicle()) {
00148       GroupStatistics::CountVehicle(v, 1);
00149       OrderBackup::Restore(v, p2);
00150     }
00151   }
00152 
00153   return value;
00154 }
00155 
00156 CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *v, uint16 data, uint32 user);
00157 
00170 CommandCost CmdSellVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00171 {
00172   Vehicle *v = Vehicle::GetIfValid(GB(p1, 0, 20));
00173   if (v == NULL) return CMD_ERROR;
00174 
00175   Vehicle *front = v->First();
00176 
00177   CommandCost ret = CheckOwnership(front->owner);
00178   if (ret.Failed()) return ret;
00179 
00180   if (front->vehstatus & VS_CRASHED) return_cmd_error(STR_ERROR_VEHICLE_IS_DESTROYED);
00181 
00182   if (!front->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAIN_MUST_BE_STOPPED_INSIDE_DEPOT + front->type);
00183 
00184   /* Can we actually make the order backup, i.e. are there enough orders? */
00185   if (p1 & MAKE_ORDER_BACKUP_FLAG &&
00186       front->orders.list != NULL &&
00187       !front->orders.list->IsShared() &&
00188       !Order::CanAllocateItem(front->orders.list->GetNumOrders())) {
00189     /* Only happens in exceptional cases when there aren't enough orders anyhow.
00190      * Thus it should be safe to just drop the orders in that case. */
00191     p1 &= ~MAKE_ORDER_BACKUP_FLAG;
00192   }
00193 
00194   if (v->type == VEH_TRAIN) {
00195     ret = CmdSellRailWagon(flags, v, GB(p1, 20, 12), p2);
00196   } else {
00197     ret = CommandCost(EXPENSES_NEW_VEHICLES, -front->value);
00198 
00199     if (flags & DC_EXEC) {
00200       if (front->IsPrimaryVehicle() && p1 & MAKE_ORDER_BACKUP_FLAG) OrderBackup::Backup(front, p2);
00201       delete front;
00202     }
00203   }
00204 
00205   return ret;
00206 }
00207 
00217 static int GetRefitCostFactor(const Vehicle *v, EngineID engine_type, CargoID new_cid, byte new_subtype, bool *auto_refit_allowed)
00218 {
00219   /* Prepare callback param with info about the new cargo type. */
00220   const Engine *e = Engine::Get(engine_type);
00221 
00222   /* Is this vehicle a NewGRF vehicle? */
00223   if (e->GetGRF() != NULL) {
00224     const CargoSpec *cs = CargoSpec::Get(new_cid);
00225     uint32 param1 = (cs->classes << 16) | (new_subtype << 8) | e->GetGRF()->cargo_map[new_cid];
00226 
00227     uint16 cb_res = GetVehicleCallback(CBID_VEHICLE_REFIT_COST, param1, 0, engine_type, v);
00228     if (cb_res != CALLBACK_FAILED) {
00229       *auto_refit_allowed = HasBit(cb_res, 14);
00230       int factor = GB(cb_res, 0, 14);
00231       if (factor >= 0x2000) factor -= 0x4000; // Treat as signed integer.
00232       return factor;
00233     }
00234   }
00235 
00236   *auto_refit_allowed = e->info.refit_cost == 0;
00237   return (v == NULL || v->cargo_type != new_cid) ? e->info.refit_cost : 0;
00238 }
00239 
00249 static CommandCost GetRefitCost(const Vehicle *v, EngineID engine_type, CargoID new_cid, byte new_subtype, bool *auto_refit_allowed)
00250 {
00251   ExpensesType expense_type;
00252   const Engine *e = Engine::Get(engine_type);
00253   Price base_price;
00254   int cost_factor = GetRefitCostFactor(v, engine_type, new_cid, new_subtype, auto_refit_allowed);
00255   switch (e->type) {
00256     case VEH_SHIP:
00257       base_price = PR_BUILD_VEHICLE_SHIP;
00258       expense_type = EXPENSES_SHIP_RUN;
00259       break;
00260 
00261     case VEH_ROAD:
00262       base_price = PR_BUILD_VEHICLE_ROAD;
00263       expense_type = EXPENSES_ROADVEH_RUN;
00264       break;
00265 
00266     case VEH_AIRCRAFT:
00267       base_price = PR_BUILD_VEHICLE_AIRCRAFT;
00268       expense_type = EXPENSES_AIRCRAFT_RUN;
00269       break;
00270 
00271     case VEH_TRAIN:
00272       base_price = (e->u.rail.railveh_type == RAILVEH_WAGON) ? PR_BUILD_VEHICLE_WAGON : PR_BUILD_VEHICLE_TRAIN;
00273       cost_factor <<= 1;
00274       expense_type = EXPENSES_TRAIN_RUN;
00275       break;
00276 
00277     default: NOT_REACHED();
00278   }
00279   if (cost_factor < 0) {
00280     return CommandCost(expense_type, -GetPrice(base_price, -cost_factor, e->GetGRF(), -10));
00281   } else {
00282     return CommandCost(expense_type, GetPrice(base_price, cost_factor, e->GetGRF(), -10));
00283   }
00284 }
00285 
00287 struct RefitResult {
00288   Vehicle *v;         
00289   uint capacity;      
00290   uint mail_capacity; 
00291   byte subtype;       
00292 };
00293 
00306 static CommandCost RefitVehicle(Vehicle *v, bool only_this, uint8 num_vehicles, CargoID new_cid, byte new_subtype, DoCommandFlag flags, bool auto_refit)
00307 {
00308   CommandCost cost(v->GetExpenseType(false));
00309   uint total_capacity = 0;
00310   uint total_mail_capacity = 0;
00311   num_vehicles = num_vehicles == 0 ? UINT8_MAX : num_vehicles;
00312 
00313   VehicleSet vehicles_to_refit;
00314   if (!only_this) {
00315     GetVehicleSet(vehicles_to_refit, v, num_vehicles);
00316     /* In this case, we need to check the whole chain. */
00317     v = v->First();
00318   }
00319 
00320   static SmallVector<RefitResult, 16> refit_result;
00321   refit_result.Clear();
00322 
00323   v->InvalidateNewGRFCacheOfChain();
00324   byte actual_subtype = new_subtype;
00325   for (; v != NULL; v = (only_this ? NULL : v->Next())) {
00326     /* Reset actual_subtype for every new vehicle */
00327     if (!v->IsArticulatedPart()) actual_subtype = new_subtype;
00328 
00329     if (v->type == VEH_TRAIN && !vehicles_to_refit.Contains(v->index) && !only_this) continue;
00330 
00331     const Engine *e = v->GetEngine();
00332     if (!e->CanCarryCargo()) continue;
00333 
00334     /* If the vehicle is not refittable, or does not allow automatic refitting,
00335      * count its capacity nevertheless if the cargo matches */
00336     bool refittable = HasBit(e->info.refit_mask, new_cid) && (!auto_refit || HasBit(e->info.misc_flags, EF_AUTO_REFIT));
00337     if (!refittable && v->cargo_type != new_cid) continue;
00338 
00339     /* Determine best fitting subtype if requested */
00340     if (actual_subtype == 0xFF) {
00341       actual_subtype = GetBestFittingSubType(v, v, new_cid);
00342     }
00343 
00344     /* Back up the vehicle's cargo type */
00345     CargoID temp_cid = v->cargo_type;
00346     byte temp_subtype = v->cargo_subtype;
00347     if (refittable) {
00348       v->cargo_type = new_cid;
00349       v->cargo_subtype = actual_subtype;
00350     }
00351 
00352     uint16 mail_capacity = 0;
00353     uint amount = e->DetermineCapacity(v, &mail_capacity);
00354     total_capacity += amount;
00355     /* mail_capacity will always be zero if the vehicle is not an aircraft. */
00356     total_mail_capacity += mail_capacity;
00357 
00358     if (!refittable) continue;
00359 
00360     /* Restore the original cargo type */
00361     v->cargo_type = temp_cid;
00362     v->cargo_subtype = temp_subtype;
00363 
00364     bool auto_refit_allowed;
00365     CommandCost refit_cost = GetRefitCost(v, v->engine_type, new_cid, actual_subtype, &auto_refit_allowed);
00366     if (auto_refit && !auto_refit_allowed) {
00367       /* Sorry, auto-refitting not allowed, subtract the cargo amount again from the total. */
00368       total_capacity -= amount;
00369       total_mail_capacity -= mail_capacity;
00370 
00371       if (v->cargo_type == new_cid) {
00372         /* Add the old capacity nevertheless, if the cargo matches */
00373         total_capacity += v->cargo_cap;
00374         if (v->type == VEH_AIRCRAFT) total_mail_capacity += v->Next()->cargo_cap;
00375       }
00376       continue;
00377     }
00378     cost.AddCost(refit_cost);
00379 
00380     /* Record the refitting.
00381      * Do not execute the refitting immediately, so DetermineCapacity and GetRefitCost do the same in test and exec run.
00382      * (weird NewGRFs)
00383      * Note:
00384      *  - If the capacity of vehicles depends on other vehicles in the chain, the actual capacity is
00385      *    set after RefitVehicle() via ConsistChanged() and friends. The estimation via _returned_refit_capacity will be wrong.
00386      *  - We have to call the refit cost callback with the pre-refit configuration of the chain because we want refit and
00387      *    autorefit to behave the same, and we need its result for auto_refit_allowed.
00388      */
00389     RefitResult *result = refit_result.Append();
00390     result->v = v;
00391     result->capacity = amount;
00392     result->mail_capacity = mail_capacity;
00393     result->subtype = actual_subtype;
00394   }
00395 
00396   if (flags & DC_EXEC) {
00397     /* Store the result */
00398     for (RefitResult *result = refit_result.Begin(); result != refit_result.End(); result++) {
00399       Vehicle *u = result->v;
00400       u->refit_cap = (u->cargo_type == new_cid) ? min(result->capacity, u->refit_cap) : 0;
00401       if (u->cargo.Count() > u->refit_cap) u->cargo.Truncate(u->cargo.Count() - u->refit_cap);
00402       u->cargo_type = new_cid;
00403       u->cargo_cap = result->capacity;
00404       u->cargo_subtype = result->subtype;
00405       if (u->type == VEH_AIRCRAFT) {
00406         Vehicle *w = u->Next();
00407         w->refit_cap = min(w->refit_cap, result->mail_capacity);
00408         w->cargo_cap = result->mail_capacity;
00409         if (w->cargo.Count() > w->refit_cap) w->cargo.Truncate(w->cargo.Count() - w->refit_cap);
00410       }
00411     }
00412   }
00413 
00414   refit_result.Clear();
00415   _returned_refit_capacity = total_capacity;
00416   _returned_mail_refit_capacity = total_mail_capacity;
00417   return cost;
00418 }
00419 
00435 CommandCost CmdRefitVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00436 {
00437   Vehicle *v = Vehicle::GetIfValid(p1);
00438   if (v == NULL) return CMD_ERROR;
00439 
00440   /* Don't allow disasters and sparks and such to be refitted.
00441    * We cannot check for IsPrimaryVehicle as autoreplace also refits in free wagon chains. */
00442   if (!IsCompanyBuildableVehicleType(v->type)) return CMD_ERROR;
00443 
00444   Vehicle *front = v->First();
00445 
00446   CommandCost ret = CheckOwnership(front->owner);
00447   if (ret.Failed()) return ret;
00448 
00449   bool auto_refit = HasBit(p2, 6);
00450 
00451   /* Don't allow shadows and such to be refitted. */
00452   if (v != front && (v->type == VEH_SHIP || v->type == VEH_AIRCRAFT)) return CMD_ERROR;
00453   /* Allow auto-refitting only during loading and normal refitting only in a depot. */
00454   if ((!auto_refit || !front->current_order.IsType(OT_LOADING)) && !front->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAIN_MUST_BE_STOPPED_INSIDE_DEPOT + front->type);
00455   if (front->vehstatus & VS_CRASHED) return_cmd_error(STR_ERROR_VEHICLE_IS_DESTROYED);
00456 
00457   /* Check cargo */
00458   CargoID new_cid = GB(p2, 0, 5);
00459   byte new_subtype = GB(p2, 8, 8);
00460   if (new_cid >= NUM_CARGO) return CMD_ERROR;
00461 
00462   /* For ships and aircrafts there is always only one. */
00463   bool only_this = HasBit(p2, 7) || front->type == VEH_SHIP || front->type == VEH_AIRCRAFT;
00464   uint8 num_vehicles = GB(p2, 16, 8);
00465 
00466   CommandCost cost = RefitVehicle(v, only_this, num_vehicles, new_cid, new_subtype, flags, auto_refit);
00467 
00468   if (flags & DC_EXEC) {
00469     /* Update the cached variables */
00470     switch (v->type) {
00471       case VEH_TRAIN:
00472         Train::From(front)->ConsistChanged(auto_refit);
00473         break;
00474       case VEH_ROAD:
00475         RoadVehUpdateCache(RoadVehicle::From(front), auto_refit);
00476         if (_settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL) RoadVehicle::From(front)->CargoChanged();
00477         break;
00478 
00479       case VEH_SHIP:
00480         v->InvalidateNewGRFCacheOfChain();
00481         v->colourmap = PAL_NONE; // invalidate vehicle colour map
00482         Ship::From(v)->UpdateCache();
00483         break;
00484 
00485       case VEH_AIRCRAFT:
00486         v->InvalidateNewGRFCacheOfChain();
00487         v->colourmap = PAL_NONE; // invalidate vehicle colour map
00488         UpdateAircraftCache(Aircraft::From(v), true);
00489         break;
00490 
00491       default: NOT_REACHED();
00492     }
00493 
00494     InvalidateWindowData(WC_VEHICLE_DETAILS, front->index);
00495     SetWindowDirty(WC_VEHICLE_DEPOT, front->tile);
00496     InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
00497   } else {
00498     /* Always invalidate the cache; querycost might have filled it. */
00499     v->InvalidateNewGRFCacheOfChain();
00500   }
00501 
00502   return cost;
00503 }
00504 
00514 CommandCost CmdStartStopVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00515 {
00516   /* Disable the effect of p2 bit 0, when DC_AUTOREPLACE is not set */
00517   if ((flags & DC_AUTOREPLACE) == 0) SetBit(p2, 0);
00518 
00519   Vehicle *v = Vehicle::GetIfValid(p1);
00520   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
00521 
00522   CommandCost ret = CheckOwnership(v->owner);
00523   if (ret.Failed()) return ret;
00524 
00525   if (v->vehstatus & VS_CRASHED) return_cmd_error(STR_ERROR_VEHICLE_IS_DESTROYED);
00526 
00527   switch (v->type) {
00528     case VEH_TRAIN:
00529       if ((v->vehstatus & VS_STOPPED) && Train::From(v)->gcache.cached_power == 0) return_cmd_error(STR_ERROR_TRAIN_START_NO_POWER);
00530       break;
00531 
00532     case VEH_SHIP:
00533     case VEH_ROAD:
00534       break;
00535 
00536     case VEH_AIRCRAFT: {
00537       Aircraft *a = Aircraft::From(v);
00538       /* cannot stop airplane when in flight, or when taking off / landing */
00539       if (!(v->vehstatus & VS_CRASHED) && a->state >= STARTTAKEOFF && a->state < TERM7) return_cmd_error(STR_ERROR_AIRCRAFT_IS_IN_FLIGHT);
00540       break;
00541     }
00542 
00543     default: return CMD_ERROR;
00544   }
00545 
00546   if (HasBit(p2, 0)) {
00547     /* Check if this vehicle can be started/stopped. Failure means 'allow'. */
00548     uint16 callback = GetVehicleCallback(CBID_VEHICLE_START_STOP_CHECK, 0, 0, v->engine_type, v);
00549     StringID error = STR_NULL;
00550     if (callback != CALLBACK_FAILED) {
00551       if (v->GetGRF()->grf_version < 8) {
00552         /* 8 bit result 0xFF means 'allow' */
00553         if (callback < 0x400 && GB(callback, 0, 8) != 0xFF) error = GetGRFStringID(v->GetGRFID(), 0xD000 + callback);
00554       } else {
00555         if (callback < 0x400) {
00556           error = GetGRFStringID(v->GetGRFID(), 0xD000 + callback);
00557         } else {
00558           switch (callback) {
00559             case 0x400: // allow
00560               break;
00561 
00562             default: // unknown reason -> disallow
00563               error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
00564               break;
00565           }
00566         }
00567       }
00568     }
00569     if (error != STR_NULL) return_cmd_error(error);
00570   }
00571 
00572   if (flags & DC_EXEC) {
00573     if (v->IsStoppedInDepot() && (flags & DC_AUTOREPLACE) == 0) DeleteVehicleNews(p1, STR_NEWS_TRAIN_IS_WAITING + v->type);
00574 
00575     v->vehstatus ^= VS_STOPPED;
00576     if (v->type != VEH_TRAIN) v->cur_speed = 0; // trains can stop 'slowly'
00577     v->MarkDirty();
00578     SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
00579     SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
00580     SetWindowClassesDirty(GetWindowClassForVehicleType(v->type));
00581   }
00582   return CommandCost();
00583 }
00584 
00596 CommandCost CmdMassStartStopVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00597 {
00598   VehicleList list;
00599   bool do_start = HasBit(p1, 0);
00600   bool vehicle_list_window = HasBit(p1, 1);
00601 
00602   VehicleListIdentifier vli;
00603   if (!vli.Unpack(p2)) return CMD_ERROR;
00604   if (!IsCompanyBuildableVehicleType(vli.vtype)) return CMD_ERROR;
00605 
00606   if (vehicle_list_window) {
00607     if (!GenerateVehicleSortList(&list, vli)) return CMD_ERROR;
00608   } else {
00609     /* Get the list of vehicles in the depot */
00610     BuildDepotVehicleList(vli.vtype, tile, &list, NULL);
00611   }
00612 
00613   for (uint i = 0; i < list.Length(); i++) {
00614     const Vehicle *v = list[i];
00615 
00616     if (!!(v->vehstatus & VS_STOPPED) != do_start) continue;
00617 
00618     if (!vehicle_list_window && !v->IsChainInDepot()) continue;
00619 
00620     /* Just try and don't care if some vehicle's can't be stopped. */
00621     DoCommand(tile, v->index, 0, flags, CMD_START_STOP_VEHICLE);
00622   }
00623 
00624   return CommandCost();
00625 }
00626 
00636 CommandCost CmdDepotSellAllVehicles(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00637 {
00638   VehicleList list;
00639 
00640   CommandCost cost(EXPENSES_NEW_VEHICLES);
00641   VehicleType vehicle_type = Extract<VehicleType, 0, 3>(p1);
00642 
00643   if (!IsCompanyBuildableVehicleType(vehicle_type)) return CMD_ERROR;
00644 
00645   uint sell_command = GetCmdSellVeh(vehicle_type);
00646 
00647   /* Get the list of vehicles in the depot */
00648   BuildDepotVehicleList(vehicle_type, tile, &list, &list);
00649 
00650   CommandCost last_error = CMD_ERROR;
00651   bool had_success = false;
00652   for (uint i = 0; i < list.Length(); i++) {
00653     CommandCost ret = DoCommand(tile, list[i]->index | (1 << 20), 0, flags, sell_command);
00654     if (ret.Succeeded()) {
00655       cost.AddCost(ret);
00656       had_success = true;
00657     } else {
00658       last_error = ret;
00659     }
00660   }
00661 
00662   return had_success ? cost : last_error;
00663 }
00664 
00674 CommandCost CmdDepotMassAutoReplace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00675 {
00676   VehicleList list;
00677   CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES);
00678   VehicleType vehicle_type = Extract<VehicleType, 0, 3>(p1);
00679 
00680   if (!IsCompanyBuildableVehicleType(vehicle_type)) return CMD_ERROR;
00681   if (!IsDepotTile(tile) || !IsTileOwner(tile, _current_company)) return CMD_ERROR;
00682 
00683   /* Get the list of vehicles in the depot */
00684   BuildDepotVehicleList(vehicle_type, tile, &list, &list, true);
00685 
00686   for (uint i = 0; i < list.Length(); i++) {
00687     const Vehicle *v = list[i];
00688 
00689     /* Ensure that the vehicle completely in the depot */
00690     if (!v->IsChainInDepot()) continue;
00691 
00692     CommandCost ret = DoCommand(0, v->index, 0, flags, CMD_AUTOREPLACE_VEHICLE);
00693 
00694     if (ret.Succeeded()) cost.AddCost(ret);
00695   }
00696   return cost;
00697 }
00698 
00704 static bool IsUniqueVehicleName(const char *name)
00705 {
00706   const Vehicle *v;
00707 
00708   FOR_ALL_VEHICLES(v) {
00709     if (v->name != NULL && strcmp(v->name, name) == 0) return false;
00710   }
00711 
00712   return true;
00713 }
00714 
00720 static void CloneVehicleName(const Vehicle *src, Vehicle *dst)
00721 {
00722   char buf[256];
00723 
00724   /* Find the position of the first digit in the last group of digits. */
00725   size_t number_position;
00726   for (number_position = strlen(src->name); number_position > 0; number_position--) {
00727     /* The design of UTF-8 lets this work simply without having to check
00728      * for UTF-8 sequences. */
00729     if (src->name[number_position - 1] < '0' || src->name[number_position - 1] > '9') break;
00730   }
00731 
00732   /* Format buffer and determine starting number. */
00733   int num;
00734   byte padding = 0;
00735   if (number_position == strlen(src->name)) {
00736     /* No digit at the end, so start at number 2. */
00737     strecpy(buf, src->name, lastof(buf));
00738     strecat(buf, " ", lastof(buf));
00739     number_position = strlen(buf);
00740     num = 2;
00741   } else {
00742     /* Found digits, parse them and start at the next number. */
00743     strecpy(buf, src->name, lastof(buf));
00744     buf[number_position] = '\0';
00745     char *endptr;
00746     num = strtol(&src->name[number_position], &endptr, 10) + 1;
00747     padding = endptr - &src->name[number_position];
00748   }
00749 
00750   /* Check if this name is already taken. */
00751   for (int max_iterations = 1000; max_iterations > 0; max_iterations--, num++) {
00752     /* Attach the number to the temporary name. */
00753     seprintf(&buf[number_position], lastof(buf), "%0*d", padding, num);
00754 
00755     /* Check the name is unique. */
00756     if (IsUniqueVehicleName(buf)) {
00757       dst->name = strdup(buf);
00758       break;
00759     }
00760   }
00761 
00762   /* All done. If we didn't find a name, it'll just use its default. */
00763 }
00764 
00774 CommandCost CmdCloneVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00775 {
00776   CommandCost total_cost(EXPENSES_NEW_VEHICLES);
00777 
00778   Vehicle *v = Vehicle::GetIfValid(p1);
00779   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
00780   Vehicle *v_front = v;
00781   Vehicle *w = NULL;
00782   Vehicle *w_front = NULL;
00783   Vehicle *w_rear = NULL;
00784 
00785   /*
00786    * v_front is the front engine in the original vehicle
00787    * v is the car/vehicle of the original vehicle that is currently being copied
00788    * w_front is the front engine of the cloned vehicle
00789    * w is the car/vehicle currently being cloned
00790    * w_rear is the rear end of the cloned train. It's used to add more cars and is only used by trains
00791    */
00792 
00793   CommandCost ret = CheckOwnership(v->owner);
00794   if (ret.Failed()) return ret;
00795 
00796   if (v->type == VEH_TRAIN && (!v->IsFrontEngine() || Train::From(v)->crash_anim_pos >= 4400)) return CMD_ERROR;
00797 
00798   /* check that we can allocate enough vehicles */
00799   if (!(flags & DC_EXEC)) {
00800     int veh_counter = 0;
00801     do {
00802       veh_counter++;
00803     } while ((v = v->Next()) != NULL);
00804 
00805     if (!Vehicle::CanAllocateItem(veh_counter)) {
00806       return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
00807     }
00808   }
00809 
00810   v = v_front;
00811 
00812   do {
00813     if (v->type == VEH_TRAIN && Train::From(v)->IsRearDualheaded()) {
00814       /* we build the rear ends of multiheaded trains with the front ones */
00815       continue;
00816     }
00817 
00818     /* In case we're building a multi headed vehicle and the maximum number of
00819      * vehicles is almost reached (e.g. max trains - 1) not all vehicles would
00820      * be cloned. When the non-primary engines were build they were seen as
00821      * 'new' vehicles whereas they would immediately be joined with a primary
00822      * engine. This caused the vehicle to be not build as 'the limit' had been
00823      * reached, resulting in partially build vehicles and such. */
00824     DoCommandFlag build_flags = flags;
00825     if ((flags & DC_EXEC) && !v->IsPrimaryVehicle()) build_flags |= DC_AUTOREPLACE;
00826 
00827     CommandCost cost = DoCommand(tile, v->engine_type | (1 << 16), 0, build_flags, GetCmdBuildVeh(v));
00828 
00829     if (cost.Failed()) {
00830       /* Can't build a part, then sell the stuff we already made; clear up the mess */
00831       if (w_front != NULL) DoCommand(w_front->tile, w_front->index | (1 << 20), 0, flags, GetCmdSellVeh(w_front));
00832       return cost;
00833     }
00834 
00835     total_cost.AddCost(cost);
00836 
00837     if (flags & DC_EXEC) {
00838       w = Vehicle::Get(_new_vehicle_id);
00839 
00840       if (v->type == VEH_TRAIN && HasBit(Train::From(v)->flags, VRF_REVERSE_DIRECTION)) {
00841         SetBit(Train::From(w)->flags, VRF_REVERSE_DIRECTION);
00842       }
00843 
00844       if (v->type == VEH_TRAIN && !v->IsFrontEngine()) {
00845         /* this s a train car
00846          * add this unit to the end of the train */
00847         CommandCost result = DoCommand(0, w->index | 1 << 20, w_rear->index, flags, CMD_MOVE_RAIL_VEHICLE);
00848         if (result.Failed()) {
00849           /* The train can't be joined to make the same consist as the original.
00850            * Sell what we already made (clean up) and return an error.           */
00851           DoCommand(w_front->tile, w_front->index | 1 << 20, 0, flags, GetCmdSellVeh(w_front));
00852           DoCommand(w_front->tile, w->index       | 1 << 20, 0, flags, GetCmdSellVeh(w));
00853           return result; // return error and the message returned from CMD_MOVE_RAIL_VEHICLE
00854         }
00855       } else {
00856         /* this is a front engine or not a train. */
00857         w_front = w;
00858         w->service_interval = v->service_interval;
00859         w->SetServiceIntervalIsCustom(v->ServiceIntervalIsCustom());
00860         w->SetServiceIntervalIsPercent(v->ServiceIntervalIsPercent());
00861       }
00862       w_rear = w; // trains needs to know the last car in the train, so they can add more in next loop
00863     }
00864   } while (v->type == VEH_TRAIN && (v = v->GetNextVehicle()) != NULL);
00865 
00866   if ((flags & DC_EXEC) && v_front->type == VEH_TRAIN) {
00867     /* for trains this needs to be the front engine due to the callback function */
00868     _new_vehicle_id = w_front->index;
00869   }
00870 
00871   if (flags & DC_EXEC) {
00872     /* Cloned vehicles belong to the same group */
00873     DoCommand(0, v_front->group_id, w_front->index, flags, CMD_ADD_VEHICLE_GROUP);
00874   }
00875 
00876 
00877   /* Take care of refitting. */
00878   w = w_front;
00879   v = v_front;
00880 
00881   /* Both building and refitting are influenced by newgrf callbacks, which
00882    * makes it impossible to accurately estimate the cloning costs. In
00883    * particular, it is possible for engines of the same type to be built with
00884    * different numbers of articulated parts, so when refitting we have to
00885    * loop over real vehicles first, and then the articulated parts of those
00886    * vehicles in a different loop. */
00887   do {
00888     do {
00889       if (flags & DC_EXEC) {
00890         assert(w != NULL);
00891 
00892         /* Find out what's the best sub type */
00893         byte subtype = GetBestFittingSubType(v, w, v->cargo_type);
00894         if (w->cargo_type != v->cargo_type || w->cargo_subtype != subtype) {
00895           CommandCost cost = DoCommand(0, w->index, v->cargo_type | 1U << 7 | (subtype << 8), flags, GetCmdRefitVeh(v));
00896           if (cost.Succeeded()) total_cost.AddCost(cost);
00897         }
00898 
00899         if (w->IsGroundVehicle() && w->HasArticulatedPart()) {
00900           w = w->GetNextArticulatedPart();
00901         } else {
00902           break;
00903         }
00904       } else {
00905         const Engine *e = v->GetEngine();
00906         CargoID initial_cargo = (e->CanCarryCargo() ? e->GetDefaultCargoType() : (CargoID)CT_INVALID);
00907 
00908         if (v->cargo_type != initial_cargo && initial_cargo != CT_INVALID) {
00909           bool dummy;
00910           total_cost.AddCost(GetRefitCost(NULL, v->engine_type, v->cargo_type, v->cargo_subtype, &dummy));
00911         }
00912       }
00913 
00914       if (v->IsGroundVehicle() && v->HasArticulatedPart()) {
00915         v = v->GetNextArticulatedPart();
00916       } else {
00917         break;
00918       }
00919     } while (v != NULL);
00920 
00921     if ((flags & DC_EXEC) && v->type == VEH_TRAIN) w = w->GetNextVehicle();
00922   } while (v->type == VEH_TRAIN && (v = v->GetNextVehicle()) != NULL);
00923 
00924   if (flags & DC_EXEC) {
00925     /*
00926      * Set the orders of the vehicle. Cannot do it earlier as we need
00927      * the vehicle refitted before doing this, otherwise the moved
00928      * cargo types might not match (passenger vs non-passenger)
00929      */
00930     DoCommand(0, w_front->index | (p2 & 1 ? CO_SHARE : CO_COPY) << 30, v_front->index, flags, CMD_CLONE_ORDER);
00931 
00932     /* Now clone the vehicle's name, if it has one. */
00933     if (v_front->name != NULL) CloneVehicleName(v_front, w_front);
00934   }
00935 
00936   /* Since we can't estimate the cost of cloning a vehicle accurately we must
00937    * check whether the company has enough money manually. */
00938   if (!CheckCompanyHasMoney(total_cost)) {
00939     if (flags & DC_EXEC) {
00940       /* The vehicle has already been bought, so now it must be sold again. */
00941       DoCommand(w_front->tile, w_front->index | 1 << 20, 0, flags, GetCmdSellVeh(w_front));
00942     }
00943     return total_cost;
00944   }
00945 
00946   return total_cost;
00947 }
00948 
00956 static CommandCost SendAllVehiclesToDepot(DoCommandFlag flags, bool service, const VehicleListIdentifier &vli)
00957 {
00958   VehicleList list;
00959 
00960   if (!GenerateVehicleSortList(&list, vli)) return CMD_ERROR;
00961 
00962   /* Send all the vehicles to a depot */
00963   bool had_success = false;
00964   for (uint i = 0; i < list.Length(); i++) {
00965     const Vehicle *v = list[i];
00966     CommandCost ret = DoCommand(v->tile, v->index | (service ? DEPOT_SERVICE : 0U) | DEPOT_DONT_CANCEL, 0, flags, GetCmdSendToDepot(vli.vtype));
00967 
00968     if (ret.Succeeded()) {
00969       had_success = true;
00970 
00971       /* Return 0 if DC_EXEC is not set this is a valid goto depot command)
00972        * In this case we know that at least one vehicle can be sent to a depot
00973        * and we will issue the command. We can now safely quit the loop, knowing
00974        * it will succeed at least once. With DC_EXEC we really need to send them to the depot */
00975       if (!(flags & DC_EXEC)) break;
00976     }
00977   }
00978 
00979   return had_success ? CommandCost() : CMD_ERROR;
00980 }
00981 
00993 CommandCost CmdSendVehicleToDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00994 {
00995   if (p1 & DEPOT_MASS_SEND) {
00996     /* Mass goto depot requested */
00997     VehicleListIdentifier vli;
00998     if (!vli.Unpack(p2)) return CMD_ERROR;
00999     return SendAllVehiclesToDepot(flags, (p1 & DEPOT_SERVICE) != 0, vli);
01000   }
01001 
01002   Vehicle *v = Vehicle::GetIfValid(GB(p1, 0, 20));
01003   if (v == NULL) return CMD_ERROR;
01004   if (!v->IsPrimaryVehicle()) return CMD_ERROR;
01005 
01006   return v->SendToDepot(flags, (DepotCommand)(p1 & DEPOT_COMMAND_MASK));
01007 }
01008 
01018 CommandCost CmdRenameVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01019 {
01020   Vehicle *v = Vehicle::GetIfValid(p1);
01021   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01022 
01023   CommandCost ret = CheckOwnership(v->owner);
01024   if (ret.Failed()) return ret;
01025 
01026   bool reset = StrEmpty(text);
01027 
01028   if (!reset) {
01029     if (Utf8StringLength(text) >= MAX_LENGTH_VEHICLE_NAME_CHARS) return CMD_ERROR;
01030     if (!(flags & DC_AUTOREPLACE) && !IsUniqueVehicleName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
01031   }
01032 
01033   if (flags & DC_EXEC) {
01034     free(v->name);
01035     v->name = reset ? NULL : strdup(text);
01036     InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 1);
01037     MarkWholeScreenDirty();
01038   }
01039 
01040   return CommandCost();
01041 }
01042 
01043 
01056 CommandCost CmdChangeServiceInt(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01057 {
01058   Vehicle *v = Vehicle::GetIfValid(p1);
01059   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01060 
01061   CommandCost ret = CheckOwnership(v->owner);
01062   if (ret.Failed()) return ret;
01063 
01064   const Company *company = Company::Get(v->owner);
01065   bool iscustom  = HasBit(p2, 16);
01066   bool ispercent = iscustom ? HasBit(p2, 17) : company->settings.vehicle.servint_ispercent;
01067 
01068   uint16 serv_int;
01069   if (iscustom) {
01070     serv_int = GB(p2, 0, 16);
01071     if (serv_int != GetServiceIntervalClamped(serv_int, ispercent)) return CMD_ERROR;
01072   } else {
01073     serv_int = CompanyServiceInterval(company, v->type);
01074   }
01075 
01076   if (flags & DC_EXEC) {
01077     v->SetServiceInterval(serv_int);
01078     v->SetServiceIntervalIsCustom(iscustom);
01079     v->SetServiceIntervalIsPercent(ispercent);
01080     SetWindowDirty(WC_VEHICLE_DETAILS, v->index);
01081   }
01082 
01083   return CommandCost();
01084 }