Codechange: Don't use globals for return values from vehicle command procs.
[openttd-github.git] / src / vehicle_cmd.cpp
blob438f733678a216210e371492a2da22b5ff4ebbf4
1 /*
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/>.
6 */
8 /** @file vehicle_cmd.cpp Commands for vehicles. */
10 #include "stdafx.h"
11 #include "roadveh.h"
12 #include "news_func.h"
13 #include "airport.h"
14 #include "cmd_helper.h"
15 #include "command_func.h"
16 #include "company_func.h"
17 #include "train.h"
18 #include "aircraft.h"
19 #include "newgrf_text.h"
20 #include "vehicle_func.h"
21 #include "string_func.h"
22 #include "depot_map.h"
23 #include "vehiclelist.h"
24 #include "engine_func.h"
25 #include "articulated_vehicles.h"
26 #include "autoreplace_gui.h"
27 #include "group.h"
28 #include "order_backup.h"
29 #include "ship.h"
30 #include "newgrf.h"
31 #include "company_base.h"
32 #include "core/random_func.hpp"
33 #include "vehicle_cmd.h"
34 #include "aircraft_cmd.h"
35 #include "autoreplace_cmd.h"
36 #include "group_cmd.h"
37 #include "order_cmd.h"
38 #include "roadveh_cmd.h"
39 #include "train_cmd.h"
40 #include "ship_cmd.h"
41 #include <sstream>
42 #include <iomanip>
44 #include "table/strings.h"
46 #include "safeguards.h"
48 /* Tables used in vehicle_func.h to find the right error message for a certain vehicle type */
49 const StringID _veh_build_msg_table[] = {
50 STR_ERROR_CAN_T_BUY_TRAIN,
51 STR_ERROR_CAN_T_BUY_ROAD_VEHICLE,
52 STR_ERROR_CAN_T_BUY_SHIP,
53 STR_ERROR_CAN_T_BUY_AIRCRAFT,
56 const StringID _veh_sell_msg_table[] = {
57 STR_ERROR_CAN_T_SELL_TRAIN,
58 STR_ERROR_CAN_T_SELL_ROAD_VEHICLE,
59 STR_ERROR_CAN_T_SELL_SHIP,
60 STR_ERROR_CAN_T_SELL_AIRCRAFT,
63 const StringID _veh_refit_msg_table[] = {
64 STR_ERROR_CAN_T_REFIT_TRAIN,
65 STR_ERROR_CAN_T_REFIT_ROAD_VEHICLE,
66 STR_ERROR_CAN_T_REFIT_SHIP,
67 STR_ERROR_CAN_T_REFIT_AIRCRAFT,
70 const StringID _send_to_depot_msg_table[] = {
71 STR_ERROR_CAN_T_SEND_TRAIN_TO_DEPOT,
72 STR_ERROR_CAN_T_SEND_ROAD_VEHICLE_TO_DEPOT,
73 STR_ERROR_CAN_T_SEND_SHIP_TO_DEPOT,
74 STR_ERROR_CAN_T_SEND_AIRCRAFT_TO_HANGAR,
78 /**
79 * Build a vehicle.
80 * @param flags for command
81 * @param tile tile of depot where the vehicle is built
82 * @param eid vehicle type being built.
83 * @param use_free_vehicles use free vehicles when building the vehicle.
84 * @param cargo refit cargo type.
85 * @param client_id User
86 * @return the cost of this operation + the new vehicle ID + the refitted capacity + the refitted mail capacity (aircraft) or an error
88 std::tuple<CommandCost, VehicleID, uint, uint16> CmdBuildVehicle(DoCommandFlag flags, TileIndex tile, EngineID eid, bool use_free_vehicles, CargoID cargo, ClientID client_id)
90 /* Elementary check for valid location. */
91 if (!IsDepotTile(tile) || !IsTileOwner(tile, _current_company)) return { CMD_ERROR, INVALID_VEHICLE, 0, 0 };
93 VehicleType type = GetDepotVehicleType(tile);
95 /* Validate the engine type. */
96 if (!IsEngineBuildable(eid, type, _current_company)) return { CommandCost(STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE + type), INVALID_VEHICLE, 0, 0 };
98 /* Validate the cargo type. */
99 if (cargo >= NUM_CARGO && cargo != CT_INVALID) return { CMD_ERROR, INVALID_VEHICLE, 0, 0 };
101 const Engine *e = Engine::Get(eid);
102 CommandCost value(EXPENSES_NEW_VEHICLES, e->GetCost());
104 /* Engines without valid cargo should not be available */
105 CargoID default_cargo = e->GetDefaultCargoType();
106 if (default_cargo == CT_INVALID) return { CMD_ERROR, INVALID_VEHICLE, 0, 0 };
108 bool refitting = cargo != CT_INVALID && cargo != default_cargo;
110 /* Check whether the number of vehicles we need to build can be built according to pool space. */
111 uint num_vehicles;
112 switch (type) {
113 case VEH_TRAIN: num_vehicles = (e->u.rail.railveh_type == RAILVEH_MULTIHEAD ? 2 : 1) + CountArticulatedParts(eid, false); break;
114 case VEH_ROAD: num_vehicles = 1 + CountArticulatedParts(eid, false); break;
115 case VEH_SHIP: num_vehicles = 1; break;
116 case VEH_AIRCRAFT: num_vehicles = e->u.air.subtype & AIR_CTOL ? 2 : 3; break;
117 default: NOT_REACHED(); // Safe due to IsDepotTile()
119 if (!Vehicle::CanAllocateItem(num_vehicles)) return { CommandCost(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME), INVALID_VEHICLE, 0, 0 };
121 /* Check whether we can allocate a unit number. Autoreplace does not allocate
122 * an unit number as it will (always) reuse the one of the replaced vehicle
123 * and (train) wagons don't have an unit number in any scenario. */
124 UnitID unit_num = (flags & DC_QUERY_COST || flags & DC_AUTOREPLACE || (type == VEH_TRAIN && e->u.rail.railveh_type == RAILVEH_WAGON)) ? 0 : GetFreeUnitNumber(type);
125 if (unit_num == UINT16_MAX) return { CommandCost(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME), INVALID_VEHICLE, 0, 0 };
127 /* If we are refitting we need to temporarily purchase the vehicle to be able to
128 * test it. */
129 DoCommandFlag subflags = flags;
130 if (refitting && !(flags & DC_EXEC)) subflags |= DC_EXEC | DC_AUTOREPLACE;
132 /* Vehicle construction needs random bits, so we have to save the random
133 * seeds to prevent desyncs. */
134 SavedRandomSeeds saved_seeds;
135 SaveRandomSeeds(&saved_seeds);
137 Vehicle *v = nullptr;
138 switch (type) {
139 case VEH_TRAIN: value.AddCost(CmdBuildRailVehicle(subflags, tile, e, use_free_vehicles, &v)); break;
140 case VEH_ROAD: value.AddCost(CmdBuildRoadVehicle(subflags, tile, e, &v)); break;
141 case VEH_SHIP: value.AddCost(CmdBuildShip (subflags, tile, e, &v)); break;
142 case VEH_AIRCRAFT: value.AddCost(CmdBuildAircraft (subflags, tile, e, &v)); break;
143 default: NOT_REACHED(); // Safe due to IsDepotTile()
146 VehicleID veh_id = INVALID_VEHICLE;
147 uint refitted_capacity = 0;
148 uint16 refitted_mail_capacity = 0;
149 if (value.Succeeded()) {
150 if (subflags & DC_EXEC) {
151 v->unitnumber = unit_num;
152 v->value = value.GetCost();
153 veh_id = v->index;
156 if (refitting) {
157 /* Refit only one vehicle. If we purchased an engine, it may have gained free wagons. */
158 CommandCost cc;
159 std::tie(cc, refitted_capacity, refitted_mail_capacity) = CmdRefitVehicle(flags, v->index, cargo, 0, false, false, 1);
160 value.AddCost(cc);
161 } else {
162 /* Fill in non-refitted capacities */
163 refitted_capacity = e->GetDisplayDefaultCapacity(&refitted_mail_capacity);
166 if (flags & DC_EXEC) {
167 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
168 InvalidateWindowClassesData(GetWindowClassForVehicleType(type), 0);
169 SetWindowDirty(WC_COMPANY, _current_company);
170 if (IsLocalCompany()) {
171 InvalidateAutoreplaceWindow(v->engine_type, v->group_id); // updates the auto replace window (must be called before incrementing num_engines)
175 if (subflags & DC_EXEC) {
176 GroupStatistics::CountEngine(v, 1);
177 GroupStatistics::UpdateAutoreplace(_current_company);
179 if (v->IsPrimaryVehicle()) {
180 GroupStatistics::CountVehicle(v, 1);
181 if (!(subflags & DC_AUTOREPLACE)) OrderBackup::Restore(v, client_id);
186 /* If we are not in DC_EXEC undo everything */
187 if (flags != subflags) {
188 Command<CMD_SELL_VEHICLE>::Do(DC_EXEC, v->index, false, false, INVALID_CLIENT_ID);
192 /* Only restore if we actually did some refitting */
193 if (flags != subflags) RestoreRandomSeeds(saved_seeds);
195 return { value, veh_id, refitted_capacity, refitted_mail_capacity };
199 * Sell a vehicle.
200 * @param flags for command.
201 * @aram v_id vehicle ID being sold.
202 * @param sell_chain sell the vehicle and all vehicles following it in the chain.
203 * @param backup_order make a backup of the vehicle's order (if an engine).
204 * @param client_id User.
205 * @param text unused.
206 * @return the cost of this operation or an error.
208 CommandCost CmdSellVehicle(DoCommandFlag flags, VehicleID v_id, bool sell_chain, bool backup_order, ClientID client_id)
210 Vehicle *v = Vehicle::GetIfValid(v_id);
211 if (v == nullptr) return CMD_ERROR;
213 Vehicle *front = v->First();
215 CommandCost ret = CheckOwnership(front->owner);
216 if (ret.Failed()) return ret;
218 if (front->vehstatus & VS_CRASHED) return_cmd_error(STR_ERROR_VEHICLE_IS_DESTROYED);
220 if (!front->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAIN_MUST_BE_STOPPED_INSIDE_DEPOT + front->type);
222 /* Can we actually make the order backup, i.e. are there enough orders? */
223 if (backup_order &&
224 front->orders.list != nullptr &&
225 !front->orders.list->IsShared() &&
226 !Order::CanAllocateItem(front->orders.list->GetNumOrders())) {
227 /* Only happens in exceptional cases when there aren't enough orders anyhow.
228 * Thus it should be safe to just drop the orders in that case. */
229 backup_order = false;
232 if (v->type == VEH_TRAIN) {
233 ret = CmdSellRailWagon(flags, v, sell_chain, backup_order, client_id);
234 } else {
235 ret = CommandCost(EXPENSES_NEW_VEHICLES, -front->value);
237 if (flags & DC_EXEC) {
238 if (front->IsPrimaryVehicle() && backup_order) OrderBackup::Backup(front, client_id);
239 delete front;
243 return ret;
247 * Helper to run the refit cost callback.
248 * @param v The vehicle we are refitting, can be nullptr.
249 * @param engine_type Which engine to refit
250 * @param new_cid Cargo type we are refitting to.
251 * @param new_subtype New cargo subtype.
252 * @param[out] auto_refit_allowed The refit is allowed as an auto-refit.
253 * @return Price for refitting
255 static int GetRefitCostFactor(const Vehicle *v, EngineID engine_type, CargoID new_cid, byte new_subtype, bool *auto_refit_allowed)
257 /* Prepare callback param with info about the new cargo type. */
258 const Engine *e = Engine::Get(engine_type);
260 /* Is this vehicle a NewGRF vehicle? */
261 if (e->GetGRF() != nullptr) {
262 const CargoSpec *cs = CargoSpec::Get(new_cid);
263 uint32 param1 = (cs->classes << 16) | (new_subtype << 8) | e->GetGRF()->cargo_map[new_cid];
265 uint16 cb_res = GetVehicleCallback(CBID_VEHICLE_REFIT_COST, param1, 0, engine_type, v);
266 if (cb_res != CALLBACK_FAILED) {
267 *auto_refit_allowed = HasBit(cb_res, 14);
268 int factor = GB(cb_res, 0, 14);
269 if (factor >= 0x2000) factor -= 0x4000; // Treat as signed integer.
270 return factor;
274 *auto_refit_allowed = e->info.refit_cost == 0;
275 return (v == nullptr || v->cargo_type != new_cid) ? e->info.refit_cost : 0;
279 * Learn the price of refitting a certain engine
280 * @param v The vehicle we are refitting, can be nullptr.
281 * @param engine_type Which engine to refit
282 * @param new_cid Cargo type we are refitting to.
283 * @param new_subtype New cargo subtype.
284 * @param[out] auto_refit_allowed The refit is allowed as an auto-refit.
285 * @return Price for refitting
287 static CommandCost GetRefitCost(const Vehicle *v, EngineID engine_type, CargoID new_cid, byte new_subtype, bool *auto_refit_allowed)
289 ExpensesType expense_type;
290 const Engine *e = Engine::Get(engine_type);
291 Price base_price;
292 int cost_factor = GetRefitCostFactor(v, engine_type, new_cid, new_subtype, auto_refit_allowed);
293 switch (e->type) {
294 case VEH_SHIP:
295 base_price = PR_BUILD_VEHICLE_SHIP;
296 expense_type = EXPENSES_SHIP_RUN;
297 break;
299 case VEH_ROAD:
300 base_price = PR_BUILD_VEHICLE_ROAD;
301 expense_type = EXPENSES_ROADVEH_RUN;
302 break;
304 case VEH_AIRCRAFT:
305 base_price = PR_BUILD_VEHICLE_AIRCRAFT;
306 expense_type = EXPENSES_AIRCRAFT_RUN;
307 break;
309 case VEH_TRAIN:
310 base_price = (e->u.rail.railveh_type == RAILVEH_WAGON) ? PR_BUILD_VEHICLE_WAGON : PR_BUILD_VEHICLE_TRAIN;
311 cost_factor <<= 1;
312 expense_type = EXPENSES_TRAIN_RUN;
313 break;
315 default: NOT_REACHED();
317 if (cost_factor < 0) {
318 return CommandCost(expense_type, -GetPrice(base_price, -cost_factor, e->GetGRF(), -10));
319 } else {
320 return CommandCost(expense_type, GetPrice(base_price, cost_factor, e->GetGRF(), -10));
324 /** Helper structure for RefitVehicle() */
325 struct RefitResult {
326 Vehicle *v; ///< Vehicle to refit
327 uint capacity; ///< New capacity of vehicle
328 uint mail_capacity; ///< New mail capacity of aircraft
329 byte subtype; ///< cargo subtype to refit to
333 * Refits a vehicle (chain).
334 * This is the vehicle-type independent part of the CmdRefitXXX functions.
335 * @param v The vehicle to refit.
336 * @param only_this Whether to only refit this vehicle, or to check the rest of them.
337 * @param num_vehicles Number of vehicles to refit (not counting articulated parts). Zero means the whole chain.
338 * @param new_cid Cargotype to refit to
339 * @param new_subtype Cargo subtype to refit to. 0xFF means to try keeping the same subtype according to GetBestFittingSubType().
340 * @param flags Command flags
341 * @param auto_refit Refitting is done as automatic refitting outside a depot.
342 * @return Refit cost + refittet capacity + mail capacity (aircraft).
344 static std::tuple<CommandCost, uint, uint16> RefitVehicle(Vehicle *v, bool only_this, uint8 num_vehicles, CargoID new_cid, byte new_subtype, DoCommandFlag flags, bool auto_refit)
346 CommandCost cost(v->GetExpenseType(false));
347 uint total_capacity = 0;
348 uint total_mail_capacity = 0;
349 num_vehicles = num_vehicles == 0 ? UINT8_MAX : num_vehicles;
351 VehicleSet vehicles_to_refit;
352 if (!only_this) {
353 GetVehicleSet(vehicles_to_refit, v, num_vehicles);
354 /* In this case, we need to check the whole chain. */
355 v = v->First();
358 std::vector<RefitResult> refit_result;
360 v->InvalidateNewGRFCacheOfChain();
361 byte actual_subtype = new_subtype;
362 for (; v != nullptr; v = (only_this ? nullptr : v->Next())) {
363 /* Reset actual_subtype for every new vehicle */
364 if (!v->IsArticulatedPart()) actual_subtype = new_subtype;
366 if (v->type == VEH_TRAIN && std::find(vehicles_to_refit.begin(), vehicles_to_refit.end(), v->index) == vehicles_to_refit.end() && !only_this) continue;
368 const Engine *e = v->GetEngine();
369 if (!e->CanCarryCargo()) continue;
371 /* If the vehicle is not refittable, or does not allow automatic refitting,
372 * count its capacity nevertheless if the cargo matches */
373 bool refittable = HasBit(e->info.refit_mask, new_cid) && (!auto_refit || HasBit(e->info.misc_flags, EF_AUTO_REFIT));
374 if (!refittable && v->cargo_type != new_cid) continue;
376 /* Determine best fitting subtype if requested */
377 if (actual_subtype == 0xFF) {
378 actual_subtype = GetBestFittingSubType(v, v, new_cid);
381 /* Back up the vehicle's cargo type */
382 CargoID temp_cid = v->cargo_type;
383 byte temp_subtype = v->cargo_subtype;
384 if (refittable) {
385 v->cargo_type = new_cid;
386 v->cargo_subtype = actual_subtype;
389 uint16 mail_capacity = 0;
390 uint amount = e->DetermineCapacity(v, &mail_capacity);
391 total_capacity += amount;
392 /* mail_capacity will always be zero if the vehicle is not an aircraft. */
393 total_mail_capacity += mail_capacity;
395 if (!refittable) continue;
397 /* Restore the original cargo type */
398 v->cargo_type = temp_cid;
399 v->cargo_subtype = temp_subtype;
401 bool auto_refit_allowed;
402 CommandCost refit_cost = GetRefitCost(v, v->engine_type, new_cid, actual_subtype, &auto_refit_allowed);
403 if (auto_refit && (flags & DC_QUERY_COST) == 0 && !auto_refit_allowed) {
404 /* Sorry, auto-refitting not allowed, subtract the cargo amount again from the total.
405 * When querrying cost/capacity (for example in order refit GUI), we always assume 'allowed'.
406 * It is not predictable. */
407 total_capacity -= amount;
408 total_mail_capacity -= mail_capacity;
410 if (v->cargo_type == new_cid) {
411 /* Add the old capacity nevertheless, if the cargo matches */
412 total_capacity += v->cargo_cap;
413 if (v->type == VEH_AIRCRAFT) total_mail_capacity += v->Next()->cargo_cap;
415 continue;
417 cost.AddCost(refit_cost);
419 /* Record the refitting.
420 * Do not execute the refitting immediately, so DetermineCapacity and GetRefitCost do the same in test and exec run.
421 * (weird NewGRFs)
422 * Note:
423 * - If the capacity of vehicles depends on other vehicles in the chain, the actual capacity is
424 * set after RefitVehicle() via ConsistChanged() and friends. The estimation via _returned_refit_capacity will be wrong.
425 * - We have to call the refit cost callback with the pre-refit configuration of the chain because we want refit and
426 * autorefit to behave the same, and we need its result for auto_refit_allowed.
428 refit_result.push_back({v, amount, mail_capacity, actual_subtype});
431 if (flags & DC_EXEC) {
432 /* Store the result */
433 for (RefitResult &result : refit_result) {
434 Vehicle *u = result.v;
435 u->refit_cap = (u->cargo_type == new_cid) ? std::min<uint16>(result.capacity, u->refit_cap) : 0;
436 if (u->cargo.TotalCount() > u->refit_cap) u->cargo.Truncate(u->cargo.TotalCount() - u->refit_cap);
437 u->cargo_type = new_cid;
438 u->cargo_cap = result.capacity;
439 u->cargo_subtype = result.subtype;
440 if (u->type == VEH_AIRCRAFT) {
441 Vehicle *w = u->Next();
442 w->refit_cap = std::min<uint16>(w->refit_cap, result.mail_capacity);
443 w->cargo_cap = result.mail_capacity;
444 if (w->cargo.TotalCount() > w->refit_cap) w->cargo.Truncate(w->cargo.TotalCount() - w->refit_cap);
449 refit_result.clear();
450 return { cost, total_capacity, total_mail_capacity };
454 * Refits a vehicle to the specified cargo type.
455 * @param flags type of operation
456 * @param veh_id vehicle ID to refit
457 * @param new_cid New cargo type to refit to.
458 * @param new_subtype New cargo subtype to refit to. 0xFF means to try keeping the same subtype according to GetBestFittingSubType().
459 * @param auto_refit Automatic refitting.
460 * @param only_this Refit only this vehicle. Used only for cloning vehicles.
461 * @param num_vehicles Number of vehicles to refit (not counting articulated parts). Zero means all vehicles.
462 * Only used if "refit only this vehicle" is false.
463 * @return the cost of this operation or an error
465 std::tuple<CommandCost, uint, uint16> CmdRefitVehicle(DoCommandFlag flags, VehicleID veh_id, CargoID new_cid, byte new_subtype, bool auto_refit, bool only_this, uint8 num_vehicles)
467 Vehicle *v = Vehicle::GetIfValid(veh_id);
468 if (v == nullptr) return { CMD_ERROR, 0, 0 };
470 /* Don't allow disasters and sparks and such to be refitted.
471 * We cannot check for IsPrimaryVehicle as autoreplace also refits in free wagon chains. */
472 if (!IsCompanyBuildableVehicleType(v->type)) return { CMD_ERROR, 0, 0 };
474 Vehicle *front = v->First();
476 CommandCost ret = CheckOwnership(front->owner);
477 if (ret.Failed()) return { ret, 0, 0 };
479 bool free_wagon = v->type == VEH_TRAIN && Train::From(front)->IsFreeWagon(); // used by autoreplace/renew
481 /* Don't allow shadows and such to be refitted. */
482 if (v != front && (v->type == VEH_SHIP || v->type == VEH_AIRCRAFT)) return { CMD_ERROR, 0, 0 };
484 /* Allow auto-refitting only during loading and normal refitting only in a depot. */
485 if ((flags & DC_QUERY_COST) == 0 && // used by the refit GUI, including the order refit GUI.
486 !free_wagon && // used by autoreplace/renew
487 (!auto_refit || !front->current_order.IsType(OT_LOADING)) && // refit inside stations
488 !front->IsStoppedInDepot()) { // refit inside depots
489 return { CommandCost(STR_ERROR_TRAIN_MUST_BE_STOPPED_INSIDE_DEPOT + front->type), 0, 0};
492 if (front->vehstatus & VS_CRASHED) return { CommandCost(STR_ERROR_VEHICLE_IS_DESTROYED), 0, 0};
494 /* Check cargo */
495 if (new_cid >= NUM_CARGO) return { CMD_ERROR, 0, 0 };
497 /* For ships and aircraft there is always only one. */
498 only_this |= front->type == VEH_SHIP || front->type == VEH_AIRCRAFT;
500 auto [cost, refit_capacity, mail_capacity] = RefitVehicle(v, only_this, num_vehicles, new_cid, new_subtype, flags, auto_refit);
502 if (flags & DC_EXEC) {
503 /* Update the cached variables */
504 switch (v->type) {
505 case VEH_TRAIN:
506 Train::From(front)->ConsistChanged(auto_refit ? CCF_AUTOREFIT : CCF_REFIT);
507 break;
508 case VEH_ROAD:
509 RoadVehUpdateCache(RoadVehicle::From(front), auto_refit);
510 if (_settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL) RoadVehicle::From(front)->CargoChanged();
511 break;
513 case VEH_SHIP:
514 v->InvalidateNewGRFCacheOfChain();
515 Ship::From(v)->UpdateCache();
516 break;
518 case VEH_AIRCRAFT:
519 v->InvalidateNewGRFCacheOfChain();
520 UpdateAircraftCache(Aircraft::From(v), true);
521 break;
523 default: NOT_REACHED();
525 front->MarkDirty();
527 if (!free_wagon) {
528 InvalidateWindowData(WC_VEHICLE_DETAILS, front->index);
529 InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
531 SetWindowDirty(WC_VEHICLE_DEPOT, front->tile);
532 } else {
533 /* Always invalidate the cache; querycost might have filled it. */
534 v->InvalidateNewGRFCacheOfChain();
537 return { cost, refit_capacity, mail_capacity };
541 * Start/Stop a vehicle
542 * @param flags type of operation
543 * @param veh_id vehicle to start/stop, don't forget to change CcStartStopVehicle if you modify this!
544 * @param evaluate_startstop_cb Shall the start/stop newgrf callback be evaluated (only valid with DC_AUTOREPLACE for network safety)
545 * @return the cost of this operation or an error
547 CommandCost CmdStartStopVehicle(DoCommandFlag flags, VehicleID veh_id, bool evaluate_startstop_cb)
549 /* Disable the effect of p2 bit 0, when DC_AUTOREPLACE is not set */
550 if ((flags & DC_AUTOREPLACE) == 0) evaluate_startstop_cb = true;
552 Vehicle *v = Vehicle::GetIfValid(veh_id);
553 if (v == nullptr || !v->IsPrimaryVehicle()) return CMD_ERROR;
555 CommandCost ret = CheckOwnership(v->owner);
556 if (ret.Failed()) return ret;
558 if (v->vehstatus & VS_CRASHED) return_cmd_error(STR_ERROR_VEHICLE_IS_DESTROYED);
560 switch (v->type) {
561 case VEH_TRAIN:
562 if ((v->vehstatus & VS_STOPPED) && Train::From(v)->gcache.cached_power == 0) return_cmd_error(STR_ERROR_TRAIN_START_NO_POWER);
563 break;
565 case VEH_SHIP:
566 case VEH_ROAD:
567 break;
569 case VEH_AIRCRAFT: {
570 Aircraft *a = Aircraft::From(v);
571 /* cannot stop airplane when in flight, or when taking off / landing */
572 if (a->state >= STARTTAKEOFF && a->state < TERM7) return_cmd_error(STR_ERROR_AIRCRAFT_IS_IN_FLIGHT);
573 if (HasBit(a->flags, VAF_HELI_DIRECT_DESCENT)) return_cmd_error(STR_ERROR_AIRCRAFT_IS_IN_FLIGHT);
574 break;
577 default: return CMD_ERROR;
580 if (evaluate_startstop_cb) {
581 /* Check if this vehicle can be started/stopped. Failure means 'allow'. */
582 uint16 callback = GetVehicleCallback(CBID_VEHICLE_START_STOP_CHECK, 0, 0, v->engine_type, v);
583 StringID error = STR_NULL;
584 if (callback != CALLBACK_FAILED) {
585 if (v->GetGRF()->grf_version < 8) {
586 /* 8 bit result 0xFF means 'allow' */
587 if (callback < 0x400 && GB(callback, 0, 8) != 0xFF) error = GetGRFStringID(v->GetGRFID(), 0xD000 + callback);
588 } else {
589 if (callback < 0x400) {
590 error = GetGRFStringID(v->GetGRFID(), 0xD000 + callback);
591 } else {
592 switch (callback) {
593 case 0x400: // allow
594 break;
596 default: // unknown reason -> disallow
597 error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
598 break;
603 if (error != STR_NULL) return_cmd_error(error);
606 if (flags & DC_EXEC) {
607 if (v->IsStoppedInDepot() && (flags & DC_AUTOREPLACE) == 0) DeleteVehicleNews(veh_id, STR_NEWS_TRAIN_IS_WAITING + v->type);
609 v->vehstatus ^= VS_STOPPED;
610 if (v->type != VEH_TRAIN) v->cur_speed = 0; // trains can stop 'slowly'
611 v->MarkDirty();
612 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
613 SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
614 SetWindowClassesDirty(GetWindowClassForVehicleType(v->type));
615 InvalidateWindowData(WC_VEHICLE_VIEW, v->index);
617 return CommandCost();
621 * Starts or stops a lot of vehicles
622 * @param flags type of operation
623 * @param tile Tile of the depot where the vehicles are started/stopped (only used for depots)
624 * @param do_start set = start vehicles, unset = stop vehicles
625 * @param vehicle_list_window if set, then it's a vehicle list window, not a depot and Tile is ignored in this case
626 * @param vli VehicleListIdentifier
627 * @return the cost of this operation or an error
629 CommandCost CmdMassStartStopVehicle(DoCommandFlag flags, TileIndex tile, bool do_start, bool vehicle_list_window, const VehicleListIdentifier &vli)
631 VehicleList list;
633 if (!vli.Valid()) return CMD_ERROR;
634 if (!IsCompanyBuildableVehicleType(vli.vtype)) return CMD_ERROR;
636 if (vehicle_list_window) {
637 if (!GenerateVehicleSortList(&list, vli)) return CMD_ERROR;
638 } else {
639 /* Get the list of vehicles in the depot */
640 BuildDepotVehicleList(vli.vtype, tile, &list, nullptr);
643 for (uint i = 0; i < list.size(); i++) {
644 const Vehicle *v = list[i];
646 if (!!(v->vehstatus & VS_STOPPED) != do_start) continue;
648 if (!vehicle_list_window && !v->IsChainInDepot()) continue;
650 /* Just try and don't care if some vehicle's can't be stopped. */
651 Command<CMD_START_STOP_VEHICLE>::Do(flags, v->index, false);
654 return CommandCost();
658 * Sells all vehicles in a depot
659 * @param flags type of operation
660 * @param tile Tile of the depot where the depot is
661 * @param vehicle_type Vehicle type
662 * @return the cost of this operation or an error
664 CommandCost CmdDepotSellAllVehicles(DoCommandFlag flags, TileIndex tile, VehicleType vehicle_type)
666 VehicleList list;
668 CommandCost cost(EXPENSES_NEW_VEHICLES);
670 if (!IsCompanyBuildableVehicleType(vehicle_type)) return CMD_ERROR;
672 /* Get the list of vehicles in the depot */
673 BuildDepotVehicleList(vehicle_type, tile, &list, &list);
675 CommandCost last_error = CMD_ERROR;
676 bool had_success = false;
677 for (uint i = 0; i < list.size(); i++) {
678 CommandCost ret = Command<CMD_SELL_VEHICLE>::Do(flags, list[i]->index, true, false, INVALID_CLIENT_ID);
679 if (ret.Succeeded()) {
680 cost.AddCost(ret);
681 had_success = true;
682 } else {
683 last_error = ret;
687 return had_success ? cost : last_error;
691 * Autoreplace all vehicles in the depot
692 * @param flags type of operation
693 * @param tile Tile of the depot where the vehicles are
694 * @param vehicle_type Type of vehicle
695 * @return the cost of this operation or an error
697 CommandCost CmdDepotMassAutoReplace(DoCommandFlag flags, TileIndex tile, VehicleType vehicle_type)
699 VehicleList list;
700 CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES);
702 if (!IsCompanyBuildableVehicleType(vehicle_type)) return CMD_ERROR;
703 if (!IsDepotTile(tile) || !IsTileOwner(tile, _current_company)) return CMD_ERROR;
705 /* Get the list of vehicles in the depot */
706 BuildDepotVehicleList(vehicle_type, tile, &list, &list, true);
708 for (uint i = 0; i < list.size(); i++) {
709 const Vehicle *v = list[i];
711 /* Ensure that the vehicle completely in the depot */
712 if (!v->IsChainInDepot()) continue;
714 CommandCost ret = Command<CMD_AUTOREPLACE_VEHICLE>::Do(flags, v->index);
716 if (ret.Succeeded()) cost.AddCost(ret);
718 return cost;
722 * Test if a name is unique among vehicle names.
723 * @param name Name to test.
724 * @return True ifffffff the name is unique.
726 static bool IsUniqueVehicleName(const std::string &name)
728 for (const Vehicle *v : Vehicle::Iterate()) {
729 if (!v->name.empty() && v->name == name) return false;
732 return true;
736 * Clone the custom name of a vehicle, adding or incrementing a number.
737 * @param src Source vehicle, with a custom name.
738 * @param dst Destination vehicle.
740 static void CloneVehicleName(const Vehicle *src, Vehicle *dst)
742 std::string buf;
744 /* Find the position of the first digit in the last group of digits. */
745 size_t number_position;
746 for (number_position = src->name.length(); number_position > 0; number_position--) {
747 /* The design of UTF-8 lets this work simply without having to check
748 * for UTF-8 sequences. */
749 if (src->name[number_position - 1] < '0' || src->name[number_position - 1] > '9') break;
752 /* Format buffer and determine starting number. */
753 long num;
754 byte padding = 0;
755 if (number_position == src->name.length()) {
756 /* No digit at the end, so start at number 2. */
757 buf = src->name;
758 buf += " ";
759 number_position = buf.length();
760 num = 2;
761 } else {
762 /* Found digits, parse them and start at the next number. */
763 buf = src->name.substr(0, number_position);
765 auto num_str = src->name.substr(number_position);
766 padding = (byte)num_str.length();
768 std::istringstream iss(num_str);
769 iss >> num;
770 num++;
773 /* Check if this name is already taken. */
774 for (int max_iterations = 1000; max_iterations > 0; max_iterations--, num++) {
775 std::ostringstream oss;
777 /* Attach the number to the temporary name. */
778 oss << buf << std::setw(padding) << std::setfill('0') << std::internal << num;
780 /* Check the name is unique. */
781 auto new_name = oss.str();
782 if (IsUniqueVehicleName(new_name)) {
783 dst->name = new_name;
784 break;
788 /* All done. If we didn't find a name, it'll just use its default. */
792 * Clone a vehicle. If it is a train, it will clone all the cars too
793 * @param flags type of operation
794 * @param tile tile of the depot where the cloned vehicle is build
795 * @param veh_id the original vehicle's index
796 * @param share_orders shared orders, else copied orders
797 * @return the cost of this operation + the new vehicle ID or an error
799 std::tuple<CommandCost, VehicleID> CmdCloneVehicle(DoCommandFlag flags, TileIndex tile, VehicleID veh_id, bool share_orders)
801 CommandCost total_cost(EXPENSES_NEW_VEHICLES);
803 Vehicle *v = Vehicle::GetIfValid(veh_id);
804 if (v == nullptr || !v->IsPrimaryVehicle()) return { CMD_ERROR, INVALID_VEHICLE };
805 Vehicle *v_front = v;
806 Vehicle *w = nullptr;
807 Vehicle *w_front = nullptr;
808 Vehicle *w_rear = nullptr;
811 * v_front is the front engine in the original vehicle
812 * v is the car/vehicle of the original vehicle that is currently being copied
813 * w_front is the front engine of the cloned vehicle
814 * w is the car/vehicle currently being cloned
815 * w_rear is the rear end of the cloned train. It's used to add more cars and is only used by trains
818 CommandCost ret = CheckOwnership(v->owner);
819 if (ret.Failed()) return { ret, INVALID_VEHICLE };
821 if (v->type == VEH_TRAIN && (!v->IsFrontEngine() || Train::From(v)->crash_anim_pos >= 4400)) return { CMD_ERROR, INVALID_VEHICLE };
823 /* check that we can allocate enough vehicles */
824 if (!(flags & DC_EXEC)) {
825 int veh_counter = 0;
826 do {
827 veh_counter++;
828 } while ((v = v->Next()) != nullptr);
830 if (!Vehicle::CanAllocateItem(veh_counter)) {
831 return { CommandCost(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME), INVALID_VEHICLE };
835 v = v_front;
837 VehicleID new_veh_id = INVALID_VEHICLE;
838 do {
839 if (v->type == VEH_TRAIN && Train::From(v)->IsRearDualheaded()) {
840 /* we build the rear ends of multiheaded trains with the front ones */
841 continue;
844 /* In case we're building a multi headed vehicle and the maximum number of
845 * vehicles is almost reached (e.g. max trains - 1) not all vehicles would
846 * be cloned. When the non-primary engines were build they were seen as
847 * 'new' vehicles whereas they would immediately be joined with a primary
848 * engine. This caused the vehicle to be not build as 'the limit' had been
849 * reached, resulting in partially build vehicles and such. */
850 DoCommandFlag build_flags = flags;
851 if ((flags & DC_EXEC) && !v->IsPrimaryVehicle()) build_flags |= DC_AUTOREPLACE;
853 CommandCost cost;
854 std::tie(cost, new_veh_id, std::ignore, std::ignore) = Command<CMD_BUILD_VEHICLE>::Do(build_flags, tile, v->engine_type, false, CT_INVALID, INVALID_CLIENT_ID);
856 if (cost.Failed()) {
857 /* Can't build a part, then sell the stuff we already made; clear up the mess */
858 if (w_front != nullptr) Command<CMD_SELL_VEHICLE>::Do(flags, w_front->index, true, false, INVALID_CLIENT_ID);
859 return { cost, INVALID_VEHICLE };
862 total_cost.AddCost(cost);
864 if (flags & DC_EXEC) {
865 w = Vehicle::Get(new_veh_id);
867 if (v->type == VEH_TRAIN && HasBit(Train::From(v)->flags, VRF_REVERSE_DIRECTION)) {
868 SetBit(Train::From(w)->flags, VRF_REVERSE_DIRECTION);
871 if (v->type == VEH_TRAIN && !v->IsFrontEngine()) {
872 /* this s a train car
873 * add this unit to the end of the train */
874 CommandCost result = Command<CMD_MOVE_RAIL_VEHICLE>::Do(flags, w->index, w_rear->index, true);
875 if (result.Failed()) {
876 /* The train can't be joined to make the same consist as the original.
877 * Sell what we already made (clean up) and return an error. */
878 Command<CMD_SELL_VEHICLE>::Do(flags, w_front->index, true, false, INVALID_CLIENT_ID);
879 Command<CMD_SELL_VEHICLE>::Do(flags, w->index, true, false, INVALID_CLIENT_ID);
880 return { result, INVALID_VEHICLE }; // return error and the message returned from CMD_MOVE_RAIL_VEHICLE
882 } else {
883 /* this is a front engine or not a train. */
884 w_front = w;
885 w->service_interval = v->service_interval;
886 w->SetServiceIntervalIsCustom(v->ServiceIntervalIsCustom());
887 w->SetServiceIntervalIsPercent(v->ServiceIntervalIsPercent());
889 w_rear = w; // trains needs to know the last car in the train, so they can add more in next loop
891 } while (v->type == VEH_TRAIN && (v = v->GetNextVehicle()) != nullptr);
893 if ((flags & DC_EXEC) && v_front->type == VEH_TRAIN) {
894 /* for trains this needs to be the front engine due to the callback function */
895 new_veh_id = w_front->index;
898 if (flags & DC_EXEC) {
899 /* Cloned vehicles belong to the same group */
900 Command<CMD_ADD_VEHICLE_GROUP>::Do(flags, v_front->group_id, w_front->index, false);
904 /* Take care of refitting. */
905 w = w_front;
906 v = v_front;
908 /* Both building and refitting are influenced by newgrf callbacks, which
909 * makes it impossible to accurately estimate the cloning costs. In
910 * particular, it is possible for engines of the same type to be built with
911 * different numbers of articulated parts, so when refitting we have to
912 * loop over real vehicles first, and then the articulated parts of those
913 * vehicles in a different loop. */
914 do {
915 do {
916 if (flags & DC_EXEC) {
917 assert(w != nullptr);
919 /* Find out what's the best sub type */
920 byte subtype = GetBestFittingSubType(v, w, v->cargo_type);
921 if (w->cargo_type != v->cargo_type || w->cargo_subtype != subtype) {
922 CommandCost cost = std::get<0>(Command<CMD_REFIT_VEHICLE>::Do(flags, w->index, v->cargo_type, subtype, false, true, 0));
923 if (cost.Succeeded()) total_cost.AddCost(cost);
926 if (w->IsGroundVehicle() && w->HasArticulatedPart()) {
927 w = w->GetNextArticulatedPart();
928 } else {
929 break;
931 } else {
932 const Engine *e = v->GetEngine();
933 CargoID initial_cargo = (e->CanCarryCargo() ? e->GetDefaultCargoType() : (CargoID)CT_INVALID);
935 if (v->cargo_type != initial_cargo && initial_cargo != CT_INVALID) {
936 bool dummy;
937 total_cost.AddCost(GetRefitCost(nullptr, v->engine_type, v->cargo_type, v->cargo_subtype, &dummy));
941 if (v->IsGroundVehicle() && v->HasArticulatedPart()) {
942 v = v->GetNextArticulatedPart();
943 } else {
944 break;
946 } while (v != nullptr);
948 if ((flags & DC_EXEC) && v->type == VEH_TRAIN) w = w->GetNextVehicle();
949 } while (v->type == VEH_TRAIN && (v = v->GetNextVehicle()) != nullptr);
951 if (flags & DC_EXEC) {
953 * Set the orders of the vehicle. Cannot do it earlier as we need
954 * the vehicle refitted before doing this, otherwise the moved
955 * cargo types might not match (passenger vs non-passenger)
957 CommandCost result = Command<CMD_CLONE_ORDER>::Do(flags, (share_orders ? CO_SHARE : CO_COPY), w_front->index, v_front->index);
958 if (result.Failed()) {
959 /* The vehicle has already been bought, so now it must be sold again. */
960 Command<CMD_SELL_VEHICLE>::Do(flags, w_front->index, true, false, INVALID_CLIENT_ID);
961 return { total_cost, INVALID_VEHICLE };
964 /* Now clone the vehicle's name, if it has one. */
965 if (!v_front->name.empty()) CloneVehicleName(v_front, w_front);
967 /* Since we can't estimate the cost of cloning a vehicle accurately we must
968 * check whether the company has enough money manually. */
969 if (!CheckCompanyHasMoney(total_cost)) {
970 /* The vehicle has already been bought, so now it must be sold again. */
971 Command<CMD_SELL_VEHICLE>::Do(flags, w_front->index, true, false, INVALID_CLIENT_ID);
972 return { total_cost, INVALID_VEHICLE };
976 return { total_cost, new_veh_id };
980 * Send all vehicles of type to depots
981 * @param flags the flags used for DoCommand()
982 * @param service should the vehicles only get service in the depots
983 * @param vli identifier of the vehicle list
984 * @return 0 for success and CMD_ERROR if no vehicle is able to go to depot
986 static CommandCost SendAllVehiclesToDepot(DoCommandFlag flags, bool service, const VehicleListIdentifier &vli)
988 VehicleList list;
990 if (!GenerateVehicleSortList(&list, vli)) return CMD_ERROR;
992 /* Send all the vehicles to a depot */
993 bool had_success = false;
994 for (uint i = 0; i < list.size(); i++) {
995 const Vehicle *v = list[i];
996 CommandCost ret = Command<CMD_SEND_VEHICLE_TO_DEPOT>::Do(flags, v->index, (service ? DepotCommand::Service : DepotCommand::None) | DepotCommand::DontCancel, {});
998 if (ret.Succeeded()) {
999 had_success = true;
1001 /* Return 0 if DC_EXEC is not set this is a valid goto depot command)
1002 * In this case we know that at least one vehicle can be sent to a depot
1003 * and we will issue the command. We can now safely quit the loop, knowing
1004 * it will succeed at least once. With DC_EXEC we really need to send them to the depot */
1005 if (!(flags & DC_EXEC)) break;
1009 return had_success ? CommandCost() : CMD_ERROR;
1013 * Send a vehicle to the depot.
1014 * @param flags for command type
1015 * @param veh_id vehicle ID to send to the depot
1016 * @param depot_cmd DEPOT_ flags (see vehicle_type.h)
1017 * @param vli VehicleListIdentifier.
1018 * @return the cost of this operation or an error
1020 CommandCost CmdSendVehicleToDepot(DoCommandFlag flags, VehicleID veh_id, DepotCommand depot_cmd, const VehicleListIdentifier &vli)
1022 if ((depot_cmd & DepotCommand::MassSend) != DepotCommand::None) {
1023 /* Mass goto depot requested */
1024 if (!vli.Valid()) return CMD_ERROR;
1025 return SendAllVehiclesToDepot(flags, (depot_cmd & DepotCommand::Service) != DepotCommand::None, vli);
1028 Vehicle *v = Vehicle::GetIfValid(veh_id);
1029 if (v == nullptr) return CMD_ERROR;
1030 if (!v->IsPrimaryVehicle()) return CMD_ERROR;
1032 return v->SendToDepot(flags, depot_cmd);
1036 * Give a custom name to your vehicle
1037 * @param flags type of operation
1038 * @param veh_id vehicle ID to name
1039 * @param text the new name or an empty string when resetting to the default
1040 * @return the cost of this operation or an error
1042 CommandCost CmdRenameVehicle(DoCommandFlag flags, VehicleID veh_id, const std::string &text)
1044 Vehicle *v = Vehicle::GetIfValid(veh_id);
1045 if (v == nullptr || !v->IsPrimaryVehicle()) return CMD_ERROR;
1047 CommandCost ret = CheckOwnership(v->owner);
1048 if (ret.Failed()) return ret;
1050 bool reset = text.empty();
1052 if (!reset) {
1053 if (Utf8StringLength(text) >= MAX_LENGTH_VEHICLE_NAME_CHARS) return CMD_ERROR;
1054 if (!(flags & DC_AUTOREPLACE) && !IsUniqueVehicleName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1057 if (flags & DC_EXEC) {
1058 if (reset) {
1059 v->name.clear();
1060 } else {
1061 v->name = text;
1063 InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 1);
1064 MarkWholeScreenDirty();
1067 return CommandCost();
1072 * Change the service interval of a vehicle
1073 * @param flags type of operation
1074 * @param veh_id vehicle ID that is being service-interval-changed
1075 * @param serv_int new service interval
1076 * @param is_custom service interval is custom flag
1077 * @param is_percent service interval is percentage flag
1078 * @return the cost of this operation or an error
1080 CommandCost CmdChangeServiceInt(DoCommandFlag flags, VehicleID veh_id, uint16 serv_int, bool is_custom, bool is_percent)
1082 Vehicle *v = Vehicle::GetIfValid(veh_id);
1083 if (v == nullptr || !v->IsPrimaryVehicle()) return CMD_ERROR;
1085 CommandCost ret = CheckOwnership(v->owner);
1086 if (ret.Failed()) return ret;
1088 const Company *company = Company::Get(v->owner);
1089 is_percent = is_custom ? is_percent : company->settings.vehicle.servint_ispercent;
1091 if (is_custom) {
1092 if (serv_int != GetServiceIntervalClamped(serv_int, is_percent)) return CMD_ERROR;
1093 } else {
1094 serv_int = CompanyServiceInterval(company, v->type);
1097 if (flags & DC_EXEC) {
1098 v->SetServiceInterval(serv_int);
1099 v->SetServiceIntervalIsCustom(is_custom);
1100 v->SetServiceIntervalIsPercent(is_percent);
1101 SetWindowDirty(WC_VEHICLE_DETAILS, v->index);
1104 return CommandCost();