# 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 "vehicle_gui.h"
    00020 #include "train.h"
    00021 #include "aircraft.h"
    00022 #include "newgrf_text.h"
    00023 #include "window_func.h"
    00024 #include "vehicle_func.h"
    00025 #include "string_func.h"
    00026 #include "depot_map.h"
    00027 #include "vehiclelist.h"
    00028 #include "engine_func.h"
    00029 #include "articulated_vehicles.h"
    00030 #include "autoreplace_gui.h"
    00031 #include "company_base.h"
    00032 #include "order_backup.h"
    00033
    00034 #include "table/strings.h"
    00035
    00036 /* Tables used in vehicle.h to find the right command for a certain vehicle type */
    00037 const uint32 _veh_build_proc_table[] = {
    00038   CMD_BUILD_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_TRAIN),
    00039   CMD_BUILD_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_ROAD_VEHICLE),
    00040   CMD_BUILD_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_SHIP),
    00041   CMD_BUILD_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_AIRCRAFT),
    00042 };
    00043
    00044 const uint32 _veh_sell_proc_table[] = {
    00045   CMD_SELL_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_SELL_TRAIN),
    00046   CMD_SELL_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_SELL_ROAD_VEHICLE),
    00047   CMD_SELL_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_SELL_SHIP),
    00048   CMD_SELL_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_SELL_AIRCRAFT),
    00049 };
    00050
    00051 const uint32 _veh_refit_proc_table[] = {
    00052   CMD_REFIT_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_REFIT_TRAIN),
    00053   CMD_REFIT_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_REFIT_ROAD_VEHICLE),
    00054   CMD_REFIT_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_REFIT_SHIP),
    00055   CMD_REFIT_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_REFIT_AIRCRAFT),
    00056 };
    00057
    00058 const uint32 _send_to_depot_proc_table[] = {
    00059   /* TrainGotoDepot has a nice randomizer in the pathfinder, which causes desyncs... */
    00060   CMD_SEND_VEHICLE_TO_DEPOT | CMD_MSG(STR_ERROR_CAN_T_SEND_TRAIN_TO_DEPOT) | CMD_NO_TEST_IF_IN_NETWORK,
    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
    00142     }
    00143
    00144     Company::Get(_current_company)->num_engines[eid]++;
    00145
    00146     if (v->IsPrimaryVehicle()) OrderBackup::Restore(v, p2);
    00147   }
    00148
    00149   return value;
    00150 }
    00151
    00152 CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *v, uint16 data, uint32 user);
    00153
    00166 CommandCost CmdSellVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00167 {
    00168   Vehicle *v = Vehicle::GetIfValid(GB(p1, 0, 20));
    00169   if (v == NULL) return CMD_ERROR;
    00170
    00171   Vehicle *front = v->First();
    00172
    00173   CommandCost ret = CheckOwnership(front->owner);
    00174   if (ret.Failed()) return ret;
    00175
    00176   if (front->vehstatus & VS_CRASHED) return_cmd_error(STR_ERROR_VEHICLE_IS_DESTROYED);
    00177
    00178   if (!front->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAIN_MUST_BE_STOPPED_INSIDE_DEPOT + front->type);
    00179
    00180   /* Can we actually make the order backup, i.e. are there enough orders? */
    00181   if (p1 & MAKE_ORDER_BACKUP_FLAG &&
    00182       front->orders.list != NULL &&
    00183       !front->orders.list->IsShared() &&
    00184       !Order::CanAllocateItem(front->orders.list->GetNumOrders())) {
    00185     /* Only happens in exceptional cases when there aren't enough orders anyhow.
    00186      * Thus it should be safe to just drop the orders in that case. */
    00187     p1 &= ~MAKE_ORDER_BACKUP_FLAG;
    00188   }
    00189
    00190   if (v->type == VEH_TRAIN) {
    00191     ret = CmdSellRailWagon(flags, v, GB(p1, 20, 12), p2);
    00192   } else {
    00193     ret = CommandCost(EXPENSES_NEW_VEHICLES, -front->value);
    00194
    00195     if (flags & DC_EXEC) {
    00196       if (v->IsPrimaryVehicle() && p1 & MAKE_ORDER_BACKUP_FLAG) OrderBackup::Backup(v, p2);
    00197       delete front;
    00198     }
    00199   }
    00200
    00201   return ret;
    00202 }
    00203
    00209 static CommandCost GetRefitCost(EngineID engine_type)
    00210 {
    00211   ExpensesType expense_type;
    00212   const Engine *e = Engine::Get(engine_type);
    00213   Price base_price;
    00214   uint cost_factor = e->info.refit_cost;
    00215   switch (e->type) {
    00216     case VEH_SHIP:
    00217       base_price = PR_BUILD_VEHICLE_SHIP;
    00218       expense_type = EXPENSES_SHIP_RUN;
    00219       break;
    00220
    00221     case VEH_ROAD:
    00222       base_price = PR_BUILD_VEHICLE_ROAD;
    00223       expense_type = EXPENSES_ROADVEH_RUN;
    00224       break;
    00225
    00226     case VEH_AIRCRAFT:
    00227       base_price = PR_BUILD_VEHICLE_AIRCRAFT;
    00228       expense_type = EXPENSES_AIRCRAFT_RUN;
    00229       break;
    00230
    00231     case VEH_TRAIN:
    00232       base_price = (e->u.rail.railveh_type == RAILVEH_WAGON) ? PR_BUILD_VEHICLE_WAGON : PR_BUILD_VEHICLE_TRAIN;
    00233       cost_factor <<= 1;
    00234       expense_type = EXPENSES_TRAIN_RUN;
    00235       break;
    00236
    00237     default: NOT_REACHED();
    00238   }
    00239   return CommandCost(expense_type, GetPrice(base_price, cost_factor, e->grf_prop.grffile, -10));
    00240 }
    00241
    00253 static CommandCost RefitVehicle(Vehicle *v, bool only_this, uint8 num_vehicles, CargoID new_cid, byte new_subtype, DoCommandFlag flags)
    00254 {
    00255   CommandCost cost(v->GetExpenseType(false));
    00256   uint total_capacity = 0;
    00257   uint total_mail_capacity = 0;
    00258   num_vehicles = num_vehicles == 0 ? UINT8_MAX : num_vehicles;
    00259
    00260   VehicleSet vehicles_to_refit;
    00261   if (!only_this) {
    00262     GetVehicleSet(vehicles_to_refit, v, num_vehicles);
    00263     /* In this case, we need to check the whole chain. */
    00264     v = v->First();
    00265   }
    00266
    00267   v->InvalidateNewGRFCacheOfChain();
    00268   for (; v != NULL; v = (only_this ? NULL : v->Next())) {
    00269     if (v->type == VEH_TRAIN && !vehicles_to_refit.Contains(v->index) && !only_this) continue;
    00270
    00271     const Engine *e = Engine::Get(v->engine_type);
    00272     if (!e->CanCarryCargo()) continue;
    00273
    00274     /* If the vehicle is not refittable, count its capacity nevertheless if the cargo matches */
    00275     bool refittable = HasBit(e->info.refit_mask, new_cid);
    00276     if (!refittable && v->cargo_type != new_cid) continue;
    00277
    00278     /* Back up the vehicle's cargo type */
    00279     CargoID temp_cid = v->cargo_type;
    00280     byte temp_subtype = v->cargo_subtype;
    00281     if (refittable) {
    00282       v->cargo_type = new_cid;
    00283       v->cargo_subtype = new_subtype;
    00284     }
    00285
    00286     uint16 mail_capacity = 0;
    00287     uint amount = GetVehicleCapacity(v, &mail_capacity);
    00288     total_capacity += amount;
    00289     /* mail_capacity will always be zero if the vehicle is not an aircraft. */
    00290     total_mail_capacity += mail_capacity;
    00291
    00292     if (!refittable) continue;
    00293
    00294     /* Restore the original cargo type */
    00295     v->cargo_type = temp_cid;
    00296     v->cargo_subtype = temp_subtype;
    00297
    00298     if (new_cid != v->cargo_type) {
    00299       cost.AddCost(GetRefitCost(v->engine_type));
    00300     }
    00301
    00302     if (flags & DC_EXEC) {
    00303       v->cargo.Truncate((v->cargo_type == new_cid) ? amount : 0);
    00304       v->cargo_type = new_cid;
    00305       v->cargo_cap = amount;
    00306       v->cargo_subtype = new_subtype;
    00307       if (v->type == VEH_AIRCRAFT) {
    00308         Vehicle *u = v->Next();
    00309         u->cargo_cap = mail_capacity;
    00310         u->cargo.Truncate(mail_capacity);
    00311       }
    00312     }
    00313   }
    00314
    00315   _returned_refit_capacity = total_capacity;
    00316   _returned_mail_refit_capacity = total_mail_capacity;
    00317   return cost;
    00318 }
    00319
    00334 CommandCost CmdRefitVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00335 {
    00336   Vehicle *v = Vehicle::GetIfValid(p1);
    00337   if (v == NULL) return CMD_ERROR;
    00338
    00339   /* Don't allow disasters and sparks and such to be refitted.
    00340    * We cannot check for IsPrimaryVehicle as autoreplace also refits in free wagon chains. */
    00341   if (!IsCompanyBuildableVehicleType(v->type)) return CMD_ERROR;
    00342
    00343   Vehicle *front = v->First();
    00344
    00345   CommandCost ret = CheckOwnership(front->owner);
    00346   if (ret.Failed()) return ret;
    00347
    00348   /* Don't allow shadows and such to be refitted. */
    00349   if (v != front && (v->type == VEH_SHIP || v->type == VEH_AIRCRAFT)) return CMD_ERROR;
    00350   if (!front->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAIN_MUST_BE_STOPPED_INSIDE_DEPOT + front->type);
    00351   if (front->vehstatus & VS_CRASHED) return_cmd_error(STR_ERROR_VEHICLE_IS_DESTROYED);
    00352
    00353   /* Check cargo */
    00354   CargoID new_cid = GB(p2, 0, 5);
    00355   byte new_subtype = GB(p2, 8, 8);
    00356   if (new_cid >= NUM_CARGO) return CMD_ERROR;
    00357
    00358   /* For ships and aircrafts there is always only one. */
    00359   bool only_this = HasBit(p2, 7) || front->type == VEH_SHIP || front->type == VEH_AIRCRAFT;
    00360   uint8 num_vehicles = GB(p2, 16, 8);
    00361
    00362   CommandCost cost = RefitVehicle(v, only_this, num_vehicles, new_cid, new_subtype, flags);
    00363
    00364   if (flags & DC_EXEC) {
    00365     /* Update the cached variables */
    00366     switch (v->type) {
    00367       case VEH_TRAIN:
    00368         Train::From(front)->ConsistChanged(false);
    00369         break;
    00370       case VEH_ROAD:
    00371         RoadVehUpdateCache(RoadVehicle::From(front));
    00372         if (_settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL) RoadVehicle::From(front)->CargoChanged();
    00373         break;
    00374
    00375       case VEH_SHIP:
    00376       case VEH_AIRCRAFT:
    00377         v->InvalidateNewGRFCacheOfChain();
    00378         v->colourmap = PAL_NONE; // invalidate vehicle colour map
    00379         break;
    00380
    00381       default: NOT_REACHED();
    00382     }
    00383
    00384     InvalidateWindowData(WC_VEHICLE_DETAILS, front->index);
    00385     SetWindowDirty(WC_VEHICLE_DEPOT, front->tile);
    00386     InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
    00387   } else {
    00388     /* Always invalidate the cache; querycost might have filled it. */
    00389     v->InvalidateNewGRFCacheOfChain();
    00390   }
    00391
    00392   return cost;
    00393 }
    00394
    00404 CommandCost CmdStartStopVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00405 {
    00406   /* Disable the effect of p2 bit 0, when DC_AUTOREPLACE is not set */
    00407   if ((flags & DC_AUTOREPLACE) == 0) SetBit(p2, 0);
    00408
    00409   Vehicle *v = Vehicle::GetIfValid(p1);
    00410   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
    00411
    00412   CommandCost ret = CheckOwnership(v->owner);
    00413   if (ret.Failed()) return ret;
    00414
    00415   if (v->vehstatus & VS_CRASHED) return_cmd_error(STR_ERROR_VEHICLE_IS_DESTROYED);
    00416
    00417   switch (v->type) {
    00418     case VEH_TRAIN:
    00419       if ((v->vehstatus & VS_STOPPED) && Train::From(v)->gcache.cached_power == 0) return_cmd_error(STR_ERROR_TRAIN_START_NO_CATENARY);
    00420       break;
    00421
    00422     case VEH_SHIP:
    00423     case VEH_ROAD:
    00424       break;
    00425
    00426     case VEH_AIRCRAFT: {
    00427       Aircraft *a = Aircraft::From(v);
    00428       /* cannot stop airplane when in flight, or when taking off / landing */
    00429       if (!(v->vehstatus & VS_CRASHED) && a->state >= STARTTAKEOFF && a->state < TERM7) return_cmd_error(STR_ERROR_AIRCRAFT_IS_IN_FLIGHT);
    00430       break;
    00431     }
    00432
    00433     default: return CMD_ERROR;
    00434   }
    00435
    00436   /* Check if this vehicle can be started/stopped. The callback will fail or
    00437    * return 0xFF if it can. */
    00438   uint16 callback = GetVehicleCallback(CBID_VEHICLE_START_STOP_CHECK, 0, 0, v->engine_type, v);
    00439   if (callback != CALLBACK_FAILED && GB(callback, 0, 8) != 0xFF && HasBit(p2, 0)) {
    00440     StringID error = GetGRFStringID(GetEngineGRFID(v->engine_type), 0xD000 + callback);
    00441     return_cmd_error(error);
    00442   }
    00443
    00444   if (flags & DC_EXEC) {
    00445     if (v->IsStoppedInDepot() && (flags & DC_AUTOREPLACE) == 0) DeleteVehicleNews(p1, STR_NEWS_TRAIN_IS_WAITING + v->type);
    00446
    00447     v->vehstatus ^= VS_STOPPED;
    00448     if (v->type != VEH_TRAIN) v->cur_speed = 0; // trains can stop 'slowly'
    00449     v->MarkDirty();
    00450     SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    00451     SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
    00452     SetWindowClassesDirty(GetWindowClassForVehicleType(v->type));
    00453   }
    00454   return CommandCost();
    00455 }
    00456
    00468 CommandCost CmdMassStartStopVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00469 {
    00470   VehicleList list;
    00471   bool do_start = HasBit(p1, 0);
    00472   bool vehicle_list_window = HasBit(p1, 1);
    00473
    00474   VehicleListIdentifier vli;
    00475   if (!vli.Unpack(p2)) return CMD_ERROR;
    00476   if (!IsCompanyBuildableVehicleType(vli.vtype)) return CMD_ERROR;
    00477
    00478   if (vehicle_list_window) {
    00479     if (!GenerateVehicleSortList(&list, vli)) return CMD_ERROR;
    00480   } else {
    00481     /* Get the list of vehicles in the depot */
    00482     BuildDepotVehicleList(vli.vtype, tile, &list, NULL);
    00483   }
    00484
    00485   for (uint i = 0; i < list.Length(); i++) {
    00486     const Vehicle *v = list[i];
    00487
    00488     if (!!(v->vehstatus & VS_STOPPED) != do_start) continue;
    00489
    00490     if (!vehicle_list_window) {
    00491       if (vli.vtype == VEH_TRAIN) {
    00492         if (!Train::From(v)->IsInDepot()) continue;
    00493       } else {
    00494         if (!(v->vehstatus & VS_HIDDEN)) continue;
    00495       }
    00496     }
    00497
    00498     /* Just try and don't care if some vehicle's can't be stopped. */
    00499     DoCommand(tile, v->index, 0, flags, CMD_START_STOP_VEHICLE);
    00500   }
    00501
    00502   return CommandCost();
    00503 }
    00504
    00514 CommandCost CmdDepotSellAllVehicles(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00515 {
    00516   VehicleList list;
    00517
    00518   CommandCost cost(EXPENSES_NEW_VEHICLES);
    00519   VehicleType vehicle_type = Extract<VehicleType, 0, 3>(p1);
    00520   uint sell_command = GetCmdSellVeh(vehicle_type);
    00521
    00522   if (!IsCompanyBuildableVehicleType(vehicle_type)) return CMD_ERROR;
    00523
    00524   /* Get the list of vehicles in the depot */
    00525   BuildDepotVehicleList(vehicle_type, tile, &list, &list);
    00526
    00527   CommandCost last_error = CMD_ERROR;
    00528   bool had_success = false;
    00529   for (uint i = 0; i < list.Length(); i++) {
    00530     CommandCost ret = DoCommand(tile, list[i]->index | (1 << 20), 0, flags, sell_command);
    00531     if (ret.Succeeded()) {
    00532       cost.AddCost(ret);
    00533       had_success = true;
    00534     } else {
    00535       last_error = ret;
    00536     }
    00537   }
    00538
    00539   return had_success ? cost : last_error;
    00540 }
    00541
    00551 CommandCost CmdDepotMassAutoReplace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00552 {
    00553   VehicleList list;
    00554   CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES);
    00555   VehicleType vehicle_type = Extract<VehicleType, 0, 3>(p1);
    00556
    00557   if (!IsCompanyBuildableVehicleType(vehicle_type)) return CMD_ERROR;
    00558   if (!IsDepotTile(tile) || !IsTileOwner(tile, _current_company)) return CMD_ERROR;
    00559
    00560   /* Get the list of vehicles in the depot */
    00561   BuildDepotVehicleList(vehicle_type, tile, &list, &list, true);
    00562
    00563   for (uint i = 0; i < list.Length(); i++) {
    00564     const Vehicle *v = list[i];
    00565
    00566     /* Ensure that the vehicle completely in the depot */
    00567     if (!v->IsInDepot()) continue;
    00568
    00569     CommandCost ret = DoCommand(0, v->index, 0, flags, CMD_AUTOREPLACE_VEHICLE);
    00570
    00571     if (ret.Succeeded()) cost.AddCost(ret);
    00572   }
    00573   return cost;
    00574 }
    00575
    00581 static bool IsUniqueVehicleName(const char *name)
    00582 {
    00583   const Vehicle *v;
    00584
    00585   FOR_ALL_VEHICLES(v) {
    00586     if (v->name != NULL && strcmp(v->name, name) == 0) return false;
    00587   }
    00588
    00589   return true;
    00590 }
    00591
    00597 static void CloneVehicleName(const Vehicle *src, Vehicle *dst)
    00598 {
    00599   char buf[256];
    00600
    00601   /* Find the position of the first digit in the last group of digits. */
    00602   size_t number_position;
    00603   for (number_position = strlen(src->name); number_position > 0; number_position--) {
    00604     /* The design of UTF-8 lets this work simply without having to check
    00605      * for UTF-8 sequences. */
    00606     if (src->name[number_position - 1] < '0' || src->name[number_position - 1] > '9') break;
    00607   }
    00608
    00609   /* Format buffer and determine starting number. */
    00610   int num;
    00611   byte padding = 0;
    00612   if (number_position == strlen(src->name)) {
    00613     /* No digit at the end, so start at number 2. */
    00614     strecpy(buf, src->name, lastof(buf));
    00615     strecat(buf, " ", lastof(buf));
    00616     number_position = strlen(buf);
    00617     num = 2;
    00618   } else {
    00619     /* Found digits, parse them and start at the next number. */
    00620     strecpy(buf, src->name, lastof(buf));
    00621     buf[number_position] = '\0';
    00622     char *endptr;
    00623     num = strtol(&src->name[number_position], &endptr, 10) + 1;
    00624     padding = endptr - &src->name[number_position];
    00625   }
    00626
    00627   /* Check if this name is already taken. */
    00628   for (int max_iterations = 1000; max_iterations > 0; max_iterations--, num++) {
    00629     /* Attach the number to the temporary name. */
    00630     seprintf(&buf[number_position], lastof(buf), "%0*d", padding, num);
    00631
    00632     /* Check the name is unique. */
    00633     if (IsUniqueVehicleName(buf)) {
    00634       dst->name = strdup(buf);
    00635       break;
    00636     }
    00637   }
    00638
    00639   /* All done. If we didn't find a name, it'll just use its default. */
    00640 }
    00641
    00651 CommandCost CmdCloneVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00652 {
    00653   CommandCost total_cost(EXPENSES_NEW_VEHICLES);
    00654
    00655   Vehicle *v = Vehicle::GetIfValid(p1);
    00656   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
    00657   Vehicle *v_front = v;
    00658   Vehicle *w = NULL;
    00659   Vehicle *w_front = NULL;
    00660   Vehicle *w_rear = NULL;
    00661
    00662   /*
    00663    * v_front is the front engine in the original vehicle
    00664    * v is the car/vehicle of the original vehicle that is currently being copied
    00665    * w_front is the front engine of the cloned vehicle
    00666    * w is the car/vehicle currently being cloned
    00667    * w_rear is the rear end of the cloned train. It's used to add more cars and is only used by trains
    00668    */
    00669
    00670   CommandCost ret = CheckOwnership(v->owner);
    00671   if (ret.Failed()) return ret;
    00672
    00673   if (v->type == VEH_TRAIN && (!v->IsFrontEngine() || Train::From(v)->crash_anim_pos >= 4400)) return CMD_ERROR;
    00674
    00675   /* check that we can allocate enough vehicles */
    00676   if (!(flags & DC_EXEC)) {
    00677     int veh_counter = 0;
    00678     do {
    00679       veh_counter++;
    00680     } while ((v = v->Next()) != NULL);
    00681
    00682     if (!Vehicle::CanAllocateItem(veh_counter)) {
    00683       return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
    00684     }
    00685   }
    00686
    00687   v = v_front;
    00688
    00689   do {
    00690     if (v->type == VEH_TRAIN && Train::From(v)->IsRearDualheaded()) {
    00691       /* we build the rear ends of multiheaded trains with the front ones */
    00692       continue;
    00693     }
    00694
    00695     /* In case we're building a multi headed vehicle and the maximum number of
    00696      * vehicles is almost reached (e.g. max trains - 1) not all vehicles would
    00697      * be cloned. When the non-primary engines were build they were seen as
    00698      * 'new' vehicles whereas they would immediately be joined with a primary
    00699      * engine. This caused the vehicle to be not build as 'the limit' had been
    00700      * reached, resulting in partially build vehicles and such. */
    00701     DoCommandFlag build_flags = flags;
    00702     if ((flags & DC_EXEC) && !v->IsPrimaryVehicle()) build_flags |= DC_AUTOREPLACE;
    00703
    00704     CommandCost cost = DoCommand(tile, v->engine_type | (1 << 16), 0, build_flags, GetCmdBuildVeh(v));
    00705
    00706     if (cost.Failed()) {
    00707       /* Can't build a part, then sell the stuff we already made; clear up the mess */
    00708       if (w_front != NULL) DoCommand(w_front->tile, w_front->index | (1 << 20), 0, flags, GetCmdSellVeh(w_front));
    00709       return cost;
    00710     }
    00711
    00712     total_cost.AddCost(cost);
    00713
    00714     if (flags & DC_EXEC) {
    00715       w = Vehicle::Get(_new_vehicle_id);
    00716
    00717       if (v->type == VEH_TRAIN && HasBit(Train::From(v)->flags, VRF_REVERSE_DIRECTION)) {
    00718         SetBit(Train::From(w)->flags, VRF_REVERSE_DIRECTION);
    00719       }
    00720
    00721       if (v->type == VEH_TRAIN && !v->IsFrontEngine()) {
    00722         /* this s a train car
    00723          * add this unit to the end of the train */
    00724         CommandCost result = DoCommand(0, w->index | 1 << 20, w_rear->index, flags, CMD_MOVE_RAIL_VEHICLE);
    00725         if (result.Failed()) {
    00726           /* The train can't be joined to make the same consist as the original.
    00727            * Sell what we already made (clean up) and return an error.           */
    00728           DoCommand(w_front->tile, w_front->index | 1 << 20, 0, flags, GetCmdSellVeh(w_front));
    00729           DoCommand(w_front->tile, w->index       | 1 << 20, 0, flags, GetCmdSellVeh(w));
    00730           return result; // return error and the message returned from CMD_MOVE_RAIL_VEHICLE
    00731         }
    00732       } else {
    00733         /* this is a front engine or not a train. */
    00734         w_front = w;
    00735         w->service_interval = v->service_interval;
    00736       }
    00737       w_rear = w; // trains needs to know the last car in the train, so they can add more in next loop
    00738     }
    00739   } while (v->type == VEH_TRAIN && (v = v->GetNextVehicle()) != NULL);
    00740
    00741   if ((flags & DC_EXEC) && v_front->type == VEH_TRAIN) {
    00742     /* for trains this needs to be the front engine due to the callback function */
    00743     _new_vehicle_id = w_front->index;
    00744   }
    00745
    00746   if (flags & DC_EXEC) {
    00747     /* Cloned vehicles belong to the same group */
    00748     DoCommand(0, v_front->group_id, w_front->index, flags, CMD_ADD_VEHICLE_GROUP);
    00749   }
    00750
    00751
    00752   /* Take care of refitting. */
    00753   w = w_front;
    00754   v = v_front;
    00755
    00756   /* Both building and refitting are influenced by newgrf callbacks, which
    00757    * makes it impossible to accurately estimate the cloning costs. In
    00758    * particular, it is possible for engines of the same type to be built with
    00759    * different numbers of articulated parts, so when refitting we have to
    00760    * loop over real vehicles first, and then the articulated parts of those
    00761    * vehicles in a different loop. */
    00762   do {
    00763     do {
    00764       if (flags & DC_EXEC) {
    00765         assert(w != NULL);
    00766
    00767         /* Find out what's the best sub type */
    00768         byte subtype = GetBestFittingSubType(v, w);
    00769         if (w->cargo_type != v->cargo_type || w->cargo_subtype != subtype) {
    00770           CommandCost cost = DoCommand(0, w->index, v->cargo_type | 1U << 7 | (subtype << 8), flags, GetCmdRefitVeh(v));
    00771           if (cost.Succeeded()) total_cost.AddCost(cost);
    00772         }
    00773
    00774         if (w->IsGroundVehicle() && w->HasArticulatedPart()) {
    00775           w = w->GetNextArticulatedPart();
    00776         } else {
    00777           break;
    00778         }
    00779       } else {
    00780         const Engine *e = Engine::Get(v->engine_type);
    00781         CargoID initial_cargo = (e->CanCarryCargo() ? e->GetDefaultCargoType() : (CargoID)CT_INVALID);
    00782
    00783         if (v->cargo_type != initial_cargo && initial_cargo != CT_INVALID) {
    00784           total_cost.AddCost(GetRefitCost(v->engine_type));
    00785         }
    00786       }
    00787
    00788       if (v->IsGroundVehicle() && v->HasArticulatedPart()) {
    00789         v = v->GetNextArticulatedPart();
    00790       } else {
    00791         break;
    00792       }
    00793     } while (v != NULL);
    00794
    00795     if ((flags & DC_EXEC) && v->type == VEH_TRAIN) w = w->GetNextVehicle();
    00796   } while (v->type == VEH_TRAIN && (v = v->GetNextVehicle()) != NULL);
    00797
    00798   if (flags & DC_EXEC) {
    00799     /*
    00800      * Set the orders of the vehicle. Cannot do it earlier as we need
    00801      * the vehicle refitted before doing this, otherwise the moved
    00802      * cargo types might not match (passenger vs non-passenger)
    00803      */
    00804     DoCommand(0, w_front->index | (p2 & 1 ? CO_SHARE : CO_COPY) << 30, v_front->index, flags, CMD_CLONE_ORDER);
    00805
    00806     /* Now clone the vehicle's name, if it has one. */
    00807     if (v_front->name != NULL) CloneVehicleName(v_front, w_front);
    00808   }
    00809
    00810   /* Since we can't estimate the cost of cloning a vehicle accurately we must
    00811    * check whether the company has enough money manually. */
    00812   if (!CheckCompanyHasMoney(total_cost)) {
    00813     if (flags & DC_EXEC) {
    00814       /* The vehicle has already been bought, so now it must be sold again. */
    00815       DoCommand(w_front->tile, w_front->index | 1 << 20, 0, flags, GetCmdSellVeh(w_front));
    00816     }
    00817     return total_cost;
    00818   }
    00819
    00820   return total_cost;
    00821 }
    00822
    00830 static CommandCost SendAllVehiclesToDepot(DoCommandFlag flags, bool service, const VehicleListIdentifier &vli)
    00831 {
    00832   VehicleList list;
    00833
    00834   if (!GenerateVehicleSortList(&list, vli)) return CMD_ERROR;
    00835
    00836   /* Send all the vehicles to a depot */
    00837   bool had_success = false;
    00838   for (uint i = 0; i < list.Length(); i++) {
    00839     const Vehicle *v = list[i];
    00840     CommandCost ret = DoCommand(v->tile, v->index | (service ? DEPOT_SERVICE : 0U) | DEPOT_DONT_CANCEL, 0, flags, GetCmdSendToDepot(vli.vtype));
    00841
    00842     if (ret.Succeeded()) {
    00843       had_success = true;
    00844
    00845       /* Return 0 if DC_EXEC is not set this is a valid goto depot command)
    00846        * In this case we know that at least one vehicle can be sent to a depot
    00847        * and we will issue the command. We can now safely quit the loop, knowing
    00848        * it will succeed at least once. With DC_EXEC we really need to send them to the depot */
    00849       if (!(flags & DC_EXEC)) break;
    00850     }
    00851   }
    00852
    00853   return had_success ? CommandCost() : CMD_ERROR;
    00854 }
    00855
    00867 CommandCost CmdSendVehicleToDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00868 {
    00869   if (p1 & DEPOT_MASS_SEND) {
    00870     /* Mass goto depot requested */
    00871     VehicleListIdentifier vli;
    00872     if (!vli.Unpack(p2)) return CMD_ERROR;
    00873     return SendAllVehiclesToDepot(flags, (p1 & DEPOT_SERVICE) != 0, vli);
    00874   }
    00875
    00876   Vehicle *v = Vehicle::GetIfValid(GB(p1, 0, 20));
    00877   if (v == NULL) return CMD_ERROR;
    00878
    00879   return v->SendToDepot(flags, (DepotCommand)(p1 & DEPOT_COMMAND_MASK));
    00880 }
    00881
    00891 CommandCost CmdRenameVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00892 {
    00893   Vehicle *v = Vehicle::GetIfValid(p1);
    00894   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
    00895
    00896   CommandCost ret = CheckOwnership(v->owner);
    00897   if (ret.Failed()) return ret;
    00898
    00899   bool reset = StrEmpty(text);
    00900
    00901   if (!reset) {
    00902     if (Utf8StringLength(text) >= MAX_LENGTH_VEHICLE_NAME_CHARS) return CMD_ERROR;
    00903     if (!(flags & DC_AUTOREPLACE) && !IsUniqueVehicleName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
    00904   }
    00905
    00906   if (flags & DC_EXEC) {
    00907     free(v->name);
    00908     v->name = reset ? NULL : strdup(text);
    00909     InvalidateWindowClassesData(WC_TRAINS_LIST, 1);
    00910     MarkWholeScreenDirty();
    00911   }
    00912
    00913   return CommandCost();
    00914 }
    00915
    00916
    00926 CommandCost CmdChangeServiceInt(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00927 {
    00928   Vehicle *v = Vehicle::GetIfValid(p1);
    00929   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
    00930
    00931   CommandCost ret = CheckOwnership(v->owner);
    00932   if (ret.Failed()) return ret;
    00933
    00934   uint16 serv_int = GetServiceIntervalClamped(p2, v->owner); // Double check the service interval from the user-input
    00935   if (serv_int != p2) return CMD_ERROR;
    00936
    00937   if (flags & DC_EXEC) {
    00938     v->service_interval = serv_int;
    00939     SetWindowDirty(WC_VEHICLE_DETAILS, v->index);
    00940   }
    00941
    00942   return CommandCost();
    00943 }