# autoreplace_cmd.cpp

Go to the documentation of this file.

    00001 /* $Id: autoreplace_cmd.cpp 15692 2009-03-12 19:40:16Z frosch $ */
    00002
    00005 #include "stdafx.h"
    00006 #include "company_func.h"
    00007 #include "vehicle_gui.h"
    00008 #include "train.h"
    00009 #include "rail.h"
    00010 #include "command_func.h"
    00011 #include "engine_base.h"
    00012 #include "engine_func.h"
    00013 #include "vehicle_func.h"
    00014 #include "functions.h"
    00015 #include "autoreplace_func.h"
    00016 #include "articulated_vehicles.h"
    00017 #include "core/alloc_func.hpp"
    00018
    00019 #include "table/strings.h"
    00020
    00027 static bool EnginesGotCargoInCommon(EngineID engine_a, EngineID engine_b, VehicleType type)
    00028 {
    00029   uint32 available_cargos_a = GetUnionOfArticulatedRefitMasks(engine_a, type, true);
    00030   uint32 available_cargos_b = GetUnionOfArticulatedRefitMasks(engine_b, type, true);
    00031   return (available_cargos_a == 0 || available_cargos_b == 0 || (available_cargos_a & available_cargos_b) != 0);
    00032 }
    00033
    00041 bool CheckAutoreplaceValidity(EngineID from, EngineID to, CompanyID company)
    00042 {
    00043   /* First we make sure that it's a valid type the user requested
    00044    * check that it's an engine that is in the engine array */
    00045   if (!IsEngineIndex(from) || !IsEngineIndex(to)) return false;
    00046
    00047   /* we can't replace an engine into itself (that would be autorenew) */
    00048   if (from == to) return false;
    00049
    00050   VehicleType type = GetEngine(from)->type;
    00051
    00052   /* check that the new vehicle type is available to the company and its type is the same as the original one */
    00053   if (!IsEngineBuildable(to, type, company)) return false;
    00054
    00055   switch (type) {
    00056     case VEH_TRAIN: {
    00057       const RailVehicleInfo *rvi_from = RailVehInfo(from);
    00058       const RailVehicleInfo *rvi_to   = RailVehInfo(to);
    00059
    00060       /* make sure the railtypes are compatible */
    00061       if ((GetRailTypeInfo(rvi_from->railtype)->compatible_railtypes & GetRailTypeInfo(rvi_to->railtype)->compatible_railtypes) == 0) return false;
    00062
    00063       /* make sure we do not replace wagons with engines or vise versa */
    00064       if ((rvi_from->railveh_type == RAILVEH_WAGON) != (rvi_to->railveh_type == RAILVEH_WAGON)) return false;
    00065       break;
    00066     }
    00067
    00068     case VEH_ROAD:
    00069       /* make sure that we do not replace a tram with a normal road vehicles or vise versa */
    00070       if (HasBit(EngInfo(from)->misc_flags, EF_ROAD_TRAM) != HasBit(EngInfo(to)->misc_flags, EF_ROAD_TRAM)) return false;
    00071       break;
    00072
    00073     case VEH_AIRCRAFT:
    00074       /* make sure that we do not replace a plane with a helicopter or vise versa */
    00075       if ((AircraftVehInfo(from)->subtype & AIR_CTOL) != (AircraftVehInfo(to)->subtype & AIR_CTOL)) return false;
    00076       break;
    00077
    00078     default: break;
    00079   }
    00080
    00081   /* the engines needs to be able to carry the same cargo */
    00082   return EnginesGotCargoInCommon(from, to, type);
    00083 }
    00084
    00090 static void TransferCargo(Vehicle *old_veh, Vehicle *new_head, bool part_of_chain)
    00091 {
    00092   assert(!part_of_chain || new_head->IsPrimaryVehicle());
    00093   /* Loop through source parts */
    00094   for (Vehicle *src = old_veh; src != NULL; src = src->Next()) {
    00095     if (!part_of_chain && src->type == VEH_TRAIN && src != old_veh && src != old_veh->u.rail.other_multiheaded_part && !IsArticulatedPart(src)) {
    00096       /* Skip vehicles, which do not belong to old_veh */
    00097       src = GetLastEnginePart(src);
    00098       continue;
    00099     }
    00100     if (src->cargo_type >= NUM_CARGO || src->cargo.Count() == 0) continue;
    00101
    00102     /* Find free space in the new chain */
    00103     for (Vehicle *dest = new_head; dest != NULL && src->cargo.Count() > 0; dest = dest->Next()) {
    00104       if (!part_of_chain && dest->type == VEH_TRAIN && dest != new_head && dest != new_head->u.rail.other_multiheaded_part && !IsArticulatedPart(dest)) {
    00105         /* Skip vehicles, which do not belong to new_head */
    00106         dest = GetLastEnginePart(dest);
    00107         continue;
    00108       }
    00109       if (dest->cargo_type != src->cargo_type) continue;
    00110
    00111       uint amount = min(src->cargo.Count(), dest->cargo_cap - dest->cargo.Count());
    00112       if (amount <= 0) continue;
    00113
    00114       src->cargo.MoveTo(&dest->cargo, amount);
    00115     }
    00116   }
    00117
    00118   /* Update train weight etc., the old vehicle will be sold anyway */
    00119   if (part_of_chain && new_head->type == VEH_TRAIN) TrainConsistChanged(new_head, true);
    00120 }
    00121
    00128 static bool VerifyAutoreplaceRefitForOrders(const Vehicle *v, EngineID engine_type)
    00129 {
    00130   const Order *o;
    00131   const Vehicle *u;
    00132
    00133   uint32 union_refit_mask_a = GetUnionOfArticulatedRefitMasks(v->engine_type, v->type, false);
    00134   uint32 union_refit_mask_b = GetUnionOfArticulatedRefitMasks(engine_type, v->type, false);
    00135
    00136   if (v->type == VEH_TRAIN) {
    00137     u = v->First();
    00138   } else {
    00139     u = v;
    00140   }
    00141
    00142   FOR_VEHICLE_ORDERS(u, o) {
    00143     if (!o->IsRefit()) continue;
    00144     CargoID cargo_type = o->GetRefitCargo();
    00145
    00146     if (!HasBit(union_refit_mask_a, cargo_type)) continue;
    00147     if (!HasBit(union_refit_mask_b, cargo_type)) return false;
    00148   }
    00149
    00150   return true;
    00151 }
    00152
    00162 static CargoID GetNewCargoTypeForReplace(Vehicle *v, EngineID engine_type, bool part_of_chain)
    00163 {
    00164   CargoID cargo_type;
    00165
    00166   if (GetUnionOfArticulatedRefitMasks(engine_type, v->type, true) == 0) return CT_NO_REFIT; // Don't try to refit an engine with no cargo capacity
    00167
    00168   if (IsArticulatedVehicleCarryingDifferentCargos(v, &cargo_type)) return CT_INVALID; // We cannot refit to mixed cargos in an automated way
    00169
    00170   uint32 available_cargo_types = GetIntersectionOfArticulatedRefitMasks(engine_type, v->type, true);
    00171
    00172   if (cargo_type == CT_INVALID) {
    00173     if (v->type != VEH_TRAIN) return CT_NO_REFIT; // If the vehicle does not carry anything at all, every replacement is fine.
    00174
    00175     if (!part_of_chain) return CT_NO_REFIT;
    00176
    00177     /* the old engine didn't have cargo capacity, but the new one does
    00178      * now we will figure out what cargo the train is carrying and refit to fit this */
    00179
    00180     for (v = v->First(); v != NULL; v = v->Next()) {
    00181       if (v->cargo_cap == 0) continue;
    00182       /* Now we found a cargo type being carried on the train and we will see if it is possible to carry to this one */
    00183       if (HasBit(available_cargo_types, v->cargo_type)) {
    00184         /* Do we have to refit the vehicle, or is it already carrying the right cargo? */
    00185         uint16 *default_capacity = GetCapacityOfArticulatedParts(engine_type, v->type);
    00186         for (CargoID cid = 0; cid < NUM_CARGO; cid++) {
    00187           if (cid != v->cargo_type && default_capacity[cid] > 0) return v->cargo_type;
    00188         }
    00189
    00190         return CT_NO_REFIT;
    00191       }
    00192     }
    00193
    00194     return CT_NO_REFIT; // We failed to find a cargo type on the old vehicle and we will not refit the new one
    00195   } else {
    00196     if (!HasBit(available_cargo_types, cargo_type)) return CT_INVALID; // We can't refit the vehicle to carry the cargo we want
    00197
    00198     if (part_of_chain && !VerifyAutoreplaceRefitForOrders(v, engine_type)) return CT_INVALID; // Some refit orders lose their effect
    00199
    00200     /* Do we have to refit the vehicle, or is it already carrying the right cargo? */
    00201     uint16 *default_capacity = GetCapacityOfArticulatedParts(engine_type, v->type);
    00202     for (CargoID cid = 0; cid < NUM_CARGO; cid++) {
    00203       if (cid != cargo_type && default_capacity[cid] > 0) return cargo_type;
    00204     }
    00205
    00206     return CT_NO_REFIT;
    00207   }
    00208 }
    00209
    00215 static EngineID GetNewEngineType(const Vehicle *v, const Company *c)
    00216 {
    00217   assert(v->type != VEH_TRAIN || !IsArticulatedPart(v));
    00218
    00219   if (v->type == VEH_TRAIN && IsRearDualheaded(v)) {
    00220     /* we build the rear ends of multiheaded trains with the front ones */
    00221     return INVALID_ENGINE;
    00222   }
    00223
    00224   EngineID e = EngineReplacementForCompany(c, v->engine_type, v->group_id);
    00225
    00226   if (e != INVALID_ENGINE && IsEngineBuildable(e, v->type, _current_company)) {
    00227     return e;
    00228   }
    00229
    00230   if (v->NeedsAutorenewing(c) && // replace if engine is too old
    00231       IsEngineBuildable(v->engine_type, v->type, _current_company)) { // engine can still be build
    00232     return v->engine_type;
    00233   }
    00234
    00235   return INVALID_ENGINE;
    00236 }
    00237
    00245 static CommandCost BuildReplacementVehicle(Vehicle *old_veh, Vehicle **new_vehicle, bool part_of_chain)
    00246 {
    00247   *new_vehicle = NULL;
    00248
    00249   /* Shall the vehicle be replaced? */
    00250   const Company *c = GetCompany(_current_company);
    00251   EngineID e = GetNewEngineType(old_veh, c);
    00252   if (e == INVALID_ENGINE) return CommandCost(); // neither autoreplace is set, nor autorenew is triggered
    00253
    00254   /* Does it need to be refitted */
    00255   CargoID refit_cargo = GetNewCargoTypeForReplace(old_veh, e, part_of_chain);
    00256   if (refit_cargo == CT_INVALID) return CommandCost(); // incompatible cargos
    00257
    00258   /* Build the new vehicle */
    00259   CommandCost cost = DoCommand(old_veh->tile, e, 0, DC_EXEC | DC_AUTOREPLACE, GetCmdBuildVeh(old_veh));
    00260   if (cost.Failed()) return cost;
    00261
    00262   Vehicle *new_veh = GetVehicle(_new_vehicle_id);
    00263   *new_vehicle = new_veh;
    00264
    00265   /* Refit the vehicle if needed */
    00266   if (refit_cargo != CT_NO_REFIT) {
    00267     cost.AddCost(DoCommand(0, new_veh->index, refit_cargo, DC_EXEC, GetCmdRefitVeh(new_veh)));
    00268     assert(cost.Succeeded()); // This should be ensured by GetNewCargoTypeForReplace()
    00269   }
    00270
    00271   /* Try to reverse the vehicle, but do not care if it fails as the new type might not be reversible */
    00272   if (new_veh->type == VEH_TRAIN && HasBit(old_veh->u.rail.flags, VRF_REVERSE_DIRECTION)) {
    00273     DoCommand(0, new_veh->index, true, DC_EXEC, CMD_REVERSE_TRAIN_DIRECTION);
    00274   }
    00275
    00276   return cost;
    00277 }
    00278
    00284 static inline CommandCost StartStopVehicle(const Vehicle *v, bool evaluate_callback)
    00285 {
    00286   return DoCommand(0, v->index, evaluate_callback ? 1 : 0, DC_EXEC | DC_AUTOREPLACE, CMD_START_STOP_VEHICLE);
    00287 }
    00288
    00295 static inline CommandCost MoveVehicle(const Vehicle *v, const Vehicle *after, DoCommandFlag flags, bool whole_chain)
    00296 {
    00297   return DoCommand(0, v->index | (after != NULL ? after->index : INVALID_VEHICLE) << 16, whole_chain ? 1 : 0, flags, CMD_MOVE_RAIL_VEHICLE);
    00298 }
    00299
    00305 static CommandCost CopyHeadSpecificThings(Vehicle *old_head, Vehicle *new_head, DoCommandFlag flags)
    00306 {
    00307   CommandCost cost = CommandCost();
    00308
    00309   /* Share orders */
    00310   if (cost.Succeeded() && old_head != new_head) cost.AddCost(DoCommand(0, (old_head->index << 16) | new_head->index, CO_SHARE, DC_EXEC, CMD_CLONE_ORDER));
    00311
    00312   /* Copy group membership */
    00313   if (cost.Succeeded() && old_head != new_head) cost.AddCost(DoCommand(0, old_head->group_id, new_head->index, DC_EXEC, CMD_ADD_VEHICLE_GROUP));
    00314
    00315   /* Perform start/stop check whether the new vehicle suits newgrf restrictions etc. */
    00316   if (cost.Succeeded()) {
    00317     /* Start the vehicle, might be denied by certain things */
    00318     assert((new_head->vehstatus & VS_STOPPED) != 0);
    00319     cost.AddCost(StartStopVehicle(new_head, true));
    00320
    00321     /* Stop the vehicle again, but do not care about evil newgrfs allowing starting but not stopping :p */
    00322     if (cost.Succeeded()) cost.AddCost(StartStopVehicle(new_head, false));
    00323   }
    00324
    00325   /* Last do those things which do never fail (resp. we do not care about), but which are not undo-able */
    00326   if (cost.Succeeded() && old_head != new_head && (flags & DC_EXEC) != 0) {
    00327     /* Copy vehicle name */
    00328     if (old_head->name != NULL) {
    00329       DoCommand(0, new_head->index, 0, DC_EXEC | DC_AUTOREPLACE, CMD_RENAME_VEHICLE, old_head->name);
    00330     }
    00331
    00332     /* Copy other things which cannot be copied by a command and which shall not stay resetted from the build vehicle command */
    00333     new_head->CopyVehicleConfigAndStatistics(old_head);
    00334
    00335     /* Switch vehicle windows to the new vehicle, so they are not closed when the old vehicle is sold */
    00336     ChangeVehicleViewWindow(old_head->index, new_head->index);
    00337   }
    00338
    00339   return cost;
    00340 }
    00341
    00348 static CommandCost ReplaceFreeUnit(Vehicle **single_unit, DoCommandFlag flags, bool *nothing_to_do)
    00349 {
    00350   Vehicle *old_v = *single_unit;
    00351   assert(old_v->type == VEH_TRAIN && !IsArticulatedPart(old_v) && !IsRearDualheaded(old_v));
    00352
    00353   CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, 0);
    00354
    00355   /* Build and refit replacement vehicle */
    00356   Vehicle *new_v = NULL;
    00357   cost.AddCost(BuildReplacementVehicle(old_v, &new_v, false));
    00358
    00359   /* Was a new vehicle constructed? */
    00360   if (cost.Succeeded() && new_v != NULL) {
    00361     *nothing_to_do = false;
    00362
    00363     if ((flags & DC_EXEC) != 0) {
    00364       /* Move the new vehicle behind the old */
    00365       MoveVehicle(new_v, old_v, DC_EXEC, false);
    00366
    00367       /* Take over cargo
    00368        * Note: We do only transfer cargo from the old to the new vehicle.
    00369        *       I.e. we do not transfer remaining cargo to other vehicles.
    00370        *       Else you would also need to consider moving cargo to other free chains,
    00371        *       or doing the same in ReplaceChain(), which would be quite troublesome.
    00372        */
    00373       TransferCargo(old_v, new_v, false);
    00374
    00375       *single_unit = new_v;
    00376     }
    00377
    00378     /* Sell the old vehicle */
    00379     cost.AddCost(DoCommand(0, old_v->index, 0, flags, GetCmdSellVeh(old_v)));
    00380
    00381     /* If we are not in DC_EXEC undo everything */
    00382     if ((flags & DC_EXEC) == 0) {
    00383       DoCommand(0, new_v->index, 0, DC_EXEC, GetCmdSellVeh(new_v));
    00384     }
    00385   }
    00386
    00387   return cost;
    00388 }
    00389
    00397 static CommandCost ReplaceChain(Vehicle **chain, DoCommandFlag flags, bool wagon_removal, bool *nothing_to_do)
    00398 {
    00399   Vehicle *old_head = *chain;
    00400   assert(old_head->IsPrimaryVehicle());
    00401
    00402   CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, 0);
    00403
    00404   if (old_head->type == VEH_TRAIN) {
    00405     /* Store the length of the old vehicle chain, rounded up to whole tiles */
    00406     uint16 old_total_length = (old_head->u.rail.cached_total_length + TILE_SIZE - 1) / TILE_SIZE * TILE_SIZE;
    00407
    00408     int num_units = 0;
    00409     for (Vehicle *w = old_head; w != NULL; w = GetNextUnit(w)) num_units++;
    00410
    00411     Vehicle **old_vehs = CallocT<Vehicle *>(num_units);
    00412     Vehicle **new_vehs = CallocT<Vehicle *>(num_units);
    00413     Money *new_costs = MallocT<Money>(num_units);
    00414
    00415     /* Collect vehicles and build replacements
    00416      * Note: The replacement vehicles can only successfully build as long as the old vehicles are still in their chain */
    00417     int i;
    00418     Vehicle *w;
    00419     for (w = old_head, i = 0; w != NULL; w = GetNextUnit(w), i++) {
    00420       assert(i < num_units);
    00421       old_vehs[i] = w;
    00422
    00423       CommandCost ret = BuildReplacementVehicle(old_vehs[i], &new_vehs[i], true);
    00424       cost.AddCost(ret);
    00425       if (cost.Failed()) break;
    00426
    00427       new_costs[i] = ret.GetCost();
    00428       if (new_vehs[i] != NULL) *nothing_to_do = false;
    00429     }
    00430     Vehicle *new_head = (new_vehs[0] != NULL ? new_vehs[0] : old_vehs[0]);
    00431
    00432     /* Note: When autoreplace has already failed here, old_vehs[] is not completely initialized. But it is also not needed. */
    00433     if (cost.Succeeded()) {
    00434       /* Separate the head, so we can start constructing the new chain */
    00435       Vehicle *second = GetNextUnit(old_head);
    00436       if (second != NULL) cost.AddCost(MoveVehicle(second, NULL, DC_EXEC | DC_AUTOREPLACE, true));
    00437
    00438       assert(GetNextUnit(new_head) == NULL);
    00439
    00440       /* Append engines to the new chain
    00441        * We do this from back to front, so that the head of the temporary vehicle chain does not change all the time.
    00442        * OTOH the vehicle attach callback is more expensive this way :s */
    00443       Vehicle *last_engine = NULL;
    00444       if (cost.Succeeded()) {
    00445         for (int i = num_units - 1; i > 0; i--) {
    00446           Vehicle *append = (new_vehs[i] != NULL ? new_vehs[i] : old_vehs[i]);
    00447
    00448           if (RailVehInfo(append->engine_type)->railveh_type == RAILVEH_WAGON) continue;
    00449
    00450           if (last_engine == NULL) last_engine = append;
    00451           cost.AddCost(MoveVehicle(append, new_head, DC_EXEC, false));
    00452           if (cost.Failed()) break;
    00453         }
    00454         if (last_engine == NULL) last_engine = new_head;
    00455       }
    00456
    00457       /* When wagon removal is enabled and the new engines without any wagons are already longer than the old, we have to fail */
    00458       if (cost.Succeeded() && wagon_removal && new_head->u.rail.cached_total_length > old_total_length) cost = CommandCost(STR_TRAIN_TOO_LONG_AFTER_REPLACEMENT);
    00459
    00460       /* Append/insert wagons into the new vehicle chain
    00461        * We do this from back to front, so we can stop when wagon removal or maximum train length (i.e. from mammoth-train setting) is triggered.
    00462        */
    00463       if (cost.Succeeded()) {
    00464         for (int i = num_units - 1; i > 0; i--) {
    00465           assert(last_engine != NULL);
    00466           Vehicle *append = (new_vehs[i] != NULL ? new_vehs[i] : old_vehs[i]);
    00467
    00468           if (RailVehInfo(append->engine_type)->railveh_type == RAILVEH_WAGON) {
    00469             /* Insert wagon after 'last_engine' */
    00470             CommandCost res = MoveVehicle(append, last_engine, DC_EXEC, false);
    00471
    00472             if (res.Succeeded() && wagon_removal && new_head->u.rail.cached_total_length > old_total_length) {
    00473               MoveVehicle(append, NULL, DC_EXEC | DC_AUTOREPLACE, false);
    00474               break;
    00475             }
    00476
    00477             cost.AddCost(res);
    00478             if (cost.Failed()) break;
    00479           } else {
    00480             /* We have reached 'last_engine', continue with the next engine towards the front */
    00481             assert(append == last_engine);
    00482             last_engine = GetPrevUnit(last_engine);
    00483           }
    00484         }
    00485       }
    00486
    00487       /* Sell superfluous new vehicles that could not be inserted. */
    00488       if (cost.Succeeded() && wagon_removal) {
    00489         for (int i = 1; i < num_units; i++) {
    00490           Vehicle *wagon = new_vehs[i];
    00491           if (wagon == NULL) continue;
    00492           if (wagon->First() == new_head) break;
    00493
    00494           assert(RailVehInfo(wagon->engine_type)->railveh_type == RAILVEH_WAGON);
    00495
    00496           /* Sell wagon */
    00497           CommandCost ret = DoCommand(0, wagon->index, 0, DC_EXEC, GetCmdSellVeh(wagon));
    00498           assert(ret.Succeeded());
    00499           new_vehs[i] = NULL;
    00500
    00501           /* Revert the money subtraction when the vehicle was built.
    00502            * This value is different from the sell value, esp. because of refitting */
    00503           cost.AddCost(-new_costs[i]);
    00504         }
    00505       }
    00506
    00507       /* The new vehicle chain is constructed, now take over orders and everything... */
    00508       if (cost.Succeeded()) cost.AddCost(CopyHeadSpecificThings(old_head, new_head, flags));
    00509
    00510       if (cost.Succeeded()) {
    00511         /* Success ! */
    00512         if ((flags & DC_EXEC) != 0 && new_head != old_head) {
    00513           *chain = new_head;
    00514         }
    00515
    00516         /* Transfer cargo of old vehicles and sell them */
    00517         for (int i = 0; i < num_units; i++) {
    00518           Vehicle *w = old_vehs[i];
    00519           /* Is the vehicle again part of the new chain?
    00520            * Note: We cannot test 'new_vehs[i] != NULL' as wagon removal might cause to remove both */
    00521           if (w->First() == new_head) continue;
    00522
    00523           if ((flags & DC_EXEC) != 0) TransferCargo(w, new_head, true);
    00524
    00525           /* Sell the vehicle.
    00526            * Note: This might temporarly construct new trains, so use DC_AUTOREPLACE to prevent
    00527            *       it from failing due to engine limits. */
    00528           cost.AddCost(DoCommand(0, w->index, 0, flags | DC_AUTOREPLACE, GetCmdSellVeh(w)));
    00529           if ((flags & DC_EXEC) != 0) {
    00530             old_vehs[i] = NULL;
    00531             if (i == 0) old_head = NULL;
    00532           }
    00533         }
    00534       }
    00535
    00536       /* If we are not in DC_EXEC undo everything, i.e. rearrange old vehicles.
    00537        * We do this from back to front, so that the head of the temporary vehicle chain does not change all the time.
    00538        * Note: The vehicle attach callback is disabled here :) */
    00539       if ((flags & DC_EXEC) == 0) {
    00540         /* Separate the head, so we can reattach the old vehicles */
    00541         Vehicle *second = GetNextUnit(old_head);
    00542         if (second != NULL) MoveVehicle(second, NULL, DC_EXEC | DC_AUTOREPLACE, true);
    00543
    00544         assert(GetNextUnit(old_head) == NULL);
    00545
    00546         for (int i = num_units - 1; i > 0; i--) {
    00547           CommandCost ret = MoveVehicle(old_vehs[i], old_head, DC_EXEC | DC_AUTOREPLACE, false);
    00548           assert(ret.Succeeded());
    00549         }
    00550       }
    00551     }
    00552
    00553     /* Finally undo buying of new vehicles */
    00554     if ((flags & DC_EXEC) == 0) {
    00555       for (int i = num_units - 1; i >= 0; i--) {
    00556         if (new_vehs[i] != NULL) {
    00557           DoCommand(0, new_vehs[i]->index, 0, DC_EXEC, GetCmdSellVeh(new_vehs[i]));
    00558           new_vehs[i] = NULL;
    00559         }
    00560       }
    00561     }
    00562
    00563     free(old_vehs);
    00564     free(new_vehs);
    00565     free(new_costs);
    00566   } else {
    00567     /* Build and refit replacement vehicle */
    00568     Vehicle *new_head = NULL;
    00569     cost.AddCost(BuildReplacementVehicle(old_head, &new_head, true));
    00570
    00571     /* Was a new vehicle constructed? */
    00572     if (cost.Succeeded() && new_head != NULL) {
    00573       *nothing_to_do = false;
    00574
    00575       /* The new vehicle is constructed, now take over orders and everything... */
    00576       cost.AddCost(CopyHeadSpecificThings(old_head, new_head, flags));
    00577
    00578       if (cost.Succeeded()) {
    00579         /* The new vehicle is constructed, now take over cargo */
    00580         if ((flags & DC_EXEC) != 0) {
    00581           TransferCargo(old_head, new_head, true);
    00582           *chain = new_head;
    00583         }
    00584
    00585         /* Sell the old vehicle */
    00586         cost.AddCost(DoCommand(0, old_head->index, 0, flags, GetCmdSellVeh(old_head)));
    00587       }
    00588
    00589       /* If we are not in DC_EXEC undo everything */
    00590       if ((flags & DC_EXEC) == 0) {
    00591         DoCommand(0, new_head->index, 0, DC_EXEC, GetCmdSellVeh(new_head));
    00592       }
    00593     }
    00594   }
    00595
    00596   return cost;
    00597 }
    00598
    00606 CommandCost CmdAutoreplaceVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00607 {
    00608   CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, 0);
    00609   bool nothing_to_do = true;
    00610
    00611   if (!IsValidVehicleID(p1)) return CMD_ERROR;
    00612   Vehicle *v = GetVehicle(p1);
    00613   if (!CheckOwnership(v->owner)) return CMD_ERROR;
    00614   if (!v->IsInDepot()) return CMD_ERROR;
    00615   if (HASBITS(v->vehstatus, VS_CRASHED)) return CMD_ERROR;
    00616
    00617   bool free_wagon = false;
    00618   if (v->type == VEH_TRAIN) {
    00619     if (IsArticulatedPart(v) || IsRearDualheaded(v)) return CMD_ERROR;
    00620     free_wagon = !IsFrontEngine(v);
    00621     if (free_wagon && IsFrontEngine(v->First())) return CMD_ERROR;
    00622   } else {
    00623     if (!v->IsPrimaryVehicle()) return CMD_ERROR;
    00624   }
    00625
    00626   const Company *c = GetCompany(_current_company);
    00627   bool wagon_removal = c->renew_keep_length;
    00628
    00629   /* Test whether any replacement is set, before issuing a whole lot of commands that would end in nothing changed */
    00630   Vehicle *w = v;
    00631   bool any_replacements = false;
    00632   while (w != NULL && !any_replacements) {
    00633     any_replacements = (GetNewEngineType(w, c) != INVALID_ENGINE);
    00634     w = (!free_wagon && w->type == VEH_TRAIN ? GetNextUnit(w) : NULL);
    00635   }
    00636
    00637   if (any_replacements) {
    00638     bool was_stopped = free_wagon || ((v->vehstatus & VS_STOPPED) != 0);
    00639
    00640     /* Stop the vehicle */
    00641     if (!was_stopped) cost.AddCost(StartStopVehicle(v, true));
    00642     if (cost.Failed()) return cost;
    00643
    00644     assert(v->IsStoppedInDepot());
    00645
    00646     /* We have to construct the new vehicle chain to test whether it is valid.
    00647      * Vehicle construction needs random bits, so we have to save the random seeds
    00648      * to prevent desyncs and to replay newgrf callbacks during DC_EXEC */
    00649     SavedRandomSeeds saved_seeds;
    00650     SaveRandomSeeds(&saved_seeds);
    00651     if (free_wagon) {
    00652       cost.AddCost(ReplaceFreeUnit(&v, flags & ~DC_EXEC, &nothing_to_do));
    00653     } else {
    00654       cost.AddCost(ReplaceChain(&v, flags & ~DC_EXEC, wagon_removal, &nothing_to_do));
    00655     }
    00656     RestoreRandomSeeds(saved_seeds);
    00657
    00658     if (cost.Succeeded() && (flags & DC_EXEC) != 0) {
    00659       CommandCost ret;
    00660       if (free_wagon) {
    00661         ret = ReplaceFreeUnit(&v, flags, &nothing_to_do);
    00662       } else {
    00663         ret = ReplaceChain(&v, flags, wagon_removal, &nothing_to_do);
    00664       }
    00665       assert(ret.Succeeded() && ret.GetCost() == cost.GetCost());
    00666     }
    00667
    00668     /* Restart the vehicle */
    00669     if (!was_stopped) cost.AddCost(StartStopVehicle(v, false));
    00670   }
    00671
    00672   if (cost.Succeeded() && nothing_to_do) cost = CommandCost(STR_AUTOREPLACE_NOTHING_TO_DO);
    00673   return cost;
    00674 }