OpenTTD
vehicle_cmd.cpp
Go to the documentation of this file.
1 /* $Id: vehicle_cmd.cpp 26509 2014-04-25 15:40:32Z rubidium $ */
2 
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  */
9 
12 #include "stdafx.h"
13 #include "roadveh.h"
14 #include "news_func.h"
15 #include "airport.h"
16 #include "cmd_helper.h"
17 #include "command_func.h"
18 #include "company_func.h"
19 #include "train.h"
20 #include "aircraft.h"
21 #include "newgrf_text.h"
22 #include "vehicle_func.h"
23 #include "string_func.h"
24 #include "depot_map.h"
25 #include "vehiclelist.h"
26 #include "engine_func.h"
27 #include "articulated_vehicles.h"
28 #include "autoreplace_gui.h"
29 #include "group.h"
30 #include "order_backup.h"
31 #include "ship.h"
32 #include "newgrf.h"
33 #include "company_base.h"
34 
35 #include "table/strings.h"
36 
37 #include "safeguards.h"
38 
39 /* Tables used in vehicle.h to find the right command for a certain vehicle type */
40 const uint32 _veh_build_proc_table[] = {
41  CMD_BUILD_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_TRAIN),
42  CMD_BUILD_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_ROAD_VEHICLE),
43  CMD_BUILD_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_SHIP),
44  CMD_BUILD_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_AIRCRAFT),
45 };
46 
47 const uint32 _veh_sell_proc_table[] = {
48  CMD_SELL_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_SELL_TRAIN),
49  CMD_SELL_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_SELL_ROAD_VEHICLE),
50  CMD_SELL_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_SELL_SHIP),
51  CMD_SELL_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_SELL_AIRCRAFT),
52 };
53 
54 const uint32 _veh_refit_proc_table[] = {
55  CMD_REFIT_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_REFIT_TRAIN),
56  CMD_REFIT_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_REFIT_ROAD_VEHICLE),
57  CMD_REFIT_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_REFIT_SHIP),
58  CMD_REFIT_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_REFIT_AIRCRAFT),
59 };
60 
61 const uint32 _send_to_depot_proc_table[] = {
62  CMD_SEND_VEHICLE_TO_DEPOT | CMD_MSG(STR_ERROR_CAN_T_SEND_TRAIN_TO_DEPOT),
63  CMD_SEND_VEHICLE_TO_DEPOT | CMD_MSG(STR_ERROR_CAN_T_SEND_ROAD_VEHICLE_TO_DEPOT),
64  CMD_SEND_VEHICLE_TO_DEPOT | CMD_MSG(STR_ERROR_CAN_T_SEND_SHIP_TO_DEPOT),
65  CMD_SEND_VEHICLE_TO_DEPOT | CMD_MSG(STR_ERROR_CAN_T_SEND_AIRCRAFT_TO_HANGAR),
66 };
67 
68 
69 CommandCost CmdBuildRailVehicle(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **v);
70 CommandCost CmdBuildRoadVehicle(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **v);
71 CommandCost CmdBuildShip (TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **v);
72 CommandCost CmdBuildAircraft (TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **v);
73 
85 CommandCost CmdBuildVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
86 {
87  /* Elementary check for valid location. */
88  if (!IsDepotTile(tile) || !IsTileOwner(tile, _current_company)) return CMD_ERROR;
89 
90  VehicleType type = GetDepotVehicleType(tile);
91 
92  /* Validate the engine type. */
93  EngineID eid = GB(p1, 0, 16);
94  if (!IsEngineBuildable(eid, type, _current_company)) return_cmd_error(STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE + type);
95 
96  const Engine *e = Engine::Get(eid);
98 
99  /* Engines without valid cargo should not be available */
100  if (e->GetDefaultCargoType() == CT_INVALID) return CMD_ERROR;
101 
102  /* Check whether the number of vehicles we need to build can be built according to pool space. */
103  uint num_vehicles;
104  switch (type) {
105  case VEH_TRAIN: num_vehicles = (e->u.rail.railveh_type == RAILVEH_MULTIHEAD ? 2 : 1) + CountArticulatedParts(eid, false); break;
106  case VEH_ROAD: num_vehicles = 1 + CountArticulatedParts(eid, false); break;
107  case VEH_SHIP: num_vehicles = 1; break;
108  case VEH_AIRCRAFT: num_vehicles = e->u.air.subtype & AIR_CTOL ? 2 : 3; break;
109  default: NOT_REACHED(); // Safe due to IsDepotTile()
110  }
111  if (!Vehicle::CanAllocateItem(num_vehicles)) return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
112 
113  /* Check whether we can allocate a unit number. Autoreplace does not allocate
114  * an unit number as it will (always) reuse the one of the replaced vehicle
115  * and (train) wagons don't have an unit number in any scenario. */
116  UnitID unit_num = (flags & DC_AUTOREPLACE || (type == VEH_TRAIN && e->u.rail.railveh_type == RAILVEH_WAGON)) ? 0 : GetFreeUnitNumber(type);
117  if (unit_num == UINT16_MAX) return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
118 
119  Vehicle *v;
120  switch (type) {
121  case VEH_TRAIN: value.AddCost(CmdBuildRailVehicle(tile, flags, e, GB(p1, 16, 16), &v)); break;
122  case VEH_ROAD: value.AddCost(CmdBuildRoadVehicle(tile, flags, e, GB(p1, 16, 16), &v)); break;
123  case VEH_SHIP: value.AddCost(CmdBuildShip (tile, flags, e, GB(p1, 16, 16), &v)); break;
124  case VEH_AIRCRAFT: value.AddCost(CmdBuildAircraft (tile, flags, e, GB(p1, 16, 16), &v)); break;
125  default: NOT_REACHED(); // Safe due to IsDepotTile()
126  }
127 
128  if (value.Succeeded() && flags & DC_EXEC) {
129  v->unitnumber = unit_num;
130  v->value = value.GetCost();
131 
135  if (IsLocalCompany()) {
136  InvalidateAutoreplaceWindow(v->engine_type, v->group_id); // updates the auto replace window (must be called before incrementing num_engines)
137  }
138 
141 
142  if (v->IsPrimaryVehicle()) {
144  OrderBackup::Restore(v, p2);
145  }
146  }
147 
148  return value;
149 }
150 
151 CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *v, uint16 data, uint32 user);
152 
165 CommandCost CmdSellVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
166 {
167  Vehicle *v = Vehicle::GetIfValid(GB(p1, 0, 20));
168  if (v == NULL) return CMD_ERROR;
169 
170  Vehicle *front = v->First();
171 
172  CommandCost ret = CheckOwnership(front->owner);
173  if (ret.Failed()) return ret;
174 
175  if (front->vehstatus & VS_CRASHED) return_cmd_error(STR_ERROR_VEHICLE_IS_DESTROYED);
176 
177  if (!front->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAIN_MUST_BE_STOPPED_INSIDE_DEPOT + front->type);
178 
179  /* Can we actually make the order backup, i.e. are there enough orders? */
180  if (p1 & MAKE_ORDER_BACKUP_FLAG &&
181  front->orders.list != NULL &&
182  !front->orders.list->IsShared() &&
184  /* Only happens in exceptional cases when there aren't enough orders anyhow.
185  * Thus it should be safe to just drop the orders in that case. */
186  p1 &= ~MAKE_ORDER_BACKUP_FLAG;
187  }
188 
189  if (v->type == VEH_TRAIN) {
190  ret = CmdSellRailWagon(flags, v, GB(p1, 20, 12), p2);
191  } else {
192  ret = CommandCost(EXPENSES_NEW_VEHICLES, -front->value);
193 
194  if (flags & DC_EXEC) {
195  if (front->IsPrimaryVehicle() && p1 & MAKE_ORDER_BACKUP_FLAG) OrderBackup::Backup(front, p2);
196  delete front;
197  }
198  }
199 
200  return ret;
201 }
202 
212 static int GetRefitCostFactor(const Vehicle *v, EngineID engine_type, CargoID new_cid, byte new_subtype, bool *auto_refit_allowed)
213 {
214  /* Prepare callback param with info about the new cargo type. */
215  const Engine *e = Engine::Get(engine_type);
216 
217  /* Is this vehicle a NewGRF vehicle? */
218  if (e->GetGRF() != NULL) {
219  const CargoSpec *cs = CargoSpec::Get(new_cid);
220  uint32 param1 = (cs->classes << 16) | (new_subtype << 8) | e->GetGRF()->cargo_map[new_cid];
221 
222  uint16 cb_res = GetVehicleCallback(CBID_VEHICLE_REFIT_COST, param1, 0, engine_type, v);
223  if (cb_res != CALLBACK_FAILED) {
224  *auto_refit_allowed = HasBit(cb_res, 14);
225  int factor = GB(cb_res, 0, 14);
226  if (factor >= 0x2000) factor -= 0x4000; // Treat as signed integer.
227  return factor;
228  }
229  }
230 
231  *auto_refit_allowed = e->info.refit_cost == 0;
232  return (v == NULL || v->cargo_type != new_cid) ? e->info.refit_cost : 0;
233 }
234 
244 static CommandCost GetRefitCost(const Vehicle *v, EngineID engine_type, CargoID new_cid, byte new_subtype, bool *auto_refit_allowed)
245 {
246  ExpensesType expense_type;
247  const Engine *e = Engine::Get(engine_type);
248  Price base_price;
249  int cost_factor = GetRefitCostFactor(v, engine_type, new_cid, new_subtype, auto_refit_allowed);
250  switch (e->type) {
251  case VEH_SHIP:
252  base_price = PR_BUILD_VEHICLE_SHIP;
253  expense_type = EXPENSES_SHIP_RUN;
254  break;
255 
256  case VEH_ROAD:
257  base_price = PR_BUILD_VEHICLE_ROAD;
258  expense_type = EXPENSES_ROADVEH_RUN;
259  break;
260 
261  case VEH_AIRCRAFT:
262  base_price = PR_BUILD_VEHICLE_AIRCRAFT;
263  expense_type = EXPENSES_AIRCRAFT_RUN;
264  break;
265 
266  case VEH_TRAIN:
267  base_price = (e->u.rail.railveh_type == RAILVEH_WAGON) ? PR_BUILD_VEHICLE_WAGON : PR_BUILD_VEHICLE_TRAIN;
268  cost_factor <<= 1;
269  expense_type = EXPENSES_TRAIN_RUN;
270  break;
271 
272  default: NOT_REACHED();
273  }
274  if (cost_factor < 0) {
275  return CommandCost(expense_type, -GetPrice(base_price, -cost_factor, e->GetGRF(), -10));
276  } else {
277  return CommandCost(expense_type, GetPrice(base_price, cost_factor, e->GetGRF(), -10));
278  }
279 }
280 
282 struct RefitResult {
284  uint capacity;
286  byte subtype;
287 };
288 
301 static CommandCost RefitVehicle(Vehicle *v, bool only_this, uint8 num_vehicles, CargoID new_cid, byte new_subtype, DoCommandFlag flags, bool auto_refit)
302 {
303  CommandCost cost(v->GetExpenseType(false));
304  uint total_capacity = 0;
305  uint total_mail_capacity = 0;
306  num_vehicles = num_vehicles == 0 ? UINT8_MAX : num_vehicles;
307 
308  VehicleSet vehicles_to_refit;
309  if (!only_this) {
310  GetVehicleSet(vehicles_to_refit, v, num_vehicles);
311  /* In this case, we need to check the whole chain. */
312  v = v->First();
313  }
314 
315  static SmallVector<RefitResult, 16> refit_result;
316  refit_result.Clear();
317 
319  byte actual_subtype = new_subtype;
320  for (; v != NULL; v = (only_this ? NULL : v->Next())) {
321  /* Reset actual_subtype for every new vehicle */
322  if (!v->IsArticulatedPart()) actual_subtype = new_subtype;
323 
324  if (v->type == VEH_TRAIN && !vehicles_to_refit.Contains(v->index) && !only_this) continue;
325 
326  const Engine *e = v->GetEngine();
327  if (!e->CanCarryCargo()) continue;
328 
329  /* If the vehicle is not refittable, or does not allow automatic refitting,
330  * count its capacity nevertheless if the cargo matches */
331  bool refittable = HasBit(e->info.refit_mask, new_cid) && (!auto_refit || HasBit(e->info.misc_flags, EF_AUTO_REFIT));
332  if (!refittable && v->cargo_type != new_cid) continue;
333 
334  /* Determine best fitting subtype if requested */
335  if (actual_subtype == 0xFF) {
336  actual_subtype = GetBestFittingSubType(v, v, new_cid);
337  }
338 
339  /* Back up the vehicle's cargo type */
340  CargoID temp_cid = v->cargo_type;
341  byte temp_subtype = v->cargo_subtype;
342  if (refittable) {
343  v->cargo_type = new_cid;
344  v->cargo_subtype = actual_subtype;
345  }
346 
347  uint16 mail_capacity = 0;
348  uint amount = e->DetermineCapacity(v, &mail_capacity);
349  total_capacity += amount;
350  /* mail_capacity will always be zero if the vehicle is not an aircraft. */
351  total_mail_capacity += mail_capacity;
352 
353  if (!refittable) continue;
354 
355  /* Restore the original cargo type */
356  v->cargo_type = temp_cid;
357  v->cargo_subtype = temp_subtype;
358 
359  bool auto_refit_allowed;
360  CommandCost refit_cost = GetRefitCost(v, v->engine_type, new_cid, actual_subtype, &auto_refit_allowed);
361  if (auto_refit && !auto_refit_allowed) {
362  /* Sorry, auto-refitting not allowed, subtract the cargo amount again from the total. */
363  total_capacity -= amount;
364  total_mail_capacity -= mail_capacity;
365 
366  if (v->cargo_type == new_cid) {
367  /* Add the old capacity nevertheless, if the cargo matches */
368  total_capacity += v->cargo_cap;
369  if (v->type == VEH_AIRCRAFT) total_mail_capacity += v->Next()->cargo_cap;
370  }
371  continue;
372  }
373  cost.AddCost(refit_cost);
374 
375  /* Record the refitting.
376  * Do not execute the refitting immediately, so DetermineCapacity and GetRefitCost do the same in test and exec run.
377  * (weird NewGRFs)
378  * Note:
379  * - If the capacity of vehicles depends on other vehicles in the chain, the actual capacity is
380  * set after RefitVehicle() via ConsistChanged() and friends. The estimation via _returned_refit_capacity will be wrong.
381  * - We have to call the refit cost callback with the pre-refit configuration of the chain because we want refit and
382  * autorefit to behave the same, and we need its result for auto_refit_allowed.
383  */
384  RefitResult *result = refit_result.Append();
385  result->v = v;
386  result->capacity = amount;
387  result->mail_capacity = mail_capacity;
388  result->subtype = actual_subtype;
389  }
390 
391  if (flags & DC_EXEC) {
392  /* Store the result */
393  for (RefitResult *result = refit_result.Begin(); result != refit_result.End(); result++) {
394  Vehicle *u = result->v;
395  u->refit_cap = (u->cargo_type == new_cid) ? min(result->capacity, u->refit_cap) : 0;
396  if (u->cargo.TotalCount() > u->refit_cap) u->cargo.Truncate(u->cargo.TotalCount() - u->refit_cap);
397  u->cargo_type = new_cid;
398  u->cargo_cap = result->capacity;
399  u->cargo_subtype = result->subtype;
400  if (u->type == VEH_AIRCRAFT) {
401  Vehicle *w = u->Next();
402  w->refit_cap = min(w->refit_cap, result->mail_capacity);
403  w->cargo_cap = result->mail_capacity;
404  if (w->cargo.TotalCount() > w->refit_cap) w->cargo.Truncate(w->cargo.TotalCount() - w->refit_cap);
405  }
406  }
407  }
408 
409  refit_result.Clear();
410  _returned_refit_capacity = total_capacity;
411  _returned_mail_refit_capacity = total_mail_capacity;
412  return cost;
413 }
414 
430 CommandCost CmdRefitVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
431 {
432  Vehicle *v = Vehicle::GetIfValid(p1);
433  if (v == NULL) return CMD_ERROR;
434 
435  /* Don't allow disasters and sparks and such to be refitted.
436  * We cannot check for IsPrimaryVehicle as autoreplace also refits in free wagon chains. */
438 
439  Vehicle *front = v->First();
440 
441  CommandCost ret = CheckOwnership(front->owner);
442  if (ret.Failed()) return ret;
443 
444  bool auto_refit = HasBit(p2, 6);
445  bool free_wagon = v->type == VEH_TRAIN && Train::From(front)->IsFreeWagon(); // used by autoreplace/renew
446 
447  /* Don't allow shadows and such to be refitted. */
448  if (v != front && (v->type == VEH_SHIP || v->type == VEH_AIRCRAFT)) return CMD_ERROR;
449  /* Allow auto-refitting only during loading and normal refitting only in a depot. */
450  if (!free_wagon && (!auto_refit || !front->current_order.IsType(OT_LOADING)) && !front->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAIN_MUST_BE_STOPPED_INSIDE_DEPOT + front->type);
451  if (front->vehstatus & VS_CRASHED) return_cmd_error(STR_ERROR_VEHICLE_IS_DESTROYED);
452 
453  /* Check cargo */
454  CargoID new_cid = GB(p2, 0, 5);
455  byte new_subtype = GB(p2, 8, 8);
456  if (new_cid >= NUM_CARGO) return CMD_ERROR;
457 
458  /* For ships and aircrafts there is always only one. */
459  bool only_this = HasBit(p2, 7) || front->type == VEH_SHIP || front->type == VEH_AIRCRAFT;
460  uint8 num_vehicles = GB(p2, 16, 8);
461 
462  CommandCost cost = RefitVehicle(v, only_this, num_vehicles, new_cid, new_subtype, flags, auto_refit);
463 
464  if (flags & DC_EXEC) {
465  /* Update the cached variables */
466  switch (v->type) {
467  case VEH_TRAIN:
468  Train::From(front)->ConsistChanged(auto_refit ? CCF_AUTOREFIT : CCF_REFIT);
469  break;
470  case VEH_ROAD:
471  RoadVehUpdateCache(RoadVehicle::From(front), auto_refit);
473  break;
474 
475  case VEH_SHIP:
477  Ship::From(v)->UpdateCache();
478  break;
479 
480  case VEH_AIRCRAFT:
483  break;
484 
485  default: NOT_REACHED();
486  }
487  front->MarkDirty();
488 
489  if (!free_wagon) {
492  }
494  } else {
495  /* Always invalidate the cache; querycost might have filled it. */
497  }
498 
499  return cost;
500 }
501 
511 CommandCost CmdStartStopVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
512 {
513  /* Disable the effect of p2 bit 0, when DC_AUTOREPLACE is not set */
514  if ((flags & DC_AUTOREPLACE) == 0) SetBit(p2, 0);
515 
516  Vehicle *v = Vehicle::GetIfValid(p1);
517  if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
518 
519  CommandCost ret = CheckOwnership(v->owner);
520  if (ret.Failed()) return ret;
521 
522  if (v->vehstatus & VS_CRASHED) return_cmd_error(STR_ERROR_VEHICLE_IS_DESTROYED);
523 
524  switch (v->type) {
525  case VEH_TRAIN:
526  if ((v->vehstatus & VS_STOPPED) && Train::From(v)->gcache.cached_power == 0) return_cmd_error(STR_ERROR_TRAIN_START_NO_POWER);
527  break;
528 
529  case VEH_SHIP:
530  case VEH_ROAD:
531  break;
532 
533  case VEH_AIRCRAFT: {
534  Aircraft *a = Aircraft::From(v);
535  /* cannot stop airplane when in flight, or when taking off / landing */
536  if (!(v->vehstatus & VS_CRASHED) && a->state >= STARTTAKEOFF && a->state < TERM7) return_cmd_error(STR_ERROR_AIRCRAFT_IS_IN_FLIGHT);
537  break;
538  }
539 
540  default: return CMD_ERROR;
541  }
542 
543  if (HasBit(p2, 0)) {
544  /* Check if this vehicle can be started/stopped. Failure means 'allow'. */
545  uint16 callback = GetVehicleCallback(CBID_VEHICLE_START_STOP_CHECK, 0, 0, v->engine_type, v);
546  StringID error = STR_NULL;
547  if (callback != CALLBACK_FAILED) {
548  if (v->GetGRF()->grf_version < 8) {
549  /* 8 bit result 0xFF means 'allow' */
550  if (callback < 0x400 && GB(callback, 0, 8) != 0xFF) error = GetGRFStringID(v->GetGRFID(), 0xD000 + callback);
551  } else {
552  if (callback < 0x400) {
553  error = GetGRFStringID(v->GetGRFID(), 0xD000 + callback);
554  } else {
555  switch (callback) {
556  case 0x400: // allow
557  break;
558 
559  default: // unknown reason -> disallow
560  error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
561  break;
562  }
563  }
564  }
565  }
566  if (error != STR_NULL) return_cmd_error(error);
567  }
568 
569  if (flags & DC_EXEC) {
570  if (v->IsStoppedInDepot() && (flags & DC_AUTOREPLACE) == 0) DeleteVehicleNews(p1, STR_NEWS_TRAIN_IS_WAITING + v->type);
571 
572  v->vehstatus ^= VS_STOPPED;
573  if (v->type != VEH_TRAIN) v->cur_speed = 0; // trains can stop 'slowly'
574  v->MarkDirty();
578  }
579  return CommandCost();
580 }
581 
593 CommandCost CmdMassStartStopVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
594 {
595  VehicleList list;
596  bool do_start = HasBit(p1, 0);
597  bool vehicle_list_window = HasBit(p1, 1);
598 
600  if (!vli.Unpack(p2)) return CMD_ERROR;
602 
603  if (vehicle_list_window) {
604  if (!GenerateVehicleSortList(&list, vli)) return CMD_ERROR;
605  } else {
606  /* Get the list of vehicles in the depot */
607  BuildDepotVehicleList(vli.vtype, tile, &list, NULL);
608  }
609 
610  for (uint i = 0; i < list.Length(); i++) {
611  const Vehicle *v = list[i];
612 
613  if (!!(v->vehstatus & VS_STOPPED) != do_start) continue;
614 
615  if (!vehicle_list_window && !v->IsChainInDepot()) continue;
616 
617  /* Just try and don't care if some vehicle's can't be stopped. */
618  DoCommand(tile, v->index, 0, flags, CMD_START_STOP_VEHICLE);
619  }
620 
621  return CommandCost();
622 }
623 
633 CommandCost CmdDepotSellAllVehicles(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
634 {
635  VehicleList list;
636 
638  VehicleType vehicle_type = Extract<VehicleType, 0, 3>(p1);
639 
640  if (!IsCompanyBuildableVehicleType(vehicle_type)) return CMD_ERROR;
641 
642  uint sell_command = GetCmdSellVeh(vehicle_type);
643 
644  /* Get the list of vehicles in the depot */
645  BuildDepotVehicleList(vehicle_type, tile, &list, &list);
646 
647  CommandCost last_error = CMD_ERROR;
648  bool had_success = false;
649  for (uint i = 0; i < list.Length(); i++) {
650  CommandCost ret = DoCommand(tile, list[i]->index | (1 << 20), 0, flags, sell_command);
651  if (ret.Succeeded()) {
652  cost.AddCost(ret);
653  had_success = true;
654  } else {
655  last_error = ret;
656  }
657  }
658 
659  return had_success ? cost : last_error;
660 }
661 
671 CommandCost CmdDepotMassAutoReplace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
672 {
673  VehicleList list;
675  VehicleType vehicle_type = Extract<VehicleType, 0, 3>(p1);
676 
677  if (!IsCompanyBuildableVehicleType(vehicle_type)) return CMD_ERROR;
678  if (!IsDepotTile(tile) || !IsTileOwner(tile, _current_company)) return CMD_ERROR;
679 
680  /* Get the list of vehicles in the depot */
681  BuildDepotVehicleList(vehicle_type, tile, &list, &list, true);
682 
683  for (uint i = 0; i < list.Length(); i++) {
684  const Vehicle *v = list[i];
685 
686  /* Ensure that the vehicle completely in the depot */
687  if (!v->IsChainInDepot()) continue;
688 
689  CommandCost ret = DoCommand(0, v->index, 0, flags, CMD_AUTOREPLACE_VEHICLE);
690 
691  if (ret.Succeeded()) cost.AddCost(ret);
692  }
693  return cost;
694 }
695 
701 static bool IsUniqueVehicleName(const char *name)
702 {
703  const Vehicle *v;
704 
705  FOR_ALL_VEHICLES(v) {
706  if (v->name != NULL && strcmp(v->name, name) == 0) return false;
707  }
708 
709  return true;
710 }
711 
717 static void CloneVehicleName(const Vehicle *src, Vehicle *dst)
718 {
719  char buf[256];
720 
721  /* Find the position of the first digit in the last group of digits. */
722  size_t number_position;
723  for (number_position = strlen(src->name); number_position > 0; number_position--) {
724  /* The design of UTF-8 lets this work simply without having to check
725  * for UTF-8 sequences. */
726  if (src->name[number_position - 1] < '0' || src->name[number_position - 1] > '9') break;
727  }
728 
729  /* Format buffer and determine starting number. */
730  int num;
731  byte padding = 0;
732  if (number_position == strlen(src->name)) {
733  /* No digit at the end, so start at number 2. */
734  strecpy(buf, src->name, lastof(buf));
735  strecat(buf, " ", lastof(buf));
736  number_position = strlen(buf);
737  num = 2;
738  } else {
739  /* Found digits, parse them and start at the next number. */
740  strecpy(buf, src->name, lastof(buf));
741  buf[number_position] = '\0';
742  char *endptr;
743  num = strtol(&src->name[number_position], &endptr, 10) + 1;
744  padding = endptr - &src->name[number_position];
745  }
746 
747  /* Check if this name is already taken. */
748  for (int max_iterations = 1000; max_iterations > 0; max_iterations--, num++) {
749  /* Attach the number to the temporary name. */
750  seprintf(&buf[number_position], lastof(buf), "%0*d", padding, num);
751 
752  /* Check the name is unique. */
753  if (IsUniqueVehicleName(buf)) {
754  dst->name = stredup(buf);
755  break;
756  }
757  }
758 
759  /* All done. If we didn't find a name, it'll just use its default. */
760 }
761 
771 CommandCost CmdCloneVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
772 {
774 
775  Vehicle *v = Vehicle::GetIfValid(p1);
776  if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
777  Vehicle *v_front = v;
778  Vehicle *w = NULL;
779  Vehicle *w_front = NULL;
780  Vehicle *w_rear = NULL;
781 
782  /*
783  * v_front is the front engine in the original vehicle
784  * v is the car/vehicle of the original vehicle that is currently being copied
785  * w_front is the front engine of the cloned vehicle
786  * w is the car/vehicle currently being cloned
787  * w_rear is the rear end of the cloned train. It's used to add more cars and is only used by trains
788  */
789 
790  CommandCost ret = CheckOwnership(v->owner);
791  if (ret.Failed()) return ret;
792 
793  if (v->type == VEH_TRAIN && (!v->IsFrontEngine() || Train::From(v)->crash_anim_pos >= 4400)) return CMD_ERROR;
794 
795  /* check that we can allocate enough vehicles */
796  if (!(flags & DC_EXEC)) {
797  int veh_counter = 0;
798  do {
799  veh_counter++;
800  } while ((v = v->Next()) != NULL);
801 
802  if (!Vehicle::CanAllocateItem(veh_counter)) {
803  return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
804  }
805  }
806 
807  v = v_front;
808 
809  do {
810  if (v->type == VEH_TRAIN && Train::From(v)->IsRearDualheaded()) {
811  /* we build the rear ends of multiheaded trains with the front ones */
812  continue;
813  }
814 
815  /* In case we're building a multi headed vehicle and the maximum number of
816  * vehicles is almost reached (e.g. max trains - 1) not all vehicles would
817  * be cloned. When the non-primary engines were build they were seen as
818  * 'new' vehicles whereas they would immediately be joined with a primary
819  * engine. This caused the vehicle to be not build as 'the limit' had been
820  * reached, resulting in partially build vehicles and such. */
821  DoCommandFlag build_flags = flags;
822  if ((flags & DC_EXEC) && !v->IsPrimaryVehicle()) build_flags |= DC_AUTOREPLACE;
823 
824  CommandCost cost = DoCommand(tile, v->engine_type | (1 << 16), 0, build_flags, GetCmdBuildVeh(v));
825 
826  if (cost.Failed()) {
827  /* Can't build a part, then sell the stuff we already made; clear up the mess */
828  if (w_front != NULL) DoCommand(w_front->tile, w_front->index | (1 << 20), 0, flags, GetCmdSellVeh(w_front));
829  return cost;
830  }
831 
832  total_cost.AddCost(cost);
833 
834  if (flags & DC_EXEC) {
835  w = Vehicle::Get(_new_vehicle_id);
836 
837  if (v->type == VEH_TRAIN && HasBit(Train::From(v)->flags, VRF_REVERSE_DIRECTION)) {
839  }
840 
841  if (v->type == VEH_TRAIN && !v->IsFrontEngine()) {
842  /* this s a train car
843  * add this unit to the end of the train */
844  CommandCost result = DoCommand(0, w->index | 1 << 20, w_rear->index, flags, CMD_MOVE_RAIL_VEHICLE);
845  if (result.Failed()) {
846  /* The train can't be joined to make the same consist as the original.
847  * Sell what we already made (clean up) and return an error. */
848  DoCommand(w_front->tile, w_front->index | 1 << 20, 0, flags, GetCmdSellVeh(w_front));
849  DoCommand(w_front->tile, w->index | 1 << 20, 0, flags, GetCmdSellVeh(w));
850  return result; // return error and the message returned from CMD_MOVE_RAIL_VEHICLE
851  }
852  } else {
853  /* this is a front engine or not a train. */
854  w_front = w;
856  w->SetServiceIntervalIsCustom(v->ServiceIntervalIsCustom());
857  w->SetServiceIntervalIsPercent(v->ServiceIntervalIsPercent());
858  }
859  w_rear = w; // trains needs to know the last car in the train, so they can add more in next loop
860  }
861  } while (v->type == VEH_TRAIN && (v = v->GetNextVehicle()) != NULL);
862 
863  if ((flags & DC_EXEC) && v_front->type == VEH_TRAIN) {
864  /* for trains this needs to be the front engine due to the callback function */
865  _new_vehicle_id = w_front->index;
866  }
867 
868  if (flags & DC_EXEC) {
869  /* Cloned vehicles belong to the same group */
870  DoCommand(0, v_front->group_id, w_front->index, flags, CMD_ADD_VEHICLE_GROUP);
871  }
872 
873 
874  /* Take care of refitting. */
875  w = w_front;
876  v = v_front;
877 
878  /* Both building and refitting are influenced by newgrf callbacks, which
879  * makes it impossible to accurately estimate the cloning costs. In
880  * particular, it is possible for engines of the same type to be built with
881  * different numbers of articulated parts, so when refitting we have to
882  * loop over real vehicles first, and then the articulated parts of those
883  * vehicles in a different loop. */
884  do {
885  do {
886  if (flags & DC_EXEC) {
887  assert(w != NULL);
888 
889  /* Find out what's the best sub type */
890  byte subtype = GetBestFittingSubType(v, w, v->cargo_type);
891  if (w->cargo_type != v->cargo_type || w->cargo_subtype != subtype) {
892  CommandCost cost = DoCommand(0, w->index, v->cargo_type | 1U << 7 | (subtype << 8), flags, GetCmdRefitVeh(v));
893  if (cost.Succeeded()) total_cost.AddCost(cost);
894  }
895 
896  if (w->IsGroundVehicle() && w->HasArticulatedPart()) {
897  w = w->GetNextArticulatedPart();
898  } else {
899  break;
900  }
901  } else {
902  const Engine *e = v->GetEngine();
903  CargoID initial_cargo = (e->CanCarryCargo() ? e->GetDefaultCargoType() : (CargoID)CT_INVALID);
904 
905  if (v->cargo_type != initial_cargo && initial_cargo != CT_INVALID) {
906  bool dummy;
907  total_cost.AddCost(GetRefitCost(NULL, v->engine_type, v->cargo_type, v->cargo_subtype, &dummy));
908  }
909  }
910 
911  if (v->IsGroundVehicle() && v->HasArticulatedPart()) {
912  v = v->GetNextArticulatedPart();
913  } else {
914  break;
915  }
916  } while (v != NULL);
917 
918  if ((flags & DC_EXEC) && v->type == VEH_TRAIN) w = w->GetNextVehicle();
919  } while (v->type == VEH_TRAIN && (v = v->GetNextVehicle()) != NULL);
920 
921  if (flags & DC_EXEC) {
922  /*
923  * Set the orders of the vehicle. Cannot do it earlier as we need
924  * the vehicle refitted before doing this, otherwise the moved
925  * cargo types might not match (passenger vs non-passenger)
926  */
927  DoCommand(0, w_front->index | (p2 & 1 ? CO_SHARE : CO_COPY) << 30, v_front->index, flags, CMD_CLONE_ORDER);
928 
929  /* Now clone the vehicle's name, if it has one. */
930  if (v_front->name != NULL) CloneVehicleName(v_front, w_front);
931  }
932 
933  /* Since we can't estimate the cost of cloning a vehicle accurately we must
934  * check whether the company has enough money manually. */
935  if (!CheckCompanyHasMoney(total_cost)) {
936  if (flags & DC_EXEC) {
937  /* The vehicle has already been bought, so now it must be sold again. */
938  DoCommand(w_front->tile, w_front->index | 1 << 20, 0, flags, GetCmdSellVeh(w_front));
939  }
940  return total_cost;
941  }
942 
943  return total_cost;
944 }
945 
954 {
955  VehicleList list;
956 
957  if (!GenerateVehicleSortList(&list, vli)) return CMD_ERROR;
958 
959  /* Send all the vehicles to a depot */
960  bool had_success = false;
961  for (uint i = 0; i < list.Length(); i++) {
962  const Vehicle *v = list[i];
963  CommandCost ret = DoCommand(v->tile, v->index | (service ? DEPOT_SERVICE : 0U) | DEPOT_DONT_CANCEL, 0, flags, GetCmdSendToDepot(vli.vtype));
964 
965  if (ret.Succeeded()) {
966  had_success = true;
967 
968  /* Return 0 if DC_EXEC is not set this is a valid goto depot command)
969  * In this case we know that at least one vehicle can be sent to a depot
970  * and we will issue the command. We can now safely quit the loop, knowing
971  * it will succeed at least once. With DC_EXEC we really need to send them to the depot */
972  if (!(flags & DC_EXEC)) break;
973  }
974  }
975 
976  return had_success ? CommandCost() : CMD_ERROR;
977 }
978 
990 CommandCost CmdSendVehicleToDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
991 {
992  if (p1 & DEPOT_MASS_SEND) {
993  /* Mass goto depot requested */
995  if (!vli.Unpack(p2)) return CMD_ERROR;
996  return SendAllVehiclesToDepot(flags, (p1 & DEPOT_SERVICE) != 0, vli);
997  }
998 
999  Vehicle *v = Vehicle::GetIfValid(GB(p1, 0, 20));
1000  if (v == NULL) return CMD_ERROR;
1001  if (!v->IsPrimaryVehicle()) return CMD_ERROR;
1002 
1003  return v->SendToDepot(flags, (DepotCommand)(p1 & DEPOT_COMMAND_MASK));
1004 }
1005 
1015 CommandCost CmdRenameVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1016 {
1017  Vehicle *v = Vehicle::GetIfValid(p1);
1018  if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
1019 
1020  CommandCost ret = CheckOwnership(v->owner);
1021  if (ret.Failed()) return ret;
1022 
1023  bool reset = StrEmpty(text);
1024 
1025  if (!reset) {
1027  if (!(flags & DC_AUTOREPLACE) && !IsUniqueVehicleName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1028  }
1029 
1030  if (flags & DC_EXEC) {
1031  free(v->name);
1032  v->name = reset ? NULL : stredup(text);
1035  }
1036 
1037  return CommandCost();
1038 }
1039 
1040 
1053 CommandCost CmdChangeServiceInt(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1054 {
1055  Vehicle *v = Vehicle::GetIfValid(p1);
1056  if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
1057 
1058  CommandCost ret = CheckOwnership(v->owner);
1059  if (ret.Failed()) return ret;
1060 
1061  const Company *company = Company::Get(v->owner);
1062  bool iscustom = HasBit(p2, 16);
1063  bool ispercent = iscustom ? HasBit(p2, 17) : company->settings.vehicle.servint_ispercent;
1064 
1065  uint16 serv_int;
1066  if (iscustom) {
1067  serv_int = GB(p2, 0, 16);
1068  if (serv_int != GetServiceIntervalClamped(serv_int, ispercent)) return CMD_ERROR;
1069  } else {
1070  serv_int = CompanyServiceInterval(company, v->type);
1071  }
1072 
1073  if (flags & DC_EXEC) {
1074  v->SetServiceInterval(serv_int);
1075  v->SetServiceIntervalIsCustom(iscustom);
1076  v->SetServiceIntervalIsPercent(ispercent);
1078  }
1079 
1080  return CommandCost();
1081 }