2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * 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 /** @file autoreplace_cmd.cpp Deals with autoreplace execution but not the setup */
11 #include "company_func.h"
13 #include "command_func.h"
14 #include "engine_func.h"
15 #include "vehicle_func.h"
16 #include "autoreplace_func.h"
17 #include "autoreplace_gui.h"
18 #include "articulated_vehicles.h"
19 #include "core/random_func.hpp"
20 #include "vehiclelist.h"
23 #include "news_func.h"
24 #include "strings_func.h"
26 #include "table/strings.h"
28 #include "safeguards.h"
30 extern void ChangeVehicleViewports(VehicleID from_index
, VehicleID to_index
);
31 extern void ChangeVehicleNews(VehicleID from_index
, VehicleID to_index
);
32 extern void ChangeVehicleViewWindow(VehicleID from_index
, VehicleID to_index
);
35 * Figure out if two engines got at least one type of cargo in common (refitting if needed)
36 * @param engine_a one of the EngineIDs
37 * @param engine_b the other EngineID
38 * @return true if they can both carry the same type of cargo (or at least one of them got no capacity at all)
40 static bool EnginesHaveCargoInCommon(EngineID engine_a
, EngineID engine_b
)
42 CargoTypes available_cargoes_a
= GetUnionOfArticulatedRefitMasks(engine_a
, true);
43 CargoTypes available_cargoes_b
= GetUnionOfArticulatedRefitMasks(engine_b
, true);
44 return (available_cargoes_a
== 0 || available_cargoes_b
== 0 || (available_cargoes_a
& available_cargoes_b
) != 0);
48 * Checks some basic properties whether autoreplace is allowed
49 * @param from Origin engine
50 * @param to Destination engine
51 * @param company Company to check for
52 * @return true if autoreplace is allowed
54 bool CheckAutoreplaceValidity(EngineID from
, EngineID to
, CompanyID company
)
56 assert(Engine::IsValidID(from
) && Engine::IsValidID(to
));
58 /* we can't replace an engine into itself (that would be autorenew) */
59 if (from
== to
) return false;
61 const Engine
*e_from
= Engine::Get(from
);
62 const Engine
*e_to
= Engine::Get(to
);
63 VehicleType type
= e_from
->type
;
65 /* check that the new vehicle type is available to the company and its type is the same as the original one */
66 if (!IsEngineBuildable(to
, type
, company
)) return false;
70 /* make sure the railtypes are compatible */
71 if ((GetRailTypeInfo(e_from
->u
.rail
.railtype
)->compatible_railtypes
& GetRailTypeInfo(e_to
->u
.rail
.railtype
)->compatible_railtypes
) == 0) return false;
73 /* make sure we do not replace wagons with engines or vice versa */
74 if ((e_from
->u
.rail
.railveh_type
== RAILVEH_WAGON
) != (e_to
->u
.rail
.railveh_type
== RAILVEH_WAGON
)) return false;
79 /* make sure the roadtypes are compatible */
80 if ((GetRoadTypeInfo(e_from
->u
.road
.roadtype
)->powered_roadtypes
& GetRoadTypeInfo(e_to
->u
.road
.roadtype
)->powered_roadtypes
) == ROADTYPES_NONE
) return false;
82 /* make sure that we do not replace a tram with a normal road vehicles or vice versa */
83 if (HasBit(e_from
->info
.misc_flags
, EF_ROAD_TRAM
) != HasBit(e_to
->info
.misc_flags
, EF_ROAD_TRAM
)) return false;
87 /* make sure that we do not replace a plane with a helicopter or vice versa */
88 if ((e_from
->u
.air
.subtype
& AIR_CTOL
) != (e_to
->u
.air
.subtype
& AIR_CTOL
)) return false;
94 /* the engines needs to be able to carry the same cargo */
95 return EnginesHaveCargoInCommon(from
, to
);
99 * Check the capacity of all vehicles in a chain and spread cargo if needed.
100 * @param v The vehicle to check.
101 * @pre You can only do this if the consist is not loading or unloading. It
102 * must not carry reserved cargo, nor cargo to be unloaded or transferred.
104 void CheckCargoCapacity(Vehicle
*v
)
106 assert(v
== nullptr || v
->First() == v
);
108 for (Vehicle
*src
= v
; src
!= nullptr; src
= src
->Next()) {
109 assert(src
->cargo
.TotalCount() == src
->cargo
.ActionCount(VehicleCargoList::MTA_KEEP
));
111 /* Do we need to more cargo away? */
112 if (src
->cargo
.TotalCount() <= src
->cargo_cap
) continue;
114 /* We need to move a particular amount. Try that on the other vehicles. */
115 uint to_spread
= src
->cargo
.TotalCount() - src
->cargo_cap
;
116 for (Vehicle
*dest
= v
; dest
!= nullptr && to_spread
!= 0; dest
= dest
->Next()) {
117 assert(dest
->cargo
.TotalCount() == dest
->cargo
.ActionCount(VehicleCargoList::MTA_KEEP
));
118 if (dest
->cargo
.TotalCount() >= dest
->cargo_cap
|| dest
->cargo_type
!= src
->cargo_type
) continue;
120 uint amount
= std::min(to_spread
, dest
->cargo_cap
- dest
->cargo
.TotalCount());
121 src
->cargo
.Shift(amount
, &dest
->cargo
);
125 /* Any left-overs will be thrown away, but not their feeder share. */
126 if (src
->cargo_cap
< src
->cargo
.TotalCount()) src
->cargo
.Truncate(src
->cargo
.TotalCount() - src
->cargo_cap
);
131 * Transfer cargo from a single (articulated )old vehicle to the new vehicle chain
132 * @param old_veh Old vehicle that will be sold
133 * @param new_head Head of the completely constructed new vehicle chain
134 * @param part_of_chain The vehicle is part of a train
135 * @pre You can only do this if both consists are not loading or unloading.
136 * They must not carry reserved cargo, nor cargo to be unloaded or
139 static void TransferCargo(Vehicle
*old_veh
, Vehicle
*new_head
, bool part_of_chain
)
141 assert(!part_of_chain
|| new_head
->IsPrimaryVehicle());
142 /* Loop through source parts */
143 for (Vehicle
*src
= old_veh
; src
!= nullptr; src
= src
->Next()) {
144 assert(src
->cargo
.TotalCount() == src
->cargo
.ActionCount(VehicleCargoList::MTA_KEEP
));
145 if (!part_of_chain
&& src
->type
== VEH_TRAIN
&& src
!= old_veh
&& src
!= Train::From(old_veh
)->other_multiheaded_part
&& !src
->IsArticulatedPart()) {
146 /* Skip vehicles, which do not belong to old_veh */
147 src
= src
->GetLastEnginePart();
150 if (src
->cargo_type
>= NUM_CARGO
|| src
->cargo
.TotalCount() == 0) continue;
152 /* Find free space in the new chain */
153 for (Vehicle
*dest
= new_head
; dest
!= nullptr && src
->cargo
.TotalCount() > 0; dest
= dest
->Next()) {
154 assert(dest
->cargo
.TotalCount() == dest
->cargo
.ActionCount(VehicleCargoList::MTA_KEEP
));
155 if (!part_of_chain
&& dest
->type
== VEH_TRAIN
&& dest
!= new_head
&& dest
!= Train::From(new_head
)->other_multiheaded_part
&& !dest
->IsArticulatedPart()) {
156 /* Skip vehicles, which do not belong to new_head */
157 dest
= dest
->GetLastEnginePart();
160 if (dest
->cargo_type
!= src
->cargo_type
) continue;
162 uint amount
= std::min(src
->cargo
.TotalCount(), dest
->cargo_cap
- dest
->cargo
.TotalCount());
163 if (amount
<= 0) continue;
165 src
->cargo
.Shift(amount
, &dest
->cargo
);
169 /* Update train weight etc., the old vehicle will be sold anyway */
170 if (part_of_chain
&& new_head
->type
== VEH_TRAIN
) Train::From(new_head
)->ConsistChanged(CCF_LOADUNLOAD
);
174 * Tests whether refit orders that applied to v will also apply to the new vehicle type
175 * @param v The vehicle to be replaced
176 * @param engine_type The type we want to replace with
177 * @return true iff all refit orders stay valid
179 static bool VerifyAutoreplaceRefitForOrders(const Vehicle
*v
, EngineID engine_type
)
181 CargoTypes union_refit_mask_a
= GetUnionOfArticulatedRefitMasks(v
->engine_type
, false);
182 CargoTypes union_refit_mask_b
= GetUnionOfArticulatedRefitMasks(engine_type
, false);
184 const Vehicle
*u
= (v
->type
== VEH_TRAIN
) ? v
->First() : v
;
185 for (const Order
*o
: u
->Orders()) {
186 if (!o
->IsRefit() || o
->IsAutoRefit()) continue;
187 CargoID cargo_type
= o
->GetRefitCargo();
189 if (!HasBit(union_refit_mask_a
, cargo_type
)) continue;
190 if (!HasBit(union_refit_mask_b
, cargo_type
)) return false;
197 * Gets the index of the first refit order that is incompatible with the requested engine type
198 * @param v The vehicle to be replaced
199 * @param engine_type The type we want to replace with
200 * @return index of the incompatible order or -1 if none were found
202 static int GetIncompatibleRefitOrderIdForAutoreplace(const Vehicle
*v
, EngineID engine_type
)
204 CargoTypes union_refit_mask
= GetUnionOfArticulatedRefitMasks(engine_type
, false);
207 const Vehicle
*u
= (v
->type
== VEH_TRAIN
) ? v
->First() : v
;
209 const OrderList
*orders
= u
->orders
.list
;
210 if (orders
== nullptr) return -1;
211 for (VehicleOrderID i
= 0; i
< orders
->GetNumOrders(); i
++) {
212 o
= orders
->GetOrderAt(i
);
213 if (!o
->IsRefit()) continue;
214 if (!HasBit(union_refit_mask
, o
->GetRefitCargo())) return i
;
221 * Function to find what type of cargo to refit to when autoreplacing
222 * @param *v Original vehicle that is being replaced.
223 * @param engine_type The EngineID of the vehicle that is being replaced to
224 * @param part_of_chain The vehicle is part of a train
225 * @return The cargo type to replace to
226 * CT_NO_REFIT is returned if no refit is needed
227 * 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
229 static CargoID
GetNewCargoTypeForReplace(Vehicle
*v
, EngineID engine_type
, bool part_of_chain
)
231 CargoTypes available_cargo_types
, union_mask
;
232 GetArticulatedRefitMasks(engine_type
, true, &union_mask
, &available_cargo_types
);
234 if (union_mask
== 0) return CT_NO_REFIT
; // Don't try to refit an engine with no cargo capacity
237 if (IsArticulatedVehicleCarryingDifferentCargoes(v
, &cargo_type
)) return CT_INVALID
; // We cannot refit to mixed cargoes in an automated way
239 if (cargo_type
== CT_INVALID
) {
240 if (v
->type
!= VEH_TRAIN
) return CT_NO_REFIT
; // If the vehicle does not carry anything at all, every replacement is fine.
242 if (!part_of_chain
) return CT_NO_REFIT
;
244 /* the old engine didn't have cargo capacity, but the new one does
245 * now we will figure out what cargo the train is carrying and refit to fit this */
247 for (v
= v
->First(); v
!= nullptr; v
= v
->Next()) {
248 if (!v
->GetEngine()->CanCarryCargo()) continue;
249 /* Now we found a cargo type being carried on the train and we will see if it is possible to carry to this one */
250 if (HasBit(available_cargo_types
, v
->cargo_type
)) return v
->cargo_type
;
253 return CT_NO_REFIT
; // We failed to find a cargo type on the old vehicle and we will not refit the new one
255 if (!HasBit(available_cargo_types
, cargo_type
)) return CT_INVALID
; // We can't refit the vehicle to carry the cargo we want
257 if (part_of_chain
&& !VerifyAutoreplaceRefitForOrders(v
, engine_type
)) return CT_INVALID
; // Some refit orders lose their effect
264 * Get the EngineID of the replacement for a vehicle
265 * @param v The vehicle to find a replacement for
266 * @param c The vehicle's owner (it's faster to forward the pointer than refinding it)
267 * @param always_replace Always replace, even if not old.
268 * @param[out] e the EngineID of the replacement. INVALID_ENGINE if no replacement is found
269 * @return Error if the engine to build is not available
271 static CommandCost
GetNewEngineType(const Vehicle
*v
, const Company
*c
, bool always_replace
, EngineID
&e
)
273 assert(v
->type
!= VEH_TRAIN
|| !v
->IsArticulatedPart());
277 if (v
->type
== VEH_TRAIN
&& Train::From(v
)->IsRearDualheaded()) {
278 /* we build the rear ends of multiheaded trains with the front ones */
279 return CommandCost();
282 bool replace_when_old
;
283 e
= EngineReplacementForCompany(c
, v
->engine_type
, v
->group_id
, &replace_when_old
);
284 if (!always_replace
&& replace_when_old
&& !v
->NeedsAutorenewing(c
, false)) e
= INVALID_ENGINE
;
286 /* Autoreplace, if engine is available */
287 if (e
!= INVALID_ENGINE
&& IsEngineBuildable(e
, v
->type
, _current_company
)) {
288 return CommandCost();
291 /* Autorenew if needed */
292 if (v
->NeedsAutorenewing(c
)) e
= v
->engine_type
;
294 /* Nothing to do or all is fine? */
295 if (e
== INVALID_ENGINE
|| IsEngineBuildable(e
, v
->type
, _current_company
)) return CommandCost();
297 /* The engine we need is not available. Report error to user */
298 return CommandCost(STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE
+ v
->type
);
302 * Builds and refits a replacement vehicle
303 * 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)
304 * @param old_veh A single (articulated/multiheaded) vehicle that shall be replaced.
305 * @param new_vehicle Returns the newly build and refitted vehicle
306 * @param part_of_chain The vehicle is part of a train
307 * @return cost or error
309 static CommandCost
BuildReplacementVehicle(Vehicle
*old_veh
, Vehicle
**new_vehicle
, bool part_of_chain
)
311 *new_vehicle
= nullptr;
313 /* Shall the vehicle be replaced? */
314 const Company
*c
= Company::Get(_current_company
);
316 CommandCost cost
= GetNewEngineType(old_veh
, c
, true, e
);
317 if (cost
.Failed()) return cost
;
318 if (e
== INVALID_ENGINE
) return CommandCost(); // neither autoreplace is set, nor autorenew is triggered
320 /* Does it need to be refitted */
321 CargoID refit_cargo
= GetNewCargoTypeForReplace(old_veh
, e
, part_of_chain
);
322 if (refit_cargo
== CT_INVALID
) {
323 if (!IsLocalCompany()) return CommandCost();
325 SetDParam(0, old_veh
->index
);
327 int order_id
= GetIncompatibleRefitOrderIdForAutoreplace(old_veh
, e
);
328 if (order_id
!= -1) {
329 /* Orders contained a refit order that is incompatible with the new vehicle. */
330 SetDParam(1, STR_ERROR_AUTOREPLACE_INCOMPATIBLE_REFIT
);
331 SetDParam(2, order_id
+ 1); // 1-based indexing for display
333 /* Current cargo is incompatible with the new vehicle. */
334 SetDParam(1, STR_ERROR_AUTOREPLACE_INCOMPATIBLE_CARGO
);
335 SetDParam(2, CargoSpec::Get(old_veh
->cargo_type
)->name
);
338 AddVehicleAdviceNewsItem(STR_NEWS_VEHICLE_AUTORENEW_FAILED
, old_veh
->index
);
339 return CommandCost();
342 /* Build the new vehicle */
343 cost
= DoCommand(old_veh
->tile
, e
| (CT_INVALID
<< 24), 0, DC_EXEC
| DC_AUTOREPLACE
, GetCmdBuildVeh(old_veh
));
344 if (cost
.Failed()) return cost
;
346 Vehicle
*new_veh
= Vehicle::Get(_new_vehicle_id
);
347 *new_vehicle
= new_veh
;
349 /* Refit the vehicle if needed */
350 if (refit_cargo
!= CT_NO_REFIT
) {
351 byte subtype
= GetBestFittingSubType(old_veh
, new_veh
, refit_cargo
);
353 cost
.AddCost(DoCommand(0, new_veh
->index
, refit_cargo
| (subtype
<< 8), DC_EXEC
, GetCmdRefitVeh(new_veh
)));
354 assert(cost
.Succeeded()); // This should be ensured by GetNewCargoTypeForReplace()
357 /* Try to reverse the vehicle, but do not care if it fails as the new type might not be reversible */
358 if (new_veh
->type
== VEH_TRAIN
&& HasBit(Train::From(old_veh
)->flags
, VRF_REVERSE_DIRECTION
)) {
359 DoCommand(0, new_veh
->index
, true, DC_EXEC
, CMD_REVERSE_TRAIN_DIRECTION
);
366 * Issue a start/stop command
368 * @param evaluate_callback shall the start/stop callback be evaluated?
369 * @return success or error
371 static inline CommandCost
CmdStartStopVehicle(const Vehicle
*v
, bool evaluate_callback
)
373 return DoCommand(0, v
->index
, evaluate_callback
? 1 : 0, DC_EXEC
| DC_AUTOREPLACE
, CMD_START_STOP_VEHICLE
);
377 * Issue a train vehicle move command
378 * @param v The vehicle to move
379 * @param after The vehicle to insert 'v' after, or nullptr to start new chain
380 * @param flags the command flags to use
381 * @param whole_chain move all vehicles following 'v' (true), or only 'v' (false)
382 * @return success or error
384 static inline CommandCost
CmdMoveVehicle(const Vehicle
*v
, const Vehicle
*after
, DoCommandFlag flags
, bool whole_chain
)
386 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
);
390 * Copy head specific things to the new vehicle chain after it was successfully constructed
391 * @param old_head The old front vehicle (no wagons attached anymore)
392 * @param new_head The new head of the completely replaced vehicle chain
393 * @param flags the command flags to use
395 static CommandCost
CopyHeadSpecificThings(Vehicle
*old_head
, Vehicle
*new_head
, DoCommandFlag flags
)
397 CommandCost cost
= CommandCost();
400 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
));
402 /* Copy group membership */
403 if (cost
.Succeeded() && old_head
!= new_head
) cost
.AddCost(DoCommand(0, old_head
->group_id
, new_head
->index
, DC_EXEC
, CMD_ADD_VEHICLE_GROUP
));
405 /* Perform start/stop check whether the new vehicle suits newgrf restrictions etc. */
406 if (cost
.Succeeded()) {
407 /* Start the vehicle, might be denied by certain things */
408 assert((new_head
->vehstatus
& VS_STOPPED
) != 0);
409 cost
.AddCost(CmdStartStopVehicle(new_head
, true));
411 /* Stop the vehicle again, but do not care about evil newgrfs allowing starting but not stopping :p */
412 if (cost
.Succeeded()) cost
.AddCost(CmdStartStopVehicle(new_head
, false));
415 /* Last do those things which do never fail (resp. we do not care about), but which are not undo-able */
416 if (cost
.Succeeded() && old_head
!= new_head
&& (flags
& DC_EXEC
) != 0) {
417 /* Copy other things which cannot be copied by a command and which shall not stay resetted from the build vehicle command */
418 new_head
->CopyVehicleConfigAndStatistics(old_head
);
420 /* Switch vehicle windows/news to the new vehicle, so they are not closed/deleted when the old vehicle is sold */
421 ChangeVehicleViewports(old_head
->index
, new_head
->index
);
422 ChangeVehicleViewWindow(old_head
->index
, new_head
->index
);
423 ChangeVehicleNews(old_head
->index
, new_head
->index
);
430 * Replace a single unit in a free wagon chain
431 * @param single_unit vehicle to let autoreplace/renew operator on
432 * @param flags command flags
433 * @param nothing_to_do is set to 'false' when something was done (only valid when not failed)
434 * @return cost or error
436 static CommandCost
ReplaceFreeUnit(Vehicle
**single_unit
, DoCommandFlag flags
, bool *nothing_to_do
)
438 Train
*old_v
= Train::From(*single_unit
);
439 assert(!old_v
->IsArticulatedPart() && !old_v
->IsRearDualheaded());
441 CommandCost cost
= CommandCost(EXPENSES_NEW_VEHICLES
, 0);
443 /* Build and refit replacement vehicle */
444 Vehicle
*new_v
= nullptr;
445 cost
.AddCost(BuildReplacementVehicle(old_v
, &new_v
, false));
447 /* Was a new vehicle constructed? */
448 if (cost
.Succeeded() && new_v
!= nullptr) {
449 *nothing_to_do
= false;
451 if ((flags
& DC_EXEC
) != 0) {
452 /* Move the new vehicle behind the old */
453 CmdMoveVehicle(new_v
, old_v
, DC_EXEC
, false);
456 * Note: We do only transfer cargo from the old to the new vehicle.
457 * I.e. we do not transfer remaining cargo to other vehicles.
458 * Else you would also need to consider moving cargo to other free chains,
459 * or doing the same in ReplaceChain(), which would be quite troublesome.
461 TransferCargo(old_v
, new_v
, false);
463 *single_unit
= new_v
;
465 AI::NewEvent(old_v
->owner
, new ScriptEventVehicleAutoReplaced(old_v
->index
, new_v
->index
));
468 /* Sell the old vehicle */
469 cost
.AddCost(DoCommand(0, old_v
->index
, 0, flags
, GetCmdSellVeh(old_v
)));
471 /* If we are not in DC_EXEC undo everything */
472 if ((flags
& DC_EXEC
) == 0) {
473 DoCommand(0, new_v
->index
, 0, DC_EXEC
, GetCmdSellVeh(new_v
));
481 * Replace a whole vehicle chain
482 * @param chain vehicle chain to let autoreplace/renew operator on
483 * @param flags command flags
484 * @param wagon_removal remove wagons when the resulting chain occupies more tiles than the old did
485 * @param nothing_to_do is set to 'false' when something was done (only valid when not failed)
486 * @return cost or error
488 static CommandCost
ReplaceChain(Vehicle
**chain
, DoCommandFlag flags
, bool wagon_removal
, bool *nothing_to_do
)
490 Vehicle
*old_head
= *chain
;
491 assert(old_head
->IsPrimaryVehicle());
493 CommandCost cost
= CommandCost(EXPENSES_NEW_VEHICLES
, 0);
495 if (old_head
->type
== VEH_TRAIN
) {
496 /* Store the length of the old vehicle chain, rounded up to whole tiles */
497 uint16 old_total_length
= CeilDiv(Train::From(old_head
)->gcache
.cached_total_length
, TILE_SIZE
) * TILE_SIZE
;
499 int num_units
= 0; ///< Number of units in the chain
500 for (Train
*w
= Train::From(old_head
); w
!= nullptr; w
= w
->GetNextUnit()) num_units
++;
502 Train
**old_vehs
= CallocT
<Train
*>(num_units
); ///< Will store vehicles of the old chain in their order
503 Train
**new_vehs
= CallocT
<Train
*>(num_units
); ///< New vehicles corresponding to old_vehs or nullptr if no replacement
504 Money
*new_costs
= MallocT
<Money
>(num_units
); ///< Costs for buying and refitting the new vehicles
506 /* Collect vehicles and build replacements
507 * Note: The replacement vehicles can only successfully build as long as the old vehicles are still in their chain */
510 for (w
= Train::From(old_head
), i
= 0; w
!= nullptr; w
= w
->GetNextUnit(), i
++) {
511 assert(i
< num_units
);
514 CommandCost ret
= BuildReplacementVehicle(old_vehs
[i
], (Vehicle
**)&new_vehs
[i
], true);
516 if (cost
.Failed()) break;
518 new_costs
[i
] = ret
.GetCost();
519 if (new_vehs
[i
] != nullptr) *nothing_to_do
= false;
521 Train
*new_head
= (new_vehs
[0] != nullptr ? new_vehs
[0] : old_vehs
[0]);
523 /* Note: When autoreplace has already failed here, old_vehs[] is not completely initialized. But it is also not needed. */
524 if (cost
.Succeeded()) {
525 /* Separate the head, so we can start constructing the new chain */
526 Train
*second
= Train::From(old_head
)->GetNextUnit();
527 if (second
!= nullptr) cost
.AddCost(CmdMoveVehicle(second
, nullptr, DC_EXEC
| DC_AUTOREPLACE
, true));
529 assert(Train::From(new_head
)->GetNextUnit() == nullptr);
531 /* Append engines to the new chain
532 * We do this from back to front, so that the head of the temporary vehicle chain does not change all the time.
533 * That way we also have less trouble when exceeding the unitnumber limit.
534 * OTOH the vehicle attach callback is more expensive this way :s */
535 Train
*last_engine
= nullptr; ///< Shall store the last engine unit after this step
536 if (cost
.Succeeded()) {
537 for (int i
= num_units
- 1; i
> 0; i
--) {
538 Train
*append
= (new_vehs
[i
] != nullptr ? new_vehs
[i
] : old_vehs
[i
]);
540 if (RailVehInfo(append
->engine_type
)->railveh_type
== RAILVEH_WAGON
) continue;
542 if (new_vehs
[i
] != nullptr) {
543 /* Move the old engine to a separate row with DC_AUTOREPLACE. Else
544 * moving the wagon in front may fail later due to unitnumber limit.
545 * (We have to attach wagons without DC_AUTOREPLACE.) */
546 CmdMoveVehicle(old_vehs
[i
], nullptr, DC_EXEC
| DC_AUTOREPLACE
, false);
549 if (last_engine
== nullptr) last_engine
= append
;
550 cost
.AddCost(CmdMoveVehicle(append
, new_head
, DC_EXEC
, false));
551 if (cost
.Failed()) break;
553 if (last_engine
== nullptr) last_engine
= new_head
;
556 /* When wagon removal is enabled and the new engines without any wagons are already longer than the old, we have to fail */
557 if (cost
.Succeeded() && wagon_removal
&& new_head
->gcache
.cached_total_length
> old_total_length
) cost
= CommandCost(STR_ERROR_TRAIN_TOO_LONG_AFTER_REPLACEMENT
);
559 /* Append/insert wagons into the new vehicle chain
560 * 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.
562 if (cost
.Succeeded()) {
563 for (int i
= num_units
- 1; i
> 0; i
--) {
564 assert(last_engine
!= nullptr);
565 Vehicle
*append
= (new_vehs
[i
] != nullptr ? new_vehs
[i
] : old_vehs
[i
]);
567 if (RailVehInfo(append
->engine_type
)->railveh_type
== RAILVEH_WAGON
) {
568 /* Insert wagon after 'last_engine' */
569 CommandCost res
= CmdMoveVehicle(append
, last_engine
, DC_EXEC
, false);
571 /* When we allow removal of wagons, either the move failing due
572 * to the train becoming too long, or the train becoming longer
573 * would move the vehicle to the empty vehicle chain. */
574 if (wagon_removal
&& (res
.Failed() ? res
.GetErrorMessage() == STR_ERROR_TRAIN_TOO_LONG
: new_head
->gcache
.cached_total_length
> old_total_length
)) {
575 CmdMoveVehicle(append
, nullptr, DC_EXEC
| DC_AUTOREPLACE
, false);
580 if (cost
.Failed()) break;
582 /* We have reached 'last_engine', continue with the next engine towards the front */
583 assert(append
== last_engine
);
584 last_engine
= last_engine
->GetPrevUnit();
589 /* Sell superfluous new vehicles that could not be inserted. */
590 if (cost
.Succeeded() && wagon_removal
) {
591 assert(new_head
->gcache
.cached_total_length
<= _settings_game
.vehicle
.max_train_length
* TILE_SIZE
);
592 for (int i
= 1; i
< num_units
; i
++) {
593 Vehicle
*wagon
= new_vehs
[i
];
594 if (wagon
== nullptr) continue;
595 if (wagon
->First() == new_head
) break;
597 assert(RailVehInfo(wagon
->engine_type
)->railveh_type
== RAILVEH_WAGON
);
600 [[maybe_unused
]] CommandCost ret
= DoCommand(0, wagon
->index
, 0, DC_EXEC
, GetCmdSellVeh(wagon
));
601 assert(ret
.Succeeded());
602 new_vehs
[i
] = nullptr;
604 /* Revert the money subtraction when the vehicle was built.
605 * This value is different from the sell value, esp. because of refitting */
606 cost
.AddCost(-new_costs
[i
]);
610 /* The new vehicle chain is constructed, now take over orders and everything... */
611 if (cost
.Succeeded()) cost
.AddCost(CopyHeadSpecificThings(old_head
, new_head
, flags
));
613 if (cost
.Succeeded()) {
615 if ((flags
& DC_EXEC
) != 0 && new_head
!= old_head
) {
617 AI::NewEvent(old_head
->owner
, new ScriptEventVehicleAutoReplaced(old_head
->index
, new_head
->index
));
620 /* Transfer cargo of old vehicles and sell them */
621 for (int i
= 0; i
< num_units
; i
++) {
622 Vehicle
*w
= old_vehs
[i
];
623 /* Is the vehicle again part of the new chain?
624 * Note: We cannot test 'new_vehs[i] != nullptr' as wagon removal might cause to remove both */
625 if (w
->First() == new_head
) continue;
627 if ((flags
& DC_EXEC
) != 0) TransferCargo(w
, new_head
, true);
630 * Note: This might temporarily construct new trains, so use DC_AUTOREPLACE to prevent
631 * it from failing due to engine limits. */
632 cost
.AddCost(DoCommand(0, w
->index
, 0, flags
| DC_AUTOREPLACE
, GetCmdSellVeh(w
)));
633 if ((flags
& DC_EXEC
) != 0) {
634 old_vehs
[i
] = nullptr;
635 if (i
== 0) old_head
= nullptr;
639 if ((flags
& DC_EXEC
) != 0) CheckCargoCapacity(new_head
);
642 /* If we are not in DC_EXEC undo everything, i.e. rearrange old vehicles.
643 * We do this from back to front, so that the head of the temporary vehicle chain does not change all the time.
644 * Note: The vehicle attach callback is disabled here :) */
645 if ((flags
& DC_EXEC
) == 0) {
646 /* Separate the head, so we can reattach the old vehicles */
647 Train
*second
= Train::From(old_head
)->GetNextUnit();
648 if (second
!= nullptr) CmdMoveVehicle(second
, nullptr, DC_EXEC
| DC_AUTOREPLACE
, true);
650 assert(Train::From(old_head
)->GetNextUnit() == nullptr);
652 for (int i
= num_units
- 1; i
> 0; i
--) {
653 [[maybe_unused
]] CommandCost ret
= CmdMoveVehicle(old_vehs
[i
], old_head
, DC_EXEC
| DC_AUTOREPLACE
, false);
654 assert(ret
.Succeeded());
659 /* Finally undo buying of new vehicles */
660 if ((flags
& DC_EXEC
) == 0) {
661 for (int i
= num_units
- 1; i
>= 0; i
--) {
662 if (new_vehs
[i
] != nullptr) {
663 DoCommand(0, new_vehs
[i
]->index
, 0, DC_EXEC
, GetCmdSellVeh(new_vehs
[i
]));
664 new_vehs
[i
] = nullptr;
673 /* Build and refit replacement vehicle */
674 Vehicle
*new_head
= nullptr;
675 cost
.AddCost(BuildReplacementVehicle(old_head
, &new_head
, true));
677 /* Was a new vehicle constructed? */
678 if (cost
.Succeeded() && new_head
!= nullptr) {
679 *nothing_to_do
= false;
681 /* The new vehicle is constructed, now take over orders and everything... */
682 cost
.AddCost(CopyHeadSpecificThings(old_head
, new_head
, flags
));
684 if (cost
.Succeeded()) {
685 /* The new vehicle is constructed, now take over cargo */
686 if ((flags
& DC_EXEC
) != 0) {
687 TransferCargo(old_head
, new_head
, true);
690 AI::NewEvent(old_head
->owner
, new ScriptEventVehicleAutoReplaced(old_head
->index
, new_head
->index
));
693 /* Sell the old vehicle */
694 cost
.AddCost(DoCommand(0, old_head
->index
, 0, flags
, GetCmdSellVeh(old_head
)));
697 /* If we are not in DC_EXEC undo everything */
698 if ((flags
& DC_EXEC
) == 0) {
699 DoCommand(0, new_head
->index
, 0, DC_EXEC
, GetCmdSellVeh(new_head
));
708 * Autoreplaces a vehicle
709 * Trains are replaced as a whole chain, free wagons in depot are replaced on their own
710 * @param tile not used
711 * @param flags type of operation
712 * @param p1 Index of vehicle
715 * @return the cost of this operation or an error
717 CommandCost
CmdAutoreplaceVehicle(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const std::string
&text
)
719 Vehicle
*v
= Vehicle::GetIfValid(p1
);
720 if (v
== nullptr) return CMD_ERROR
;
722 CommandCost ret
= CheckOwnership(v
->owner
);
723 if (ret
.Failed()) return ret
;
725 if (!v
->IsChainInDepot()) return CMD_ERROR
;
726 if (v
->vehstatus
& VS_CRASHED
) return CMD_ERROR
;
728 bool free_wagon
= false;
729 if (v
->type
== VEH_TRAIN
) {
730 Train
*t
= Train::From(v
);
731 if (t
->IsArticulatedPart() || t
->IsRearDualheaded()) return CMD_ERROR
;
732 free_wagon
= !t
->IsFrontEngine();
733 if (free_wagon
&& t
->First()->IsFrontEngine()) return CMD_ERROR
;
735 if (!v
->IsPrimaryVehicle()) return CMD_ERROR
;
738 const Company
*c
= Company::Get(_current_company
);
739 bool wagon_removal
= c
->settings
.renew_keep_length
;
741 const Group
*g
= Group::GetIfValid(v
->group_id
);
742 if (g
!= nullptr) wagon_removal
= HasBit(g
->flags
, GroupFlags::GF_REPLACE_WAGON_REMOVAL
);
744 /* Test whether any replacement is set, before issuing a whole lot of commands that would end in nothing changed */
746 bool any_replacements
= false;
747 while (w
!= nullptr) {
749 CommandCost cost
= GetNewEngineType(w
, c
, false, e
);
750 if (cost
.Failed()) return cost
;
751 any_replacements
|= (e
!= INVALID_ENGINE
);
752 w
= (!free_wagon
&& w
->type
== VEH_TRAIN
? Train::From(w
)->GetNextUnit() : nullptr);
755 CommandCost cost
= CommandCost(EXPENSES_NEW_VEHICLES
, 0);
756 bool nothing_to_do
= true;
758 if (any_replacements
) {
759 bool was_stopped
= free_wagon
|| ((v
->vehstatus
& VS_STOPPED
) != 0);
761 /* Stop the vehicle */
762 if (!was_stopped
) cost
.AddCost(CmdStartStopVehicle(v
, true));
763 if (cost
.Failed()) return cost
;
765 assert(free_wagon
|| v
->IsStoppedInDepot());
767 /* We have to construct the new vehicle chain to test whether it is valid.
768 * Vehicle construction needs random bits, so we have to save the random seeds
769 * to prevent desyncs and to replay newgrf callbacks during DC_EXEC */
770 SavedRandomSeeds saved_seeds
;
771 SaveRandomSeeds(&saved_seeds
);
773 cost
.AddCost(ReplaceFreeUnit(&v
, flags
& ~DC_EXEC
, ¬hing_to_do
));
775 cost
.AddCost(ReplaceChain(&v
, flags
& ~DC_EXEC
, wagon_removal
, ¬hing_to_do
));
777 RestoreRandomSeeds(saved_seeds
);
779 if (cost
.Succeeded() && (flags
& DC_EXEC
) != 0) {
782 ret
= ReplaceFreeUnit(&v
, flags
, ¬hing_to_do
);
784 ret
= ReplaceChain(&v
, flags
, wagon_removal
, ¬hing_to_do
);
786 assert(ret
.Succeeded() && ret
.GetCost() == cost
.GetCost());
789 /* Restart the vehicle */
790 if (!was_stopped
) cost
.AddCost(CmdStartStopVehicle(v
, false));
793 if (cost
.Succeeded() && nothing_to_do
) cost
= CommandCost(STR_ERROR_AUTOREPLACE_NOTHING_TO_DO
);
798 * Change engine renewal parameters
800 * @param flags operation to perform
801 * @param p1 packed data
802 * - bit 0 = replace when engine gets old?
803 * - bits 16-31 = engine group
804 * @param p2 packed data
805 * - bits 0-15 = old engine type
806 * - bits 16-31 = new engine type
808 * @return the cost of this operation or an error
810 CommandCost
CmdSetAutoReplace(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const std::string
&text
)
812 Company
*c
= Company::GetIfValid(_current_company
);
813 if (c
== nullptr) return CMD_ERROR
;
815 EngineID old_engine_type
= GB(p2
, 0, 16);
816 EngineID new_engine_type
= GB(p2
, 16, 16);
817 GroupID id_g
= GB(p1
, 16, 16);
820 if (Group::IsValidID(id_g
) ? Group::Get(id_g
)->owner
!= _current_company
: !IsAllGroupID(id_g
) && !IsDefaultGroupID(id_g
)) return CMD_ERROR
;
821 if (!Engine::IsValidID(old_engine_type
)) return CMD_ERROR
;
823 if (new_engine_type
!= INVALID_ENGINE
) {
824 if (!Engine::IsValidID(new_engine_type
)) return CMD_ERROR
;
825 if (!CheckAutoreplaceValidity(old_engine_type
, new_engine_type
, _current_company
)) return CMD_ERROR
;
827 cost
= AddEngineReplacementForCompany(c
, old_engine_type
, new_engine_type
, id_g
, HasBit(p1
, 0), flags
);
829 cost
= RemoveEngineReplacementForCompany(c
, old_engine_type
, id_g
, flags
);
832 if (flags
& DC_EXEC
) {
833 GroupStatistics::UpdateAutoreplace(_current_company
);
834 if (IsLocalCompany()) SetWindowDirty(WC_REPLACE_VEHICLE
, Engine::Get(old_engine_type
)->type
);
836 const VehicleType vt
= Engine::Get(old_engine_type
)->type
;
837 SetWindowDirty(GetWindowClassForVehicleType(vt
), VehicleListIdentifier(VL_GROUP_LIST
, vt
, _current_company
).Pack());
839 if ((flags
& DC_EXEC
) && IsLocalCompany()) InvalidateAutoreplaceWindow(old_engine_type
, id_g
);