Show snow on depot tiles. (Looks weird my ass)
[openttd-joker.git] / src / autoreplace_cmd.cpp
blob8a48ef82be2c38ac69728e000e58daf3c2fb3c28
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 "tracerestrict.h"
22 #include "core/random_func.hpp"
24 #include "table/strings.h"
26 #include "safeguards.h"
28 extern void ChangeVehicleViewports(VehicleID from_index, VehicleID to_index);
29 extern void ChangeVehicleNews(VehicleID from_index, VehicleID to_index);
30 extern void ChangeVehicleViewWindow(VehicleID from_index, VehicleID to_index);
32 /**
33 * Figure out if two engines got at least one type of cargo in common (refitting if needed)
34 * @param engine_a one of the EngineIDs
35 * @param engine_b the other EngineID
36 * @param type the type of the engines
37 * @return true if they can both carry the same type of cargo (or at least one of them got no capacity at all)
39 static bool EnginesHaveCargoInCommon(EngineID engine_a, EngineID engine_b)
41 uint32 available_cargoes_a = GetUnionOfArticulatedRefitMasks(engine_a, true);
42 uint32 available_cargoes_b = GetUnionOfArticulatedRefitMasks(engine_b, true);
43 return (available_cargoes_a == 0 || available_cargoes_b == 0 || (available_cargoes_a & available_cargoes_b) != 0);
46 /**
47 * Checks some basic properties whether autoreplace is allowed
48 * @param from Origin engine
49 * @param to Destination engine
50 * @param company Company to check for
51 * @return true if autoreplace is allowed
53 bool CheckAutoreplaceValidity(EngineID from, EngineID to, CompanyID company)
55 assert(Engine::IsValidID(from) && Engine::IsValidID(to));
57 /* we can't replace an engine into itself (that would be autorenew) */
58 //if (from == to) return false;
60 const Engine *e_from = Engine::Get(from);
61 const Engine *e_to = Engine::Get(to);
62 VehicleType type = e_from->type;
64 /* check that the new vehicle type is available to the company and its type is the same as the original one */
65 if (!IsEngineBuildable(to, type, company)) return false;
67 switch (type) {
68 case VEH_TRAIN: {
69 /* make sure the railtypes are compatible */
70 if ((GetRailTypeInfo(e_from->u.rail.railtype)->compatible_railtypes & GetRailTypeInfo(e_to->u.rail.railtype)->compatible_railtypes) == 0) return false;
72 /* make sure we do not replace wagons with engines or vice versa */
73 if ((e_from->u.rail.railveh_type == RAILVEH_WAGON) != (e_to->u.rail.railveh_type == RAILVEH_WAGON)) return false;
74 break;
77 case VEH_ROAD:
78 /* make sure that we do not replace a tram with a normal road vehicles or vice versa */
79 if (HasBit(e_from->info.misc_flags, EF_ROAD_TRAM) != HasBit(e_to->info.misc_flags, EF_ROAD_TRAM)) return false;
80 break;
82 case VEH_AIRCRAFT:
83 /* make sure that we do not replace a plane with a helicopter or vice versa */
84 if ((e_from->u.air.subtype & AIR_CTOL) != (e_to->u.air.subtype & AIR_CTOL)) return false;
85 break;
87 default: break;
90 /* the engines needs to be able to carry the same cargo */
91 return EnginesHaveCargoInCommon(from, to);
94 /**
95 * Check the capacity of all vehicles in a chain and spread cargo if needed.
96 * @param v The vehicle to check.
97 * @pre You can only do this if the consist is not loading or unloading. It
98 * must not carry reserved cargo, nor cargo to be unloaded or transferred.
100 void CheckCargoCapacity(Vehicle *v)
102 assert(v == nullptr || v->First() == v);
104 for (Vehicle *src = v; src != nullptr; src = src->Next()) {
105 assert(src->cargo.TotalCount() == src->cargo.ActionCount(VehicleCargoList::MTA_KEEP));
107 /* Do we need to more cargo away? */
108 if (src->cargo.TotalCount() <= src->cargo_cap) continue;
110 /* We need to move a particular amount. Try that on the other vehicles. */
111 uint to_spread = src->cargo.TotalCount() - src->cargo_cap;
112 for (Vehicle *dest = v; dest != nullptr && to_spread != 0; dest = dest->Next()) {
113 assert(dest->cargo.TotalCount() == dest->cargo.ActionCount(VehicleCargoList::MTA_KEEP));
114 if (dest->cargo.TotalCount() >= dest->cargo_cap || dest->cargo_type != src->cargo_type) continue;
116 uint amount = min(to_spread, dest->cargo_cap - dest->cargo.TotalCount());
117 src->cargo.Shift(amount, &dest->cargo);
118 to_spread -= amount;
121 /* Any left-overs will be thrown away, but not their feeder share. */
122 if (src->cargo_cap < src->cargo.TotalCount()) src->cargo.Truncate(src->cargo.TotalCount() - src->cargo_cap);
127 * Transfer cargo from a single (articulated )old vehicle to the new vehicle chain
128 * @param old_veh Old vehicle that will be sold
129 * @param new_head Head of the completely constructed new vehicle chain
130 * @param part_of_chain The vehicle is part of a train
131 * @pre You can only do this if both consists are not loading or unloading.
132 * They must not carry reserved cargo, nor cargo to be unloaded or
133 * transferred.
135 static void TransferCargo(Vehicle *old_veh, Vehicle *new_head, bool part_of_chain)
137 assert(!part_of_chain || new_head->IsPrimaryVehicle());
138 /* Loop through source parts */
139 for (Vehicle *src = old_veh; src != nullptr; src = src->Next()) {
140 assert(src->cargo.TotalCount() == src->cargo.ActionCount(VehicleCargoList::MTA_KEEP));
141 if (!part_of_chain && src->type == VEH_TRAIN && src != old_veh && src != Train::From(old_veh)->other_multiheaded_part && !src->IsArticulatedPart()) {
142 /* Skip vehicles, which do not belong to old_veh */
143 src = src->GetLastEnginePart();
144 continue;
146 if (src->cargo_type >= NUM_CARGO || src->cargo.TotalCount() == 0) continue;
148 /* Find free space in the new chain */
149 for (Vehicle *dest = new_head; dest != nullptr && src->cargo.TotalCount() > 0; dest = dest->Next()) {
150 assert(dest->cargo.TotalCount() == dest->cargo.ActionCount(VehicleCargoList::MTA_KEEP));
151 if (!part_of_chain && dest->type == VEH_TRAIN && dest != new_head && dest != Train::From(new_head)->other_multiheaded_part && !dest->IsArticulatedPart()) {
152 /* Skip vehicles, which do not belong to new_head */
153 dest = dest->GetLastEnginePart();
154 continue;
156 if (dest->cargo_type != src->cargo_type) continue;
158 uint amount = min(src->cargo.TotalCount(), dest->cargo_cap - dest->cargo.TotalCount());
159 if (amount <= 0) continue;
161 src->cargo.Shift(amount, &dest->cargo);
165 /* Update train weight etc., the old vehicle will be sold anyway */
166 if (part_of_chain && new_head->type == VEH_TRAIN) Train::From(new_head)->ConsistChanged(CCF_LOADUNLOAD);
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() || o->IsAutoRefit()) continue;
185 CargoID cargo_type = o->GetRefitCargo();
187 if (!HasBit(union_refit_mask_a, cargo_type)) continue;
188 if (!HasBit(union_refit_mask_b, cargo_type)) 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 != nullptr; 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 same_type_only Only replace with same engine type.
243 * @param [out] e the EngineID of the replacement. INVALID_ENGINE if no replacement is found
244 * @return Error if the engine to build is not available
246 static CommandCost GetNewEngineType(const Vehicle *v, const Company *c, bool always_replace, bool same_type_only, EngineID &e)
248 assert(v->type != VEH_TRAIN || !v->IsArticulatedPart());
250 e = INVALID_ENGINE;
252 if (v->type == VEH_TRAIN && Train::From(v)->IsRearDualheaded()) {
253 /* we build the rear ends of multiheaded trains with the front ones */
254 return CommandCost();
257 if (!same_type_only) {
258 bool replace_when_old;
259 e = EngineReplacementForCompany(c, v->engine_type, v->group_id, &replace_when_old);
260 if (!always_replace && replace_when_old && !v->NeedsAutorenewing(c, false)) e = INVALID_ENGINE;
263 /* Autoreplace, if engine is available */
264 if (e != INVALID_ENGINE && IsEngineBuildable(e, v->type, _current_company)) {
265 return CommandCost();
268 /* Autorenew if needed */
269 if (v->NeedsAutorenewing(c)) e = v->engine_type;
271 /* Nothing to do or all is fine? */
272 if (e == INVALID_ENGINE || IsEngineBuildable(e, v->type, _current_company)) return CommandCost();
274 /* The engine we need is not available. Report error to user */
275 return CommandCost(STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE + v->type);
279 * Builds and refits a replacement vehicle
280 * 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)
281 * @param old_veh A single (articulated/multiheaded) vehicle that shall be replaced.
282 * @param new_vehicle Returns the newly build and refitted vehicle
283 * @param part_of_chain The vehicle is part of a train
284 * @param same_type_only Only replace with same engine type.
285 * @return cost or error
287 static CommandCost BuildReplacementVehicle(Vehicle *old_veh, Vehicle **new_vehicle, bool part_of_chain, bool same_type_only)
289 *new_vehicle = nullptr;
291 /* Shall the vehicle be replaced? */
292 const Company *c = Company::Get(_current_company);
293 EngineID e;
294 CommandCost cost = GetNewEngineType(old_veh, c, true, same_type_only, e);
295 if (cost.Failed()) return cost;
296 if (e == INVALID_ENGINE) return CommandCost(); // neither autoreplace is set, nor autorenew is triggered
298 /* Does it need to be refitted */
299 CargoID refit_cargo = GetNewCargoTypeForReplace(old_veh, e, part_of_chain);
300 if (refit_cargo == CT_INVALID) return CommandCost(); // incompatible cargoes
302 /* Build the new vehicle */
303 cost = DoCommand(old_veh->tile, e, 0, DC_EXEC | DC_AUTOREPLACE, GetCmdBuildVeh(old_veh));
304 if (cost.Failed()) return cost;
306 Vehicle *new_veh = Vehicle::Get(_new_vehicle_id);
307 *new_vehicle = new_veh;
309 /* Refit the vehicle if needed */
310 if (refit_cargo != CT_NO_REFIT) {
311 byte subtype = GetBestFittingSubType(old_veh, new_veh, refit_cargo);
313 cost.AddCost(DoCommand(0, new_veh->index, refit_cargo | (subtype << 8), DC_EXEC, GetCmdRefitVeh(new_veh)));
314 assert(cost.Succeeded()); // This should be ensured by GetNewCargoTypeForReplace()
317 /* Try to reverse the vehicle, but do not care if it fails as the new type might not be reversible */
318 if (new_veh->type == VEH_TRAIN && HasBit(Train::From(old_veh)->flags, VRF_REVERSE_DIRECTION)) {
319 DoCommand(0, new_veh->index, true, DC_EXEC, CMD_REVERSE_TRAIN_DIRECTION);
322 return cost;
326 * Issue a start/stop command
327 * @param v a vehicle
328 * @param evaluate_callback shall the start/stop callback be evaluated?
329 * @return success or error
331 static inline CommandCost CmdStartStopVehicle(const Vehicle *v, bool evaluate_callback)
333 return DoCommand(0, v->index, evaluate_callback ? 1 : 0, DC_EXEC | DC_AUTOREPLACE, CMD_START_STOP_VEHICLE);
337 * Issue a train vehicle move command
338 * @param v The vehicle to move
339 * @param after The vehicle to insert 'v' after, or nullptr to start new chain
340 * @param flags the command flags to use
341 * @param whole_chain move all vehicles following 'v' (true), or only 'v' (false)
342 * @return success or error
344 static inline CommandCost CmdMoveVehicle(const Vehicle *v, const Vehicle *after, DoCommandFlag flags, bool whole_chain)
346 return DoCommand(0, v->index | (whole_chain ? 1 : 0) << 20, after != nullptr ? after->index : INVALID_VEHICLE, flags | DC_NO_CARGO_CAP_CHECK, CMD_MOVE_RAIL_VEHICLE);
350 * Copy head specific things to the new vehicle chain after it was successfully constructed
351 * @param old_head The old front vehicle (no wagons attached anymore)
352 * @param new_head The new head of the completely replaced vehicle chain
353 * @param flags the command flags to use
355 CommandCost CopyHeadSpecificThings(Vehicle *old_head, Vehicle *new_head, DoCommandFlag flags)
357 CommandCost cost = CommandCost();
359 /* Share orders */
360 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));
362 /* Copy group membership */
363 if (cost.Succeeded() && old_head != new_head) cost.AddCost(DoCommand(0, old_head->group_id, new_head->index, DC_EXEC, CMD_ADD_VEHICLE_GROUP));
365 /* Perform start/stop check whether the new vehicle suits newgrf restrictions etc. */
366 if (cost.Succeeded()) {
367 /* Start the vehicle, might be denied by certain things */
368 assert((new_head->vehstatus & VS_STOPPED) != 0);
369 cost.AddCost(CmdStartStopVehicle(new_head, true));
371 /* Stop the vehicle again, but do not care about evil newgrfs allowing starting but not stopping :p */
372 if (cost.Succeeded()) cost.AddCost(CmdStartStopVehicle(new_head, false));
375 /* Last do those things which do never fail (resp. we do not care about), but which are not undo-able */
376 if (cost.Succeeded() && old_head != new_head && (flags & DC_EXEC) != 0) {
377 /* Copy other things which cannot be copied by a command and which shall not stay resetted from the build vehicle command */
378 new_head->CopyVehicleConfigAndStatistics(old_head);
380 /* Switch vehicle windows/news to the new vehicle, so they are not closed/deleted when the old vehicle is sold */
381 ChangeVehicleViewports(old_head->index, new_head->index);
382 ChangeVehicleViewWindow(old_head->index, new_head->index);
383 ChangeVehicleNews(old_head->index, new_head->index);
386 return cost;
390 * Replace a single unit in a free wagon chain
391 * @param single_unit vehicle to let autoreplace/renew operator on
392 * @param flags command flags
393 * @param nothing_to_do is set to 'false' when something was done (only valid when not failed)
394 * @param same_type_only Only replace with same engine type.
395 * @return cost or error
397 static CommandCost ReplaceFreeUnit(Vehicle **single_unit, DoCommandFlag flags, bool *nothing_to_do, bool same_type_only)
399 Train *old_v = Train::From(*single_unit);
400 assert(!old_v->IsArticulatedPart() && !old_v->IsRearDualheaded());
402 CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, 0);
404 /* Build and refit replacement vehicle */
405 Vehicle *new_v = nullptr;
406 cost.AddCost(BuildReplacementVehicle(old_v, &new_v, false, same_type_only));
408 /* Was a new vehicle constructed? */
409 if (cost.Succeeded() && new_v != nullptr) {
410 *nothing_to_do = false;
412 if ((flags & DC_EXEC) != 0) {
413 /* Move the new vehicle behind the old */
414 CmdMoveVehicle(new_v, old_v, DC_EXEC, false);
416 /* Take over cargo
417 * Note: We do only transfer cargo from the old to the new vehicle.
418 * I.e. we do not transfer remaining cargo to other vehicles.
419 * Else you would also need to consider moving cargo to other free chains,
420 * or doing the same in ReplaceChain(), which would be quite troublesome.
422 TransferCargo(old_v, new_v, false);
424 *single_unit = new_v;
427 /* Sell the old vehicle */
428 cost.AddCost(DoCommand(0, old_v->index, 0, flags, GetCmdSellVeh(old_v)));
430 /* If we are not in DC_EXEC undo everything */
431 if ((flags & DC_EXEC) == 0) {
432 DoCommand(0, new_v->index, 0, DC_EXEC, GetCmdSellVeh(new_v));
436 return cost;
440 * Replace a whole vehicle chain
441 * @param chain vehicle chain to let autoreplace/renew operator on
442 * @param flags command flags
443 * @param wagon_removal remove wagons when the resulting chain occupies more tiles than the old did
444 * @param nothing_to_do is set to 'false' when something was done (only valid when not failed)
445 * @param same_type_only Only replace with same engine type.
446 * @return cost or error
448 static CommandCost ReplaceChain(Vehicle **chain, DoCommandFlag flags, bool wagon_removal, bool *nothing_to_do, bool same_type_only)
450 Vehicle *old_head = *chain;
451 assert(old_head->IsPrimaryVehicle());
453 CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, 0);
455 if (old_head->type == VEH_TRAIN) {
456 /* Store the length of the old vehicle chain, rounded up to whole tiles */
457 uint16 old_total_length = CeilDiv(Train::From(old_head)->gcache.cached_total_length, TILE_SIZE) * TILE_SIZE;
459 int num_units = 0; ///< Number of units in the chain
460 for (Train *w = Train::From(old_head); w != nullptr; w = w->GetNextUnit()) num_units++;
462 Train **old_vehs = CallocT<Train *>(num_units); ///< Will store vehicles of the old chain in their order
463 Train **new_vehs = CallocT<Train *>(num_units); ///< New vehicles corresponding to old_vehs or nullptr if no replacement
464 Money *new_costs = MallocT<Money>(num_units); ///< Costs for buying and refitting the new vehicles
466 /* Collect vehicles and build replacements
467 * Note: The replacement vehicles can only successfully build as long as the old vehicles are still in their chain */
468 int i;
469 Train *w;
470 for (w = Train::From(old_head), i = 0; w != nullptr; w = w->GetNextUnit(), i++) {
471 assert(i < num_units);
472 old_vehs[i] = w;
474 CommandCost ret = BuildReplacementVehicle(old_vehs[i], (Vehicle**)&new_vehs[i], true, same_type_only);
475 cost.AddCost(ret);
476 if (cost.Failed()) break;
478 new_costs[i] = ret.GetCost();
479 if (new_vehs[i] != nullptr) *nothing_to_do = false;
481 Train *new_head = (new_vehs[0] != nullptr ? new_vehs[0] : old_vehs[0]);
483 /* Note: When autoreplace has already failed here, old_vehs[] is not completely initialized. But it is also not needed. */
484 if (cost.Succeeded()) {
485 /* Separate the head, so we can start constructing the new chain */
486 Train *second = Train::From(old_head)->GetNextUnit();
487 if (second != nullptr) cost.AddCost(CmdMoveVehicle(second, nullptr, DC_EXEC | DC_AUTOREPLACE, true));
489 assert(Train::From(new_head)->GetNextUnit() == nullptr);
491 /* Append engines to the new chain
492 * We do this from back to front, so that the head of the temporary vehicle chain does not change all the time.
493 * That way we also have less trouble when exceeding the unitnumber limit.
494 * OTOH the vehicle attach callback is more expensive this way :s */
495 Train *last_engine = nullptr; ///< Shall store the last engine unit after this step
496 if (cost.Succeeded()) {
497 for (int i = num_units - 1; i > 0; i--) {
498 Train *append = (new_vehs[i] != nullptr ? new_vehs[i] : old_vehs[i]);
500 if (RailVehInfo(append->engine_type)->railveh_type == RAILVEH_WAGON) continue;
502 if (new_vehs[i] != nullptr) {
503 /* Move the old engine to a separate row with DC_AUTOREPLACE. Else
504 * moving the wagon in front may fail later due to unitnumber limit.
505 * (We have to attach wagons without DC_AUTOREPLACE.) */
506 CmdMoveVehicle(old_vehs[i], nullptr, DC_EXEC | DC_AUTOREPLACE, false);
509 if (last_engine == nullptr) last_engine = append;
510 cost.AddCost(CmdMoveVehicle(append, new_head, DC_EXEC, false));
511 if (cost.Failed()) break;
513 if (last_engine == nullptr) last_engine = new_head;
516 /* When wagon removal is enabled and the new engines without any wagons are already longer than the old, we have to fail */
517 if (cost.Succeeded() && wagon_removal && new_head->gcache.cached_total_length > old_total_length) cost = CommandCost(STR_ERROR_TRAIN_TOO_LONG_AFTER_REPLACEMENT);
519 /* Append/insert wagons into the new vehicle chain
520 * 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.
522 if (cost.Succeeded()) {
523 for (int i = num_units - 1; i > 0; i--) {
524 assert(last_engine != nullptr);
525 Vehicle *append = (new_vehs[i] != nullptr ? new_vehs[i] : old_vehs[i]);
527 if (RailVehInfo(append->engine_type)->railveh_type == RAILVEH_WAGON) {
528 /* Insert wagon after 'last_engine' */
529 CommandCost res = CmdMoveVehicle(append, last_engine, DC_EXEC, false);
531 /* When we allow removal of wagons, either the move failing due
532 * to the train becoming too long, or the train becoming longer
533 * would move the vehicle to the empty vehicle chain. */
534 if (wagon_removal && (res.Failed() ? res.GetErrorMessage() == STR_ERROR_TRAIN_TOO_LONG : new_head->gcache.cached_total_length > old_total_length)) {
535 CmdMoveVehicle(append, nullptr, DC_EXEC | DC_AUTOREPLACE, false);
536 break;
539 cost.AddCost(res);
540 if (cost.Failed()) break;
541 } else {
542 /* We have reached 'last_engine', continue with the next engine towards the front */
543 assert(append == last_engine);
544 last_engine = last_engine->GetPrevUnit();
549 /* Sell superfluous new vehicles that could not be inserted. */
550 if (cost.Succeeded() && wagon_removal) {
551 assert(new_head->gcache.cached_total_length <= _settings_game.vehicle.max_train_length * TILE_SIZE);
552 for (int i = 1; i < num_units; i++) {
553 Vehicle *wagon = new_vehs[i];
554 if (wagon == nullptr) continue;
555 if (wagon->First() == new_head) break;
557 assert(RailVehInfo(wagon->engine_type)->railveh_type == RAILVEH_WAGON);
559 /* Sell wagon */
560 CommandCost ret = DoCommand(0, wagon->index, 0, DC_EXEC, GetCmdSellVeh(wagon));
561 assert(ret.Succeeded());
562 new_vehs[i] = nullptr;
564 /* Revert the money subtraction when the vehicle was built.
565 * This value is different from the sell value, esp. because of refitting */
566 cost.AddCost(-new_costs[i]);
570 /* The new vehicle chain is constructed, now take over orders and everything... */
571 if (cost.Succeeded()) cost.AddCost(CopyHeadSpecificThings(old_head, new_head, flags));
573 if (cost.Succeeded()) {
574 /* Success ! */
575 if ((flags & DC_EXEC) != 0 && new_head != old_head) {
576 *chain = new_head;
577 if (HasBit(Train::From(old_head)->flags, VRF_HAVE_SLOT)) {
578 TraceRestrictTransferVehicleOccupantInAllSlots(old_head->index, new_head->index);
579 ClrBit(Train::From(old_head)->flags, VRF_HAVE_SLOT);
580 SetBit(Train::From(new_head)->flags, VRF_HAVE_SLOT);
584 /* Transfer cargo of old vehicles and sell them */
585 for (int i = 0; i < num_units; i++) {
586 Vehicle *w = old_vehs[i];
587 /* Is the vehicle again part of the new chain?
588 * Note: We cannot test 'new_vehs[i] != nullptr' as wagon removal might cause to remove both */
589 if (w->First() == new_head) continue;
591 if ((flags & DC_EXEC) != 0) TransferCargo(w, new_head, true);
593 /* Sell the vehicle.
594 * Note: This might temporarly construct new trains, so use DC_AUTOREPLACE to prevent
595 * it from failing due to engine limits. */
596 cost.AddCost(DoCommand(0, w->index, 0, flags | DC_AUTOREPLACE, GetCmdSellVeh(w)));
597 if ((flags & DC_EXEC) != 0) {
598 old_vehs[i] = nullptr;
599 if (i == 0) old_head = nullptr;
603 if ((flags & DC_EXEC) != 0) CheckCargoCapacity(new_head);
606 /* If we are not in DC_EXEC undo everything, i.e. rearrange old vehicles.
607 * We do this from back to front, so that the head of the temporary vehicle chain does not change all the time.
608 * Note: The vehicle attach callback is disabled here :) */
609 if ((flags & DC_EXEC) == 0) {
610 /* Separate the head, so we can reattach the old vehicles */
611 Train *second = Train::From(old_head)->GetNextUnit();
612 if (second != nullptr) CmdMoveVehicle(second, nullptr, DC_EXEC | DC_AUTOREPLACE, true);
614 assert(Train::From(old_head)->GetNextUnit() == nullptr);
616 for (int i = num_units - 1; i > 0; i--) {
617 CommandCost ret = CmdMoveVehicle(old_vehs[i], old_head, DC_EXEC | DC_AUTOREPLACE, false);
618 assert(ret.Succeeded());
623 /* Finally undo buying of new vehicles */
624 if ((flags & DC_EXEC) == 0) {
625 for (int i = num_units - 1; i >= 0; i--) {
626 if (new_vehs[i] != nullptr) {
627 DoCommand(0, new_vehs[i]->index, 0, DC_EXEC, GetCmdSellVeh(new_vehs[i]));
628 new_vehs[i] = nullptr;
633 free(old_vehs);
634 free(new_vehs);
635 free(new_costs);
636 } else {
637 /* Build and refit replacement vehicle */
638 Vehicle *new_head = nullptr;
639 cost.AddCost(BuildReplacementVehicle(old_head, &new_head, true, same_type_only));
641 /* Was a new vehicle constructed? */
642 if (cost.Succeeded() && new_head != nullptr) {
643 *nothing_to_do = false;
645 /* The new vehicle is constructed, now take over orders and everything... */
646 cost.AddCost(CopyHeadSpecificThings(old_head, new_head, flags));
648 if (cost.Succeeded()) {
649 /* The new vehicle is constructed, now take over cargo */
650 if ((flags & DC_EXEC) != 0) {
651 TransferCargo(old_head, new_head, true);
652 *chain = new_head;
655 /* Sell the old vehicle */
656 cost.AddCost(DoCommand(0, old_head->index, 0, flags, GetCmdSellVeh(old_head)));
659 /* If we are not in DC_EXEC undo everything */
660 if ((flags & DC_EXEC) == 0) {
661 DoCommand(0, new_head->index, 0, DC_EXEC, GetCmdSellVeh(new_head));
666 return cost;
670 * Autoreplaces a vehicle
671 * Trains are replaced as a whole chain, free wagons in depot are replaced on their own
672 * @param tile not used
673 * @param flags type of operation
674 * @param p1 Index of vehicle
675 * @param p2 packed data
676 * - bit 0 = Autoreplace with same type only
677 * @param text unused
678 * @return the cost of this operation or an error
680 CommandCost CmdAutoreplaceVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
682 Vehicle *v = Vehicle::GetIfValid(p1);
683 if (v == nullptr) return CommandError();
685 CommandCost ret = CheckOwnership(v->owner);
686 if (ret.Failed()) return ret;
688 if (!v->IsChainInDepot()) return CommandError();
689 if (v->vehstatus & VS_CRASHED) return CommandError();
691 bool free_wagon = false;
692 if (v->type == VEH_TRAIN) {
693 Train *t = Train::From(v);
694 if (t->IsArticulatedPart() || t->IsRearDualheaded()) return CommandError();
695 free_wagon = !t->IsFrontEngine();
696 if (free_wagon && t->First()->IsFrontEngine()) return CommandError();
697 } else {
698 if (!v->IsPrimaryVehicle()) return CommandError();
701 const Company *c = Company::Get(_current_company);
702 bool wagon_removal = c->settings.renew_keep_length;
703 bool same_type_only = HasBit(p2, 0);
705 /* Test whether any replacement is set, before issuing a whole lot of commands that would end in nothing changed */
706 Vehicle *w = v;
707 bool any_replacements = false;
708 while (w != nullptr) {
709 EngineID e;
710 CommandCost cost = GetNewEngineType(w, c, false, same_type_only, e);
711 if (cost.Failed()) return cost;
712 any_replacements |= (e != INVALID_ENGINE);
713 w = (!free_wagon && w->type == VEH_TRAIN ? Train::From(w)->GetNextUnit() : nullptr);
716 CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, 0);
717 bool nothing_to_do = true;
719 if (any_replacements) {
720 bool was_stopped = free_wagon || ((v->vehstatus & VS_STOPPED) != 0);
722 /* Stop the vehicle */
723 if (!was_stopped) cost.AddCost(CmdStartStopVehicle(v, true));
724 if (cost.Failed()) return cost;
726 assert(free_wagon || v->IsStoppedInDepot());
728 /* We have to construct the new vehicle chain to test whether it is valid.
729 * Vehicle construction needs random bits, so we have to save the random seeds
730 * to prevent desyncs and to replay newgrf callbacks during DC_EXEC */
731 SavedRandomSeeds saved_seeds;
732 SaveRandomSeeds(&saved_seeds);
733 if (free_wagon) {
734 cost.AddCost(ReplaceFreeUnit(&v, flags & ~DC_EXEC, &nothing_to_do, same_type_only));
735 } else {
736 cost.AddCost(ReplaceChain(&v, flags & ~DC_EXEC, wagon_removal, &nothing_to_do, same_type_only));
738 RestoreRandomSeeds(saved_seeds);
740 if (cost.Succeeded() && (flags & DC_EXEC) != 0) {
741 CommandCost ret;
742 if (free_wagon) {
743 ret = ReplaceFreeUnit(&v, flags, &nothing_to_do, same_type_only);
744 } else {
745 ret = ReplaceChain(&v, flags, wagon_removal, &nothing_to_do, same_type_only);
747 assert(ret.Succeeded() && ret.GetCost() == cost.GetCost());
750 /* Restart the vehicle */
751 if (!was_stopped) cost.AddCost(CmdStartStopVehicle(v, false));
754 if (cost.Succeeded() && nothing_to_do) cost = CommandCost(STR_ERROR_AUTOREPLACE_NOTHING_TO_DO);
755 return cost;
759 * Change engine renewal parameters
760 * @param tile unused
761 * @param flags operation to perform
762 * @param p1 packed data
763 * - bit 0 = replace when engine gets old?
764 * - bits 16-31 = engine group
765 * @param p2 packed data
766 * - bits 0-15 = old engine type
767 * - bits 16-31 = new engine type
768 * @param text unused
769 * @return the cost of this operation or an error
771 CommandCost CmdSetAutoReplace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
773 Company *c = Company::GetIfValid(_current_company);
774 if (c == nullptr) return CommandError();
776 EngineID old_engine_type = GB(p2, 0, 16);
777 EngineID new_engine_type = GB(p2, 16, 16);
778 GroupID id_g = GB(p1, 16, 16);
779 CommandCost cost;
781 if (Group::IsValidID(id_g) ? Group::Get(id_g)->owner != _current_company : !IsAllGroupID(id_g) && !IsDefaultGroupID(id_g)) return CommandError();
782 if (!Engine::IsValidID(old_engine_type)) return CommandError();
784 if (new_engine_type != INVALID_ENGINE) {
785 if (!Engine::IsValidID(new_engine_type)) return CommandError();
786 if (!CheckAutoreplaceValidity(old_engine_type, new_engine_type, _current_company)) return CommandError();
788 cost = AddEngineReplacementForCompany(c, old_engine_type, new_engine_type, id_g, HasBit(p1, 0), flags);
789 } else {
790 cost = RemoveEngineReplacementForCompany(c, old_engine_type, id_g, flags);
793 if (flags & DC_EXEC) {
794 GroupStatistics::UpdateAutoreplace(_current_company);
795 if (IsLocalCompany()) SetWindowDirty(WC_REPLACE_VEHICLE, Engine::Get(old_engine_type)->type);
797 if ((flags & DC_EXEC) && IsLocalCompany()) InvalidateAutoreplaceWindow(old_engine_type, id_g);
799 return cost;