autoreplace_cmd.cpp

Go to the documentation of this file.
00001 /* $Id: autoreplace_cmd.cpp 21924 2011-01-29 17:30:25Z terkhen $ */
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 "functions.h"
00019 #include "autoreplace_func.h"
00020 #include "autoreplace_gui.h"
00021 #include "group.h"
00022 #include "articulated_vehicles.h"
00023 #include "core/random_func.hpp"
00024 
00025 #include "table/strings.h"
00026 
00027 extern void ChangeVehicleViewports(VehicleID from_index, VehicleID to_index);
00028 extern void ChangeVehicleNews(VehicleID from_index, VehicleID to_index);
00029 extern void ChangeVehicleViewWindow(VehicleID from_index, VehicleID to_index);
00030 
00038 static bool EnginesHaveCargoInCommon(EngineID engine_a, EngineID engine_b)
00039 {
00040   uint32 available_cargos_a = GetUnionOfArticulatedRefitMasks(engine_a, true);
00041   uint32 available_cargos_b = GetUnionOfArticulatedRefitMasks(engine_b, true);
00042   return (available_cargos_a == 0 || available_cargos_b == 0 || (available_cargos_a & available_cargos_b) != 0);
00043 }
00044 
00052 bool CheckAutoreplaceValidity(EngineID from, EngineID to, CompanyID company)
00053 {
00054   assert(Engine::IsValidID(from) && Engine::IsValidID(to));
00055 
00056   /* we can't replace an engine into itself (that would be autorenew) */
00057   if (from == to) return false;
00058 
00059   const Engine *e_from = Engine::Get(from);
00060   const Engine *e_to = Engine::Get(to);
00061   VehicleType type = e_from->type;
00062 
00063   /* check that the new vehicle type is available to the company and its type is the same as the original one */
00064   if (!IsEngineBuildable(to, type, company)) return false;
00065 
00066   switch (type) {
00067     case VEH_TRAIN: {
00068       /* make sure the railtypes are compatible */
00069       if ((GetRailTypeInfo(e_from->u.rail.railtype)->compatible_railtypes & GetRailTypeInfo(e_to->u.rail.railtype)->compatible_railtypes) == 0) return false;
00070 
00071       /* make sure we do not replace wagons with engines or vise versa */
00072       if ((e_from->u.rail.railveh_type == RAILVEH_WAGON) != (e_to->u.rail.railveh_type == RAILVEH_WAGON)) return false;
00073       break;
00074     }
00075 
00076     case VEH_ROAD:
00077       /* make sure that we do not replace a tram with a normal road vehicles or vise versa */
00078       if (HasBit(e_from->info.misc_flags, EF_ROAD_TRAM) != HasBit(e_to->info.misc_flags, EF_ROAD_TRAM)) return false;
00079       break;
00080 
00081     case VEH_AIRCRAFT:
00082       /* make sure that we do not replace a plane with a helicopter or vise versa */
00083       if ((e_from->u.air.subtype & AIR_CTOL) != (e_to->u.air.subtype & AIR_CTOL)) return false;
00084       break;
00085 
00086     default: break;
00087   }
00088 
00089   /* the engines needs to be able to carry the same cargo */
00090   return EnginesHaveCargoInCommon(from, to);
00091 }
00092 
00099 static void TransferCargo(Vehicle *old_veh, Vehicle *new_head, bool part_of_chain)
00100 {
00101   assert(!part_of_chain || new_head->IsPrimaryVehicle());
00102   /* Loop through source parts */
00103   for (Vehicle *src = old_veh; src != NULL; src = src->Next()) {
00104     if (!part_of_chain && src->type == VEH_TRAIN && src != old_veh && src != Train::From(old_veh)->other_multiheaded_part && !src->IsArticulatedPart()) {
00105       /* Skip vehicles, which do not belong to old_veh */
00106       src = src->GetLastEnginePart();
00107       continue;
00108     }
00109     if (src->cargo_type >= NUM_CARGO || src->cargo.Count() == 0) continue;
00110 
00111     /* Find free space in the new chain */
00112     for (Vehicle *dest = new_head; dest != NULL && src->cargo.Count() > 0; dest = dest->Next()) {
00113       if (!part_of_chain && dest->type == VEH_TRAIN && dest != new_head && dest != Train::From(new_head)->other_multiheaded_part && !dest->IsArticulatedPart()) {
00114         /* Skip vehicles, which do not belong to new_head */
00115         dest = dest->GetLastEnginePart();
00116         continue;
00117       }
00118       if (dest->cargo_type != src->cargo_type) continue;
00119 
00120       uint amount = min(src->cargo.Count(), dest->cargo_cap - dest->cargo.Count());
00121       if (amount <= 0) continue;
00122 
00123       src->cargo.MoveTo(&dest->cargo, amount, VehicleCargoList::MTA_UNLOAD, NULL);
00124     }
00125   }
00126 
00127   /* Update train weight etc., the old vehicle will be sold anyway */
00128   if (part_of_chain && new_head->type == VEH_TRAIN) Train::From(new_head)->ConsistChanged(true);
00129 }
00130 
00137 static bool VerifyAutoreplaceRefitForOrders(const Vehicle *v, EngineID engine_type)
00138 {
00139 
00140   uint32 union_refit_mask_a = GetUnionOfArticulatedRefitMasks(v->engine_type, false);
00141   uint32 union_refit_mask_b = GetUnionOfArticulatedRefitMasks(engine_type, false);
00142 
00143   const Order *o;
00144   const Vehicle *u = (v->type == VEH_TRAIN) ? v->First() : v;
00145   FOR_VEHICLE_ORDERS(u, o) {
00146     if (!o->IsRefit()) continue;
00147     CargoID cargo_type = o->GetRefitCargo();
00148 
00149     if (!HasBit(union_refit_mask_a, cargo_type)) continue;
00150     if (!HasBit(union_refit_mask_b, cargo_type)) return false;
00151   }
00152 
00153   return true;
00154 }
00155 
00165 static CargoID GetNewCargoTypeForReplace(Vehicle *v, EngineID engine_type, bool part_of_chain)
00166 {
00167   uint32 available_cargo_types, union_mask;
00168   GetArticulatedRefitMasks(engine_type, true, &union_mask, &available_cargo_types);
00169 
00170   if (union_mask == 0) return CT_NO_REFIT; // Don't try to refit an engine with no cargo capacity
00171 
00172   CargoID cargo_type;
00173   if (IsArticulatedVehicleCarryingDifferentCargos(v, &cargo_type)) return CT_INVALID; // We cannot refit to mixed cargos in an automated way
00174 
00175   if (cargo_type == CT_INVALID) {
00176     if (v->type != VEH_TRAIN) return CT_NO_REFIT; // If the vehicle does not carry anything at all, every replacement is fine.
00177 
00178     if (!part_of_chain) return CT_NO_REFIT;
00179 
00180     /* the old engine didn't have cargo capacity, but the new one does
00181      * now we will figure out what cargo the train is carrying and refit to fit this */
00182 
00183     for (v = v->First(); v != NULL; v = v->Next()) {
00184       if (v->cargo_cap == 0) continue;
00185       /* Now we found a cargo type being carried on the train and we will see if it is possible to carry to this one */
00186       if (HasBit(available_cargo_types, v->cargo_type)) {
00187         /* Do we have to refit the vehicle, or is it already carrying the right cargo? */
00188         CargoArray default_capacity = GetCapacityOfArticulatedParts(engine_type);
00189         for (CargoID cid = 0; cid < NUM_CARGO; cid++) {
00190           if (cid != v->cargo_type && default_capacity[cid] > 0) return v->cargo_type;
00191         }
00192 
00193         return CT_NO_REFIT;
00194       }
00195     }
00196 
00197     return CT_NO_REFIT; // We failed to find a cargo type on the old vehicle and we will not refit the new one
00198   } else {
00199     if (!HasBit(available_cargo_types, cargo_type)) return CT_INVALID; // We can't refit the vehicle to carry the cargo we want
00200 
00201     if (part_of_chain && !VerifyAutoreplaceRefitForOrders(v, engine_type)) return CT_INVALID; // Some refit orders lose their effect
00202 
00203     /* Do we have to refit the vehicle, or is it already carrying the right cargo? */
00204     CargoArray default_capacity = GetCapacityOfArticulatedParts(engine_type);
00205     for (CargoID cid = 0; cid < NUM_CARGO; cid++) {
00206       if (cid != cargo_type && default_capacity[cid] > 0) return cargo_type;
00207     }
00208 
00209     return CT_NO_REFIT;
00210   }
00211 }
00212 
00219 static EngineID GetNewEngineType(const Vehicle *v, const Company *c)
00220 {
00221   assert(v->type != VEH_TRAIN || !v->IsArticulatedPart());
00222 
00223   if (v->type == VEH_TRAIN && Train::From(v)->IsRearDualheaded()) {
00224     /* we build the rear ends of multiheaded trains with the front ones */
00225     return INVALID_ENGINE;
00226   }
00227 
00228   EngineID e = EngineReplacementForCompany(c, v->engine_type, v->group_id);
00229 
00230   if (e != INVALID_ENGINE && IsEngineBuildable(e, v->type, _current_company)) {
00231     return e;
00232   }
00233 
00234   if (v->NeedsAutorenewing(c) && // replace if engine is too old
00235       IsEngineBuildable(v->engine_type, v->type, _current_company)) { // engine can still be build
00236     return v->engine_type;
00237   }
00238 
00239   return INVALID_ENGINE;
00240 }
00241 
00250 static CommandCost BuildReplacementVehicle(Vehicle *old_veh, Vehicle **new_vehicle, bool part_of_chain)
00251 {
00252   *new_vehicle = NULL;
00253 
00254   /* Shall the vehicle be replaced? */
00255   const Company *c = Company::Get(_current_company);
00256   EngineID e = GetNewEngineType(old_veh, c);
00257   if (e == INVALID_ENGINE) return CommandCost(); // neither autoreplace is set, nor autorenew is triggered
00258 
00259   /* Does it need to be refitted */
00260   CargoID refit_cargo = GetNewCargoTypeForReplace(old_veh, e, part_of_chain);
00261   if (refit_cargo == CT_INVALID) return CommandCost(); // incompatible cargos
00262 
00263   /* Build the new vehicle */
00264   CommandCost cost = DoCommand(old_veh->tile, e, 0, DC_EXEC | DC_AUTOREPLACE, GetCmdBuildVeh(old_veh));
00265   if (cost.Failed()) return cost;
00266 
00267   Vehicle *new_veh = Vehicle::Get(_new_vehicle_id);
00268   *new_vehicle = new_veh;
00269 
00270   /* Refit the vehicle if needed */
00271   byte subtype = GetBestFittingSubType(old_veh, new_veh);
00272   /* If the subtype isn't zero and the refit cargo is not set,
00273    * we're better off setting the refit cargo too. */
00274   if (subtype != 0 && refit_cargo == CT_NO_REFIT) refit_cargo = old_veh->cargo_type;
00275 
00276   if (refit_cargo != CT_NO_REFIT) {
00277     cost.AddCost(DoCommand(0, new_veh->index, refit_cargo | (subtype << 8), DC_EXEC, GetCmdRefitVeh(new_veh)));
00278     assert(cost.Succeeded()); // This should be ensured by GetNewCargoTypeForReplace()
00279   }
00280 
00281   /* Try to reverse the vehicle, but do not care if it fails as the new type might not be reversible */
00282   if (new_veh->type == VEH_TRAIN && HasBit(Train::From(old_veh)->flags, VRF_REVERSE_DIRECTION)) {
00283     DoCommand(0, new_veh->index, true, DC_EXEC, CMD_REVERSE_TRAIN_DIRECTION);
00284   }
00285 
00286   return cost;
00287 }
00288 
00295 static inline CommandCost CmdStartStopVehicle(const Vehicle *v, bool evaluate_callback)
00296 {
00297   return DoCommand(0, v->index, evaluate_callback ? 1 : 0, DC_EXEC | DC_AUTOREPLACE, CMD_START_STOP_VEHICLE);
00298 }
00299 
00308 static inline CommandCost CmdMoveVehicle(const Vehicle *v, const Vehicle *after, DoCommandFlag flags, bool whole_chain)
00309 {
00310   return DoCommand(0, v->index | (whole_chain ? 1 : 0) << 20, after != NULL ? after->index : INVALID_VEHICLE, flags, CMD_MOVE_RAIL_VEHICLE);
00311 }
00312 
00319 static CommandCost CopyHeadSpecificThings(Vehicle *old_head, Vehicle *new_head, DoCommandFlag flags)
00320 {
00321   CommandCost cost = CommandCost();
00322 
00323   /* Share orders */
00324   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));
00325 
00326   /* Copy group membership */
00327   if (cost.Succeeded() && old_head != new_head) cost.AddCost(DoCommand(0, old_head->group_id, new_head->index, DC_EXEC, CMD_ADD_VEHICLE_GROUP));
00328 
00329   /* Perform start/stop check whether the new vehicle suits newgrf restrictions etc. */
00330   if (cost.Succeeded()) {
00331     /* Start the vehicle, might be denied by certain things */
00332     assert((new_head->vehstatus & VS_STOPPED) != 0);
00333     cost.AddCost(CmdStartStopVehicle(new_head, true));
00334 
00335     /* Stop the vehicle again, but do not care about evil newgrfs allowing starting but not stopping :p */
00336     if (cost.Succeeded()) cost.AddCost(CmdStartStopVehicle(new_head, false));
00337   }
00338 
00339   /* Last do those things which do never fail (resp. we do not care about), but which are not undo-able */
00340   if (cost.Succeeded() && old_head != new_head && (flags & DC_EXEC) != 0) {
00341     /* Copy vehicle name */
00342     if (old_head->name != NULL) {
00343       DoCommand(0, new_head->index, 0, DC_EXEC | DC_AUTOREPLACE, CMD_RENAME_VEHICLE, old_head->name);
00344     }
00345 
00346     /* Copy other things which cannot be copied by a command and which shall not stay resetted from the build vehicle command */
00347     new_head->CopyVehicleConfigAndStatistics(old_head);
00348 
00349     /* Switch vehicle windows/news to the new vehicle, so they are not closed/deleted when the old vehicle is sold */
00350     ChangeVehicleViewports(old_head->index, new_head->index);
00351     ChangeVehicleViewWindow(old_head->index, new_head->index);
00352     ChangeVehicleNews(old_head->index, new_head->index);
00353   }
00354 
00355   return cost;
00356 }
00357 
00365 static CommandCost ReplaceFreeUnit(Vehicle **single_unit, DoCommandFlag flags, bool *nothing_to_do)
00366 {
00367   Train *old_v = Train::From(*single_unit);
00368   assert(!old_v->IsArticulatedPart() && !old_v->IsRearDualheaded());
00369 
00370   CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, 0);
00371 
00372   /* Build and refit replacement vehicle */
00373   Vehicle *new_v = NULL;
00374   cost.AddCost(BuildReplacementVehicle(old_v, &new_v, false));
00375 
00376   /* Was a new vehicle constructed? */
00377   if (cost.Succeeded() && new_v != NULL) {
00378     *nothing_to_do = false;
00379 
00380     if ((flags & DC_EXEC) != 0) {
00381       /* Move the new vehicle behind the old */
00382       CmdMoveVehicle(new_v, old_v, DC_EXEC, false);
00383 
00384       /* Take over cargo
00385        * Note: We do only transfer cargo from the old to the new vehicle.
00386        *       I.e. we do not transfer remaining cargo to other vehicles.
00387        *       Else you would also need to consider moving cargo to other free chains,
00388        *       or doing the same in ReplaceChain(), which would be quite troublesome.
00389        */
00390       TransferCargo(old_v, new_v, false);
00391 
00392       *single_unit = new_v;
00393     }
00394 
00395     /* Sell the old vehicle */
00396     cost.AddCost(DoCommand(0, old_v->index, 0, flags, GetCmdSellVeh(old_v)));
00397 
00398     /* If we are not in DC_EXEC undo everything */
00399     if ((flags & DC_EXEC) == 0) {
00400       DoCommand(0, new_v->index, 0, DC_EXEC, GetCmdSellVeh(new_v));
00401     }
00402   }
00403 
00404   return cost;
00405 }
00406 
00415 static CommandCost ReplaceChain(Vehicle **chain, DoCommandFlag flags, bool wagon_removal, bool *nothing_to_do)
00416 {
00417   Vehicle *old_head = *chain;
00418   assert(old_head->IsPrimaryVehicle());
00419 
00420   CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, 0);
00421 
00422   if (old_head->type == VEH_TRAIN) {
00423     /* Store the length of the old vehicle chain, rounded up to whole tiles */
00424     uint16 old_total_length = CeilDiv(Train::From(old_head)->gcache.cached_total_length, TILE_SIZE) * TILE_SIZE;
00425 
00426     int num_units = 0; 
00427     for (Train *w = Train::From(old_head); w != NULL; w = w->GetNextUnit()) num_units++;
00428 
00429     Train **old_vehs = CallocT<Train *>(num_units); 
00430     Train **new_vehs = CallocT<Train *>(num_units); 
00431     Money *new_costs = MallocT<Money>(num_units);   
00432 
00433     /* Collect vehicles and build replacements
00434      * Note: The replacement vehicles can only successfully build as long as the old vehicles are still in their chain */
00435     int i;
00436     Train *w;
00437     for (w = Train::From(old_head), i = 0; w != NULL; w = w->GetNextUnit(), i++) {
00438       assert(i < num_units);
00439       old_vehs[i] = w;
00440 
00441       CommandCost ret = BuildReplacementVehicle(old_vehs[i], (Vehicle**)&new_vehs[i], true);
00442       cost.AddCost(ret);
00443       if (cost.Failed()) break;
00444 
00445       new_costs[i] = ret.GetCost();
00446       if (new_vehs[i] != NULL) *nothing_to_do = false;
00447     }
00448     Train *new_head = (new_vehs[0] != NULL ? new_vehs[0] : old_vehs[0]);
00449 
00450     /* Note: When autoreplace has already failed here, old_vehs[] is not completely initialized. But it is also not needed. */
00451     if (cost.Succeeded()) {
00452       /* Separate the head, so we can start constructing the new chain */
00453       Train *second = Train::From(old_head)->GetNextUnit();
00454       if (second != NULL) cost.AddCost(CmdMoveVehicle(second, NULL, DC_EXEC | DC_AUTOREPLACE, true));
00455 
00456       assert(Train::From(new_head)->GetNextUnit() == NULL);
00457 
00458       /* Append engines to the new chain
00459        * We do this from back to front, so that the head of the temporary vehicle chain does not change all the time.
00460        * That way we also have less trouble when exceeding the unitnumber limit.
00461        * OTOH the vehicle attach callback is more expensive this way :s */
00462       Train *last_engine = NULL; 
00463       if (cost.Succeeded()) {
00464         for (int i = num_units - 1; i > 0; i--) {
00465           Train *append = (new_vehs[i] != NULL ? new_vehs[i] : old_vehs[i]);
00466 
00467           if (RailVehInfo(append->engine_type)->railveh_type == RAILVEH_WAGON) continue;
00468 
00469           if (new_vehs[i] != NULL) {
00470             /* Move the old engine to a separate row with DC_AUTOREPLACE. Else
00471              * moving the wagon in front may fail later due to unitnumber limit.
00472              * (We have to attach wagons without DC_AUTOREPLACE.) */
00473             CmdMoveVehicle(old_vehs[i], NULL, DC_EXEC | DC_AUTOREPLACE, false);
00474           }
00475 
00476           if (last_engine == NULL) last_engine = append;
00477           cost.AddCost(CmdMoveVehicle(append, new_head, DC_EXEC, false));
00478           if (cost.Failed()) break;
00479         }
00480         if (last_engine == NULL) last_engine = new_head;
00481       }
00482 
00483       /* When wagon removal is enabled and the new engines without any wagons are already longer than the old, we have to fail */
00484       if (cost.Succeeded() && wagon_removal && new_head->gcache.cached_total_length > old_total_length) cost = CommandCost(STR_ERROR_TRAIN_TOO_LONG_AFTER_REPLACEMENT);
00485 
00486       /* Append/insert wagons into the new vehicle chain
00487        * 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.
00488        */
00489       if (cost.Succeeded()) {
00490         for (int i = num_units - 1; i > 0; i--) {
00491           assert(last_engine != NULL);
00492           Vehicle *append = (new_vehs[i] != NULL ? new_vehs[i] : old_vehs[i]);
00493 
00494           if (RailVehInfo(append->engine_type)->railveh_type == RAILVEH_WAGON) {
00495             /* Insert wagon after 'last_engine' */
00496             CommandCost res = CmdMoveVehicle(append, last_engine, DC_EXEC, false);
00497 
00498             if (res.Succeeded() && wagon_removal && new_head->gcache.cached_total_length > old_total_length) {
00499               CmdMoveVehicle(append, NULL, DC_EXEC | DC_AUTOREPLACE, false);
00500               break;
00501             }
00502 
00503             cost.AddCost(res);
00504             if (cost.Failed()) break;
00505           } else {
00506             /* We have reached 'last_engine', continue with the next engine towards the front */
00507             assert(append == last_engine);
00508             last_engine = last_engine->GetPrevUnit();
00509           }
00510         }
00511       }
00512 
00513       /* Sell superfluous new vehicles that could not be inserted. */
00514       if (cost.Succeeded() && wagon_removal) {
00515         for (int i = 1; i < num_units; i++) {
00516           Vehicle *wagon = new_vehs[i];
00517           if (wagon == NULL) continue;
00518           if (wagon->First() == new_head) break;
00519 
00520           assert(RailVehInfo(wagon->engine_type)->railveh_type == RAILVEH_WAGON);
00521 
00522           /* Sell wagon */
00523           CommandCost ret = DoCommand(0, wagon->index, 0, DC_EXEC, GetCmdSellVeh(wagon));
00524           assert(ret.Succeeded());
00525           new_vehs[i] = NULL;
00526 
00527           /* Revert the money subtraction when the vehicle was built.
00528            * This value is different from the sell value, esp. because of refitting */
00529           cost.AddCost(-new_costs[i]);
00530         }
00531       }
00532 
00533       /* The new vehicle chain is constructed, now take over orders and everything... */
00534       if (cost.Succeeded()) cost.AddCost(CopyHeadSpecificThings(old_head, new_head, flags));
00535 
00536       if (cost.Succeeded()) {
00537         /* Success ! */
00538         if ((flags & DC_EXEC) != 0 && new_head != old_head) {
00539           *chain = new_head;
00540         }
00541 
00542         /* Transfer cargo of old vehicles and sell them */
00543         for (int i = 0; i < num_units; i++) {
00544           Vehicle *w = old_vehs[i];
00545           /* Is the vehicle again part of the new chain?
00546            * Note: We cannot test 'new_vehs[i] != NULL' as wagon removal might cause to remove both */
00547           if (w->First() == new_head) continue;
00548 
00549           if ((flags & DC_EXEC) != 0) TransferCargo(w, new_head, true);
00550 
00551           /* Sell the vehicle.
00552            * Note: This might temporarly construct new trains, so use DC_AUTOREPLACE to prevent
00553            *       it from failing due to engine limits. */
00554           cost.AddCost(DoCommand(0, w->index, 0, flags | DC_AUTOREPLACE, GetCmdSellVeh(w)));
00555           if ((flags & DC_EXEC) != 0) {
00556             old_vehs[i] = NULL;
00557             if (i == 0) old_head = NULL;
00558           }
00559         }
00560       }
00561 
00562       /* If we are not in DC_EXEC undo everything, i.e. rearrange old vehicles.
00563        * We do this from back to front, so that the head of the temporary vehicle chain does not change all the time.
00564        * Note: The vehicle attach callback is disabled here :) */
00565       if ((flags & DC_EXEC) == 0) {
00566         /* Separate the head, so we can reattach the old vehicles */
00567         Train *second = Train::From(old_head)->GetNextUnit();
00568         if (second != NULL) CmdMoveVehicle(second, NULL, DC_EXEC | DC_AUTOREPLACE, true);
00569 
00570         assert(Train::From(old_head)->GetNextUnit() == NULL);
00571 
00572         for (int i = num_units - 1; i > 0; i--) {
00573           CommandCost ret = CmdMoveVehicle(old_vehs[i], old_head, DC_EXEC | DC_AUTOREPLACE, false);
00574           assert(ret.Succeeded());
00575         }
00576       }
00577     }
00578 
00579     /* Finally undo buying of new vehicles */
00580     if ((flags & DC_EXEC) == 0) {
00581       for (int i = num_units - 1; i >= 0; i--) {
00582         if (new_vehs[i] != NULL) {
00583           DoCommand(0, new_vehs[i]->index, 0, DC_EXEC, GetCmdSellVeh(new_vehs[i]));
00584           new_vehs[i] = NULL;
00585         }
00586       }
00587     }
00588 
00589     free(old_vehs);
00590     free(new_vehs);
00591     free(new_costs);
00592   } else {
00593     /* Build and refit replacement vehicle */
00594     Vehicle *new_head = NULL;
00595     cost.AddCost(BuildReplacementVehicle(old_head, &new_head, true));
00596 
00597     /* Was a new vehicle constructed? */
00598     if (cost.Succeeded() && new_head != NULL) {
00599       *nothing_to_do = false;
00600 
00601       /* The new vehicle is constructed, now take over orders and everything... */
00602       cost.AddCost(CopyHeadSpecificThings(old_head, new_head, flags));
00603 
00604       if (cost.Succeeded()) {
00605         /* The new vehicle is constructed, now take over cargo */
00606         if ((flags & DC_EXEC) != 0) {
00607           TransferCargo(old_head, new_head, true);
00608           *chain = new_head;
00609         }
00610 
00611         /* Sell the old vehicle */
00612         cost.AddCost(DoCommand(0, old_head->index, 0, flags, GetCmdSellVeh(old_head)));
00613       }
00614 
00615       /* If we are not in DC_EXEC undo everything */
00616       if ((flags & DC_EXEC) == 0) {
00617         DoCommand(0, new_head->index, 0, DC_EXEC, GetCmdSellVeh(new_head));
00618       }
00619     }
00620   }
00621 
00622   return cost;
00623 }
00624 
00635 CommandCost CmdAutoreplaceVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00636 {
00637   Vehicle *v = Vehicle::GetIfValid(p1);
00638   if (v == NULL) return CMD_ERROR;
00639 
00640   CommandCost ret = CheckOwnership(v->owner);
00641   if (ret.Failed()) return ret;
00642 
00643   if (!v->IsInDepot()) return CMD_ERROR;
00644   if (v->vehstatus & VS_CRASHED) return CMD_ERROR;
00645 
00646   bool free_wagon = false;
00647   if (v->type == VEH_TRAIN) {
00648     Train *t = Train::From(v);
00649     if (t->IsArticulatedPart() || t->IsRearDualheaded()) return CMD_ERROR;
00650     free_wagon = !t->IsFrontEngine();
00651     if (free_wagon && t->First()->IsFrontEngine()) return CMD_ERROR;
00652   } else {
00653     if (!v->IsPrimaryVehicle()) return CMD_ERROR;
00654   }
00655 
00656   const Company *c = Company::Get(_current_company);
00657   bool wagon_removal = c->settings.renew_keep_length;
00658 
00659   /* Test whether any replacement is set, before issuing a whole lot of commands that would end in nothing changed */
00660   Vehicle *w = v;
00661   bool any_replacements = false;
00662   while (w != NULL && !any_replacements) {
00663     any_replacements = (GetNewEngineType(w, c) != INVALID_ENGINE);
00664     w = (!free_wagon && w->type == VEH_TRAIN ? Train::From(w)->GetNextUnit() : NULL);
00665   }
00666 
00667   CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, 0);
00668   bool nothing_to_do = true;
00669 
00670   if (any_replacements) {
00671     bool was_stopped = free_wagon || ((v->vehstatus & VS_STOPPED) != 0);
00672 
00673     /* Stop the vehicle */
00674     if (!was_stopped) cost.AddCost(CmdStartStopVehicle(v, true));
00675     if (cost.Failed()) return cost;
00676 
00677     assert(v->IsStoppedInDepot());
00678 
00679     /* We have to construct the new vehicle chain to test whether it is valid.
00680      * Vehicle construction needs random bits, so we have to save the random seeds
00681      * to prevent desyncs and to replay newgrf callbacks during DC_EXEC */
00682     SavedRandomSeeds saved_seeds;
00683     SaveRandomSeeds(&saved_seeds);
00684     if (free_wagon) {
00685       cost.AddCost(ReplaceFreeUnit(&v, flags & ~DC_EXEC, &nothing_to_do));
00686     } else {
00687       cost.AddCost(ReplaceChain(&v, flags & ~DC_EXEC, wagon_removal, &nothing_to_do));
00688     }
00689     RestoreRandomSeeds(saved_seeds);
00690 
00691     if (cost.Succeeded() && (flags & DC_EXEC) != 0) {
00692       CommandCost ret;
00693       if (free_wagon) {
00694         ret = ReplaceFreeUnit(&v, flags, &nothing_to_do);
00695       } else {
00696         ret = ReplaceChain(&v, flags, wagon_removal, &nothing_to_do);
00697       }
00698       assert(ret.Succeeded() && ret.GetCost() == cost.GetCost());
00699     }
00700 
00701     /* Restart the vehicle */
00702     if (!was_stopped) cost.AddCost(CmdStartStopVehicle(v, false));
00703   }
00704 
00705   if (cost.Succeeded() && nothing_to_do) cost = CommandCost(STR_ERROR_AUTOREPLACE_NOTHING_TO_DO);
00706   return cost;
00707 }
00708 
00721 CommandCost CmdSetAutoReplace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00722 {
00723   Company *c = Company::GetIfValid(_current_company);
00724   if (c == NULL) return CMD_ERROR;
00725 
00726   EngineID old_engine_type = GB(p2, 0, 16);
00727   EngineID new_engine_type = GB(p2, 16, 16);
00728   GroupID id_g = GB(p1, 16, 16);
00729   CommandCost cost;
00730 
00731   if (!Group::IsValidID(id_g) && !IsAllGroupID(id_g) && !IsDefaultGroupID(id_g)) return CMD_ERROR;
00732   if (!Engine::IsValidID(old_engine_type)) return CMD_ERROR;
00733 
00734   if (new_engine_type != INVALID_ENGINE) {
00735     if (!Engine::IsValidID(new_engine_type)) return CMD_ERROR;
00736     if (!CheckAutoreplaceValidity(old_engine_type, new_engine_type, _current_company)) return CMD_ERROR;
00737 
00738     cost = AddEngineReplacementForCompany(c, old_engine_type, new_engine_type, id_g, flags);
00739   } else {
00740     cost = RemoveEngineReplacementForCompany(c, old_engine_type, id_g, flags);
00741   }
00742 
00743   if ((flags & DC_EXEC) && IsLocalCompany()) InvalidateAutoreplaceWindow(old_engine_type, id_g);
00744 
00745   return cost;
00746 }
00747 

Generated on Fri Feb 4 20:53:38 2011 for OpenTTD by  doxygen 1.6.1