Also scroll tile separators in the train depot
[openttd/fttd.git] / src / autoreplace_cmd.cpp
blobedd7295e7c2cc9ef2c39afe34e81e1c65cb1f99d
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
8 */
10 /** @file autoreplace_cmd.cpp Deals with autoreplace execution but not the setup */
12 #include "stdafx.h"
13 #include "company_func.h"
14 #include "train.h"
15 #include "command_func.h"
16 #include "engine_func.h"
17 #include "vehicle_func.h"
18 #include "autoreplace_func.h"
19 #include "autoreplace_gui.h"
20 #include "articulated_vehicles.h"
21 #include "core/random_func.hpp"
23 #include "table/strings.h"
25 extern void ChangeVehicleViewports(VehicleID from_index, VehicleID to_index);
26 extern void ChangeVehicleNews(VehicleID from_index, VehicleID to_index);
27 extern void ChangeVehicleViewWindow(VehicleID from_index, VehicleID to_index);
29 /**
30 * Figure out if two engines got at least one type of cargo in common (refitting if needed)
31 * @param engine_a one of the EngineIDs
32 * @param engine_b the other EngineID
33 * @param type the type of the engines
34 * @return true if they can both carry the same type of cargo (or at least one of them got no capacity at all)
36 static bool EnginesHaveCargoInCommon(EngineID engine_a, EngineID engine_b)
38 uint32 available_cargoes_a = GetUnionOfArticulatedRefitMasks(engine_a, true);
39 uint32 available_cargoes_b = GetUnionOfArticulatedRefitMasks(engine_b, true);
40 return (available_cargoes_a == 0 || available_cargoes_b == 0 || (available_cargoes_a & available_cargoes_b) != 0);
43 /**
44 * Checks some basic properties whether autoreplace is allowed
45 * @param from Origin engine
46 * @param to Destination engine
47 * @param company Company to check for
48 * @return true if autoreplace is allowed
50 bool CheckAutoreplaceValidity(EngineID from, EngineID to, CompanyID company)
52 assert(Engine::IsValidID(from) && Engine::IsValidID(to));
54 /* we can't replace an engine into itself (that would be autorenew) */
55 if (from == to) return false;
57 const Engine *e_from = Engine::Get(from);
58 const Engine *e_to = Engine::Get(to);
59 VehicleType type = e_from->type;
61 /* check that the new vehicle type is available to the company and its type is the same as the original one */
62 if (!IsEngineBuildable(to, type, company)) return false;
64 switch (type) {
65 case VEH_TRAIN: {
66 /* make sure the railtypes are compatible */
67 if ((GetRailTypeInfo(e_from->u.rail.railtype)->compatible_railtypes & GetRailTypeInfo(e_to->u.rail.railtype)->compatible_railtypes) == 0) return false;
69 /* make sure we do not replace wagons with engines or vice versa */
70 if ((e_from->u.rail.railveh_type == RAILVEH_WAGON) != (e_to->u.rail.railveh_type == RAILVEH_WAGON)) return false;
71 break;
74 case VEH_ROAD:
75 /* make sure that we do not replace a tram with a normal road vehicles or vice versa */
76 if (HasBit(e_from->info.misc_flags, EF_ROAD_TRAM) != HasBit(e_to->info.misc_flags, EF_ROAD_TRAM)) return false;
77 break;
79 case VEH_AIRCRAFT:
80 /* make sure that we do not replace a plane with a helicopter or vice versa */
81 if ((e_from->u.air.subtype & AIR_CTOL) != (e_to->u.air.subtype & AIR_CTOL)) return false;
82 break;
84 default: break;
87 /* the engines needs to be able to carry the same cargo */
88 return EnginesHaveCargoInCommon(from, to);
91 /**
92 * Check the capacity of all vehicles in a chain and spread cargo if needed.
93 * @param v The vehicle to check.
94 * @pre You can only do this if the consist is not loading or unloading. It
95 * must not carry reserved cargo, nor cargo to be unloaded or transferred.
97 void CheckCargoCapacity(Vehicle *v)
99 assert(v == NULL || v->First() == v);
101 for (Vehicle *src = v; src != NULL; src = src->Next()) {
102 assert(src->cargo.TotalCount() == src->cargo.ActionCount(VehicleCargoList::MTA_KEEP));
104 /* Do we need to more cargo away? */
105 if (src->cargo.TotalCount() <= src->cargo_cap) continue;
107 /* We need to move a particular amount. Try that on the other vehicles. */
108 uint to_spread = src->cargo.TotalCount() - src->cargo_cap;
109 for (Vehicle *dest = v; dest != NULL && to_spread != 0; dest = dest->Next()) {
110 assert(dest->cargo.TotalCount() == dest->cargo.ActionCount(VehicleCargoList::MTA_KEEP));
111 if (dest->cargo.TotalCount() >= dest->cargo_cap || dest->cargo_type != src->cargo_type) continue;
113 uint amount = min(to_spread, dest->cargo_cap - dest->cargo.TotalCount());
114 src->cargo.Shift(amount, &dest->cargo);
115 to_spread -= amount;
118 /* Any left-overs will be thrown away, but not their feeder share. */
119 if (src->cargo_cap < src->cargo.TotalCount()) src->cargo.Truncate(src->cargo.TotalCount() - src->cargo_cap);
124 * Transfer cargo from a single (articulated )old vehicle to the new vehicle chain
125 * @param old_veh Old vehicle that will be sold
126 * @param new_head Head of the completely constructed new vehicle chain
127 * @param part_of_chain The vehicle is part of a train
128 * @pre You can only do this if both consists are not loading or unloading.
129 * They must not carry reserved cargo, nor cargo to be unloaded or
130 * transferred.
132 static void TransferCargo(Vehicle *old_veh, Vehicle *new_head, bool part_of_chain)
134 if (part_of_chain) {
135 assert (new_head->IsPrimaryVehicle());
136 } else {
137 assert (old_veh->type == VEH_TRAIN);
138 assert (new_head->type == VEH_TRAIN);
141 /* Loop through source parts */
142 for (Vehicle *src = old_veh; src != NULL; src = src->Next()) {
143 assert(src->cargo.TotalCount() == src->cargo.ActionCount(VehicleCargoList::MTA_KEEP));
144 if (!part_of_chain && src != old_veh && src != Train::From(old_veh)->other_multiheaded_part && !src->IsArticulatedPart()) {
145 /* Skip vehicles, which do not belong to old_veh */
146 src = src->GetLastEnginePart();
147 continue;
149 if (src->cargo_type >= NUM_CARGO || src->cargo.TotalCount() == 0) continue;
151 /* Find free space in the new chain */
152 for (Vehicle *dest = new_head; dest != NULL && src->cargo.TotalCount() > 0; dest = dest->Next()) {
153 assert(dest->cargo.TotalCount() == dest->cargo.ActionCount(VehicleCargoList::MTA_KEEP));
154 if (!part_of_chain && dest != new_head && dest != Train::From(new_head)->other_multiheaded_part && !dest->IsArticulatedPart()) {
155 /* Skip vehicles, which do not belong to new_head */
156 dest = dest->GetLastEnginePart();
157 continue;
159 if (dest->cargo_type != src->cargo_type) continue;
161 uint amount = min(src->cargo.TotalCount(), dest->cargo_cap - dest->cargo.TotalCount());
162 if (amount <= 0) continue;
164 src->cargo.Shift(amount, &dest->cargo);
170 * Tests whether refit orders that applied to v will also apply to the new vehicle type
171 * @param v The vehicle to be replaced
172 * @param engine_type The type we want to replace with
173 * @return true iff all refit orders stay valid
175 static bool VerifyAutoreplaceRefitForOrders(const Vehicle *v, EngineID engine_type)
178 uint32 union_refit_mask_a = GetUnionOfArticulatedRefitMasks(v->engine_type, false);
179 uint32 union_refit_mask_b = GetUnionOfArticulatedRefitMasks(engine_type, false);
181 const Order *o;
182 const Vehicle *u = (v->type == VEH_TRAIN) ? v->First() : v;
183 FOR_VEHICLE_ORDERS(u, o) {
184 if (!o->IsRefit()) continue;
186 CargoMask cargo = o->GetRefitCargoMask();
187 if ((cargo & union_refit_mask_a) == 0) continue;
188 if ((cargo & union_refit_mask_b) == 0) return false;
191 return true;
195 * Function to find what type of cargo to refit to when autoreplacing
196 * @param *v Original vehicle that is being replaced.
197 * @param engine_type The EngineID of the vehicle that is being replaced to
198 * @param part_of_chain The vehicle is part of a train
199 * @return The cargo type to replace to
200 * CT_NO_REFIT is returned if no refit is needed
201 * CT_INVALID is returned when both old and new vehicle got cargo capacity and refitting the new one to the old one's cargo type isn't possible
203 static CargoID GetNewCargoTypeForReplace(Vehicle *v, EngineID engine_type, bool part_of_chain)
205 uint32 available_cargo_types, union_mask;
206 GetArticulatedRefitMasks(engine_type, true, &union_mask, &available_cargo_types);
208 if (union_mask == 0) return CT_NO_REFIT; // Don't try to refit an engine with no cargo capacity
210 CargoID cargo_type;
211 if (IsArticulatedVehicleCarryingDifferentCargoes(v, &cargo_type)) return CT_INVALID; // We cannot refit to mixed cargoes in an automated way
213 if (cargo_type == CT_INVALID) {
214 if (v->type != VEH_TRAIN) return CT_NO_REFIT; // If the vehicle does not carry anything at all, every replacement is fine.
216 if (!part_of_chain) return CT_NO_REFIT;
218 /* the old engine didn't have cargo capacity, but the new one does
219 * now we will figure out what cargo the train is carrying and refit to fit this */
221 for (v = v->First(); v != NULL; v = v->Next()) {
222 if (!v->GetEngine()->CanCarryCargo()) continue;
223 /* Now we found a cargo type being carried on the train and we will see if it is possible to carry to this one */
224 if (HasBit(available_cargo_types, v->cargo_type)) return v->cargo_type;
227 return CT_NO_REFIT; // We failed to find a cargo type on the old vehicle and we will not refit the new one
228 } else {
229 if (!HasBit(available_cargo_types, cargo_type)) return CT_INVALID; // We can't refit the vehicle to carry the cargo we want
231 if (part_of_chain && !VerifyAutoreplaceRefitForOrders(v, engine_type)) return CT_INVALID; // Some refit orders lose their effect
233 return cargo_type;
238 * Get the EngineID of the replacement for a vehicle
239 * @param v The vehicle to find a replacement for
240 * @param c The vehicle's owner (it's faster to forward the pointer than refinding it)
241 * @param always_replace Always replace, even if not old.
242 * @param [out] e the EngineID of the replacement. INVALID_ENGINE if no replacement is found
243 * @return Error if the engine to build is not available
245 static CommandCost GetNewEngineType(const Vehicle *v, const Company *c, bool always_replace, EngineID &e)
247 assert(v->type != VEH_TRAIN || !v->IsArticulatedPart());
249 e = INVALID_ENGINE;
251 if (v->type == VEH_TRAIN && Train::From(v)->IsRearDualheaded()) {
252 /* we build the rear ends of multiheaded trains with the front ones */
253 return CommandCost();
256 bool replace_when_old;
257 e = EngineReplacementForCompany(c, v->engine_type, v->group_id, &replace_when_old);
258 if (!always_replace && replace_when_old && !v->NeedsAutorenewing(c)) e = INVALID_ENGINE;
260 /* Autoreplace, if engine is available */
261 if (e != INVALID_ENGINE && IsEngineBuildable(e, v->type, _current_company)) {
262 return CommandCost();
265 /* Autorenew if needed */
266 if (c->settings.engine_renew && v->NeedsAutorenewing(c)) e = v->engine_type;
268 /* Nothing to do or all is fine? */
269 if (e == INVALID_ENGINE || IsEngineBuildable(e, v->type, _current_company)) return CommandCost();
271 /* The engine we need is not available. Report error to user */
272 return CommandCost(STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE + v->type);
276 * Builds and refits a replacement vehicle
277 * Important: The old vehicle is still in the original vehicle chain (used for determining the cargo when the old vehicle did not carry anything, but the new one does)
278 * @param old_veh A single (articulated/multiheaded) vehicle that shall be replaced.
279 * @param new_vehicle Returns the newly build and refitted vehicle
280 * @param part_of_chain The vehicle is part of a train
281 * @return cost or error
283 static CommandCost BuildReplacementVehicle(Vehicle *old_veh, Vehicle **new_vehicle, bool part_of_chain)
285 *new_vehicle = NULL;
287 /* Shall the vehicle be replaced? */
288 const Company *c = Company::Get(_current_company);
289 EngineID e;
290 CommandCost cost = GetNewEngineType(old_veh, c, true, e);
291 if (cost.Failed()) return cost;
292 if (e == INVALID_ENGINE) return CommandCost(); // neither autoreplace is set, nor autorenew is triggered
294 /* Does it need to be refitted */
295 CargoID refit_cargo = GetNewCargoTypeForReplace(old_veh, e, part_of_chain);
296 if (refit_cargo == CT_INVALID) return CommandCost(); // incompatible cargoes
298 /* Build the new vehicle */
299 cost = DoCommand(old_veh->tile, e, 0, DC_EXEC | DC_AUTOREPLACE, CMD_BUILD_VEHICLE);
300 if (cost.Failed()) return cost;
302 Vehicle *new_veh = Vehicle::Get(_new_vehicle_id);
303 *new_vehicle = new_veh;
305 /* Refit the vehicle if needed */
306 if (refit_cargo != CT_NO_REFIT) {
307 byte subtype = GetBestFittingSubType(old_veh, new_veh, refit_cargo);
309 cost.AddCost(DoCommand(0, new_veh->index, refit_cargo | (subtype << 8), DC_EXEC, CMD_REFIT_VEHICLE));
310 assert(cost.Succeeded()); // This should be ensured by GetNewCargoTypeForReplace()
313 /* Try to reverse the vehicle, but do not care if it fails as the new type might not be reversible */
314 if (new_veh->type == VEH_TRAIN && HasBit(Train::From(old_veh)->flags, VRF_REVERSE_DIRECTION)) {
315 DoCommand(0, new_veh->index, true, DC_EXEC, CMD_REVERSE_TRAIN_DIRECTION);
318 return cost;
322 * Issue a start/stop command
323 * @param v a vehicle
324 * @param evaluate_callback shall the start/stop callback be evaluated?
325 * @return success or error
327 static inline CommandCost CmdStartStopVehicle(const Vehicle *v, bool evaluate_callback)
329 return DoCommand(0, v->index, evaluate_callback ? 1 : 0, DC_EXEC | DC_AUTOREPLACE, CMD_START_STOP_VEHICLE);
333 * Issue a train vehicle move command
334 * @param v The vehicle to move
335 * @param after The vehicle to insert 'v' after, or NULL to start new chain
336 * @param flags the command flags to use
337 * @param whole_chain move all vehicles following 'v' (true), or only 'v' (false)
338 * @return success or error
340 static inline CommandCost CmdMoveVehicle(const Vehicle *v, const Vehicle *after, DoCommandFlag flags, bool whole_chain)
342 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);
346 * Copy head specific things to the new vehicle chain after it was successfully constructed
347 * @param old_head The old front vehicle (no wagons attached anymore)
348 * @param new_head The new head of the completely replaced vehicle chain
349 * @param flags the command flags to use
351 static CommandCost CopyHeadSpecificThings(Vehicle *old_head, Vehicle *new_head, DoCommandFlag flags)
353 CommandCost cost = CommandCost();
355 /* Share orders */
356 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));
358 /* Copy group membership */
359 if (cost.Succeeded() && old_head != new_head) cost.AddCost(DoCommand(0, old_head->group_id, new_head->index, DC_EXEC, CMD_ADD_VEHICLE_GROUP));
361 /* Perform start/stop check whether the new vehicle suits newgrf restrictions etc. */
362 if (cost.Succeeded()) {
363 /* Start the vehicle, might be denied by certain things */
364 assert((new_head->vehstatus & VS_STOPPED) != 0);
365 cost.AddCost(CmdStartStopVehicle(new_head, true));
367 /* Stop the vehicle again, but do not care about evil newgrfs allowing starting but not stopping :p */
368 if (cost.Succeeded()) cost.AddCost(CmdStartStopVehicle(new_head, false));
371 /* Last do those things which do never fail (resp. we do not care about), but which are not undo-able */
372 if (cost.Succeeded() && old_head != new_head && (flags & DC_EXEC) != 0) {
373 /* Copy other things which cannot be copied by a command and which shall not stay resetted from the build vehicle command */
374 new_head->CopyVehicleConfigAndStatistics(old_head);
376 /* Switch vehicle windows/news to the new vehicle, so they are not closed/deleted when the old vehicle is sold */
377 ChangeVehicleViewports(old_head->index, new_head->index);
378 ChangeVehicleViewWindow(old_head->index, new_head->index);
379 ChangeVehicleNews(old_head->index, new_head->index);
382 return cost;
386 * Replace a single unit in a free wagon chain
387 * @param single_unit vehicle to let autoreplace/renew operator on
388 * @param flags command flags
389 * @param nothing_to_do is set to 'false' when something was done (only valid when not failed)
390 * @return cost or error
392 static CommandCost ReplaceFreeUnit(Vehicle **single_unit, DoCommandFlag flags, bool *nothing_to_do)
394 Train *old_v = Train::From(*single_unit);
395 assert(!old_v->IsArticulatedPart() && !old_v->IsRearDualheaded());
397 CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, 0);
399 /* Build and refit replacement vehicle */
400 Vehicle *new_v = NULL;
401 cost.AddCost(BuildReplacementVehicle(old_v, &new_v, false));
403 /* Was a new vehicle constructed? */
404 if (cost.Succeeded() && new_v != NULL) {
405 *nothing_to_do = false;
407 if ((flags & DC_EXEC) != 0) {
408 /* Move the new vehicle behind the old */
409 CmdMoveVehicle(new_v, old_v, DC_EXEC, false);
411 /* Take over cargo
412 * Note: We do only transfer cargo from the old to the new vehicle.
413 * I.e. we do not transfer remaining cargo to other vehicles.
414 * Else you would also need to consider moving cargo to other free chains,
415 * or doing the same in ReplaceChain(), which would be quite troublesome.
417 TransferCargo(old_v, new_v, false);
419 *single_unit = new_v;
422 /* Sell the old vehicle */
423 cost.AddCost(DoCommand(0, old_v->index, 0, flags, CMD_SELL_VEHICLE));
425 /* If we are not in DC_EXEC undo everything */
426 if ((flags & DC_EXEC) == 0) {
427 DoCommand(0, new_v->index, 0, DC_EXEC, CMD_SELL_VEHICLE);
431 return cost;
435 * Replace a whole vehicle chain
436 * @param chain vehicle chain to let autoreplace/renew operator on
437 * @param flags command flags
438 * @param wagon_removal remove wagons when the resulting chain occupies more tiles than the old did
439 * @param nothing_to_do is set to 'false' when something was done (only valid when not failed)
440 * @return cost or error
442 static CommandCost ReplaceChain(Vehicle **chain, DoCommandFlag flags, bool wagon_removal, bool *nothing_to_do)
444 Vehicle *old_head = *chain;
445 assert(old_head->IsPrimaryVehicle());
447 CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, 0);
449 if (old_head->type == VEH_TRAIN) {
450 /* Store the length of the old vehicle chain, rounded up to whole tiles */
451 uint16 old_total_length = CeilDiv(Train::From(old_head)->gcache.cached_total_length, TILE_SIZE) * TILE_SIZE;
453 int num_units = 0; ///< Number of units in the chain
454 for (Train *w = Train::From(old_head); w != NULL; w = w->GetNextUnit()) num_units++;
456 Train **old_vehs = xcalloct<Train *>(num_units); ///< Will store vehicles of the old chain in their order
457 Train **new_vehs = xcalloct<Train *>(num_units); ///< New vehicles corresponding to old_vehs or NULL if no replacement
458 Money *new_costs = xmalloct<Money>(num_units); ///< Costs for buying and refitting the new vehicles
460 /* Collect vehicles and build replacements
461 * Note: The replacement vehicles can only successfully build as long as the old vehicles are still in their chain */
462 int i;
463 Train *w;
464 for (w = Train::From(old_head), i = 0; w != NULL; w = w->GetNextUnit(), i++) {
465 assert(i < num_units);
466 old_vehs[i] = w;
468 CommandCost ret = BuildReplacementVehicle(old_vehs[i], (Vehicle**)&new_vehs[i], true);
469 cost.AddCost(ret);
470 if (cost.Failed()) break;
472 new_costs[i] = ret.GetCost();
473 if (new_vehs[i] != NULL) *nothing_to_do = false;
475 Train *new_head = (new_vehs[0] != NULL ? new_vehs[0] : old_vehs[0]);
477 /* Note: When autoreplace has already failed here, old_vehs[] is not completely initialized. But it is also not needed. */
478 if (cost.Succeeded()) {
479 /* Separate the head, so we can start constructing the new chain */
480 Train *second = Train::From(old_head)->GetNextUnit();
481 if (second != NULL) cost.AddCost(CmdMoveVehicle(second, NULL, DC_EXEC | DC_AUTOREPLACE, true));
483 assert(Train::From(new_head)->GetNextUnit() == NULL);
485 /* Append engines to the new chain
486 * We do this from back to front, so that the head of the temporary vehicle chain does not change all the time.
487 * That way we also have less trouble when exceeding the unitnumber limit.
488 * OTOH the vehicle attach callback is more expensive this way :s */
489 Train *last_engine = NULL; ///< Shall store the last engine unit after this step
490 if (cost.Succeeded()) {
491 for (int i = num_units - 1; i > 0; i--) {
492 Train *append = (new_vehs[i] != NULL ? new_vehs[i] : old_vehs[i]);
494 if (RailVehInfo(append->engine_type)->railveh_type == RAILVEH_WAGON) continue;
496 if (new_vehs[i] != NULL) {
497 /* Move the old engine to a separate row with DC_AUTOREPLACE. Else
498 * moving the wagon in front may fail later due to unitnumber limit.
499 * (We have to attach wagons without DC_AUTOREPLACE.) */
500 CmdMoveVehicle(old_vehs[i], NULL, DC_EXEC | DC_AUTOREPLACE, false);
503 if (last_engine == NULL) last_engine = append;
504 cost.AddCost(CmdMoveVehicle(append, new_head, DC_EXEC, false));
505 if (cost.Failed()) break;
507 if (last_engine == NULL) last_engine = new_head;
510 /* When wagon removal is enabled and the new engines without any wagons are already longer than the old, we have to fail */
511 if (cost.Succeeded() && wagon_removal && new_head->gcache.cached_total_length > old_total_length) cost = CommandCost(STR_ERROR_TRAIN_TOO_LONG_AFTER_REPLACEMENT);
513 /* Append/insert wagons into the new vehicle chain
514 * 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.
516 if (cost.Succeeded()) {
517 for (int i = num_units - 1; i > 0; i--) {
518 assert(last_engine != NULL);
519 Vehicle *append = (new_vehs[i] != NULL ? new_vehs[i] : old_vehs[i]);
521 if (RailVehInfo(append->engine_type)->railveh_type == RAILVEH_WAGON) {
522 /* Insert wagon after 'last_engine' */
523 CommandCost res = CmdMoveVehicle(append, last_engine, DC_EXEC, false);
525 /* When we allow removal of wagons, either the move failing due
526 * to the train becoming too long, or the train becoming longer
527 * would move the vehicle to the empty vehicle chain. */
528 if (wagon_removal && (res.Failed() ? res.GetErrorMessage() == STR_ERROR_TRAIN_TOO_LONG : new_head->gcache.cached_total_length > old_total_length)) {
529 CmdMoveVehicle(append, NULL, DC_EXEC | DC_AUTOREPLACE, false);
530 break;
533 cost.AddCost(res);
534 if (cost.Failed()) break;
535 } else {
536 /* We have reached 'last_engine', continue with the next engine towards the front */
537 assert(append == last_engine);
538 last_engine = last_engine->GetPrevUnit();
543 /* Sell superfluous new vehicles that could not be inserted. */
544 if (cost.Succeeded() && wagon_removal) {
545 assert(new_head->gcache.cached_total_length <= _settings_game.vehicle.max_train_length * TILE_SIZE);
546 for (int i = 1; i < num_units; i++) {
547 Vehicle *wagon = new_vehs[i];
548 if (wagon == NULL) continue;
549 if (wagon->First() == new_head) break;
551 assert(RailVehInfo(wagon->engine_type)->railveh_type == RAILVEH_WAGON);
553 /* Sell wagon */
554 CommandCost ret = DoCommand(0, wagon->index, 0, DC_EXEC, CMD_SELL_VEHICLE);
555 assert(ret.Succeeded());
556 new_vehs[i] = NULL;
558 /* Revert the money subtraction when the vehicle was built.
559 * This value is different from the sell value, esp. because of refitting */
560 cost.AddCost(-new_costs[i]);
564 /* The new vehicle chain is constructed, now take over orders and everything... */
565 if (cost.Succeeded()) cost.AddCost(CopyHeadSpecificThings(old_head, new_head, flags));
567 if (cost.Succeeded()) {
568 /* Success ! */
569 if ((flags & DC_EXEC) != 0 && new_head != old_head) {
570 *chain = new_head;
573 /* Transfer cargo of old vehicles and sell them */
574 for (int i = 0; i < num_units; i++) {
575 Vehicle *w = old_vehs[i];
576 /* Is the vehicle again part of the new chain?
577 * Note: We cannot test 'new_vehs[i] != NULL' as wagon removal might cause to remove both */
578 if (w->First() == new_head) continue;
580 if ((flags & DC_EXEC) != 0) TransferCargo(w, new_head, true);
581 /* Update train weight etc., the old vehicle will be sold anyway */
582 new_head->ConsistChanged (CCF_LOADUNLOAD);
584 /* Sell the vehicle.
585 * Note: This might temporarly construct new trains, so use DC_AUTOREPLACE to prevent
586 * it from failing due to engine limits. */
587 cost.AddCost(DoCommand(0, w->index, 0, flags | DC_AUTOREPLACE, CMD_SELL_VEHICLE));
588 if ((flags & DC_EXEC) != 0) {
589 old_vehs[i] = NULL;
590 if (i == 0) old_head = NULL;
594 if ((flags & DC_EXEC) != 0) CheckCargoCapacity(new_head);
597 /* If we are not in DC_EXEC undo everything, i.e. rearrange old vehicles.
598 * We do this from back to front, so that the head of the temporary vehicle chain does not change all the time.
599 * Note: The vehicle attach callback is disabled here :) */
600 if ((flags & DC_EXEC) == 0) {
601 /* Separate the head, so we can reattach the old vehicles */
602 Train *second = Train::From(old_head)->GetNextUnit();
603 if (second != NULL) CmdMoveVehicle(second, NULL, DC_EXEC | DC_AUTOREPLACE, true);
605 assert(Train::From(old_head)->GetNextUnit() == NULL);
607 for (int i = num_units - 1; i > 0; i--) {
608 CommandCost ret = CmdMoveVehicle(old_vehs[i], old_head, DC_EXEC | DC_AUTOREPLACE, false);
609 assert(ret.Succeeded());
614 /* Finally undo buying of new vehicles */
615 if ((flags & DC_EXEC) == 0) {
616 for (int i = num_units - 1; i >= 0; i--) {
617 if (new_vehs[i] != NULL) {
618 DoCommand(0, new_vehs[i]->index, 0, DC_EXEC, CMD_SELL_VEHICLE);
619 new_vehs[i] = NULL;
624 free(old_vehs);
625 free(new_vehs);
626 free(new_costs);
627 } else {
628 /* Build and refit replacement vehicle */
629 Vehicle *new_head = NULL;
630 cost.AddCost(BuildReplacementVehicle(old_head, &new_head, true));
632 /* Was a new vehicle constructed? */
633 if (cost.Succeeded() && new_head != NULL) {
634 *nothing_to_do = false;
636 /* The new vehicle is constructed, now take over orders and everything... */
637 cost.AddCost(CopyHeadSpecificThings(old_head, new_head, flags));
639 if (cost.Succeeded()) {
640 /* The new vehicle is constructed, now take over cargo */
641 if ((flags & DC_EXEC) != 0) {
642 TransferCargo(old_head, new_head, true);
643 *chain = new_head;
646 /* Sell the old vehicle */
647 cost.AddCost(DoCommand(0, old_head->index, 0, flags, CMD_SELL_VEHICLE));
650 /* If we are not in DC_EXEC undo everything */
651 if ((flags & DC_EXEC) == 0) {
652 DoCommand(0, new_head->index, 0, DC_EXEC, CMD_SELL_VEHICLE);
657 return cost;
661 * Autoreplaces a vehicle
662 * Trains are replaced as a whole chain, free wagons in depot are replaced on their own
663 * @param tile not used
664 * @param flags type of operation
665 * @param p1 Index of vehicle
666 * @param p2 not used
667 * @param text unused
668 * @return the cost of this operation or an error
670 CommandCost CmdAutoreplaceVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
672 Vehicle *v = Vehicle::GetIfValid(p1);
673 if (v == NULL) return CMD_ERROR;
675 CommandCost ret = CheckOwnership(v->owner);
676 if (ret.Failed()) return ret;
678 if (!v->IsChainInDepot()) return CMD_ERROR;
679 if (v->vehstatus & VS_CRASHED) return CMD_ERROR;
681 bool free_wagon = false;
682 if (v->type == VEH_TRAIN) {
683 Train *t = Train::From(v);
684 if (t->IsArticulatedPart() || t->IsRearDualheaded()) return CMD_ERROR;
685 free_wagon = !t->IsFrontEngine();
686 if (free_wagon && t->First()->IsFrontEngine()) return CMD_ERROR;
687 } else {
688 if (!v->IsPrimaryVehicle()) return CMD_ERROR;
691 const Company *c = Company::Get(_current_company);
692 bool wagon_removal = c->settings.renew_keep_length;
694 /* Test whether any replacement is set, before issuing a whole lot of commands that would end in nothing changed */
695 Vehicle *w = v;
696 bool any_replacements = false;
697 while (w != NULL) {
698 EngineID e;
699 CommandCost cost = GetNewEngineType(w, c, false, e);
700 if (cost.Failed()) return cost;
701 any_replacements |= (e != INVALID_ENGINE);
702 w = (!free_wagon && w->type == VEH_TRAIN ? Train::From(w)->GetNextUnit() : NULL);
705 CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, 0);
706 bool nothing_to_do = true;
708 if (any_replacements) {
709 bool was_stopped = free_wagon || ((v->vehstatus & VS_STOPPED) != 0);
711 /* Stop the vehicle */
712 if (!was_stopped) cost.AddCost(CmdStartStopVehicle(v, true));
713 if (cost.Failed()) return cost;
715 assert(free_wagon || v->IsStoppedInDepot());
717 /* We have to construct the new vehicle chain to test whether it is valid.
718 * Vehicle construction needs random bits, so we have to save the random seeds
719 * to prevent desyncs and to replay newgrf callbacks during DC_EXEC */
720 SavedRandomSeeds saved_seeds;
721 SaveRandomSeeds(&saved_seeds);
722 if (free_wagon) {
723 cost.AddCost(ReplaceFreeUnit(&v, flags & ~DC_EXEC, &nothing_to_do));
724 } else {
725 cost.AddCost(ReplaceChain(&v, flags & ~DC_EXEC, wagon_removal, &nothing_to_do));
727 RestoreRandomSeeds(saved_seeds);
729 if (cost.Succeeded() && (flags & DC_EXEC) != 0) {
730 CommandCost ret;
731 if (free_wagon) {
732 ret = ReplaceFreeUnit(&v, flags, &nothing_to_do);
733 } else {
734 ret = ReplaceChain(&v, flags, wagon_removal, &nothing_to_do);
736 assert(ret.Succeeded() && ret.GetCost() == cost.GetCost());
739 /* Restart the vehicle */
740 if (!was_stopped) cost.AddCost(CmdStartStopVehicle(v, false));
743 if (cost.Succeeded() && nothing_to_do) cost = CommandCost(STR_ERROR_AUTOREPLACE_NOTHING_TO_DO);
744 return cost;
748 * Change engine renewal parameters
749 * @param tile unused
750 * @param flags operation to perform
751 * @param p1 packed data
752 * - bit 0 = replace when engine gets old?
753 * - bits 16-31 = engine group
754 * @param p2 packed data
755 * - bits 0-15 = old engine type
756 * - bits 16-31 = new engine type
757 * @param text unused
758 * @return the cost of this operation or an error
760 CommandCost CmdSetAutoReplace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
762 Company *c = Company::GetIfValid(_current_company);
763 if (c == NULL) return CMD_ERROR;
765 EngineID old_engine_type = GB(p2, 0, 16);
766 EngineID new_engine_type = GB(p2, 16, 16);
767 GroupID id_g = GB(p1, 16, 16);
768 CommandCost cost;
770 if (Group::IsValidID(id_g) ? Group::Get(id_g)->owner != _current_company : !IsAllGroupID(id_g) && !IsDefaultGroupID(id_g)) return CMD_ERROR;
771 if (!Engine::IsValidID(old_engine_type)) return CMD_ERROR;
773 if (new_engine_type != INVALID_ENGINE) {
774 if (!Engine::IsValidID(new_engine_type)) return CMD_ERROR;
775 if (!CheckAutoreplaceValidity(old_engine_type, new_engine_type, _current_company)) return CMD_ERROR;
777 cost = AddEngineReplacementForCompany(c, old_engine_type, new_engine_type, id_g, HasBit(p1, 0), flags);
778 } else {
779 cost = RemoveEngineReplacementForCompany(c, old_engine_type, id_g, flags);
782 if (flags & DC_EXEC) {
783 GroupStatistics::UpdateAutoreplace(_current_company);
784 if (IsLocalCompany()) SetWindowDirty(WC_REPLACE_VEHICLE, Engine::Get(old_engine_type)->type);
786 if ((flags & DC_EXEC) && IsLocalCompany()) InvalidateAutoreplaceWindow(old_engine_type, id_g);
788 return cost;