# autoreplace_cmd.cpp

Go to the documentation of this file.

    00001 /* $Id: autoreplace_cmd.cpp 26317 2014-02-07 23:48:56Z frosch $ */
    00002
    00003 /*
    00004  * This file is part of OpenTTD.
    00005  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
    00006  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
    00007  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
    00008  */
    00009
    00012 #include "stdafx.h"
    00013 #include "company_func.h"
    00014 #include "train.h"
    00015 #include "command_func.h"
    00016 #include "engine_func.h"
    00017 #include "vehicle_func.h"
    00018 #include "autoreplace_func.h"
    00019 #include "autoreplace_gui.h"
    00020 #include "articulated_vehicles.h"
    00021 #include "core/random_func.hpp"
    00022
    00023 #include "table/strings.h"
    00024
    00025 extern void ChangeVehicleViewports(VehicleID from_index, VehicleID to_index);
    00026 extern void ChangeVehicleNews(VehicleID from_index, VehicleID to_index);
    00027 extern void ChangeVehicleViewWindow(VehicleID from_index, VehicleID to_index);
    00028
    00036 static bool EnginesHaveCargoInCommon(EngineID engine_a, EngineID engine_b)
    00037 {
    00038   uint32 available_cargoes_a = GetUnionOfArticulatedRefitMasks(engine_a, true);
    00039   uint32 available_cargoes_b = GetUnionOfArticulatedRefitMasks(engine_b, true);
    00040   return (available_cargoes_a == 0 || available_cargoes_b == 0 || (available_cargoes_a & available_cargoes_b) != 0);
    00041 }
    00042
    00050 bool CheckAutoreplaceValidity(EngineID from, EngineID to, CompanyID company)
    00051 {
    00052   assert(Engine::IsValidID(from) && Engine::IsValidID(to));
    00053
    00054   /* we can't replace an engine into itself (that would be autorenew) */
    00055   if (from == to) return false;
    00056
    00057   const Engine *e_from = Engine::Get(from);
    00058   const Engine *e_to = Engine::Get(to);
    00059   VehicleType type = e_from->type;
    00060
    00061   /* check that the new vehicle type is available to the company and its type is the same as the original one */
    00062   if (!IsEngineBuildable(to, type, company)) return false;
    00063
    00064   switch (type) {
    00065     case VEH_TRAIN: {
    00066       /* make sure the railtypes are compatible */
    00067       if ((GetRailTypeInfo(e_from->u.rail.railtype)->compatible_railtypes & GetRailTypeInfo(e_to->u.rail.railtype)->compatible_railtypes) == 0) return false;
    00068
    00069       /* make sure we do not replace wagons with engines or vice versa */
    00070       if ((e_from->u.rail.railveh_type == RAILVEH_WAGON) != (e_to->u.rail.railveh_type == RAILVEH_WAGON)) return false;
    00071       break;
    00072     }
    00073
    00074     case VEH_ROAD:
    00075       /* make sure that we do not replace a tram with a normal road vehicles or vice versa */
    00076       if (HasBit(e_from->info.misc_flags, EF_ROAD_TRAM) != HasBit(e_to->info.misc_flags, EF_ROAD_TRAM)) return false;
    00077       break;
    00078
    00079     case VEH_AIRCRAFT:
    00080       /* make sure that we do not replace a plane with a helicopter or vice versa */
    00081       if ((e_from->u.air.subtype & AIR_CTOL) != (e_to->u.air.subtype & AIR_CTOL)) return false;
    00082       break;
    00083
    00084     default: break;
    00085   }
    00086
    00087   /* the engines needs to be able to carry the same cargo */
    00088   return EnginesHaveCargoInCommon(from, to);
    00089 }
    00090
    00097 void CheckCargoCapacity(Vehicle *v)
    00098 {
    00099   assert(v == NULL || v->First() == v);
    00100
    00101   for (Vehicle *src = v; src != NULL; src = src->Next()) {
    00102     assert(src->cargo.TotalCount() == src->cargo.ActionCount(VehicleCargoList::MTA_KEEP));
    00103
    00104     /* Do we need to more cargo away? */
    00105     if (src->cargo.TotalCount() <= src->cargo_cap) continue;
    00106
    00107     /* We need to move a particular amount. Try that on the other vehicles. */
    00108     uint to_spread = src->cargo.TotalCount() - src->cargo_cap;
    00109     for (Vehicle *dest = v; dest != NULL && to_spread != 0; dest = dest->Next()) {
    00110       assert(dest->cargo.TotalCount() == dest->cargo.ActionCount(VehicleCargoList::MTA_KEEP));
    00111       if (dest->cargo.TotalCount() >= dest->cargo_cap || dest->cargo_type != src->cargo_type) continue;
    00112
    00113       uint amount = min(to_spread, dest->cargo_cap - dest->cargo.TotalCount());
    00114       src->cargo.Shift(amount, &dest->cargo);
    00115       to_spread -= amount;
    00116     }
    00117
    00118     /* Any left-overs will be thrown away, but not their feeder share. */
    00119     if (src->cargo_cap < src->cargo.TotalCount()) src->cargo.Truncate(src->cargo.TotalCount() - src->cargo_cap);
    00120   }
    00121 }
    00122
    00132 static void TransferCargo(Vehicle *old_veh, Vehicle *new_head, bool part_of_chain)
    00133 {
    00134   assert(!part_of_chain || new_head->IsPrimaryVehicle());
    00135   /* Loop through source parts */
    00136   for (Vehicle *src = old_veh; src != NULL; src = src->Next()) {
    00137     assert(src->cargo.TotalCount() == src->cargo.ActionCount(VehicleCargoList::MTA_KEEP));
    00138     if (!part_of_chain && src->type == VEH_TRAIN && src != old_veh && src != Train::From(old_veh)->other_multiheaded_part && !src->IsArticulatedPart()) {
    00139       /* Skip vehicles, which do not belong to old_veh */
    00140       src = src->GetLastEnginePart();
    00141       continue;
    00142     }
    00143     if (src->cargo_type >= NUM_CARGO || src->cargo.TotalCount() == 0) continue;
    00144
    00145     /* Find free space in the new chain */
    00146     for (Vehicle *dest = new_head; dest != NULL && src->cargo.TotalCount() > 0; dest = dest->Next()) {
    00147       assert(dest->cargo.TotalCount() == dest->cargo.ActionCount(VehicleCargoList::MTA_KEEP));
    00148       if (!part_of_chain && dest->type == VEH_TRAIN && dest != new_head && dest != Train::From(new_head)->other_multiheaded_part && !dest->IsArticulatedPart()) {
    00149         /* Skip vehicles, which do not belong to new_head */
    00150         dest = dest->GetLastEnginePart();
    00151         continue;
    00152       }
    00153       if (dest->cargo_type != src->cargo_type) continue;
    00154
    00155       uint amount = min(src->cargo.TotalCount(), dest->cargo_cap - dest->cargo.TotalCount());
    00156       if (amount <= 0) continue;
    00157
    00158       src->cargo.Shift(amount, &dest->cargo);
    00159     }
    00160   }
    00161
    00162   /* Update train weight etc., the old vehicle will be sold anyway */
    00163   if (part_of_chain && new_head->type == VEH_TRAIN) Train::From(new_head)->ConsistChanged(CCF_LOADUNLOAD);
    00164 }
    00165
    00172 static bool VerifyAutoreplaceRefitForOrders(const Vehicle *v, EngineID engine_type)
    00173 {
    00174
    00175   uint32 union_refit_mask_a = GetUnionOfArticulatedRefitMasks(v->engine_type, false);
    00176   uint32 union_refit_mask_b = GetUnionOfArticulatedRefitMasks(engine_type, false);
    00177
    00178   const Order *o;
    00179   const Vehicle *u = (v->type == VEH_TRAIN) ? v->First() : v;
    00180   FOR_VEHICLE_ORDERS(u, o) {
    00181     if (!o->IsRefit() || o->IsAutoRefit()) continue;
    00182     CargoID cargo_type = o->GetRefitCargo();
    00183
    00184     if (!HasBit(union_refit_mask_a, cargo_type)) continue;
    00185     if (!HasBit(union_refit_mask_b, cargo_type)) return false;
    00186   }
    00187
    00188   return true;
    00189 }
    00190
    00200 static CargoID GetNewCargoTypeForReplace(Vehicle *v, EngineID engine_type, bool part_of_chain)
    00201 {
    00202   uint32 available_cargo_types, union_mask;
    00203   GetArticulatedRefitMasks(engine_type, true, &union_mask, &available_cargo_types);
    00204
    00205   if (union_mask == 0) return CT_NO_REFIT; // Don't try to refit an engine with no cargo capacity
    00206
    00207   CargoID cargo_type;
    00208   if (IsArticulatedVehicleCarryingDifferentCargoes(v, &cargo_type)) return CT_INVALID; // We cannot refit to mixed cargoes in an automated way
    00209
    00210   if (cargo_type == CT_INVALID) {
    00211     if (v->type != VEH_TRAIN) return CT_NO_REFIT; // If the vehicle does not carry anything at all, every replacement is fine.
    00212
    00213     if (!part_of_chain) return CT_NO_REFIT;
    00214
    00215     /* the old engine didn't have cargo capacity, but the new one does
    00216      * now we will figure out what cargo the train is carrying and refit to fit this */
    00217
    00218     for (v = v->First(); v != NULL; v = v->Next()) {
    00219       if (!v->GetEngine()->CanCarryCargo()) continue;
    00220       /* Now we found a cargo type being carried on the train and we will see if it is possible to carry to this one */
    00221       if (HasBit(available_cargo_types, v->cargo_type)) return v->cargo_type;
    00222     }
    00223
    00224     return CT_NO_REFIT; // We failed to find a cargo type on the old vehicle and we will not refit the new one
    00225   } else {
    00226     if (!HasBit(available_cargo_types, cargo_type)) return CT_INVALID; // We can't refit the vehicle to carry the cargo we want
    00227
    00228     if (part_of_chain && !VerifyAutoreplaceRefitForOrders(v, engine_type)) return CT_INVALID; // Some refit orders lose their effect
    00229
    00230     return cargo_type;
    00231   }
    00232 }
    00233
    00242 static CommandCost GetNewEngineType(const Vehicle *v, const Company *c, bool always_replace, EngineID &e)
    00243 {
    00244   assert(v->type != VEH_TRAIN || !v->IsArticulatedPart());
    00245
    00246   e = INVALID_ENGINE;
    00247
    00248   if (v->type == VEH_TRAIN && Train::From(v)->IsRearDualheaded()) {
    00249     /* we build the rear ends of multiheaded trains with the front ones */
    00250     return CommandCost();
    00251   }
    00252
    00253   bool replace_when_old;
    00254   e = EngineReplacementForCompany(c, v->engine_type, v->group_id, &replace_when_old);
    00255   if (!always_replace && replace_when_old && !v->NeedsAutorenewing(c, false)) e = INVALID_ENGINE;
    00256
    00257   /* Autoreplace, if engine is available */
    00258   if (e != INVALID_ENGINE && IsEngineBuildable(e, v->type, _current_company)) {
    00259     return CommandCost();
    00260   }
    00261
    00262   /* Autorenew if needed */
    00263   if (v->NeedsAutorenewing(c)) e = v->engine_type;
    00264
    00265   /* Nothing to do or all is fine? */
    00266   if (e == INVALID_ENGINE || IsEngineBuildable(e, v->type, _current_company)) return CommandCost();
    00267
    00268   /* The engine we need is not available. Report error to user */
    00269   return CommandCost(STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE + v->type);
    00270 }
    00271
    00280 static CommandCost BuildReplacementVehicle(Vehicle *old_veh, Vehicle **new_vehicle, bool part_of_chain)
    00281 {
    00282   *new_vehicle = NULL;
    00283
    00284   /* Shall the vehicle be replaced? */
    00285   const Company *c = Company::Get(_current_company);
    00286   EngineID e;
    00287   CommandCost cost = GetNewEngineType(old_veh, c, true, e);
    00288   if (cost.Failed()) return cost;
    00289   if (e == INVALID_ENGINE) return CommandCost(); // neither autoreplace is set, nor autorenew is triggered
    00290
    00291   /* Does it need to be refitted */
    00292   CargoID refit_cargo = GetNewCargoTypeForReplace(old_veh, e, part_of_chain);
    00293   if (refit_cargo == CT_INVALID) return CommandCost(); // incompatible cargoes
    00294
    00295   /* Build the new vehicle */
    00296   cost = DoCommand(old_veh->tile, e, 0, DC_EXEC | DC_AUTOREPLACE, GetCmdBuildVeh(old_veh));
    00297   if (cost.Failed()) return cost;
    00298
    00299   Vehicle *new_veh = Vehicle::Get(_new_vehicle_id);
    00300   *new_vehicle = new_veh;
    00301
    00302   /* Refit the vehicle if needed */
    00303   if (refit_cargo != CT_NO_REFIT) {
    00304     byte subtype = GetBestFittingSubType(old_veh, new_veh, refit_cargo);
    00305
    00306     cost.AddCost(DoCommand(0, new_veh->index, refit_cargo | (subtype << 8), DC_EXEC, GetCmdRefitVeh(new_veh)));
    00307     assert(cost.Succeeded()); // This should be ensured by GetNewCargoTypeForReplace()
    00308   }
    00309
    00310   /* Try to reverse the vehicle, but do not care if it fails as the new type might not be reversible */
    00311   if (new_veh->type == VEH_TRAIN && HasBit(Train::From(old_veh)->flags, VRF_REVERSE_DIRECTION)) {
    00312     DoCommand(0, new_veh->index, true, DC_EXEC, CMD_REVERSE_TRAIN_DIRECTION);
    00313   }
    00314
    00315   return cost;
    00316 }
    00317
    00324 static inline CommandCost CmdStartStopVehicle(const Vehicle *v, bool evaluate_callback)
    00325 {
    00326   return DoCommand(0, v->index, evaluate_callback ? 1 : 0, DC_EXEC | DC_AUTOREPLACE, CMD_START_STOP_VEHICLE);
    00327 }
    00328
    00337 static inline CommandCost CmdMoveVehicle(const Vehicle *v, const Vehicle *after, DoCommandFlag flags, bool whole_chain)
    00338 {
    00339   return DoCommand(0, v->index | (whole_chain ? 1 : 0) << 20, after != NULL ? after->index : INVALID_VEHICLE, flags | DC_NO_CARGO_CAP_CHECK, CMD_MOVE_RAIL_VEHICLE);
    00340 }
    00341
    00348 static CommandCost CopyHeadSpecificThings(Vehicle *old_head, Vehicle *new_head, DoCommandFlag flags)
    00349 {
    00350   CommandCost cost = CommandCost();
    00351
    00352   /* Share orders */
    00353   if (cost.Succeeded() && old_head != new_head) cost.AddCost(DoCommand(0, new_head->index | CO_SHARE << 30, old_head->index, DC_EXEC, CMD_CLONE_ORDER));
    00354
    00355   /* Copy group membership */
    00356   if (cost.Succeeded() && old_head != new_head) cost.AddCost(DoCommand(0, old_head->group_id, new_head->index, DC_EXEC, CMD_ADD_VEHICLE_GROUP));
    00357
    00358   /* Perform start/stop check whether the new vehicle suits newgrf restrictions etc. */
    00359   if (cost.Succeeded()) {
    00360     /* Start the vehicle, might be denied by certain things */
    00361     assert((new_head->vehstatus & VS_STOPPED) != 0);
    00362     cost.AddCost(CmdStartStopVehicle(new_head, true));
    00363
    00364     /* Stop the vehicle again, but do not care about evil newgrfs allowing starting but not stopping :p */
    00365     if (cost.Succeeded()) cost.AddCost(CmdStartStopVehicle(new_head, false));
    00366   }
    00367
    00368   /* Last do those things which do never fail (resp. we do not care about), but which are not undo-able */
    00369   if (cost.Succeeded() && old_head != new_head && (flags & DC_EXEC) != 0) {
    00370     /* Copy other things which cannot be copied by a command and which shall not stay resetted from the build vehicle command */
    00371     new_head->CopyVehicleConfigAndStatistics(old_head);
    00372
    00373     /* Switch vehicle windows/news to the new vehicle, so they are not closed/deleted when the old vehicle is sold */
    00374     ChangeVehicleViewports(old_head->index, new_head->index);
    00375     ChangeVehicleViewWindow(old_head->index, new_head->index);
    00376     ChangeVehicleNews(old_head->index, new_head->index);
    00377   }
    00378
    00379   return cost;
    00380 }
    00381
    00389 static CommandCost ReplaceFreeUnit(Vehicle **single_unit, DoCommandFlag flags, bool *nothing_to_do)
    00390 {
    00391   Train *old_v = Train::From(*single_unit);
    00392   assert(!old_v->IsArticulatedPart() && !old_v->IsRearDualheaded());
    00393
    00394   CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, 0);
    00395
    00396   /* Build and refit replacement vehicle */
    00397   Vehicle *new_v = NULL;
    00398   cost.AddCost(BuildReplacementVehicle(old_v, &new_v, false));
    00399
    00400   /* Was a new vehicle constructed? */
    00401   if (cost.Succeeded() && new_v != NULL) {
    00402     *nothing_to_do = false;
    00403
    00404     if ((flags & DC_EXEC) != 0) {
    00405       /* Move the new vehicle behind the old */
    00406       CmdMoveVehicle(new_v, old_v, DC_EXEC, false);
    00407
    00408       /* Take over cargo
    00409        * Note: We do only transfer cargo from the old to the new vehicle.
    00410        *       I.e. we do not transfer remaining cargo to other vehicles.
    00411        *       Else you would also need to consider moving cargo to other free chains,
    00412        *       or doing the same in ReplaceChain(), which would be quite troublesome.
    00413        */
    00414       TransferCargo(old_v, new_v, false);
    00415
    00416       *single_unit = new_v;
    00417     }
    00418
    00419     /* Sell the old vehicle */
    00420     cost.AddCost(DoCommand(0, old_v->index, 0, flags, GetCmdSellVeh(old_v)));
    00421
    00422     /* If we are not in DC_EXEC undo everything */
    00423     if ((flags & DC_EXEC) == 0) {
    00424       DoCommand(0, new_v->index, 0, DC_EXEC, GetCmdSellVeh(new_v));
    00425     }
    00426   }
    00427
    00428   return cost;
    00429 }
    00430
    00439 static CommandCost ReplaceChain(Vehicle **chain, DoCommandFlag flags, bool wagon_removal, bool *nothing_to_do)
    00440 {
    00441   Vehicle *old_head = *chain;
    00442   assert(old_head->IsPrimaryVehicle());
    00443
    00444   CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, 0);
    00445
    00446   if (old_head->type == VEH_TRAIN) {
    00447     /* Store the length of the old vehicle chain, rounded up to whole tiles */
    00448     uint16 old_total_length = CeilDiv(Train::From(old_head)->gcache.cached_total_length, TILE_SIZE) * TILE_SIZE;
    00449
    00450     int num_units = 0;
    00451     for (Train *w = Train::From(old_head); w != NULL; w = w->GetNextUnit()) num_units++;
    00452
    00453     Train **old_vehs = CallocT<Train *>(num_units);
    00454     Train **new_vehs = CallocT<Train *>(num_units);
    00455     Money *new_costs = MallocT<Money>(num_units);
    00456
    00457     /* Collect vehicles and build replacements
    00458      * Note: The replacement vehicles can only successfully build as long as the old vehicles are still in their chain */
    00459     int i;
    00460     Train *w;
    00461     for (w = Train::From(old_head), i = 0; w != NULL; w = w->GetNextUnit(), i++) {
    00462       assert(i < num_units);
    00463       old_vehs[i] = w;
    00464
    00465       CommandCost ret = BuildReplacementVehicle(old_vehs[i], (Vehicle**)&new_vehs[i], true);
    00466       cost.AddCost(ret);
    00467       if (cost.Failed()) break;
    00468
    00469       new_costs[i] = ret.GetCost();
    00470       if (new_vehs[i] != NULL) *nothing_to_do = false;
    00471     }
    00472     Train *new_head = (new_vehs[0] != NULL ? new_vehs[0] : old_vehs[0]);
    00473
    00474     /* Note: When autoreplace has already failed here, old_vehs[] is not completely initialized. But it is also not needed. */
    00475     if (cost.Succeeded()) {
    00476       /* Separate the head, so we can start constructing the new chain */
    00477       Train *second = Train::From(old_head)->GetNextUnit();
    00478       if (second != NULL) cost.AddCost(CmdMoveVehicle(second, NULL, DC_EXEC | DC_AUTOREPLACE, true));
    00479
    00480       assert(Train::From(new_head)->GetNextUnit() == NULL);
    00481
    00482       /* Append engines to the new chain
    00483        * We do this from back to front, so that the head of the temporary vehicle chain does not change all the time.
    00484        * That way we also have less trouble when exceeding the unitnumber limit.
    00485        * OTOH the vehicle attach callback is more expensive this way :s */
    00486       Train *last_engine = NULL;
    00487       if (cost.Succeeded()) {
    00488         for (int i = num_units - 1; i > 0; i--) {
    00489           Train *append = (new_vehs[i] != NULL ? new_vehs[i] : old_vehs[i]);
    00490
    00491           if (RailVehInfo(append->engine_type)->railveh_type == RAILVEH_WAGON) continue;
    00492
    00493           if (new_vehs[i] != NULL) {
    00494             /* Move the old engine to a separate row with DC_AUTOREPLACE. Else
    00495              * moving the wagon in front may fail later due to unitnumber limit.
    00496              * (We have to attach wagons without DC_AUTOREPLACE.) */
    00497             CmdMoveVehicle(old_vehs[i], NULL, DC_EXEC | DC_AUTOREPLACE, false);
    00498           }
    00499
    00500           if (last_engine == NULL) last_engine = append;
    00501           cost.AddCost(CmdMoveVehicle(append, new_head, DC_EXEC, false));
    00502           if (cost.Failed()) break;
    00503         }
    00504         if (last_engine == NULL) last_engine = new_head;
    00505       }
    00506
    00507       /* When wagon removal is enabled and the new engines without any wagons are already longer than the old, we have to fail */
    00508       if (cost.Succeeded() && wagon_removal && new_head->gcache.cached_total_length > old_total_length) cost = CommandCost(STR_ERROR_TRAIN_TOO_LONG_AFTER_REPLACEMENT);
    00509
    00510       /* Append/insert wagons into the new vehicle chain
    00511        * 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.
    00512        */
    00513       if (cost.Succeeded()) {
    00514         for (int i = num_units - 1; i > 0; i--) {
    00515           assert(last_engine != NULL);
    00516           Vehicle *append = (new_vehs[i] != NULL ? new_vehs[i] : old_vehs[i]);
    00517
    00518           if (RailVehInfo(append->engine_type)->railveh_type == RAILVEH_WAGON) {
    00519             /* Insert wagon after 'last_engine' */
    00520             CommandCost res = CmdMoveVehicle(append, last_engine, DC_EXEC, false);
    00521
    00522             /* When we allow removal of wagons, either the move failing due
    00523              * to the train becoming too long, or the train becoming longer
    00524              * would move the vehicle to the empty vehicle chain. */
    00525             if (wagon_removal && (res.Failed() ? res.GetErrorMessage() == STR_ERROR_TRAIN_TOO_LONG : new_head->gcache.cached_total_length > old_total_length)) {
    00526               CmdMoveVehicle(append, NULL, DC_EXEC | DC_AUTOREPLACE, false);
    00527               break;
    00528             }
    00529
    00530             cost.AddCost(res);
    00531             if (cost.Failed()) break;
    00532           } else {
    00533             /* We have reached 'last_engine', continue with the next engine towards the front */
    00534             assert(append == last_engine);
    00535             last_engine = last_engine->GetPrevUnit();
    00536           }
    00537         }
    00538       }
    00539
    00540       /* Sell superfluous new vehicles that could not be inserted. */
    00541       if (cost.Succeeded() && wagon_removal) {
    00542         assert(new_head->gcache.cached_total_length <= _settings_game.vehicle.max_train_length * TILE_SIZE);
    00543         for (int i = 1; i < num_units; i++) {
    00544           Vehicle *wagon = new_vehs[i];
    00545           if (wagon == NULL) continue;
    00546           if (wagon->First() == new_head) break;
    00547
    00548           assert(RailVehInfo(wagon->engine_type)->railveh_type == RAILVEH_WAGON);
    00549
    00550           /* Sell wagon */
    00551           CommandCost ret = DoCommand(0, wagon->index, 0, DC_EXEC, GetCmdSellVeh(wagon));
    00552           assert(ret.Succeeded());
    00553           new_vehs[i] = NULL;
    00554
    00555           /* Revert the money subtraction when the vehicle was built.
    00556            * This value is different from the sell value, esp. because of refitting */
    00557           cost.AddCost(-new_costs[i]);
    00558         }
    00559       }
    00560
    00561       /* The new vehicle chain is constructed, now take over orders and everything... */
    00562       if (cost.Succeeded()) cost.AddCost(CopyHeadSpecificThings(old_head, new_head, flags));
    00563
    00564       if (cost.Succeeded()) {
    00565         /* Success ! */
    00566         if ((flags & DC_EXEC) != 0 && new_head != old_head) {
    00567           *chain = new_head;
    00568         }
    00569
    00570         /* Transfer cargo of old vehicles and sell them */
    00571         for (int i = 0; i < num_units; i++) {
    00572           Vehicle *w = old_vehs[i];
    00573           /* Is the vehicle again part of the new chain?
    00574            * Note: We cannot test 'new_vehs[i] != NULL' as wagon removal might cause to remove both */
    00575           if (w->First() == new_head) continue;
    00576
    00577           if ((flags & DC_EXEC) != 0) TransferCargo(w, new_head, true);
    00578
    00579           /* Sell the vehicle.
    00580            * Note: This might temporarly construct new trains, so use DC_AUTOREPLACE to prevent
    00581            *       it from failing due to engine limits. */
    00582           cost.AddCost(DoCommand(0, w->index, 0, flags | DC_AUTOREPLACE, GetCmdSellVeh(w)));
    00583           if ((flags & DC_EXEC) != 0) {
    00584             old_vehs[i] = NULL;
    00585             if (i == 0) old_head = NULL;
    00586           }
    00587         }
    00588
    00589         if ((flags & DC_EXEC) != 0) CheckCargoCapacity(new_head);
    00590       }
    00591
    00592       /* If we are not in DC_EXEC undo everything, i.e. rearrange old vehicles.
    00593        * We do this from back to front, so that the head of the temporary vehicle chain does not change all the time.
    00594        * Note: The vehicle attach callback is disabled here :) */
    00595       if ((flags & DC_EXEC) == 0) {
    00596         /* Separate the head, so we can reattach the old vehicles */
    00597         Train *second = Train::From(old_head)->GetNextUnit();
    00598         if (second != NULL) CmdMoveVehicle(second, NULL, DC_EXEC | DC_AUTOREPLACE, true);
    00599
    00600         assert(Train::From(old_head)->GetNextUnit() == NULL);
    00601
    00602         for (int i = num_units - 1; i > 0; i--) {
    00603           CommandCost ret = CmdMoveVehicle(old_vehs[i], old_head, DC_EXEC | DC_AUTOREPLACE, false);
    00604           assert(ret.Succeeded());
    00605         }
    00606       }
    00607     }
    00608
    00609     /* Finally undo buying of new vehicles */
    00610     if ((flags & DC_EXEC) == 0) {
    00611       for (int i = num_units - 1; i >= 0; i--) {
    00612         if (new_vehs[i] != NULL) {
    00613           DoCommand(0, new_vehs[i]->index, 0, DC_EXEC, GetCmdSellVeh(new_vehs[i]));
    00614           new_vehs[i] = NULL;
    00615         }
    00616       }
    00617     }
    00618
    00619     free(old_vehs);
    00620     free(new_vehs);
    00621     free(new_costs);
    00622   } else {
    00623     /* Build and refit replacement vehicle */
    00624     Vehicle *new_head = NULL;
    00625     cost.AddCost(BuildReplacementVehicle(old_head, &new_head, true));
    00626
    00627     /* Was a new vehicle constructed? */
    00628     if (cost.Succeeded() && new_head != NULL) {
    00629       *nothing_to_do = false;
    00630
    00631       /* The new vehicle is constructed, now take over orders and everything... */
    00632       cost.AddCost(CopyHeadSpecificThings(old_head, new_head, flags));
    00633
    00634       if (cost.Succeeded()) {
    00635         /* The new vehicle is constructed, now take over cargo */
    00636         if ((flags & DC_EXEC) != 0) {
    00637           TransferCargo(old_head, new_head, true);
    00638           *chain = new_head;
    00639         }
    00640
    00641         /* Sell the old vehicle */
    00642         cost.AddCost(DoCommand(0, old_head->index, 0, flags, GetCmdSellVeh(old_head)));
    00643       }
    00644
    00645       /* If we are not in DC_EXEC undo everything */
    00646       if ((flags & DC_EXEC) == 0) {
    00647         DoCommand(0, new_head->index, 0, DC_EXEC, GetCmdSellVeh(new_head));
    00648       }
    00649     }
    00650   }
    00651
    00652   return cost;
    00653 }
    00654
    00665 CommandCost CmdAutoreplaceVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00666 {
    00667   Vehicle *v = Vehicle::GetIfValid(p1);
    00668   if (v == NULL) return CMD_ERROR;
    00669
    00670   CommandCost ret = CheckOwnership(v->owner);
    00671   if (ret.Failed()) return ret;
    00672
    00673   if (!v->IsChainInDepot()) return CMD_ERROR;
    00674   if (v->vehstatus & VS_CRASHED) return CMD_ERROR;
    00675
    00676   bool free_wagon = false;
    00677   if (v->type == VEH_TRAIN) {
    00678     Train *t = Train::From(v);
    00679     if (t->IsArticulatedPart() || t->IsRearDualheaded()) return CMD_ERROR;
    00680     free_wagon = !t->IsFrontEngine();
    00681     if (free_wagon && t->First()->IsFrontEngine()) return CMD_ERROR;
    00682   } else {
    00683     if (!v->IsPrimaryVehicle()) return CMD_ERROR;
    00684   }
    00685
    00686   const Company *c = Company::Get(_current_company);
    00687   bool wagon_removal = c->settings.renew_keep_length;
    00688
    00689   /* Test whether any replacement is set, before issuing a whole lot of commands that would end in nothing changed */
    00690   Vehicle *w = v;
    00691   bool any_replacements = false;
    00692   while (w != NULL) {
    00693     EngineID e;
    00694     CommandCost cost = GetNewEngineType(w, c, false, e);
    00695     if (cost.Failed()) return cost;
    00696     any_replacements |= (e != INVALID_ENGINE);
    00697     w = (!free_wagon && w->type == VEH_TRAIN ? Train::From(w)->GetNextUnit() : NULL);
    00698   }
    00699
    00700   CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, 0);
    00701   bool nothing_to_do = true;
    00702
    00703   if (any_replacements) {
    00704     bool was_stopped = free_wagon || ((v->vehstatus & VS_STOPPED) != 0);
    00705
    00706     /* Stop the vehicle */
    00707     if (!was_stopped) cost.AddCost(CmdStartStopVehicle(v, true));
    00708     if (cost.Failed()) return cost;
    00709
    00710     assert(free_wagon || v->IsStoppedInDepot());
    00711
    00712     /* We have to construct the new vehicle chain to test whether it is valid.
    00713      * Vehicle construction needs random bits, so we have to save the random seeds
    00714      * to prevent desyncs and to replay newgrf callbacks during DC_EXEC */
    00715     SavedRandomSeeds saved_seeds;
    00716     SaveRandomSeeds(&saved_seeds);
    00717     if (free_wagon) {
    00718       cost.AddCost(ReplaceFreeUnit(&v, flags & ~DC_EXEC, &nothing_to_do));
    00719     } else {
    00720       cost.AddCost(ReplaceChain(&v, flags & ~DC_EXEC, wagon_removal, &nothing_to_do));
    00721     }
    00722     RestoreRandomSeeds(saved_seeds);
    00723
    00724     if (cost.Succeeded() && (flags & DC_EXEC) != 0) {
    00725       CommandCost ret;
    00726       if (free_wagon) {
    00727         ret = ReplaceFreeUnit(&v, flags, &nothing_to_do);
    00728       } else {
    00729         ret = ReplaceChain(&v, flags, wagon_removal, &nothing_to_do);
    00730       }
    00731       assert(ret.Succeeded() && ret.GetCost() == cost.GetCost());
    00732     }
    00733
    00734     /* Restart the vehicle */
    00735     if (!was_stopped) cost.AddCost(CmdStartStopVehicle(v, false));
    00736   }
    00737
    00738   if (cost.Succeeded() && nothing_to_do) cost = CommandCost(STR_ERROR_AUTOREPLACE_NOTHING_TO_DO);
    00739   return cost;
    00740 }
    00741
    00755 CommandCost CmdSetAutoReplace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00756 {
    00757   Company *c = Company::GetIfValid(_current_company);
    00758   if (c == NULL) return CMD_ERROR;
    00759
    00760   EngineID old_engine_type = GB(p2, 0, 16);
    00761   EngineID new_engine_type = GB(p2, 16, 16);
    00762   GroupID id_g = GB(p1, 16, 16);
    00763   CommandCost cost;
    00764
    00765   if (Group::IsValidID(id_g) ? Group::Get(id_g)->owner != _current_company : !IsAllGroupID(id_g) && !IsDefaultGroupID(id_g)) return CMD_ERROR;
    00766   if (!Engine::IsValidID(old_engine_type)) return CMD_ERROR;
    00767
    00768   if (new_engine_type != INVALID_ENGINE) {
    00769     if (!Engine::IsValidID(new_engine_type)) return CMD_ERROR;
    00770     if (!CheckAutoreplaceValidity(old_engine_type, new_engine_type, _current_company)) return CMD_ERROR;
    00771
    00772     cost = AddEngineReplacementForCompany(c, old_engine_type, new_engine_type, id_g, HasBit(p1, 0), flags);
    00773   } else {
    00774     cost = RemoveEngineReplacementForCompany(c, old_engine_type, id_g, flags);
    00775   }
    00776
    00777   if (flags & DC_EXEC) {
    00778     GroupStatistics::UpdateAutoreplace(_current_company);
    00779     if (IsLocalCompany()) SetWindowDirty(WC_REPLACE_VEHICLE, Engine::Get(old_engine_type)->type);
    00780   }
    00781   if ((flags & DC_EXEC) && IsLocalCompany()) InvalidateAutoreplaceWindow(old_engine_type, id_g);
    00782
    00783   return cost;
    00784 }
    00785