order_cmd.cpp

Go to the documentation of this file.
00001 /* $Id: order_cmd.cpp 22392 2011-04-30 20:46:58Z rubidium $ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * 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.
00006  * 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.
00007  * 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/>.
00008  */
00009 
00012 #include "stdafx.h"
00013 #include "debug.h"
00014 #include "cmd_helper.h"
00015 #include "command_func.h"
00016 #include "company_func.h"
00017 #include "news_func.h"
00018 #include "vehicle_gui.h"
00019 #include "strings_func.h"
00020 #include "window_func.h"
00021 #include "timetable.h"
00022 #include "vehicle_func.h"
00023 #include "depot_base.h"
00024 #include "core/pool_func.hpp"
00025 #include "aircraft.h"
00026 #include "roadveh.h"
00027 #include "station_base.h"
00028 #include "waypoint_base.h"
00029 #include "company_base.h"
00030 
00031 #include "table/strings.h"
00032 
00033 /* DestinationID must be at least as large as every these below, because it can
00034  * be any of them
00035  */
00036 assert_compile(sizeof(DestinationID) >= sizeof(DepotID));
00037 assert_compile(sizeof(DestinationID) >= sizeof(StationID));
00038 
00039 OrderPool _order_pool("Order");
00040 INSTANTIATE_POOL_METHODS(Order)
00041 OrderListPool _orderlist_pool("OrderList");
00042 INSTANTIATE_POOL_METHODS(OrderList)
00043 
00048 void Order::Free()
00049 {
00050   this->type  = OT_NOTHING;
00051   this->flags = 0;
00052   this->dest  = 0;
00053   this->next  = NULL;
00054 }
00055 
00060 void Order::MakeGoToStation(StationID destination)
00061 {
00062   this->type = OT_GOTO_STATION;
00063   this->flags = 0;
00064   this->dest = destination;
00065 }
00066 
00076 void Order::MakeGoToDepot(DepotID destination, OrderDepotTypeFlags order, OrderNonStopFlags non_stop_type, OrderDepotActionFlags action, CargoID cargo, byte subtype)
00077 {
00078   this->type = OT_GOTO_DEPOT;
00079   this->SetDepotOrderType(order);
00080   this->SetDepotActionType(action);
00081   this->SetNonStopType(non_stop_type);
00082   this->dest = destination;
00083   this->SetRefit(cargo, subtype);
00084 }
00085 
00090 void Order::MakeGoToWaypoint(StationID destination)
00091 {
00092   this->type = OT_GOTO_WAYPOINT;
00093   this->flags = 0;
00094   this->dest = destination;
00095 }
00096 
00101 void Order::MakeLoading(bool ordered)
00102 {
00103   this->type = OT_LOADING;
00104   if (!ordered) this->flags = 0;
00105 }
00106 
00110 void Order::MakeLeaveStation()
00111 {
00112   this->type = OT_LEAVESTATION;
00113   this->flags = 0;
00114 }
00115 
00119 void Order::MakeDummy()
00120 {
00121   this->type = OT_DUMMY;
00122   this->flags = 0;
00123 }
00124 
00129 void Order::MakeConditional(VehicleOrderID order)
00130 {
00131   this->type = OT_CONDITIONAL;
00132   this->flags = order;
00133   this->dest = 0;
00134 }
00135 
00140 void Order::MakeAutomatic(StationID destination)
00141 {
00142   this->type = OT_AUTOMATIC;
00143   this->dest = destination;
00144 }
00145 
00152 void Order::SetRefit(CargoID cargo, byte subtype)
00153 {
00154   this->refit_cargo = cargo;
00155   this->refit_subtype = subtype;
00156 }
00157 
00163 bool Order::Equals(const Order &other) const
00164 {
00165   /* In case of go to nearest depot orders we need "only" compare the flags
00166    * with the other and not the nearest depot order bit or the actual
00167    * destination because those get clear/filled in during the order
00168    * evaluation. If we do not do this the order will continuously be seen as
00169    * a different order and it will try to find a "nearest depot" every tick. */
00170   if ((this->IsType(OT_GOTO_DEPOT) && this->type == other.type) &&
00171       ((this->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0 ||
00172        (other.GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0)) {
00173     return this->GetDepotOrderType() == other.GetDepotOrderType() &&
00174         (this->GetDepotActionType() & ~ODATFB_NEAREST_DEPOT) == (other.GetDepotActionType() & ~ODATFB_NEAREST_DEPOT);
00175   }
00176 
00177   return this->type == other.type && this->flags == other.flags && this->dest == other.dest;
00178 }
00179 
00186 uint32 Order::Pack() const
00187 {
00188   return this->dest << 16 | this->flags << 8 | this->type;
00189 }
00190 
00196 uint16 Order::MapOldOrder() const
00197 {
00198   uint16 order = this->GetType();
00199   switch (this->type) {
00200     case OT_GOTO_STATION:
00201       if (this->GetUnloadType() & OUFB_UNLOAD) SetBit(order, 5);
00202       if (this->GetLoadType() & OLFB_FULL_LOAD) SetBit(order, 6);
00203       if (this->GetNonStopType() & ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS) SetBit(order, 7);
00204       order |= GB(this->GetDestination(), 0, 8) << 8;
00205       break;
00206     case OT_GOTO_DEPOT:
00207       if (!(this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) SetBit(order, 6);
00208       SetBit(order, 7);
00209       order |= GB(this->GetDestination(), 0, 8) << 8;
00210       break;
00211     case OT_LOADING:
00212       if (this->GetLoadType() & OLFB_FULL_LOAD) SetBit(order, 6);
00213       break;
00214   }
00215   return order;
00216 }
00217 
00222 Order::Order(uint32 packed)
00223 {
00224   this->type    = (OrderType)GB(packed,  0,  8);
00225   this->flags   = GB(packed,  8,  8);
00226   this->dest    = GB(packed, 16, 16);
00227   this->next    = NULL;
00228   this->refit_cargo   = CT_NO_REFIT;
00229   this->refit_subtype = 0;
00230   this->wait_time     = 0;
00231   this->travel_time   = 0;
00232 }
00233 
00239 void InvalidateVehicleOrder(const Vehicle *v, int data)
00240 {
00241   SetWindowDirty(WC_VEHICLE_VIEW, v->index);
00242 
00243   if (data != 0) {
00244     /* Calls SetDirty() too */
00245     InvalidateWindowData(WC_VEHICLE_ORDERS,    v->index, data);
00246     InvalidateWindowData(WC_VEHICLE_TIMETABLE, v->index, data);
00247     return;
00248   }
00249 
00250   SetWindowDirty(WC_VEHICLE_ORDERS,    v->index);
00251   SetWindowDirty(WC_VEHICLE_TIMETABLE, v->index);
00252 }
00253 
00261 void Order::AssignOrder(const Order &other)
00262 {
00263   this->type  = other.type;
00264   this->flags = other.flags;
00265   this->dest  = other.dest;
00266 
00267   this->refit_cargo   = other.refit_cargo;
00268   this->refit_subtype = other.refit_subtype;
00269 
00270   this->wait_time   = other.wait_time;
00271   this->travel_time = other.travel_time;
00272 }
00273 
00279 void OrderList::Initialize(Order *chain, Vehicle *v)
00280 {
00281   this->first = chain;
00282   this->first_shared = v;
00283 
00284   this->num_orders = 0;
00285   this->num_manual_orders = 0;
00286   this->num_vehicles = 1;
00287   this->timetable_duration = 0;
00288 
00289   for (Order *o = this->first; o != NULL; o = o->next) {
00290     ++this->num_orders;
00291     if (!o->IsType(OT_AUTOMATIC)) ++this->num_manual_orders;
00292     this->timetable_duration += o->wait_time + o->travel_time;
00293   }
00294 
00295   for (Vehicle *u = this->first_shared->PreviousShared(); u != NULL; u = u->PreviousShared()) {
00296     ++this->num_vehicles;
00297     this->first_shared = u;
00298   }
00299 
00300   for (const Vehicle *u = v->NextShared(); u != NULL; u = u->NextShared()) ++this->num_vehicles;
00301 }
00302 
00308 void OrderList::FreeChain(bool keep_orderlist)
00309 {
00310   Order *next;
00311   for (Order *o = this->first; o != NULL; o = next) {
00312     next = o->next;
00313     delete o;
00314   }
00315 
00316   if (keep_orderlist) {
00317     this->first = NULL;
00318     this->num_orders = 0;
00319     this->num_manual_orders = 0;
00320     this->timetable_duration = 0;
00321   } else {
00322     delete this;
00323   }
00324 }
00325 
00331 Order *OrderList::GetOrderAt(int index) const
00332 {
00333   if (index < 0) return NULL;
00334 
00335   Order *order = this->first;
00336 
00337   while (order != NULL && index-- > 0) {
00338     order = order->next;
00339   }
00340   return order;
00341 }
00342 
00348 void OrderList::InsertOrderAt(Order *new_order, int index)
00349 {
00350   if (this->first == NULL) {
00351     this->first = new_order;
00352   } else {
00353     if (index == 0) {
00354       /* Insert as first or only order */
00355       new_order->next = this->first;
00356       this->first = new_order;
00357     } else if (index >= this->num_orders) {
00358       /* index is after the last order, add it to the end */
00359       this->GetLastOrder()->next = new_order;
00360     } else {
00361       /* Put the new order in between */
00362       Order *order = this->GetOrderAt(index - 1);
00363       new_order->next = order->next;
00364       order->next = new_order;
00365     }
00366   }
00367   ++this->num_orders;
00368   if (!new_order->IsType(OT_AUTOMATIC)) ++this->num_manual_orders;
00369   this->timetable_duration += new_order->wait_time + new_order->travel_time;
00370 }
00371 
00372 
00377 void OrderList::DeleteOrderAt(int index)
00378 {
00379   if (index >= this->num_orders) return;
00380 
00381   Order *to_remove;
00382 
00383   if (index == 0) {
00384     to_remove = this->first;
00385     this->first = to_remove->next;
00386   } else {
00387     Order *prev = GetOrderAt(index - 1);
00388     to_remove = prev->next;
00389     prev->next = to_remove->next;
00390   }
00391   --this->num_orders;
00392   if (!to_remove->IsType(OT_AUTOMATIC)) --this->num_manual_orders;
00393   this->timetable_duration -= (to_remove->wait_time + to_remove->travel_time);
00394   delete to_remove;
00395 }
00396 
00402 void OrderList::MoveOrder(int from, int to)
00403 {
00404   if (from >= this->num_orders || to >= this->num_orders || from == to) return;
00405 
00406   Order *moving_one;
00407 
00408   /* Take the moving order out of the pointer-chain */
00409   if (from == 0) {
00410     moving_one = this->first;
00411     this->first = moving_one->next;
00412   } else {
00413     Order *one_before = GetOrderAt(from - 1);
00414     moving_one = one_before->next;
00415     one_before->next = moving_one->next;
00416   }
00417 
00418   /* Insert the moving_order again in the pointer-chain */
00419   if (to == 0) {
00420     moving_one->next = this->first;
00421     this->first = moving_one;
00422   } else {
00423     Order *one_before = GetOrderAt(to - 1);
00424     moving_one->next = one_before->next;
00425     one_before->next = moving_one;
00426   }
00427 }
00428 
00434 void OrderList::RemoveVehicle(Vehicle *v)
00435 {
00436   --this->num_vehicles;
00437   if (v == this->first_shared) this->first_shared = v->NextShared();
00438 }
00439 
00444 bool OrderList::IsVehicleInSharedOrdersList(const Vehicle *v) const
00445 {
00446   for (const Vehicle *v_shared = this->first_shared; v_shared != NULL; v_shared = v_shared->NextShared()) {
00447     if (v_shared == v) return true;
00448   }
00449 
00450   return false;
00451 }
00452 
00458 int OrderList::GetPositionInSharedOrderList(const Vehicle *v) const
00459 {
00460   int count = 0;
00461   for (const Vehicle *v_shared = v->PreviousShared(); v_shared != NULL; v_shared = v_shared->PreviousShared()) count++;
00462   return count;
00463 }
00464 
00469 bool OrderList::IsCompleteTimetable() const
00470 {
00471   for (Order *o = this->first; o != NULL; o = o->next) {
00472     /* Automatic orders are, by definition, not timetabled. */
00473     if (o->IsType(OT_AUTOMATIC)) continue;
00474     if (!o->IsCompletelyTimetabled()) return false;
00475   }
00476   return true;
00477 }
00478 
00482 void OrderList::DebugCheckSanity() const
00483 {
00484   VehicleOrderID check_num_orders = 0;
00485   VehicleOrderID check_num_manual_orders = 0;
00486   uint check_num_vehicles = 0;
00487   Ticks check_timetable_duration = 0;
00488 
00489   DEBUG(misc, 6, "Checking OrderList %hu for sanity...", this->index);
00490 
00491   for (const Order *o = this->first; o != NULL; o = o->next) {
00492     ++check_num_orders;
00493     if (!o->IsType(OT_AUTOMATIC)) ++check_num_manual_orders;
00494     check_timetable_duration += o->wait_time + o->travel_time;
00495   }
00496   assert(this->num_orders == check_num_orders);
00497   assert(this->num_manual_orders == check_num_manual_orders);
00498   assert(this->timetable_duration == check_timetable_duration);
00499 
00500   for (const Vehicle *v = this->first_shared; v != NULL; v = v->NextShared()) {
00501     ++check_num_vehicles;
00502     assert(v->orders.list == this);
00503   }
00504   assert(this->num_vehicles == check_num_vehicles);
00505   DEBUG(misc, 6, "... detected %u orders (%u manual), %u vehicles, %i ticks",
00506       (uint)this->num_orders, (uint)this->num_manual_orders,
00507       this->num_vehicles, this->timetable_duration);
00508 }
00509 
00517 static inline bool OrderGoesToStation(const Vehicle *v, const Order *o)
00518 {
00519   return o->IsType(OT_GOTO_STATION) ||
00520       (v->type == VEH_AIRCRAFT && o->IsType(OT_GOTO_DEPOT) && !(o->GetDepotActionType() & ODATFB_NEAREST_DEPOT));
00521 }
00522 
00529 static void DeleteOrderWarnings(const Vehicle *v)
00530 {
00531   DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_TOO_FEW_ORDERS);
00532   DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_VOID_ORDER);
00533   DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_DUPLICATE_ENTRY);
00534   DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_INVALID_ENTRY);
00535 }
00536 
00542 TileIndex Order::GetLocation(const Vehicle *v) const
00543 {
00544   switch (this->GetType()) {
00545     case OT_GOTO_WAYPOINT:
00546     case OT_GOTO_STATION:
00547     case OT_AUTOMATIC:
00548       return BaseStation::Get(this->GetDestination())->xy;
00549 
00550     case OT_GOTO_DEPOT:
00551       if ((this->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0) return INVALID_TILE;
00552       return (v->type == VEH_AIRCRAFT) ? Station::Get(this->GetDestination())->xy : Depot::Get(this->GetDestination())->xy;
00553 
00554     default:
00555       return INVALID_TILE;
00556   }
00557 }
00558 
00559 static uint GetOrderDistance(const Order *prev, const Order *cur, const Vehicle *v, int conditional_depth = 0)
00560 {
00561   assert(v->type == VEH_SHIP);
00562 
00563   if (cur->IsType(OT_CONDITIONAL)) {
00564     if (conditional_depth > v->GetNumOrders()) return 0;
00565 
00566     conditional_depth++;
00567 
00568     int dist1 = GetOrderDistance(prev, v->GetOrder(cur->GetConditionSkipToOrder()), v, conditional_depth);
00569     int dist2 = GetOrderDistance(prev, cur->next == NULL ? v->orders.list->GetFirstOrder() : cur->next, v, conditional_depth);
00570     return max(dist1, dist2);
00571   }
00572 
00573   TileIndex prev_tile = prev->GetLocation(v);
00574   TileIndex cur_tile = cur->GetLocation(v);
00575   if (prev_tile == INVALID_TILE || cur_tile == INVALID_TILE) return 0;
00576   return DistanceManhattan(prev_tile, cur_tile);
00577 }
00578 
00592 CommandCost CmdInsertOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00593 {
00594   VehicleID veh          = GB(p1,  0, 20);
00595   VehicleOrderID sel_ord = GB(p1, 20, 8);
00596   Order new_order(p2);
00597 
00598   Vehicle *v = Vehicle::GetIfValid(veh);
00599   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
00600 
00601   CommandCost ret = CheckOwnership(v->owner);
00602   if (ret.Failed()) return ret;
00603 
00604   /* Check if the inserted order is to the correct destination (owner, type),
00605    * and has the correct flags if any */
00606   switch (new_order.GetType()) {
00607     case OT_GOTO_STATION: {
00608       const Station *st = Station::GetIfValid(new_order.GetDestination());
00609       if (st == NULL) return CMD_ERROR;
00610 
00611       if (st->owner != OWNER_NONE) {
00612         CommandCost ret = CheckOwnership(st->owner);
00613         if (ret.Failed()) return ret;
00614       }
00615 
00616       if (!CanVehicleUseStation(v, st)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
00617       for (Vehicle *u = v->FirstShared(); u != NULL; u = u->NextShared()) {
00618         if (!CanVehicleUseStation(u, st)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER_SHARED);
00619       }
00620 
00621       /* Non stop only allowed for ground vehicles. */
00622       if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && !v->IsGroundVehicle()) return CMD_ERROR;
00623 
00624       /* Filter invalid load/unload types. */
00625       switch (new_order.GetLoadType()) {
00626         case OLF_LOAD_IF_POSSIBLE: case OLFB_FULL_LOAD: case OLF_FULL_LOAD_ANY: case OLFB_NO_LOAD: break;
00627         default: return CMD_ERROR;
00628       }
00629       switch (new_order.GetUnloadType()) {
00630         case OUF_UNLOAD_IF_POSSIBLE: case OUFB_UNLOAD: case OUFB_TRANSFER: case OUFB_NO_UNLOAD: break;
00631         default: return CMD_ERROR;
00632       }
00633 
00634       /* Filter invalid stop locations */
00635       switch (new_order.GetStopLocation()) {
00636         case OSL_PLATFORM_NEAR_END:
00637         case OSL_PLATFORM_MIDDLE:
00638           if (v->type != VEH_TRAIN) return CMD_ERROR;
00639           /* FALL THROUGH */
00640         case OSL_PLATFORM_FAR_END:
00641           break;
00642 
00643         default:
00644           return CMD_ERROR;
00645       }
00646 
00647       break;
00648     }
00649 
00650     case OT_GOTO_DEPOT: {
00651       if ((new_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) == 0) {
00652         if (v->type == VEH_AIRCRAFT) {
00653           const Station *st = Station::GetIfValid(new_order.GetDestination());
00654 
00655           if (st == NULL) return CMD_ERROR;
00656 
00657           CommandCost ret = CheckOwnership(st->owner);
00658           if (ret.Failed()) return ret;
00659 
00660           if (!CanVehicleUseStation(v, st) || !st->airport.HasHangar()) {
00661             return CMD_ERROR;
00662           }
00663         } else {
00664           const Depot *dp = Depot::GetIfValid(new_order.GetDestination());
00665 
00666           if (dp == NULL) return CMD_ERROR;
00667 
00668           CommandCost ret = CheckOwnership(GetTileOwner(dp->xy));
00669           if (ret.Failed()) return ret;
00670 
00671           switch (v->type) {
00672             case VEH_TRAIN:
00673               if (!IsRailDepotTile(dp->xy)) return CMD_ERROR;
00674               break;
00675 
00676             case VEH_ROAD:
00677               if (!IsRoadDepotTile(dp->xy)) return CMD_ERROR;
00678               break;
00679 
00680             case VEH_SHIP:
00681               if (!IsShipDepotTile(dp->xy)) return CMD_ERROR;
00682               break;
00683 
00684             default: return CMD_ERROR;
00685           }
00686         }
00687       }
00688 
00689       if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && !v->IsGroundVehicle()) return CMD_ERROR;
00690       if (new_order.GetDepotOrderType() & ~(ODTFB_PART_OF_ORDERS | ((new_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS) != 0 ? ODTFB_SERVICE : 0))) return CMD_ERROR;
00691       if (new_order.GetDepotActionType() & ~(ODATFB_HALT | ODATFB_NEAREST_DEPOT)) return CMD_ERROR;
00692       if ((new_order.GetDepotOrderType() & ODTFB_SERVICE) && (new_order.GetDepotActionType() & ODATFB_HALT)) return CMD_ERROR;
00693       break;
00694     }
00695 
00696     case OT_GOTO_WAYPOINT: {
00697       const Waypoint *wp = Waypoint::GetIfValid(new_order.GetDestination());
00698       if (wp == NULL) return CMD_ERROR;
00699 
00700       switch (v->type) {
00701         default: return CMD_ERROR;
00702 
00703         case VEH_TRAIN: {
00704           if (!(wp->facilities & FACIL_TRAIN)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
00705 
00706           CommandCost ret = CheckOwnership(wp->owner);
00707           if (ret.Failed()) return ret;
00708           break;
00709         }
00710 
00711         case VEH_SHIP:
00712           if (!(wp->facilities & FACIL_DOCK)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
00713           if (wp->owner != OWNER_NONE) {
00714             CommandCost ret = CheckOwnership(wp->owner);
00715             if (ret.Failed()) return ret;
00716           }
00717           break;
00718       }
00719 
00720       /* Order flags can be any of the following for waypoints:
00721        * [non-stop]
00722        * non-stop orders (if any) are only valid for trains */
00723       if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && v->type != VEH_TRAIN) return CMD_ERROR;
00724       break;
00725     }
00726 
00727     case OT_CONDITIONAL: {
00728       VehicleOrderID skip_to = new_order.GetConditionSkipToOrder();
00729       if (skip_to != 0 && skip_to >= v->GetNumOrders()) return CMD_ERROR; // Always allow jumping to the first (even when there is no order).
00730       if (new_order.GetConditionVariable() > OCV_END) return CMD_ERROR;
00731 
00732       OrderConditionComparator occ = new_order.GetConditionComparator();
00733       if (occ > OCC_END) return CMD_ERROR;
00734       switch (new_order.GetConditionVariable()) {
00735         case OCV_REQUIRES_SERVICE:
00736           if (occ != OCC_IS_TRUE && occ != OCC_IS_FALSE) return CMD_ERROR;
00737           break;
00738 
00739         case OCV_UNCONDITIONALLY:
00740           if (occ != OCC_EQUALS) return CMD_ERROR;
00741           if (new_order.GetConditionValue() != 0) return CMD_ERROR;
00742           break;
00743 
00744         case OCV_LOAD_PERCENTAGE:
00745         case OCV_RELIABILITY:
00746           if (new_order.GetConditionValue() > 100) return CMD_ERROR;
00747           /* FALL THROUGH */
00748         default:
00749           if (occ == OCC_IS_TRUE || occ == OCC_IS_FALSE) return CMD_ERROR;
00750           break;
00751       }
00752       break;
00753     }
00754 
00755     default: return CMD_ERROR;
00756   }
00757 
00758   if (sel_ord > v->GetNumOrders()) return CMD_ERROR;
00759 
00760   if (v->GetNumOrders() >= MAX_VEH_ORDER_ID) return_cmd_error(STR_ERROR_TOO_MANY_ORDERS);
00761   if (!Order::CanAllocateItem()) return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
00762   if (v->orders.list == NULL && !OrderList::CanAllocateItem()) return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
00763 
00764   if (v->type == VEH_SHIP && _settings_game.pf.pathfinder_for_ships != VPF_NPF) {
00765     /* Make sure the new destination is not too far away from the previous */
00766     const Order *prev = NULL;
00767     uint n = 0;
00768 
00769     /* Find the last goto station or depot order before the insert location.
00770      * If the order is to be inserted at the beginning of the order list this
00771      * finds the last order in the list. */
00772     const Order *o;
00773     FOR_VEHICLE_ORDERS(v, o) {
00774       switch (o->GetType()) {
00775         case OT_GOTO_STATION:
00776         case OT_GOTO_DEPOT:
00777         case OT_GOTO_WAYPOINT:
00778           prev = o;
00779           break;
00780 
00781         default: break;
00782       }
00783       if (++n == sel_ord && prev != NULL) break;
00784     }
00785     if (prev != NULL) {
00786       uint dist = GetOrderDistance(prev, &new_order, v);
00787       if (dist >= 130) {
00788         return_cmd_error(STR_ERROR_TOO_FAR_FROM_PREVIOUS_DESTINATION);
00789       }
00790     }
00791   }
00792 
00793   if (flags & DC_EXEC) {
00794     Order *new_o = new Order();
00795     new_o->AssignOrder(new_order);
00796     InsertOrder(v, new_o, sel_ord);
00797   }
00798 
00799   return CommandCost();
00800 }
00801 
00808 void InsertOrder(Vehicle *v, Order *new_o, VehicleOrderID sel_ord)
00809 {
00810   /* Create new order and link in list */
00811   if (v->orders.list == NULL) {
00812     v->orders.list = new OrderList(new_o, v);
00813   } else {
00814     v->orders.list->InsertOrderAt(new_o, sel_ord);
00815   }
00816 
00817   Vehicle *u = v->FirstShared();
00818   DeleteOrderWarnings(u);
00819   for (; u != NULL; u = u->NextShared()) {
00820     assert(v->orders.list == u->orders.list);
00821 
00822     /* If there is added an order before the current one, we need
00823      * to update the selected order. We do not change automatic/real order indices though.
00824      * If the new order is between the current auto order and real order, the auto order will
00825      * later skip the inserted order. */
00826     if (sel_ord <= u->cur_real_order_index) {
00827       uint cur = u->cur_real_order_index + 1;
00828       /* Check if we don't go out of bound */
00829       if (cur < u->GetNumOrders()) {
00830         u->cur_real_order_index = cur;
00831       }
00832     }
00833     if (sel_ord == u->cur_auto_order_index && u->IsGroundVehicle()) {
00834       /* We are inserting an order just before the current automatic order.
00835        * We do not know whether we will reach current automatic or the newly inserted order first.
00836        * So, disable creation of automatic orders until we are on track again. */
00837       uint16 &gv_flags = u->GetGroundVehicleFlags();
00838       SetBit(gv_flags, GVF_SUPPRESS_AUTOMATIC_ORDERS);
00839     }
00840     if (sel_ord <= u->cur_auto_order_index) {
00841       uint cur = u->cur_auto_order_index + 1;
00842       /* Check if we don't go out of bound */
00843       if (cur < u->GetNumOrders()) {
00844         u->cur_auto_order_index = cur;
00845       }
00846     }
00847     /* Update any possible open window of the vehicle */
00848     InvalidateVehicleOrder(u, INVALID_VEH_ORDER_ID | (sel_ord << 8));
00849   }
00850 
00851   /* As we insert an order, the order to skip to will be 'wrong'. */
00852   VehicleOrderID cur_order_id = 0;
00853   Order *order;
00854   FOR_VEHICLE_ORDERS(v, order) {
00855     if (order->IsType(OT_CONDITIONAL)) {
00856       VehicleOrderID order_id = order->GetConditionSkipToOrder();
00857       if (order_id >= sel_ord) {
00858         order->SetConditionSkipToOrder(order_id + 1);
00859       }
00860       if (order_id == cur_order_id) {
00861         order->SetConditionSkipToOrder((order_id + 1) % v->GetNumOrders());
00862       }
00863     }
00864     cur_order_id++;
00865   }
00866 
00867   /* Make sure to rebuild the whole list */
00868   InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
00869 }
00870 
00876 static CommandCost DecloneOrder(Vehicle *dst, DoCommandFlag flags)
00877 {
00878   if (flags & DC_EXEC) {
00879     DeleteVehicleOrders(dst);
00880     InvalidateVehicleOrder(dst, -1);
00881     InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
00882   }
00883   return CommandCost();
00884 }
00885 
00895 CommandCost CmdDeleteOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00896 {
00897   VehicleID veh_id = GB(p1, 0, 20);
00898   VehicleOrderID sel_ord = GB(p2, 0, 8);
00899 
00900   Vehicle *v = Vehicle::GetIfValid(veh_id);
00901 
00902   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
00903 
00904   CommandCost ret = CheckOwnership(v->owner);
00905   if (ret.Failed()) return ret;
00906 
00907   /* If we did not select an order, we maybe want to de-clone the orders */
00908   if (sel_ord >= v->GetNumOrders()) return DecloneOrder(v, flags);
00909 
00910   if (v->GetOrder(sel_ord) == NULL) return CMD_ERROR;
00911 
00912   if (flags & DC_EXEC) DeleteOrder(v, sel_ord);
00913   return CommandCost();
00914 }
00915 
00920 static void CancelLoadingDueToDeletedOrder(Vehicle *v)
00921 {
00922   assert(v->current_order.IsType(OT_LOADING));
00923   /* NON-stop flag is misused to see if a train is in a station that is
00924    * on his order list or not */
00925   v->current_order.SetNonStopType(ONSF_STOP_EVERYWHERE);
00926   /* When full loading, "cancel" that order so the vehicle doesn't
00927    * stay indefinitely at this station anymore. */
00928   if (v->current_order.GetLoadType() & OLFB_FULL_LOAD) v->current_order.SetLoadType(OLF_LOAD_IF_POSSIBLE);
00929 }
00930 
00936 void DeleteOrder(Vehicle *v, VehicleOrderID sel_ord)
00937 {
00938   v->orders.list->DeleteOrderAt(sel_ord);
00939 
00940   Vehicle *u = v->FirstShared();
00941   DeleteOrderWarnings(u);
00942   for (; u != NULL; u = u->NextShared()) {
00943     assert(v->orders.list == u->orders.list);
00944 
00945     if (sel_ord == u->cur_real_order_index && u->current_order.IsType(OT_LOADING)) {
00946       CancelLoadingDueToDeletedOrder(u);
00947     }
00948 
00949     if (sel_ord < u->cur_real_order_index) {
00950       u->cur_real_order_index--;
00951     } else if (sel_ord == u->cur_real_order_index) {
00952       u->UpdateRealOrderIndex();
00953     }
00954 
00955     if (sel_ord < u->cur_auto_order_index) {
00956       u->cur_auto_order_index--;
00957     } else if (sel_ord == u->cur_auto_order_index) {
00958       /* Make sure the index is valid */
00959       if (u->cur_auto_order_index >= u->GetNumOrders()) u->cur_auto_order_index = 0;
00960 
00961       /* Skip non-automatic orders for the auto-order-index (e.g. if the current auto order was deleted */
00962       while (u->cur_auto_order_index != u->cur_real_order_index && !u->GetOrder(u->cur_auto_order_index)->IsType(OT_AUTOMATIC)) {
00963         u->cur_auto_order_index++;
00964         if (u->cur_auto_order_index >= u->GetNumOrders()) u->cur_auto_order_index = 0;
00965       }
00966     }
00967 
00968     /* Update any possible open window of the vehicle */
00969     InvalidateVehicleOrder(u, sel_ord | (INVALID_VEH_ORDER_ID << 8));
00970   }
00971 
00972   /* As we delete an order, the order to skip to will be 'wrong'. */
00973   VehicleOrderID cur_order_id = 0;
00974   Order *order = NULL;
00975   FOR_VEHICLE_ORDERS(v, order) {
00976     if (order->IsType(OT_CONDITIONAL)) {
00977       VehicleOrderID order_id = order->GetConditionSkipToOrder();
00978       if (order_id >= sel_ord) {
00979         order_id = max(order_id - 1, 0);
00980       }
00981       if (order_id == cur_order_id) {
00982         order_id = (order_id + 1) % v->GetNumOrders();
00983       }
00984       order->SetConditionSkipToOrder(order_id);
00985     }
00986     cur_order_id++;
00987   }
00988 
00989   InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
00990 }
00991 
01001 CommandCost CmdSkipToOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01002 {
01003   VehicleID veh_id = GB(p1, 0, 20);
01004   VehicleOrderID sel_ord = GB(p2, 0, 8);
01005 
01006   Vehicle *v = Vehicle::GetIfValid(veh_id);
01007 
01008   if (v == NULL || !v->IsPrimaryVehicle() || sel_ord == v->cur_auto_order_index || sel_ord >= v->GetNumOrders() || v->GetNumOrders() < 2) return CMD_ERROR;
01009 
01010   CommandCost ret = CheckOwnership(v->owner);
01011   if (ret.Failed()) return ret;
01012 
01013   if (flags & DC_EXEC) {
01014     v->cur_auto_order_index = v->cur_real_order_index = sel_ord;
01015     v->UpdateRealOrderIndex();
01016 
01017     if (v->current_order.IsType(OT_LOADING)) v->LeaveStation();
01018 
01019     InvalidateVehicleOrder(v, -2);
01020   }
01021 
01022   /* We have an aircraft/ship, they have a mini-schedule, so update them all */
01023   if (v->type == VEH_AIRCRAFT) SetWindowClassesDirty(WC_AIRCRAFT_LIST);
01024   if (v->type == VEH_SHIP) SetWindowClassesDirty(WC_SHIPS_LIST);
01025 
01026   return CommandCost();
01027 }
01028 
01042 CommandCost CmdMoveOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01043 {
01044   VehicleID veh = GB(p1, 0, 20);
01045   VehicleOrderID moving_order = GB(p2,  0, 16);
01046   VehicleOrderID target_order = GB(p2, 16, 16);
01047 
01048   Vehicle *v = Vehicle::GetIfValid(veh);
01049   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01050 
01051   CommandCost ret = CheckOwnership(v->owner);
01052   if (ret.Failed()) return ret;
01053 
01054   /* Don't make senseless movements */
01055   if (moving_order >= v->GetNumOrders() || target_order >= v->GetNumOrders() ||
01056       moving_order == target_order || v->GetNumOrders() <= 1) return CMD_ERROR;
01057 
01058   Order *moving_one = v->GetOrder(moving_order);
01059   /* Don't move an empty order */
01060   if (moving_one == NULL) return CMD_ERROR;
01061 
01062   if (flags & DC_EXEC) {
01063     v->orders.list->MoveOrder(moving_order, target_order);
01064 
01065     /* Update shared list */
01066     Vehicle *u = v->FirstShared();
01067 
01068     DeleteOrderWarnings(u);
01069 
01070     for (; u != NULL; u = u->NextShared()) {
01071       /* Update the current order.
01072        * There are multiple ways to move orders, which result in cur_auto_order_index
01073        * and cur_real_order_index to not longer make any sense. E.g. moving another
01074        * real order between them.
01075        *
01076        * Basically one could choose to preserve either of them, but not both.
01077        * While both ways are suitable in this or that case from a human point of view, neither
01078        * of them makes really sense.
01079        * However, from an AI point of view, preserving cur_real_order_index is the most
01080        * predictable and transparent behaviour.
01081        *
01082        * With that decision it basically does not matter what we do to cur_auto_order_index.
01083        * If we change orders between the auto- and real-index, the auto orders are mostly likely
01084        * completely out-dated anyway. So, keep it simple and just keep cur_auto_order_index as well.
01085        * The worst which can happen is that a lot of automatic orders are removed when reaching current_order.
01086        */
01087       if (u->cur_real_order_index == moving_order) {
01088         u->cur_real_order_index = target_order;
01089       } else if (u->cur_real_order_index > moving_order && u->cur_real_order_index <= target_order) {
01090         u->cur_real_order_index--;
01091       } else if (u->cur_real_order_index < moving_order && u->cur_real_order_index >= target_order) {
01092         u->cur_real_order_index++;
01093       }
01094 
01095       if (u->cur_auto_order_index == moving_order) {
01096         u->cur_auto_order_index = target_order;
01097       } else if (u->cur_auto_order_index > moving_order && u->cur_auto_order_index <= target_order) {
01098         u->cur_auto_order_index--;
01099       } else if (u->cur_auto_order_index < moving_order && u->cur_auto_order_index >= target_order) {
01100         u->cur_auto_order_index++;
01101       }
01102 
01103       assert(v->orders.list == u->orders.list);
01104       /* Update any possible open window of the vehicle */
01105       InvalidateVehicleOrder(u, moving_order | (target_order << 8));
01106     }
01107 
01108     /* As we move an order, the order to skip to will be 'wrong'. */
01109     Order *order;
01110     FOR_VEHICLE_ORDERS(v, order) {
01111       if (order->IsType(OT_CONDITIONAL)) {
01112         VehicleOrderID order_id = order->GetConditionSkipToOrder();
01113         if (order_id == moving_order) {
01114           order_id = target_order;
01115         } else if (order_id > moving_order && order_id <= target_order) {
01116           order_id--;
01117         } else if (order_id < moving_order && order_id >= target_order) {
01118           order_id++;
01119         }
01120         order->SetConditionSkipToOrder(order_id);
01121       }
01122     }
01123 
01124     /* Make sure to rebuild the whole list */
01125     InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
01126   }
01127 
01128   return CommandCost();
01129 }
01130 
01146 CommandCost CmdModifyOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01147 {
01148   VehicleOrderID sel_ord = GB(p1, 20,  8);
01149   VehicleID veh          = GB(p1,  0, 20);
01150   ModifyOrderFlags mof   = Extract<ModifyOrderFlags, 0, 4>(p2);
01151   uint16 data            = GB(p2,  4, 11);
01152 
01153   if (mof >= MOF_END) return CMD_ERROR;
01154 
01155   Vehicle *v = Vehicle::GetIfValid(veh);
01156   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01157 
01158   CommandCost ret = CheckOwnership(v->owner);
01159   if (ret.Failed()) return ret;
01160 
01161   /* Is it a valid order? */
01162   if (sel_ord >= v->GetNumOrders()) return CMD_ERROR;
01163 
01164   Order *order = v->GetOrder(sel_ord);
01165   switch (order->GetType()) {
01166     case OT_GOTO_STATION:
01167       if (mof == MOF_COND_VARIABLE || mof == MOF_COND_COMPARATOR || mof == MOF_DEPOT_ACTION || mof == MOF_COND_VALUE) return CMD_ERROR;
01168       break;
01169 
01170     case OT_GOTO_DEPOT:
01171       if (mof != MOF_NON_STOP && mof != MOF_DEPOT_ACTION) return CMD_ERROR;
01172       break;
01173 
01174     case OT_GOTO_WAYPOINT:
01175       if (mof != MOF_NON_STOP) return CMD_ERROR;
01176       break;
01177 
01178     case OT_CONDITIONAL:
01179       if (mof != MOF_COND_VARIABLE && mof != MOF_COND_COMPARATOR && mof != MOF_COND_VALUE && mof != MOF_COND_DESTINATION) return CMD_ERROR;
01180       break;
01181 
01182     default:
01183       return CMD_ERROR;
01184   }
01185 
01186   switch (mof) {
01187     default: NOT_REACHED();
01188 
01189     case MOF_NON_STOP:
01190       if (!v->IsGroundVehicle()) return CMD_ERROR;
01191       if (data >= ONSF_END) return CMD_ERROR;
01192       if (data == order->GetNonStopType()) return CMD_ERROR;
01193       break;
01194 
01195     case MOF_STOP_LOCATION:
01196       if (v->type != VEH_TRAIN) return CMD_ERROR;
01197       if (data >= OSL_END) return CMD_ERROR;
01198       break;
01199 
01200     case MOF_UNLOAD:
01201       if ((data & ~(OUFB_UNLOAD | OUFB_TRANSFER | OUFB_NO_UNLOAD)) != 0) return CMD_ERROR;
01202       /* Unload and no-unload are mutual exclusive and so are transfer and no unload. */
01203       if (data != 0 && ((data & (OUFB_UNLOAD | OUFB_TRANSFER)) != 0) == ((data & OUFB_NO_UNLOAD) != 0)) return CMD_ERROR;
01204       if (data == order->GetUnloadType()) return CMD_ERROR;
01205       break;
01206 
01207     case MOF_LOAD:
01208       if (data > OLFB_NO_LOAD || data == 1) return CMD_ERROR;
01209       if (data == order->GetLoadType()) return CMD_ERROR;
01210       break;
01211 
01212     case MOF_DEPOT_ACTION:
01213       if (data >= DA_END) return CMD_ERROR;
01214       break;
01215 
01216     case MOF_COND_VARIABLE:
01217       if (data >= OCV_END) return CMD_ERROR;
01218       break;
01219 
01220     case MOF_COND_COMPARATOR:
01221       if (data >= OCC_END) return CMD_ERROR;
01222       switch (order->GetConditionVariable()) {
01223         case OCV_UNCONDITIONALLY: return CMD_ERROR;
01224 
01225         case OCV_REQUIRES_SERVICE:
01226           if (data != OCC_IS_TRUE && data != OCC_IS_FALSE) return CMD_ERROR;
01227           break;
01228 
01229         default:
01230           if (data == OCC_IS_TRUE || data == OCC_IS_FALSE) return CMD_ERROR;
01231           break;
01232       }
01233       break;
01234 
01235     case MOF_COND_VALUE:
01236       switch (order->GetConditionVariable()) {
01237         case OCV_UNCONDITIONALLY: return CMD_ERROR;
01238 
01239         case OCV_LOAD_PERCENTAGE:
01240         case OCV_RELIABILITY:
01241           if (data > 100) return CMD_ERROR;
01242           break;
01243 
01244         default:
01245           if (data > 2047) return CMD_ERROR;
01246           break;
01247       }
01248       break;
01249 
01250     case MOF_COND_DESTINATION:
01251       if (data >= v->GetNumOrders()) return CMD_ERROR;
01252       break;
01253   }
01254 
01255   if (flags & DC_EXEC) {
01256     switch (mof) {
01257       case MOF_NON_STOP:
01258         order->SetNonStopType((OrderNonStopFlags)data);
01259         break;
01260 
01261       case MOF_STOP_LOCATION:
01262         order->SetStopLocation((OrderStopLocation)data);
01263         break;
01264 
01265       case MOF_UNLOAD:
01266         order->SetUnloadType((OrderUnloadFlags)data);
01267         break;
01268 
01269       case MOF_LOAD:
01270         order->SetLoadType((OrderLoadFlags)data);
01271         break;
01272 
01273       case MOF_DEPOT_ACTION: {
01274         switch (data) {
01275           case DA_ALWAYS_GO:
01276             order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
01277             order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
01278             break;
01279 
01280           case DA_SERVICE:
01281             order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() | ODTFB_SERVICE));
01282             order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
01283             break;
01284 
01285           case DA_STOP:
01286             order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
01287             order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() | ODATFB_HALT));
01288             break;
01289 
01290           default:
01291             NOT_REACHED();
01292         }
01293         break;
01294       }
01295 
01296       case MOF_COND_VARIABLE: {
01297         order->SetConditionVariable((OrderConditionVariable)data);
01298 
01299         OrderConditionComparator occ = order->GetConditionComparator();
01300         switch (order->GetConditionVariable()) {
01301           case OCV_UNCONDITIONALLY:
01302             order->SetConditionComparator(OCC_EQUALS);
01303             order->SetConditionValue(0);
01304             break;
01305 
01306           case OCV_REQUIRES_SERVICE:
01307             if (occ != OCC_IS_TRUE && occ != OCC_IS_FALSE) order->SetConditionComparator(OCC_IS_TRUE);
01308             break;
01309 
01310           case OCV_LOAD_PERCENTAGE:
01311           case OCV_RELIABILITY:
01312             if (order->GetConditionValue() > 100) order->SetConditionValue(100);
01313             /* FALL THROUGH */
01314           default:
01315             if (occ == OCC_IS_TRUE || occ == OCC_IS_FALSE) order->SetConditionComparator(OCC_EQUALS);
01316             break;
01317         }
01318         break;
01319       }
01320 
01321       case MOF_COND_COMPARATOR:
01322         order->SetConditionComparator((OrderConditionComparator)data);
01323         break;
01324 
01325       case MOF_COND_VALUE:
01326         order->SetConditionValue(data);
01327         break;
01328 
01329       case MOF_COND_DESTINATION:
01330         order->SetConditionSkipToOrder(data);
01331         break;
01332 
01333       default: NOT_REACHED();
01334     }
01335 
01336     /* Update the windows and full load flags, also for vehicles that share the same order list */
01337     Vehicle *u = v->FirstShared();
01338     DeleteOrderWarnings(u);
01339     for (; u != NULL; u = u->NextShared()) {
01340       /* Toggle u->current_order "Full load" flag if it changed.
01341        * However, as the same flag is used for depot orders, check
01342        * whether we are not going to a depot as there are three
01343        * cases where the full load flag can be active and only
01344        * one case where the flag is used for depot orders. In the
01345        * other cases for the OrderTypeByte the flags are not used,
01346        * so do not care and those orders should not be active
01347        * when this function is called.
01348        */
01349       if (sel_ord == u->cur_real_order_index &&
01350           (u->current_order.IsType(OT_GOTO_STATION) || u->current_order.IsType(OT_LOADING)) &&
01351           u->current_order.GetLoadType() != order->GetLoadType()) {
01352         u->current_order.SetLoadType(order->GetLoadType());
01353       }
01354       InvalidateVehicleOrder(u, -2);
01355     }
01356   }
01357 
01358   return CommandCost();
01359 }
01360 
01372 CommandCost CmdCloneOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01373 {
01374   VehicleID veh_src = GB(p2, 0, 20);
01375   VehicleID veh_dst = GB(p1, 0, 20);
01376 
01377   Vehicle *dst = Vehicle::GetIfValid(veh_dst);
01378   if (dst == NULL || !dst->IsPrimaryVehicle()) return CMD_ERROR;
01379 
01380   CommandCost ret = CheckOwnership(dst->owner);
01381   if (ret.Failed()) return ret;
01382 
01383   switch (GB(p1, 30, 2)) {
01384     case CO_SHARE: {
01385       Vehicle *src = Vehicle::GetIfValid(veh_src);
01386 
01387       /* Sanity checks */
01388       if (src == NULL || !src->IsPrimaryVehicle() || dst->type != src->type || dst == src) return CMD_ERROR;
01389 
01390       CommandCost ret = CheckOwnership(src->owner);
01391       if (ret.Failed()) return ret;
01392 
01393       /* Trucks can't share orders with busses (and visa versa) */
01394       if (src->type == VEH_ROAD && RoadVehicle::From(src)->IsBus() != RoadVehicle::From(dst)->IsBus()) {
01395         return CMD_ERROR;
01396       }
01397 
01398       /* Is the vehicle already in the shared list? */
01399       if (src->FirstShared() == dst->FirstShared()) return CMD_ERROR;
01400 
01401       const Order *order;
01402 
01403       FOR_VEHICLE_ORDERS(src, order) {
01404         if (OrderGoesToStation(dst, order) &&
01405             !CanVehicleUseStation(dst, Station::Get(order->GetDestination()))) {
01406           return_cmd_error(STR_ERROR_CAN_T_COPY_SHARE_ORDER);
01407         }
01408       }
01409 
01410       if (src->orders.list == NULL && !OrderList::CanAllocateItem()) {
01411         return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
01412       }
01413 
01414       if (flags & DC_EXEC) {
01415         /* If the destination vehicle had a OrderList, destroy it.
01416          * We only reset the order indices, if the new orders are obviously different.
01417          * (We mainly do this to keep the order indices valid and in range.) */
01418         DeleteVehicleOrders(dst, false, dst->GetNumOrders() != src->GetNumOrders());
01419 
01420         dst->orders.list = src->orders.list;
01421 
01422         /* Link this vehicle in the shared-list */
01423         dst->AddToShared(src);
01424 
01425         InvalidateVehicleOrder(dst, -1);
01426         InvalidateVehicleOrder(src, -2);
01427 
01428         InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
01429       }
01430       break;
01431     }
01432 
01433     case CO_COPY: {
01434       Vehicle *src = Vehicle::GetIfValid(veh_src);
01435 
01436       /* Sanity checks */
01437       if (src == NULL || !src->IsPrimaryVehicle() || dst->type != src->type || dst == src) return CMD_ERROR;
01438 
01439       CommandCost ret = CheckOwnership(src->owner);
01440       if (ret.Failed()) return ret;
01441 
01442       /* Trucks can't copy all the orders from busses (and visa versa),
01443        * and neither can helicopters and aircarft. */
01444       const Order *order;
01445       FOR_VEHICLE_ORDERS(src, order) {
01446         if (OrderGoesToStation(dst, order) &&
01447             !CanVehicleUseStation(dst, Station::Get(order->GetDestination()))) {
01448           return_cmd_error(STR_ERROR_CAN_T_COPY_SHARE_ORDER);
01449         }
01450       }
01451 
01452       /* make sure there are orders available */
01453       int delta = dst->IsOrderListShared() ? src->GetNumOrders() + 1 : src->GetNumOrders() - dst->GetNumOrders();
01454       if (!Order::CanAllocateItem(delta) ||
01455           ((dst->orders.list == NULL || dst->IsOrderListShared()) && !OrderList::CanAllocateItem())) {
01456         return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
01457       }
01458 
01459       if (flags & DC_EXEC) {
01460         const Order *order;
01461         Order *first = NULL;
01462         Order **order_dst;
01463 
01464         /* If the destination vehicle had an order list, destroy the chain but keep the OrderList.
01465          * We only reset the order indices, if the new orders are obviously different.
01466          * (We mainly do this to keep the order indices valid and in range.) */
01467         DeleteVehicleOrders(dst, true, dst->GetNumOrders() != src->GetNumOrders());
01468 
01469         order_dst = &first;
01470         FOR_VEHICLE_ORDERS(src, order) {
01471           *order_dst = new Order();
01472           (*order_dst)->AssignOrder(*order);
01473           order_dst = &(*order_dst)->next;
01474         }
01475         if (dst->orders.list == NULL) {
01476           dst->orders.list = new OrderList(first, dst);
01477         } else {
01478           assert(dst->orders.list->GetFirstOrder() == NULL);
01479           assert(!dst->orders.list->IsShared());
01480           delete dst->orders.list;
01481           dst->orders.list = new OrderList(first, dst);
01482         }
01483 
01484         InvalidateVehicleOrder(dst, -1);
01485 
01486         InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
01487       }
01488       break;
01489     }
01490 
01491     case CO_UNSHARE: return DecloneOrder(dst, flags);
01492     default: return CMD_ERROR;
01493   }
01494 
01495   return CommandCost();
01496 }
01497 
01510 CommandCost CmdOrderRefit(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01511 {
01512   VehicleID veh = GB(p1, 0, 20);
01513   VehicleOrderID order_number  = GB(p2, 16, 8);
01514   CargoID cargo = GB(p2, 0, 8);
01515   byte subtype  = GB(p2, 8, 8);
01516 
01517   if (cargo >= NUM_CARGO && cargo != CT_NO_REFIT) return CMD_ERROR;
01518 
01519   const Vehicle *v = Vehicle::GetIfValid(veh);
01520   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01521 
01522   CommandCost ret = CheckOwnership(v->owner);
01523   if (ret.Failed()) return ret;
01524 
01525   Order *order = v->GetOrder(order_number);
01526   if (order == NULL) return CMD_ERROR;
01527 
01528   if (flags & DC_EXEC) {
01529     order->SetRefit(cargo, subtype);
01530 
01531     for (Vehicle *u = v->FirstShared(); u != NULL; u = u->NextShared()) {
01532       /* Update any possible open window of the vehicle */
01533       InvalidateVehicleOrder(u, -2);
01534 
01535       /* If the vehicle already got the current depot set as current order, then update current order as well */
01536       if (u->cur_real_order_index == order_number && (u->current_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) {
01537         u->current_order.SetRefit(cargo, subtype);
01538       }
01539     }
01540   }
01541 
01542   return CommandCost();
01543 }
01544 
01545 
01551 void CheckOrders(const Vehicle *v)
01552 {
01553   /* Does the user wants us to check things? */
01554   if (_settings_client.gui.order_review_system == 0) return;
01555 
01556   /* Do nothing for crashed vehicles */
01557   if (v->vehstatus & VS_CRASHED) return;
01558 
01559   /* Do nothing for stopped vehicles if setting is '1' */
01560   if (_settings_client.gui.order_review_system == 1 && (v->vehstatus & VS_STOPPED)) return;
01561 
01562   /* do nothing we we're not the first vehicle in a share-chain */
01563   if (v->FirstShared() != v) return;
01564 
01565   /* Only check every 20 days, so that we don't flood the message log */
01566   if (v->owner == _local_company && v->day_counter % 20 == 0) {
01567     int n_st, problem_type = -1;
01568     const Order *order;
01569     int message = 0;
01570 
01571     /* Check the order list */
01572     n_st = 0;
01573 
01574     FOR_VEHICLE_ORDERS(v, order) {
01575       /* Dummy order? */
01576       if (order->IsType(OT_DUMMY)) {
01577         problem_type = 1;
01578         break;
01579       }
01580       /* Does station have a load-bay for this vehicle? */
01581       if (order->IsType(OT_GOTO_STATION)) {
01582         const Station *st = Station::Get(order->GetDestination());
01583 
01584         n_st++;
01585         if (!CanVehicleUseStation(v, st)) problem_type = 3;
01586       }
01587     }
01588 
01589     /* Check if the last and the first order are the same */
01590     if (v->GetNumOrders() > 1) {
01591       const Order *last = v->GetLastOrder();
01592 
01593       if (v->orders.list->GetFirstOrder()->Equals(*last)) {
01594         problem_type = 2;
01595       }
01596     }
01597 
01598     /* Do we only have 1 station in our order list? */
01599     if (n_st < 2 && problem_type == -1) problem_type = 0;
01600 
01601 #ifndef NDEBUG
01602     if (v->orders.list != NULL) v->orders.list->DebugCheckSanity();
01603 #endif
01604 
01605     /* We don't have a problem */
01606     if (problem_type < 0) return;
01607 
01608     message = STR_NEWS_VEHICLE_HAS_TOO_FEW_ORDERS + problem_type;
01609     //DEBUG(misc, 3, "Triggered News Item for vehicle %d", v->index);
01610 
01611     SetDParam(0, v->index);
01612     AddVehicleNewsItem(
01613       message,
01614       NS_ADVICE,
01615       v->index
01616     );
01617   }
01618 }
01619 
01625 void RemoveOrderFromAllVehicles(OrderType type, DestinationID destination)
01626 {
01627   Vehicle *v;
01628 
01629   /* Aircraft have StationIDs for depot orders and never use DepotIDs
01630    * This fact is handled specially below
01631    */
01632 
01633   /* Go through all vehicles */
01634   FOR_ALL_VEHICLES(v) {
01635     Order *order;
01636 
01637     order = &v->current_order;
01638     if ((v->type == VEH_AIRCRAFT && order->IsType(OT_GOTO_DEPOT) ? OT_GOTO_STATION : order->GetType()) == type &&
01639         v->current_order.GetDestination() == destination) {
01640       order->MakeDummy();
01641       SetWindowDirty(WC_VEHICLE_VIEW, v->index);
01642     }
01643 
01644     /* Clear the order from the order-list */
01645     int id = -1;
01646     FOR_VEHICLE_ORDERS(v, order) {
01647       id++;
01648 restart:
01649 
01650       OrderType ot = order->GetType();
01651       if (ot == OT_GOTO_DEPOT && (order->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0) continue;
01652       if (ot == OT_AUTOMATIC || (v->type == VEH_AIRCRAFT && ot == OT_GOTO_DEPOT)) ot = OT_GOTO_STATION;
01653       if (ot == type && order->GetDestination() == destination) {
01654         /* We want to clear automatic orders, but we don't want to make them
01655          * dummy orders. They should just vanish. Also check the actual order
01656          * type as ot is currently OT_GOTO_STATION. */
01657         if (order->IsType(OT_AUTOMATIC)) {
01658           order = order->next; // DeleteOrder() invalidates current order
01659           DeleteOrder(v, id);
01660           if (order != NULL) goto restart;
01661           break;
01662         }
01663 
01664         order->MakeDummy();
01665         for (const Vehicle *w = v->FirstShared(); w != NULL; w = w->NextShared()) {
01666           /* In GUI, simulate by removing the order and adding it back */
01667           InvalidateVehicleOrder(w, id | (INVALID_VEH_ORDER_ID << 8));
01668           InvalidateVehicleOrder(w, (INVALID_VEH_ORDER_ID << 8) | id);
01669         }
01670       }
01671     }
01672   }
01673 }
01674 
01679 bool Vehicle::HasDepotOrder() const
01680 {
01681   const Order *order;
01682 
01683   FOR_VEHICLE_ORDERS(this, order) {
01684     if (order->IsType(OT_GOTO_DEPOT)) return true;
01685   }
01686 
01687   return false;
01688 }
01689 
01699 void DeleteVehicleOrders(Vehicle *v, bool keep_orderlist, bool reset_order_indices)
01700 {
01701   DeleteOrderWarnings(v);
01702 
01703   if (v->IsOrderListShared()) {
01704     /* Remove ourself from the shared order list. */
01705     v->RemoveFromShared();
01706     v->orders.list = NULL;
01707   } else if (v->orders.list != NULL) {
01708     /* Remove the orders */
01709     v->orders.list->FreeChain(keep_orderlist);
01710     if (!keep_orderlist) v->orders.list = NULL;
01711   }
01712 
01713   if (reset_order_indices) {
01714     v->cur_auto_order_index = v->cur_real_order_index = 0;
01715     if (v->current_order.IsType(OT_LOADING)) {
01716       CancelLoadingDueToDeletedOrder(v);
01717     }
01718   }
01719 }
01720 
01728 uint16 GetServiceIntervalClamped(uint interval, CompanyID company_id)
01729 {
01730   return (Company::Get(company_id)->settings.vehicle.servint_ispercent) ? Clamp(interval, MIN_SERVINT_PERCENT, MAX_SERVINT_PERCENT) : Clamp(interval, MIN_SERVINT_DAYS, MAX_SERVINT_DAYS);
01731 }
01732 
01741 static bool CheckForValidOrders(const Vehicle *v)
01742 {
01743   const Order *order;
01744 
01745   FOR_VEHICLE_ORDERS(v, order) {
01746     switch (order->GetType()) {
01747       case OT_GOTO_STATION:
01748       case OT_GOTO_DEPOT:
01749       case OT_GOTO_WAYPOINT:
01750         return true;
01751 
01752       default:
01753         break;
01754     }
01755   }
01756 
01757   return false;
01758 }
01759 
01763 static bool OrderConditionCompare(OrderConditionComparator occ, int variable, int value)
01764 {
01765   switch (occ) {
01766     case OCC_EQUALS:      return variable == value;
01767     case OCC_NOT_EQUALS:  return variable != value;
01768     case OCC_LESS_THAN:   return variable <  value;
01769     case OCC_LESS_EQUALS: return variable <= value;
01770     case OCC_MORE_THAN:   return variable >  value;
01771     case OCC_MORE_EQUALS: return variable >= value;
01772     case OCC_IS_TRUE:     return variable != 0;
01773     case OCC_IS_FALSE:    return variable == 0;
01774     default: NOT_REACHED();
01775   }
01776 }
01777 
01784 VehicleOrderID ProcessConditionalOrder(const Order *order, const Vehicle *v)
01785 {
01786   if (order->GetType() != OT_CONDITIONAL) return INVALID_VEH_ORDER_ID;
01787 
01788   bool skip_order = false;
01789   OrderConditionComparator occ = order->GetConditionComparator();
01790   uint16 value = order->GetConditionValue();
01791 
01792   switch (order->GetConditionVariable()) {
01793     case OCV_LOAD_PERCENTAGE:  skip_order = OrderConditionCompare(occ, CalcPercentVehicleFilled(v, NULL), value); break;
01794     case OCV_RELIABILITY:      skip_order = OrderConditionCompare(occ, ToPercent16(v->reliability),       value); break;
01795     case OCV_MAX_SPEED:        skip_order = OrderConditionCompare(occ, v->GetDisplayMaxSpeed() * 10 / 16, value); break;
01796     case OCV_AGE:              skip_order = OrderConditionCompare(occ, v->age / DAYS_IN_LEAP_YEAR,        value); break;
01797     case OCV_REQUIRES_SERVICE: skip_order = OrderConditionCompare(occ, v->NeedsServicing(),               value); break;
01798     case OCV_UNCONDITIONALLY:  skip_order = true; break;
01799     default: NOT_REACHED();
01800   }
01801 
01802   return skip_order ? order->GetConditionSkipToOrder() : (VehicleOrderID)INVALID_VEH_ORDER_ID;
01803 }
01804 
01811 bool UpdateOrderDest(Vehicle *v, const Order *order, int conditional_depth)
01812 {
01813   if (conditional_depth > v->GetNumOrders()) return false;
01814 
01815   switch (order->GetType()) {
01816     case OT_GOTO_STATION:
01817       v->dest_tile = v->GetOrderStationLocation(order->GetDestination());
01818       return true;
01819 
01820     case OT_GOTO_DEPOT:
01821       if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !v->NeedsServicing()) {
01822         UpdateVehicleTimetable(v, true);
01823         v->IncrementRealOrderIndex();
01824         break;
01825       }
01826 
01827       if (v->current_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) {
01828         /* We need to search for the nearest depot (hangar). */
01829         TileIndex location;
01830         DestinationID destination;
01831         bool reverse;
01832 
01833         if (v->FindClosestDepot(&location, &destination, &reverse)) {
01834           v->dest_tile = location;
01835           v->current_order.MakeGoToDepot(destination, v->current_order.GetDepotOrderType(), v->current_order.GetNonStopType(), (OrderDepotActionFlags)(v->current_order.GetDepotActionType() & ~ODATFB_NEAREST_DEPOT), v->current_order.GetRefitCargo(), v->current_order.GetRefitSubtype());
01836 
01837           /* If there is no depot in front, reverse automatically (trains only) */
01838           if (v->type == VEH_TRAIN && reverse) DoCommand(v->tile, v->index, 0, DC_EXEC, CMD_REVERSE_TRAIN_DIRECTION);
01839 
01840           if (v->type == VEH_AIRCRAFT) {
01841             Aircraft *a = Aircraft::From(v);
01842             if (a->state == FLYING && a->targetairport != destination) {
01843               /* The aircraft is now heading for a different hangar than the next in the orders */
01844               extern void AircraftNextAirportPos_and_Order(Aircraft *a);
01845               AircraftNextAirportPos_and_Order(a);
01846             }
01847           }
01848           return true;
01849         }
01850 
01851         UpdateVehicleTimetable(v, true);
01852         v->IncrementRealOrderIndex();
01853       } else {
01854         if (v->type != VEH_AIRCRAFT) {
01855           v->dest_tile = Depot::Get(order->GetDestination())->xy;
01856         }
01857         return true;
01858       }
01859       break;
01860 
01861     case OT_GOTO_WAYPOINT:
01862       v->dest_tile = Waypoint::Get(order->GetDestination())->xy;
01863       return true;
01864 
01865     case OT_CONDITIONAL: {
01866       VehicleOrderID next_order = ProcessConditionalOrder(order, v);
01867       if (next_order != INVALID_VEH_ORDER_ID) {
01868         /* Jump to next_order. cur_auto_order_index becomes exactly that order,
01869          * cur_real_order_index might come after next_order. */
01870         UpdateVehicleTimetable(v, false);
01871         v->cur_auto_order_index = v->cur_real_order_index = next_order;
01872         v->UpdateRealOrderIndex();
01873         v->current_order_time += v->GetOrder(v->cur_real_order_index)->travel_time;
01874 
01875         /* Disable creation of automatic orders.
01876          * When inserting them we do not know that we would have to make the conditional orders point to them. */
01877         if (v->IsGroundVehicle()) {
01878           uint16 &gv_flags = v->GetGroundVehicleFlags();
01879           SetBit(gv_flags, GVF_SUPPRESS_AUTOMATIC_ORDERS);
01880         }
01881       } else {
01882         UpdateVehicleTimetable(v, true);
01883         v->IncrementRealOrderIndex();
01884       }
01885       break;
01886     }
01887 
01888     default:
01889       v->dest_tile = 0;
01890       return false;
01891   }
01892 
01893   assert(v->cur_auto_order_index < v->GetNumOrders());
01894   assert(v->cur_real_order_index < v->GetNumOrders());
01895 
01896   /* Get the current order */
01897   order = v->GetOrder(v->cur_real_order_index);
01898   if (order != NULL && order->IsType(OT_AUTOMATIC)) {
01899     assert(v->GetNumManualOrders() == 0);
01900     order = NULL;
01901   }
01902 
01903   if (order == NULL) {
01904     v->current_order.Free();
01905     v->dest_tile = 0;
01906     return false;
01907   }
01908 
01909   v->current_order = *order;
01910   return UpdateOrderDest(v, order, conditional_depth + 1);
01911 }
01912 
01920 bool ProcessOrders(Vehicle *v)
01921 {
01922   switch (v->current_order.GetType()) {
01923     case OT_GOTO_DEPOT:
01924       /* Let a depot order in the orderlist interrupt. */
01925       if (!(v->current_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) return false;
01926       break;
01927 
01928     case OT_LOADING:
01929       return false;
01930 
01931     case OT_LEAVESTATION:
01932       if (v->type != VEH_AIRCRAFT) return false;
01933       break;
01934 
01935     default: break;
01936   }
01937 
01945   bool may_reverse = v->current_order.IsType(OT_NOTHING);
01946 
01947   /* Check if we've reached a 'via' destination. */
01948   if (((v->current_order.IsType(OT_GOTO_STATION) && (v->current_order.GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION)) || v->current_order.IsType(OT_GOTO_WAYPOINT)) &&
01949       IsTileType(v->tile, MP_STATION) &&
01950       v->current_order.GetDestination() == GetStationIndex(v->tile)) {
01951     v->DeleteUnreachedAutoOrders();
01952     /* We set the last visited station here because we do not want
01953      * the train to stop at this 'via' station if the next order
01954      * is a no-non-stop order; in that case not setting the last
01955      * visited station will cause the vehicle to still stop. */
01956     v->last_station_visited = v->current_order.GetDestination();
01957     UpdateVehicleTimetable(v, true);
01958     v->IncrementAutoOrderIndex();
01959   }
01960 
01961   /* Get the current order */
01962   assert(v->cur_auto_order_index == 0 || v->cur_auto_order_index < v->GetNumOrders());
01963   v->UpdateRealOrderIndex();
01964 
01965   const Order *order = v->GetOrder(v->cur_real_order_index);
01966   if (order != NULL && order->IsType(OT_AUTOMATIC)) {
01967     assert(v->GetNumManualOrders() == 0);
01968     order = NULL;
01969   }
01970 
01971   /* If no order, do nothing. */
01972   if (order == NULL || (v->type == VEH_AIRCRAFT && !CheckForValidOrders(v))) {
01973     if (v->type == VEH_AIRCRAFT) {
01974       /* Aircraft do something vastly different here, so handle separately */
01975       extern void HandleMissingAircraftOrders(Aircraft *v);
01976       HandleMissingAircraftOrders(Aircraft::From(v));
01977       return false;
01978     }
01979 
01980     v->current_order.Free();
01981     v->dest_tile = 0;
01982     return false;
01983   }
01984 
01985   /* If it is unchanged, keep it. */
01986   if (order->Equals(v->current_order) && (v->type == VEH_AIRCRAFT || v->dest_tile != 0) &&
01987       (v->type != VEH_SHIP || !order->IsType(OT_GOTO_STATION) || Station::Get(order->GetDestination())->dock_tile != INVALID_TILE)) {
01988     return false;
01989   }
01990 
01991   /* Otherwise set it, and determine the destination tile. */
01992   v->current_order = *order;
01993 
01994   InvalidateVehicleOrder(v, -2);
01995   switch (v->type) {
01996     default:
01997       NOT_REACHED();
01998 
01999     case VEH_ROAD:
02000     case VEH_TRAIN:
02001       break;
02002 
02003     case VEH_AIRCRAFT:
02004     case VEH_SHIP:
02005       SetWindowClassesDirty(GetWindowClassForVehicleType(v->type));
02006       break;
02007   }
02008 
02009   return UpdateOrderDest(v, order) && may_reverse;
02010 }
02011 
02019 bool Order::ShouldStopAtStation(const Vehicle *v, StationID station) const
02020 {
02021   bool is_dest_station = this->IsType(OT_GOTO_STATION) && this->dest == station;
02022 
02023   return (!this->IsType(OT_GOTO_DEPOT) || (this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS) != 0) &&
02024       v->last_station_visited != station && // Do stop only when we've not just been there
02025       /* Finally do stop when there is no non-stop flag set for this type of station. */
02026       !(this->GetNonStopType() & (is_dest_station ? ONSF_NO_STOP_AT_DESTINATION_STATION : ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS));
02027 }
02028 
02029 void InitializeOrders()
02030 {
02031   _order_pool.CleanPool();
02032   _orderlist_pool.CleanPool();
02033 }

Generated on Sun May 15 19:20:12 2011 for OpenTTD by  doxygen 1.6.1