# vehicle_cmd.cpp

Go to the documentation of this file.

    00001 /* $Id: vehicle_cmd.cpp 17517 2009-09-12 20:59:34Z rubidium $ */
    00002
    00005 #include "stdafx.h"
    00006 #include "roadveh.h"
    00007 #include "gfx_func.h"
    00008 #include "news_func.h"
    00009 #include "command_func.h"
    00010 #include "company_func.h"
    00011 #include "vehicle_gui.h"
    00012 #include "train.h"
    00013 #include "newgrf_engine.h"
    00014 #include "newgrf_text.h"
    00015 #include "functions.h"
    00016 #include "window_func.h"
    00017 #include "vehicle_func.h"
    00018 #include "string_func.h"
    00019 #include "depot_map.h"
    00020 #include "vehiclelist.h"
    00021
    00022 #include "table/strings.h"
    00023
    00024 /* Tables used in vehicle.h to find the right command for a certain vehicle type */
    00025 const uint32 _veh_build_proc_table[] = {
    00026   CMD_BUILD_RAIL_VEHICLE,
    00027   CMD_BUILD_ROAD_VEH,
    00028   CMD_BUILD_SHIP,
    00029   CMD_BUILD_AIRCRAFT,
    00030 };
    00031 const uint32 _veh_sell_proc_table[] = {
    00032   CMD_SELL_RAIL_WAGON,
    00033   CMD_SELL_ROAD_VEH,
    00034   CMD_SELL_SHIP,
    00035   CMD_SELL_AIRCRAFT,
    00036 };
    00037
    00038 const uint32 _veh_refit_proc_table[] = {
    00039   CMD_REFIT_RAIL_VEHICLE,
    00040   CMD_REFIT_ROAD_VEH,
    00041   CMD_REFIT_SHIP,
    00042   CMD_REFIT_AIRCRAFT,
    00043 };
    00044
    00045 const uint32 _send_to_depot_proc_table[] = {
    00046   CMD_SEND_TRAIN_TO_DEPOT,
    00047   CMD_SEND_ROADVEH_TO_DEPOT,
    00048   CMD_SEND_SHIP_TO_DEPOT,
    00049   CMD_SEND_AIRCRAFT_TO_HANGAR,
    00050 };
    00051
    00059 CommandCost CmdStartStopVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00060 {
    00061   /* Disable the effect of p2 bit 0, when DC_AUTOREPLACE is not set */
    00062   if ((flags & DC_AUTOREPLACE) == 0) SetBit(p2, 0);
    00063
    00064   if (!IsValidVehicleID(p1)) return CMD_ERROR;
    00065
    00066   Vehicle *v = GetVehicle(p1);
    00067
    00068   if (!CheckOwnership(v->owner)) return CMD_ERROR;
    00069   if (!v->IsPrimaryVehicle()) return CMD_ERROR;
    00070
    00071   switch (v->type) {
    00072     case VEH_TRAIN:
    00073       if (v->vehstatus & VS_STOPPED && v->u.rail.cached_power == 0) return_cmd_error(STR_TRAIN_START_NO_CATENARY);
    00074       break;
    00075
    00076     case VEH_SHIP:
    00077     case VEH_ROAD:
    00078       break;
    00079
    00080     case VEH_AIRCRAFT:
    00081       /* cannot stop airplane when in flight, or when taking off / landing */
    00082       if (v->u.air.state >= STARTTAKEOFF && v->u.air.state < TERM7) return_cmd_error(STR_A017_AIRCRAFT_IS_IN_FLIGHT);
    00083       break;
    00084
    00085     default: return CMD_ERROR;
    00086   }
    00087
    00088   /* Check if this vehicle can be started/stopped. The callback will fail or
    00089    * return 0xFF if it can. */
    00090   uint16 callback = GetVehicleCallback(CBID_VEHICLE_START_STOP_CHECK, 0, 0, v->engine_type, v);
    00091   if (callback != CALLBACK_FAILED && GB(callback, 0, 8) != 0xFF && HasBit(p2, 0)) {
    00092     StringID error = GetGRFStringID(GetEngineGRFID(v->engine_type), 0xD000 + callback);
    00093     return_cmd_error(error);
    00094   }
    00095
    00096   if (flags & DC_EXEC) {
    00097     static const StringID vehicle_waiting_in_depot[] = {
    00098       STR_8814_TRAIN_IS_WAITING_IN_DEPOT,
    00099       STR_9016_ROAD_VEHICLE_IS_WAITING,
    00100       STR_981C_SHIP_IS_WAITING_IN_DEPOT,
    00101       STR_A014_AIRCRAFT_IS_WAITING_IN,
    00102     };
    00103
    00104     static const WindowClass vehicle_list[] = {
    00105       WC_TRAINS_LIST,
    00106       WC_ROADVEH_LIST,
    00107       WC_SHIPS_LIST,
    00108       WC_AIRCRAFT_LIST,
    00109     };
    00110
    00111     if (v->IsStoppedInDepot() && (flags & DC_AUTOREPLACE) == 0) DeleteVehicleNews(p1, vehicle_waiting_in_depot[v->type]);
    00112
    00113     v->vehstatus ^= VS_STOPPED;
    00114     if (v->type != VEH_TRAIN) v->cur_speed = 0; // trains can stop 'slowly'
    00115     InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    00116     InvalidateWindow(WC_VEHICLE_DEPOT, v->tile);
    00117     InvalidateWindowClasses(vehicle_list[v->type]);
    00118   }
    00119   return CommandCost();
    00120 }
    00121
    00132 CommandCost CmdMassStartStopVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00133 {
    00134   VehicleList list;
    00135   CommandCost return_value = CMD_ERROR;
    00136   VehicleType vehicle_type = (VehicleType)GB(p2, 0, 5);
    00137   bool start_stop = HasBit(p2, 5);
    00138   bool vehicle_list_window = HasBit(p2, 6);
    00139
    00140   if (vehicle_list_window) {
    00141     uint32 id = p1;
    00142     uint16 window_type = p2 & VLW_MASK;
    00143
    00144     GenerateVehicleSortList(&list, vehicle_type, _current_company, id, window_type);
    00145   } else {
    00146     /* Get the list of vehicles in the depot */
    00147     BuildDepotVehicleList(vehicle_type, tile, &list, NULL);
    00148   }
    00149
    00150   for (uint i = 0; i < list.Length(); i++) {
    00151     const Vehicle *v = list[i];
    00152
    00153     if (!!(v->vehstatus & VS_STOPPED) != start_stop) continue;
    00154
    00155     if (!vehicle_list_window) {
    00156       if (vehicle_type == VEH_TRAIN) {
    00157         if (CheckTrainInDepot(v, false) == -1) continue;
    00158       } else {
    00159         if (!(v->vehstatus & VS_HIDDEN)) continue;
    00160       }
    00161     }
    00162
    00163     CommandCost ret = DoCommand(tile, v->index, 0, flags, CMD_START_STOP_VEHICLE);
    00164
    00165     if (CmdSucceeded(ret)) {
    00166       return_value = CommandCost();
    00167       /* We know that the command is valid for at least one vehicle.
    00168        * If we haven't set DC_EXEC, then there is no point in continueing because it will be valid */
    00169       if (!(flags & DC_EXEC)) break;
    00170     }
    00171   }
    00172
    00173   return return_value;
    00174 }
    00175
    00182 CommandCost CmdDepotSellAllVehicles(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00183 {
    00184   VehicleList list;
    00185
    00186   CommandCost cost(EXPENSES_NEW_VEHICLES);
    00187   uint sell_command;
    00188   VehicleType vehicle_type = (VehicleType)GB(p1, 0, 8);
    00189
    00190   switch (vehicle_type) {
    00191     case VEH_TRAIN:    sell_command = CMD_SELL_RAIL_WAGON; break;
    00192     case VEH_ROAD:     sell_command = CMD_SELL_ROAD_VEH;   break;
    00193     case VEH_SHIP:     sell_command = CMD_SELL_SHIP;       break;
    00194     case VEH_AIRCRAFT: sell_command = CMD_SELL_AIRCRAFT;   break;
    00195     default: return CMD_ERROR;
    00196   }
    00197
    00198   /* Get the list of vehicles in the depot */
    00199   BuildDepotVehicleList(vehicle_type, tile, &list, &list);
    00200
    00201   for (uint i = 0; i < list.Length(); i++) {
    00202     CommandCost ret = DoCommand(tile, list[i]->index, 1, flags, sell_command);
    00203     if (CmdSucceeded(ret)) cost.AddCost(ret);
    00204   }
    00205
    00206   if (cost.GetCost() == 0) return CMD_ERROR; // no vehicles to sell
    00207   return cost;
    00208 }
    00209
    00219 CommandCost CmdDepotMassAutoReplace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00220 {
    00221   VehicleList list;
    00222   CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES);
    00223   VehicleType vehicle_type = (VehicleType)GB(p1, 0, 8);
    00224   bool all_or_nothing = HasBit(p2, 0);
    00225
    00226   if (!IsDepotTile(tile) || !IsTileOwner(tile, _current_company)) return CMD_ERROR;
    00227
    00228   /* Get the list of vehicles in the depot */
    00229   BuildDepotVehicleList(vehicle_type, tile, &list, &list, true);
    00230
    00231   bool did_something = false;
    00232
    00233   for (uint i = 0; i < list.Length(); i++) {
    00234     Vehicle *v = (Vehicle*)list[i];
    00235
    00236     /* Ensure that the vehicle completely in the depot */
    00237     if (!v->IsInDepot()) continue;
    00238
    00239     CommandCost ret = DoCommand(0, v->index, 0, flags, CMD_AUTOREPLACE_VEHICLE);
    00240
    00241     if (CmdSucceeded(ret)) {
    00242       did_something = true;
    00243       cost.AddCost(ret);
    00244     } else {
    00245       if (ret.GetErrorMessage() != STR_AUTOREPLACE_NOTHING_TO_DO && all_or_nothing) {
    00246         /* We failed to replace a vehicle even though we set all or nothing.
    00247          * We should never reach this if DC_EXEC is set since then it should
    00248          * have failed the estimation guess. */
    00249         assert(!(flags & DC_EXEC));
    00250         /* Now we will have to return an error. */
    00251         return CMD_ERROR;
    00252       }
    00253     }
    00254   }
    00255
    00256   if (!did_something) {
    00257     /* Either we didn't replace anything or something went wrong.
    00258      * Either way we want to return an error and not execute this command. */
    00259     cost = CMD_ERROR;
    00260   }
    00261
    00262   return cost;
    00263 }
    00264
    00269 static bool IsUniqueVehicleName(const char *name)
    00270 {
    00271   const Vehicle *v;
    00272
    00273   FOR_ALL_VEHICLES(v) {
    00274     if (v->name != NULL && strcmp(v->name, name) == 0) return false;
    00275   }
    00276
    00277   return true;
    00278 }
    00279
    00284 static void CloneVehicleName(const Vehicle *src, Vehicle *dst)
    00285 {
    00286   char buf[256];
    00287
    00288   /* Find the position of the first digit in the last group of digits. */
    00289   size_t number_position;
    00290   for (number_position = strlen(src->name); number_position > 0; number_position--) {
    00291     /* The design of UTF-8 lets this work simply without having to check
    00292      * for UTF-8 sequences. */
    00293     if (src->name[number_position - 1] < '0' || src->name[number_position - 1] > '9') break;
    00294   }
    00295
    00296   /* Format buffer and determine starting number. */
    00297   int num;
    00298   if (number_position == strlen(src->name)) {
    00299     /* No digit at the end, so start at number 2. */
    00300     strecpy(buf, src->name, lastof(buf));
    00301     strecat(buf, " ", lastof(buf));
    00302     number_position = strlen(buf);
    00303     num = 2;
    00304   } else {
    00305     /* Found digits, parse them and start at the next number. */
    00306     strecpy(buf, src->name, lastof(buf));
    00307     buf[number_position] = '\0';
    00308     num = strtol(&src->name[number_position], NULL, 10) + 1;
    00309   }
    00310
    00311   /* Check if this name is already taken. */
    00312   for (int max_iterations = 1000; max_iterations > 0; max_iterations--, num++) {
    00313     /* Attach the number to the temporary name. */
    00314     seprintf(&buf[number_position], lastof(buf), "%d", num);
    00315
    00316     /* Check the name is unique. */
    00317     if (IsUniqueVehicleName(buf)) {
    00318       dst->name = strdup(buf);
    00319       break;
    00320     }
    00321   }
    00322
    00323   /* All done. If we didn't find a name, it'll just use its default. */
    00324 }
    00325
    00332 CommandCost CmdCloneVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00333 {
    00334   CommandCost total_cost(EXPENSES_NEW_VEHICLES);
    00335   uint32 build_argument = 2;
    00336
    00337   if (!IsValidVehicleID(p1)) return CMD_ERROR;
    00338
    00339   Vehicle *v = GetVehicle(p1);
    00340   Vehicle *v_front = v;
    00341   Vehicle *w = NULL;
    00342   Vehicle *w_front = NULL;
    00343   Vehicle *w_rear = NULL;
    00344
    00345   /*
    00346    * v_front is the front engine in the original vehicle
    00347    * v is the car/vehicle of the original vehicle, that is currently being copied
    00348    * w_front is the front engine of the cloned vehicle
    00349    * w is the car/vehicle currently being cloned
    00350    * w_rear is the rear end of the cloned train. It's used to add more cars and is only used by trains
    00351    */
    00352
    00353   if (!CheckOwnership(v->owner)) return CMD_ERROR;
    00354
    00355   if (v->type == VEH_TRAIN && (!IsFrontEngine(v) || v->u.rail.crash_anim_pos >= 4400)) return CMD_ERROR;
    00356
    00357   /* check that we can allocate enough vehicles */
    00358   if (!(flags & DC_EXEC)) {
    00359     int veh_counter = 0;
    00360     do {
    00361       veh_counter++;
    00362     } while ((v = v->Next()) != NULL);
    00363
    00364     if (!Vehicle::AllocateList(NULL, veh_counter)) {
    00365       return_cmd_error(STR_00E1_TOO_MANY_VEHICLES_IN_GAME);
    00366     }
    00367   }
    00368
    00369   v = v_front;
    00370
    00371   do {
    00372     if (v->type == VEH_TRAIN && IsRearDualheaded(v)) {
    00373       /* we build the rear ends of multiheaded trains with the front ones */
    00374       continue;
    00375     }
    00376
    00377     /* In case we're building a multi headed vehicle and the maximum number of
    00378      * vehicles is almost reached (e.g. max trains - 1) not all vehicles would
    00379      * be cloned. When the non-primary engines were build they were seen as
    00380      * 'new' vehicles whereas they would immediately be joined with a primary
    00381      * engine. This caused the vehicle to be not build as 'the limit' had been
    00382      * reached, resulting in partially build vehicles and such. */
    00383     DoCommandFlag build_flags = flags;
    00384     if ((flags & DC_EXEC) && !v->IsPrimaryVehicle()) build_flags |= DC_AUTOREPLACE;
    00385
    00386     CommandCost cost = DoCommand(tile, v->engine_type, build_argument, build_flags, GetCmdBuildVeh(v));
    00387     build_argument = 3; // ensure that we only assign a number to the first engine
    00388
    00389     if (CmdFailed(cost)) {
    00390       /* Can't build a part, then sell the stuff we already made; clear up the mess */
    00391       if (w_front != NULL) DoCommand(w_front->tile, w_front->index, 1, flags, GetCmdSellVeh(w_front));
    00392       return cost;
    00393     }
    00394
    00395     total_cost.AddCost(cost);
    00396
    00397     if (flags & DC_EXEC) {
    00398       w = GetVehicle(_new_vehicle_id);
    00399
    00400       if (v->type == VEH_TRAIN && HasBit(v->u.rail.flags, VRF_REVERSE_DIRECTION)) {
    00401         SetBit(w->u.rail.flags, VRF_REVERSE_DIRECTION);
    00402       }
    00403
    00404       if (v->type == VEH_TRAIN && !IsFrontEngine(v)) {
    00405         /* this s a train car
    00406          * add this unit to the end of the train */
    00407         CommandCost result = DoCommand(0, (w_rear->index << 16) | w->index, 1, flags, CMD_MOVE_RAIL_VEHICLE);
    00408         if (CmdFailed(result)) {
    00409           /* The train can't be joined to make the same consist as the original.
    00410            * Sell what we already made (clean up) and return an error.           */
    00411           DoCommand(w_front->tile, w_front->index, 1, flags, GetCmdSellVeh(w_front));
    00412           DoCommand(w_front->tile, w->index,       1, flags, GetCmdSellVeh(w));
    00413           return result; // return error and the message returned from CMD_MOVE_RAIL_VEHICLE
    00414         }
    00415       } else {
    00416         /* this is a front engine or not a train. */
    00417         w_front = w;
    00418         w->service_interval = v->service_interval;
    00419       }
    00420       w_rear = w; // trains needs to know the last car in the train, so they can add more in next loop
    00421     }
    00422   } while (v->type == VEH_TRAIN && (v = GetNextVehicle(v)) != NULL);
    00423
    00424   if (flags & DC_EXEC && v_front->type == VEH_TRAIN) {
    00425     /* for trains this needs to be the front engine due to the callback function */
    00426     _new_vehicle_id = w_front->index;
    00427   }
    00428
    00429   if (flags & DC_EXEC) {
    00430     /* Cloned vehicles belong to the same group */
    00431     DoCommand(0, v_front->group_id, w_front->index, flags, CMD_ADD_VEHICLE_GROUP);
    00432   }
    00433
    00434
    00435   /* Take care of refitting. */
    00436   w = w_front;
    00437   v = v_front;
    00438
    00439   /* Both building and refitting are influenced by newgrf callbacks, which
    00440    * makes it impossible to accurately estimate the cloning costs. In
    00441    * particular, it is possible for engines of the same type to be built with
    00442    * different numbers of articulated parts, so when refitting we have to
    00443    * loop over real vehicles first, and then the articulated parts of those
    00444    * vehicles in a different loop. */
    00445   do {
    00446     do {
    00447       if (flags & DC_EXEC) {
    00448         assert(w != NULL);
    00449
    00450         if (w->cargo_type != v->cargo_type || w->cargo_subtype != v->cargo_subtype) {
    00451           CommandCost cost = DoCommand(0, w->index, v->cargo_type | (v->cargo_subtype << 8) | 1U << 16 , flags, GetCmdRefitVeh(v));
    00452           if (CmdSucceeded(cost)) total_cost.AddCost(cost);
    00453         }
    00454
    00455         if (w->type == VEH_TRAIN && EngineHasArticPart(w)) {
    00456           w = GetNextArticPart(w);
    00457         } else if (w->type == VEH_ROAD && RoadVehHasArticPart(w)) {
    00458           w = w->Next();
    00459         } else {
    00460           break;
    00461         }
    00462       } else {
    00463         const Engine *e = GetEngine(v->engine_type);
    00464         CargoID initial_cargo = (e->CanCarryCargo() ? e->GetDefaultCargoType() : (CargoID)CT_INVALID);
    00465
    00466         if (v->cargo_type != initial_cargo && initial_cargo != CT_INVALID) {
    00467           total_cost.AddCost(GetRefitCost(v->engine_type));
    00468         }
    00469       }
    00470
    00471       if (v->type == VEH_TRAIN && EngineHasArticPart(v)) {
    00472         v = GetNextArticPart(v);
    00473       } else if (v->type == VEH_ROAD && RoadVehHasArticPart(v)) {
    00474         v = v->Next();
    00475       } else {
    00476         break;
    00477       }
    00478     } while (v != NULL);
    00479
    00480     if ((flags & DC_EXEC) && v->type == VEH_TRAIN) w = GetNextVehicle(w);
    00481   } while (v->type == VEH_TRAIN && (v = GetNextVehicle(v)) != NULL);
    00482
    00483   if (flags & DC_EXEC) {
    00484     /*
    00485      * Set the orders of the vehicle. Cannot do it earlier as we need
    00486      * the vehicle refitted before doing this, otherwise the moved
    00487      * cargo types might not match (passenger vs non-passenger)
    00488      */
    00489     DoCommand(0, (v_front->index << 16) | w_front->index, p2 & 1 ? CO_SHARE : CO_COPY, flags, CMD_CLONE_ORDER);
    00490
    00491     /* Now clone the vehicle's name, if it has one. */
    00492     if (v_front->name != NULL) CloneVehicleName(v_front, w_front);
    00493   }
    00494
    00495   /* Since we can't estimate the cost of cloning a vehicle accurately we must
    00496    * check whether the company has enough money manually. */
    00497   if (!CheckCompanyHasMoney(total_cost)) {
    00498     if (flags & DC_EXEC) {
    00499       /* The vehicle has already been bought, so now it must be sold again. */
    00500       DoCommand(w_front->tile, w_front->index, 1, flags, GetCmdSellVeh(w_front));
    00501     }
    00502     return CMD_ERROR;
    00503   }
    00504
    00505   return total_cost;
    00506 }
    00507
    00517 CommandCost SendAllVehiclesToDepot(VehicleType type, DoCommandFlag flags, bool service, Owner owner, uint16 vlw_flag, uint32 id)
    00518 {
    00519   VehicleList list;
    00520
    00521   GenerateVehicleSortList(&list, type, owner, id, vlw_flag);
    00522
    00523   /* Send all the vehicles to a depot */
    00524   for (uint i = 0; i < list.Length(); i++) {
    00525     const Vehicle *v = list[i];
    00526     CommandCost ret = DoCommand(v->tile, v->index, (service ? 1 : 0) | DEPOT_DONT_CANCEL, flags, GetCmdSendToDepot(type));
    00527
    00528     /* Return 0 if DC_EXEC is not set this is a valid goto depot command)
    00529      * In this case we know that at least one vehicle can be sent to a depot
    00530      * and we will issue the command. We can now safely quit the loop, knowing
    00531      * it will succeed at least once. With DC_EXEC we really need to send them to the depot */
    00532     if (CmdSucceeded(ret) && !(flags & DC_EXEC)) {
    00533       return CommandCost();
    00534     }
    00535   }
    00536
    00537   return (flags & DC_EXEC) ? CommandCost() : CMD_ERROR;
    00538 }
    00539
    00546 CommandCost CmdRenameVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00547 {
    00548   if (!IsValidVehicleID(p1)) return CMD_ERROR;
    00549
    00550   Vehicle *v = GetVehicle(p1);
    00551   if (!CheckOwnership(v->owner)) return CMD_ERROR;
    00552
    00553   bool reset = StrEmpty(text);
    00554
    00555   if (!reset) {
    00556     if (strlen(text) >= MAX_LENGTH_VEHICLE_NAME_BYTES) return CMD_ERROR;
    00557     if (!(flags & DC_AUTOREPLACE) && !IsUniqueVehicleName(text)) return_cmd_error(STR_NAME_MUST_BE_UNIQUE);
    00558   }
    00559
    00560   if (flags & DC_EXEC) {
    00561     free(v->name);
    00562     v->name = reset ? NULL : strdup(text);
    00563     InvalidateWindowClassesData(WC_TRAINS_LIST, 1);
    00564     MarkWholeScreenDirty();
    00565   }
    00566
    00567   return CommandCost();
    00568 }
    00569
    00570
    00577 CommandCost CmdChangeServiceInt(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00578 {
    00579   uint16 serv_int = GetServiceIntervalClamped(p2); // Double check the service interval from the user-input
    00580
    00581   if (serv_int != p2 || !IsValidVehicleID(p1)) return CMD_ERROR;
    00582
    00583   Vehicle *v = GetVehicle(p1);
    00584
    00585   if (!CheckOwnership(v->owner)) return CMD_ERROR;
    00586
    00587   if (flags & DC_EXEC) {
    00588     v->service_interval = serv_int;
    00589     InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
    00590   }
    00591
    00592   return CommandCost();
    00593 }