order_cmd.cpp

Go to the documentation of this file.
00001 /* $Id: order_cmd.cpp 23511 2011-12-13 21:10:43Z planetmaker $ */
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 #include "order_backup.h"
00031 
00032 #include "table/strings.h"
00033 
00034 /* DestinationID must be at least as large as every these below, because it can
00035  * be any of them
00036  */
00037 assert_compile(sizeof(DestinationID) >= sizeof(DepotID));
00038 assert_compile(sizeof(DestinationID) >= sizeof(StationID));
00039 
00040 OrderPool _order_pool("Order");
00041 INSTANTIATE_POOL_METHODS(Order)
00042 OrderListPool _orderlist_pool("OrderList");
00043 INSTANTIATE_POOL_METHODS(OrderList)
00044 
00046 Order::~Order()
00047 {
00048   if (CleaningPool()) return;
00049 
00050   /* We can visit oil rigs and buoys that are not our own. They will be shown in
00051    * the list of stations. So, we need to invalidate that window if needed. */
00052   if (this->IsType(OT_GOTO_STATION) || this->IsType(OT_GOTO_WAYPOINT)) {
00053     BaseStation *bs = BaseStation::GetIfValid(this->GetDestination());
00054     if (bs != NULL && bs->owner == OWNER_NONE) InvalidateWindowClassesData(WC_STATION_LIST, 0);
00055   }
00056 }
00057 
00062 void Order::Free()
00063 {
00064   this->type  = OT_NOTHING;
00065   this->flags = 0;
00066   this->dest  = 0;
00067   this->next  = NULL;
00068 }
00069 
00074 void Order::MakeGoToStation(StationID destination)
00075 {
00076   this->type = OT_GOTO_STATION;
00077   this->flags = 0;
00078   this->dest = destination;
00079 }
00080 
00090 void Order::MakeGoToDepot(DepotID destination, OrderDepotTypeFlags order, OrderNonStopFlags non_stop_type, OrderDepotActionFlags action, CargoID cargo, byte subtype)
00091 {
00092   this->type = OT_GOTO_DEPOT;
00093   this->SetDepotOrderType(order);
00094   this->SetDepotActionType(action);
00095   this->SetNonStopType(non_stop_type);
00096   this->dest = destination;
00097   this->SetRefit(cargo, subtype);
00098 }
00099 
00104 void Order::MakeGoToWaypoint(StationID destination)
00105 {
00106   this->type = OT_GOTO_WAYPOINT;
00107   this->flags = 0;
00108   this->dest = destination;
00109 }
00110 
00115 void Order::MakeLoading(bool ordered)
00116 {
00117   this->type = OT_LOADING;
00118   if (!ordered) this->flags = 0;
00119 }
00120 
00124 void Order::MakeLeaveStation()
00125 {
00126   this->type = OT_LEAVESTATION;
00127   this->flags = 0;
00128 }
00129 
00133 void Order::MakeDummy()
00134 {
00135   this->type = OT_DUMMY;
00136   this->flags = 0;
00137 }
00138 
00143 void Order::MakeConditional(VehicleOrderID order)
00144 {
00145   this->type = OT_CONDITIONAL;
00146   this->flags = order;
00147   this->dest = 0;
00148 }
00149 
00154 void Order::MakeImplicit(StationID destination)
00155 {
00156   this->type = OT_IMPLICIT;
00157   this->dest = destination;
00158 }
00159 
00166 void Order::SetRefit(CargoID cargo, byte subtype)
00167 {
00168   this->refit_cargo = cargo;
00169   this->refit_subtype = subtype;
00170 }
00171 
00177 bool Order::Equals(const Order &other) const
00178 {
00179   /* In case of go to nearest depot orders we need "only" compare the flags
00180    * with the other and not the nearest depot order bit or the actual
00181    * destination because those get clear/filled in during the order
00182    * evaluation. If we do not do this the order will continuously be seen as
00183    * a different order and it will try to find a "nearest depot" every tick. */
00184   if ((this->IsType(OT_GOTO_DEPOT) && this->type == other.type) &&
00185       ((this->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0 ||
00186        (other.GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0)) {
00187     return this->GetDepotOrderType() == other.GetDepotOrderType() &&
00188         (this->GetDepotActionType() & ~ODATFB_NEAREST_DEPOT) == (other.GetDepotActionType() & ~ODATFB_NEAREST_DEPOT);
00189   }
00190 
00191   return this->type == other.type && this->flags == other.flags && this->dest == other.dest;
00192 }
00193 
00200 uint32 Order::Pack() const
00201 {
00202   return this->dest << 16 | this->flags << 8 | this->type;
00203 }
00204 
00210 uint16 Order::MapOldOrder() const
00211 {
00212   uint16 order = this->GetType();
00213   switch (this->type) {
00214     case OT_GOTO_STATION:
00215       if (this->GetUnloadType() & OUFB_UNLOAD) SetBit(order, 5);
00216       if (this->GetLoadType() & OLFB_FULL_LOAD) SetBit(order, 6);
00217       if (this->GetNonStopType() & ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS) SetBit(order, 7);
00218       order |= GB(this->GetDestination(), 0, 8) << 8;
00219       break;
00220     case OT_GOTO_DEPOT:
00221       if (!(this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) SetBit(order, 6);
00222       SetBit(order, 7);
00223       order |= GB(this->GetDestination(), 0, 8) << 8;
00224       break;
00225     case OT_LOADING:
00226       if (this->GetLoadType() & OLFB_FULL_LOAD) SetBit(order, 6);
00227       break;
00228   }
00229   return order;
00230 }
00231 
00236 Order::Order(uint32 packed)
00237 {
00238   this->type    = (OrderType)GB(packed,  0,  8);
00239   this->flags   = GB(packed,  8,  8);
00240   this->dest    = GB(packed, 16, 16);
00241   this->next    = NULL;
00242   this->refit_cargo   = CT_NO_REFIT;
00243   this->refit_subtype = 0;
00244   this->wait_time     = 0;
00245   this->travel_time   = 0;
00246 }
00247 
00253 void InvalidateVehicleOrder(const Vehicle *v, int data)
00254 {
00255   SetWindowDirty(WC_VEHICLE_VIEW, v->index);
00256 
00257   if (data != 0) {
00258     /* Calls SetDirty() too */
00259     InvalidateWindowData(WC_VEHICLE_ORDERS,    v->index, data);
00260     InvalidateWindowData(WC_VEHICLE_TIMETABLE, v->index, data);
00261     return;
00262   }
00263 
00264   SetWindowDirty(WC_VEHICLE_ORDERS,    v->index);
00265   SetWindowDirty(WC_VEHICLE_TIMETABLE, v->index);
00266 }
00267 
00275 void Order::AssignOrder(const Order &other)
00276 {
00277   this->type  = other.type;
00278   this->flags = other.flags;
00279   this->dest  = other.dest;
00280 
00281   this->refit_cargo   = other.refit_cargo;
00282   this->refit_subtype = other.refit_subtype;
00283 
00284   this->wait_time   = other.wait_time;
00285   this->travel_time = other.travel_time;
00286 }
00287 
00293 void OrderList::Initialize(Order *chain, Vehicle *v)
00294 {
00295   this->first = chain;
00296   this->first_shared = v;
00297 
00298   this->num_orders = 0;
00299   this->num_manual_orders = 0;
00300   this->num_vehicles = 1;
00301   this->timetable_duration = 0;
00302 
00303   for (Order *o = this->first; o != NULL; o = o->next) {
00304     ++this->num_orders;
00305     if (!o->IsType(OT_IMPLICIT)) ++this->num_manual_orders;
00306     this->timetable_duration += o->wait_time + o->travel_time;
00307   }
00308 
00309   for (Vehicle *u = this->first_shared->PreviousShared(); u != NULL; u = u->PreviousShared()) {
00310     ++this->num_vehicles;
00311     this->first_shared = u;
00312   }
00313 
00314   for (const Vehicle *u = v->NextShared(); u != NULL; u = u->NextShared()) ++this->num_vehicles;
00315 }
00316 
00322 void OrderList::FreeChain(bool keep_orderlist)
00323 {
00324   Order *next;
00325   for (Order *o = this->first; o != NULL; o = next) {
00326     next = o->next;
00327     delete o;
00328   }
00329 
00330   if (keep_orderlist) {
00331     this->first = NULL;
00332     this->num_orders = 0;
00333     this->num_manual_orders = 0;
00334     this->timetable_duration = 0;
00335   } else {
00336     delete this;
00337   }
00338 }
00339 
00345 Order *OrderList::GetOrderAt(int index) const
00346 {
00347   if (index < 0) return NULL;
00348 
00349   Order *order = this->first;
00350 
00351   while (order != NULL && index-- > 0) {
00352     order = order->next;
00353   }
00354   return order;
00355 }
00356 
00362 void OrderList::InsertOrderAt(Order *new_order, int index)
00363 {
00364   if (this->first == NULL) {
00365     this->first = new_order;
00366   } else {
00367     if (index == 0) {
00368       /* Insert as first or only order */
00369       new_order->next = this->first;
00370       this->first = new_order;
00371     } else if (index >= this->num_orders) {
00372       /* index is after the last order, add it to the end */
00373       this->GetLastOrder()->next = new_order;
00374     } else {
00375       /* Put the new order in between */
00376       Order *order = this->GetOrderAt(index - 1);
00377       new_order->next = order->next;
00378       order->next = new_order;
00379     }
00380   }
00381   ++this->num_orders;
00382   if (!new_order->IsType(OT_IMPLICIT)) ++this->num_manual_orders;
00383   this->timetable_duration += new_order->wait_time + new_order->travel_time;
00384 
00385   /* We can visit oil rigs and buoys that are not our own. They will be shown in
00386    * the list of stations. So, we need to invalidate that window if needed. */
00387   if (new_order->IsType(OT_GOTO_STATION) || new_order->IsType(OT_GOTO_WAYPOINT)) {
00388     BaseStation *bs = BaseStation::Get(new_order->GetDestination());
00389     if (bs->owner == OWNER_NONE) InvalidateWindowClassesData(WC_STATION_LIST, 0);
00390   }
00391 
00392 }
00393 
00394 
00399 void OrderList::DeleteOrderAt(int index)
00400 {
00401   if (index >= this->num_orders) return;
00402 
00403   Order *to_remove;
00404 
00405   if (index == 0) {
00406     to_remove = this->first;
00407     this->first = to_remove->next;
00408   } else {
00409     Order *prev = GetOrderAt(index - 1);
00410     to_remove = prev->next;
00411     prev->next = to_remove->next;
00412   }
00413   --this->num_orders;
00414   if (!to_remove->IsType(OT_IMPLICIT)) --this->num_manual_orders;
00415   this->timetable_duration -= (to_remove->wait_time + to_remove->travel_time);
00416   delete to_remove;
00417 }
00418 
00424 void OrderList::MoveOrder(int from, int to)
00425 {
00426   if (from >= this->num_orders || to >= this->num_orders || from == to) return;
00427 
00428   Order *moving_one;
00429 
00430   /* Take the moving order out of the pointer-chain */
00431   if (from == 0) {
00432     moving_one = this->first;
00433     this->first = moving_one->next;
00434   } else {
00435     Order *one_before = GetOrderAt(from - 1);
00436     moving_one = one_before->next;
00437     one_before->next = moving_one->next;
00438   }
00439 
00440   /* Insert the moving_order again in the pointer-chain */
00441   if (to == 0) {
00442     moving_one->next = this->first;
00443     this->first = moving_one;
00444   } else {
00445     Order *one_before = GetOrderAt(to - 1);
00446     moving_one->next = one_before->next;
00447     one_before->next = moving_one;
00448   }
00449 }
00450 
00456 void OrderList::RemoveVehicle(Vehicle *v)
00457 {
00458   --this->num_vehicles;
00459   if (v == this->first_shared) this->first_shared = v->NextShared();
00460 }
00461 
00466 bool OrderList::IsVehicleInSharedOrdersList(const Vehicle *v) const
00467 {
00468   for (const Vehicle *v_shared = this->first_shared; v_shared != NULL; v_shared = v_shared->NextShared()) {
00469     if (v_shared == v) return true;
00470   }
00471 
00472   return false;
00473 }
00474 
00480 int OrderList::GetPositionInSharedOrderList(const Vehicle *v) const
00481 {
00482   int count = 0;
00483   for (const Vehicle *v_shared = v->PreviousShared(); v_shared != NULL; v_shared = v_shared->PreviousShared()) count++;
00484   return count;
00485 }
00486 
00491 bool OrderList::IsCompleteTimetable() const
00492 {
00493   for (Order *o = this->first; o != NULL; o = o->next) {
00494     /* Implicit orders are, by definition, not timetabled. */
00495     if (o->IsType(OT_IMPLICIT)) continue;
00496     if (!o->IsCompletelyTimetabled()) return false;
00497   }
00498   return true;
00499 }
00500 
00504 void OrderList::DebugCheckSanity() const
00505 {
00506   VehicleOrderID check_num_orders = 0;
00507   VehicleOrderID check_num_manual_orders = 0;
00508   uint check_num_vehicles = 0;
00509   Ticks check_timetable_duration = 0;
00510 
00511   DEBUG(misc, 6, "Checking OrderList %hu for sanity...", this->index);
00512 
00513   for (const Order *o = this->first; o != NULL; o = o->next) {
00514     ++check_num_orders;
00515     if (!o->IsType(OT_IMPLICIT)) ++check_num_manual_orders;
00516     check_timetable_duration += o->wait_time + o->travel_time;
00517   }
00518   assert(this->num_orders == check_num_orders);
00519   assert(this->num_manual_orders == check_num_manual_orders);
00520   assert(this->timetable_duration == check_timetable_duration);
00521 
00522   for (const Vehicle *v = this->first_shared; v != NULL; v = v->NextShared()) {
00523     ++check_num_vehicles;
00524     assert(v->orders.list == this);
00525   }
00526   assert(this->num_vehicles == check_num_vehicles);
00527   DEBUG(misc, 6, "... detected %u orders (%u manual), %u vehicles, %i ticks",
00528       (uint)this->num_orders, (uint)this->num_manual_orders,
00529       this->num_vehicles, this->timetable_duration);
00530 }
00531 
00539 static inline bool OrderGoesToStation(const Vehicle *v, const Order *o)
00540 {
00541   return o->IsType(OT_GOTO_STATION) ||
00542       (v->type == VEH_AIRCRAFT && o->IsType(OT_GOTO_DEPOT) && !(o->GetDepotActionType() & ODATFB_NEAREST_DEPOT));
00543 }
00544 
00551 static void DeleteOrderWarnings(const Vehicle *v)
00552 {
00553   DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_TOO_FEW_ORDERS);
00554   DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_VOID_ORDER);
00555   DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_DUPLICATE_ENTRY);
00556   DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_INVALID_ENTRY);
00557 }
00558 
00565 TileIndex Order::GetLocation(const Vehicle *v, bool airport) const
00566 {
00567   switch (this->GetType()) {
00568     case OT_GOTO_WAYPOINT:
00569     case OT_GOTO_STATION:
00570     case OT_IMPLICIT:
00571       if (airport && v->type == VEH_AIRCRAFT) return Station::Get(this->GetDestination())->airport.tile;
00572       return BaseStation::Get(this->GetDestination())->xy;
00573 
00574     case OT_GOTO_DEPOT:
00575       if ((this->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0) return INVALID_TILE;
00576       return (v->type == VEH_AIRCRAFT) ? Station::Get(this->GetDestination())->xy : Depot::Get(this->GetDestination())->xy;
00577 
00578     default:
00579       return INVALID_TILE;
00580   }
00581 }
00582 
00592 uint GetOrderDistance(const Order *prev, const Order *cur, const Vehicle *v, int conditional_depth)
00593 {
00594   if (cur->IsType(OT_CONDITIONAL)) {
00595     if (conditional_depth > v->GetNumOrders()) return 0;
00596 
00597     conditional_depth++;
00598 
00599     int dist1 = GetOrderDistance(prev, v->GetOrder(cur->GetConditionSkipToOrder()), v, conditional_depth);
00600     int dist2 = GetOrderDistance(prev, cur->next == NULL ? v->orders.list->GetFirstOrder() : cur->next, v, conditional_depth);
00601     return max(dist1, dist2);
00602   }
00603 
00604   TileIndex prev_tile = prev->GetLocation(v, true);
00605   TileIndex cur_tile = cur->GetLocation(v, true);
00606   if (prev_tile == INVALID_TILE || cur_tile == INVALID_TILE) return 0;
00607   return v->type == VEH_AIRCRAFT ? DistanceSquare(prev_tile, cur_tile) : DistanceManhattan(prev_tile, cur_tile);
00608 }
00609 
00623 CommandCost CmdInsertOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00624 {
00625   VehicleID veh          = GB(p1,  0, 20);
00626   VehicleOrderID sel_ord = GB(p1, 20, 8);
00627   Order new_order(p2);
00628 
00629   Vehicle *v = Vehicle::GetIfValid(veh);
00630   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
00631 
00632   CommandCost ret = CheckOwnership(v->owner);
00633   if (ret.Failed()) return ret;
00634 
00635   /* Check if the inserted order is to the correct destination (owner, type),
00636    * and has the correct flags if any */
00637   switch (new_order.GetType()) {
00638     case OT_GOTO_STATION: {
00639       const Station *st = Station::GetIfValid(new_order.GetDestination());
00640       if (st == NULL) return CMD_ERROR;
00641 
00642       if (st->owner != OWNER_NONE) {
00643         CommandCost ret = CheckOwnership(st->owner);
00644         if (ret.Failed()) return ret;
00645       }
00646 
00647       if (!CanVehicleUseStation(v, st)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
00648       for (Vehicle *u = v->FirstShared(); u != NULL; u = u->NextShared()) {
00649         if (!CanVehicleUseStation(u, st)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER_SHARED);
00650       }
00651 
00652       /* Non stop only allowed for ground vehicles. */
00653       if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && !v->IsGroundVehicle()) return CMD_ERROR;
00654 
00655       /* Filter invalid load/unload types. */
00656       switch (new_order.GetLoadType()) {
00657         case OLF_LOAD_IF_POSSIBLE: case OLFB_FULL_LOAD: case OLF_FULL_LOAD_ANY: case OLFB_NO_LOAD: break;
00658         default: return CMD_ERROR;
00659       }
00660       switch (new_order.GetUnloadType()) {
00661         case OUF_UNLOAD_IF_POSSIBLE: case OUFB_UNLOAD: case OUFB_TRANSFER: case OUFB_NO_UNLOAD: break;
00662         default: return CMD_ERROR;
00663       }
00664 
00665       /* Filter invalid stop locations */
00666       switch (new_order.GetStopLocation()) {
00667         case OSL_PLATFORM_NEAR_END:
00668         case OSL_PLATFORM_MIDDLE:
00669           if (v->type != VEH_TRAIN) return CMD_ERROR;
00670           /* FALL THROUGH */
00671         case OSL_PLATFORM_FAR_END:
00672           break;
00673 
00674         default:
00675           return CMD_ERROR;
00676       }
00677 
00678       break;
00679     }
00680 
00681     case OT_GOTO_DEPOT: {
00682       if ((new_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) == 0) {
00683         if (v->type == VEH_AIRCRAFT) {
00684           const Station *st = Station::GetIfValid(new_order.GetDestination());
00685 
00686           if (st == NULL) return CMD_ERROR;
00687 
00688           CommandCost ret = CheckOwnership(st->owner);
00689           if (ret.Failed()) return ret;
00690 
00691           if (!CanVehicleUseStation(v, st) || !st->airport.HasHangar()) {
00692             return CMD_ERROR;
00693           }
00694         } else {
00695           const Depot *dp = Depot::GetIfValid(new_order.GetDestination());
00696 
00697           if (dp == NULL) return CMD_ERROR;
00698 
00699           CommandCost ret = CheckOwnership(GetTileOwner(dp->xy));
00700           if (ret.Failed()) return ret;
00701 
00702           switch (v->type) {
00703             case VEH_TRAIN:
00704               if (!IsRailDepotTile(dp->xy)) return CMD_ERROR;
00705               break;
00706 
00707             case VEH_ROAD:
00708               if (!IsRoadDepotTile(dp->xy)) return CMD_ERROR;
00709               break;
00710 
00711             case VEH_SHIP:
00712               if (!IsShipDepotTile(dp->xy)) return CMD_ERROR;
00713               break;
00714 
00715             default: return CMD_ERROR;
00716           }
00717         }
00718       }
00719 
00720       if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && !v->IsGroundVehicle()) return CMD_ERROR;
00721       if (new_order.GetDepotOrderType() & ~(ODTFB_PART_OF_ORDERS | ((new_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS) != 0 ? ODTFB_SERVICE : 0))) return CMD_ERROR;
00722       if (new_order.GetDepotActionType() & ~(ODATFB_HALT | ODATFB_NEAREST_DEPOT)) return CMD_ERROR;
00723       if ((new_order.GetDepotOrderType() & ODTFB_SERVICE) && (new_order.GetDepotActionType() & ODATFB_HALT)) return CMD_ERROR;
00724       break;
00725     }
00726 
00727     case OT_GOTO_WAYPOINT: {
00728       const Waypoint *wp = Waypoint::GetIfValid(new_order.GetDestination());
00729       if (wp == NULL) return CMD_ERROR;
00730 
00731       switch (v->type) {
00732         default: return CMD_ERROR;
00733 
00734         case VEH_TRAIN: {
00735           if (!(wp->facilities & FACIL_TRAIN)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
00736 
00737           CommandCost ret = CheckOwnership(wp->owner);
00738           if (ret.Failed()) return ret;
00739           break;
00740         }
00741 
00742         case VEH_SHIP:
00743           if (!(wp->facilities & FACIL_DOCK)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
00744           if (wp->owner != OWNER_NONE) {
00745             CommandCost ret = CheckOwnership(wp->owner);
00746             if (ret.Failed()) return ret;
00747           }
00748           break;
00749       }
00750 
00751       /* Order flags can be any of the following for waypoints:
00752        * [non-stop]
00753        * non-stop orders (if any) are only valid for trains */
00754       if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && v->type != VEH_TRAIN) return CMD_ERROR;
00755       break;
00756     }
00757 
00758     case OT_CONDITIONAL: {
00759       VehicleOrderID skip_to = new_order.GetConditionSkipToOrder();
00760       if (skip_to != 0 && skip_to >= v->GetNumOrders()) return CMD_ERROR; // Always allow jumping to the first (even when there is no order).
00761       if (new_order.GetConditionVariable() >= OCV_END) return CMD_ERROR;
00762 
00763       OrderConditionComparator occ = new_order.GetConditionComparator();
00764       if (occ >= OCC_END) return CMD_ERROR;
00765       switch (new_order.GetConditionVariable()) {
00766         case OCV_REQUIRES_SERVICE:
00767           if (occ != OCC_IS_TRUE && occ != OCC_IS_FALSE) return CMD_ERROR;
00768           break;
00769 
00770         case OCV_UNCONDITIONALLY:
00771           if (occ != OCC_EQUALS) return CMD_ERROR;
00772           if (new_order.GetConditionValue() != 0) return CMD_ERROR;
00773           break;
00774 
00775         case OCV_LOAD_PERCENTAGE:
00776         case OCV_RELIABILITY:
00777           if (new_order.GetConditionValue() > 100) return CMD_ERROR;
00778           /* FALL THROUGH */
00779         default:
00780           if (occ == OCC_IS_TRUE || occ == OCC_IS_FALSE) return CMD_ERROR;
00781           break;
00782       }
00783       break;
00784     }
00785 
00786     default: return CMD_ERROR;
00787   }
00788 
00789   if (sel_ord > v->GetNumOrders()) return CMD_ERROR;
00790 
00791   if (v->GetNumOrders() >= MAX_VEH_ORDER_ID) return_cmd_error(STR_ERROR_TOO_MANY_ORDERS);
00792   if (!Order::CanAllocateItem()) return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
00793   if (v->orders.list == NULL && !OrderList::CanAllocateItem()) return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
00794 
00795   if (v->type == VEH_SHIP && _settings_game.pf.pathfinder_for_ships != VPF_NPF) {
00796     /* Make sure the new destination is not too far away from the previous */
00797     const Order *prev = NULL;
00798     uint n = 0;
00799 
00800     /* Find the last goto station or depot order before the insert location.
00801      * If the order is to be inserted at the beginning of the order list this
00802      * finds the last order in the list. */
00803     const Order *o;
00804     FOR_VEHICLE_ORDERS(v, o) {
00805       switch (o->GetType()) {
00806         case OT_GOTO_STATION:
00807         case OT_GOTO_DEPOT:
00808         case OT_GOTO_WAYPOINT:
00809           prev = o;
00810           break;
00811 
00812         default: break;
00813       }
00814       if (++n == sel_ord && prev != NULL) break;
00815     }
00816     if (prev != NULL) {
00817       uint dist = GetOrderDistance(prev, &new_order, v);
00818       if (dist >= 130) {
00819         return_cmd_error(STR_ERROR_TOO_FAR_FROM_PREVIOUS_DESTINATION);
00820       }
00821     }
00822   }
00823 
00824   if (flags & DC_EXEC) {
00825     Order *new_o = new Order();
00826     new_o->AssignOrder(new_order);
00827     InsertOrder(v, new_o, sel_ord);
00828   }
00829 
00830   return CommandCost();
00831 }
00832 
00839 void InsertOrder(Vehicle *v, Order *new_o, VehicleOrderID sel_ord)
00840 {
00841   /* Create new order and link in list */
00842   if (v->orders.list == NULL) {
00843     v->orders.list = new OrderList(new_o, v);
00844   } else {
00845     v->orders.list->InsertOrderAt(new_o, sel_ord);
00846   }
00847 
00848   Vehicle *u = v->FirstShared();
00849   DeleteOrderWarnings(u);
00850   for (; u != NULL; u = u->NextShared()) {
00851     assert(v->orders.list == u->orders.list);
00852 
00853     /* If there is added an order before the current one, we need
00854      * to update the selected order. We do not change implicit/real order indices though.
00855      * If the new order is between the current implicit order and real order, the implicit order will
00856      * later skip the inserted order. */
00857     if (sel_ord <= u->cur_real_order_index) {
00858       uint cur = u->cur_real_order_index + 1;
00859       /* Check if we don't go out of bound */
00860       if (cur < u->GetNumOrders()) {
00861         u->cur_real_order_index = cur;
00862       }
00863     }
00864     if (sel_ord == u->cur_implicit_order_index && u->IsGroundVehicle()) {
00865       /* We are inserting an order just before the current implicit order.
00866        * We do not know whether we will reach current implicit or the newly inserted order first.
00867        * So, disable creation of implicit orders until we are on track again. */
00868       uint16 &gv_flags = u->GetGroundVehicleFlags();
00869       SetBit(gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
00870     }
00871     if (sel_ord <= u->cur_implicit_order_index) {
00872       uint cur = u->cur_implicit_order_index + 1;
00873       /* Check if we don't go out of bound */
00874       if (cur < u->GetNumOrders()) {
00875         u->cur_implicit_order_index = cur;
00876       }
00877     }
00878     /* Update any possible open window of the vehicle */
00879     InvalidateVehicleOrder(u, INVALID_VEH_ORDER_ID | (sel_ord << 8));
00880   }
00881 
00882   /* As we insert an order, the order to skip to will be 'wrong'. */
00883   VehicleOrderID cur_order_id = 0;
00884   Order *order;
00885   FOR_VEHICLE_ORDERS(v, order) {
00886     if (order->IsType(OT_CONDITIONAL)) {
00887       VehicleOrderID order_id = order->GetConditionSkipToOrder();
00888       if (order_id >= sel_ord) {
00889         order->SetConditionSkipToOrder(order_id + 1);
00890       }
00891       if (order_id == cur_order_id) {
00892         order->SetConditionSkipToOrder((order_id + 1) % v->GetNumOrders());
00893       }
00894     }
00895     cur_order_id++;
00896   }
00897 
00898   /* Make sure to rebuild the whole list */
00899   InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
00900 }
00901 
00907 static CommandCost DecloneOrder(Vehicle *dst, DoCommandFlag flags)
00908 {
00909   if (flags & DC_EXEC) {
00910     DeleteVehicleOrders(dst);
00911     InvalidateVehicleOrder(dst, -1);
00912     InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
00913   }
00914   return CommandCost();
00915 }
00916 
00926 CommandCost CmdDeleteOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00927 {
00928   VehicleID veh_id = GB(p1, 0, 20);
00929   VehicleOrderID sel_ord = GB(p2, 0, 8);
00930 
00931   Vehicle *v = Vehicle::GetIfValid(veh_id);
00932 
00933   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
00934 
00935   CommandCost ret = CheckOwnership(v->owner);
00936   if (ret.Failed()) return ret;
00937 
00938   /* If we did not select an order, we maybe want to de-clone the orders */
00939   if (sel_ord >= v->GetNumOrders()) return DecloneOrder(v, flags);
00940 
00941   if (v->GetOrder(sel_ord) == NULL) return CMD_ERROR;
00942 
00943   if (flags & DC_EXEC) DeleteOrder(v, sel_ord);
00944   return CommandCost();
00945 }
00946 
00951 static void CancelLoadingDueToDeletedOrder(Vehicle *v)
00952 {
00953   assert(v->current_order.IsType(OT_LOADING));
00954   /* NON-stop flag is misused to see if a train is in a station that is
00955    * on his order list or not */
00956   v->current_order.SetNonStopType(ONSF_STOP_EVERYWHERE);
00957   /* When full loading, "cancel" that order so the vehicle doesn't
00958    * stay indefinitely at this station anymore. */
00959   if (v->current_order.GetLoadType() & OLFB_FULL_LOAD) v->current_order.SetLoadType(OLF_LOAD_IF_POSSIBLE);
00960 }
00961 
00967 void DeleteOrder(Vehicle *v, VehicleOrderID sel_ord)
00968 {
00969   v->orders.list->DeleteOrderAt(sel_ord);
00970 
00971   Vehicle *u = v->FirstShared();
00972   DeleteOrderWarnings(u);
00973   for (; u != NULL; u = u->NextShared()) {
00974     assert(v->orders.list == u->orders.list);
00975 
00976     if (sel_ord == u->cur_real_order_index && u->current_order.IsType(OT_LOADING)) {
00977       CancelLoadingDueToDeletedOrder(u);
00978     }
00979 
00980     if (sel_ord < u->cur_real_order_index) {
00981       u->cur_real_order_index--;
00982     } else if (sel_ord == u->cur_real_order_index) {
00983       u->UpdateRealOrderIndex();
00984     }
00985 
00986     if (sel_ord < u->cur_implicit_order_index) {
00987       u->cur_implicit_order_index--;
00988     } else if (sel_ord == u->cur_implicit_order_index) {
00989       /* Make sure the index is valid */
00990       if (u->cur_implicit_order_index >= u->GetNumOrders()) u->cur_implicit_order_index = 0;
00991 
00992       /* Skip non-implicit orders for the implicit-order-index (e.g. if the current implicit order was deleted */
00993       while (u->cur_implicit_order_index != u->cur_real_order_index && !u->GetOrder(u->cur_implicit_order_index)->IsType(OT_IMPLICIT)) {
00994         u->cur_implicit_order_index++;
00995         if (u->cur_implicit_order_index >= u->GetNumOrders()) u->cur_implicit_order_index = 0;
00996       }
00997     }
00998 
00999     /* Update any possible open window of the vehicle */
01000     InvalidateVehicleOrder(u, sel_ord | (INVALID_VEH_ORDER_ID << 8));
01001   }
01002 
01003   /* As we delete an order, the order to skip to will be 'wrong'. */
01004   VehicleOrderID cur_order_id = 0;
01005   Order *order = NULL;
01006   FOR_VEHICLE_ORDERS(v, order) {
01007     if (order->IsType(OT_CONDITIONAL)) {
01008       VehicleOrderID order_id = order->GetConditionSkipToOrder();
01009       if (order_id >= sel_ord) {
01010         order_id = max(order_id - 1, 0);
01011       }
01012       if (order_id == cur_order_id) {
01013         order_id = (order_id + 1) % v->GetNumOrders();
01014       }
01015       order->SetConditionSkipToOrder(order_id);
01016     }
01017     cur_order_id++;
01018   }
01019 
01020   InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
01021 }
01022 
01032 CommandCost CmdSkipToOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01033 {
01034   VehicleID veh_id = GB(p1, 0, 20);
01035   VehicleOrderID sel_ord = GB(p2, 0, 8);
01036 
01037   Vehicle *v = Vehicle::GetIfValid(veh_id);
01038 
01039   if (v == NULL || !v->IsPrimaryVehicle() || sel_ord == v->cur_implicit_order_index || sel_ord >= v->GetNumOrders() || v->GetNumOrders() < 2) return CMD_ERROR;
01040 
01041   CommandCost ret = CheckOwnership(v->owner);
01042   if (ret.Failed()) return ret;
01043 
01044   if (flags & DC_EXEC) {
01045     v->cur_implicit_order_index = v->cur_real_order_index = sel_ord;
01046     v->UpdateRealOrderIndex();
01047 
01048     if (v->current_order.IsType(OT_LOADING)) v->LeaveStation();
01049 
01050     InvalidateVehicleOrder(v, -2);
01051   }
01052 
01053   /* We have an aircraft/ship, they have a mini-schedule, so update them all */
01054   if (v->type == VEH_AIRCRAFT) SetWindowClassesDirty(WC_AIRCRAFT_LIST);
01055   if (v->type == VEH_SHIP) SetWindowClassesDirty(WC_SHIPS_LIST);
01056 
01057   return CommandCost();
01058 }
01059 
01073 CommandCost CmdMoveOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01074 {
01075   VehicleID veh = GB(p1, 0, 20);
01076   VehicleOrderID moving_order = GB(p2,  0, 16);
01077   VehicleOrderID target_order = GB(p2, 16, 16);
01078 
01079   Vehicle *v = Vehicle::GetIfValid(veh);
01080   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01081 
01082   CommandCost ret = CheckOwnership(v->owner);
01083   if (ret.Failed()) return ret;
01084 
01085   /* Don't make senseless movements */
01086   if (moving_order >= v->GetNumOrders() || target_order >= v->GetNumOrders() ||
01087       moving_order == target_order || v->GetNumOrders() <= 1) return CMD_ERROR;
01088 
01089   Order *moving_one = v->GetOrder(moving_order);
01090   /* Don't move an empty order */
01091   if (moving_one == NULL) return CMD_ERROR;
01092 
01093   if (flags & DC_EXEC) {
01094     v->orders.list->MoveOrder(moving_order, target_order);
01095 
01096     /* Update shared list */
01097     Vehicle *u = v->FirstShared();
01098 
01099     DeleteOrderWarnings(u);
01100 
01101     for (; u != NULL; u = u->NextShared()) {
01102       /* Update the current order.
01103        * There are multiple ways to move orders, which result in cur_implicit_order_index
01104        * and cur_real_order_index to not longer make any sense. E.g. moving another
01105        * real order between them.
01106        *
01107        * Basically one could choose to preserve either of them, but not both.
01108        * While both ways are suitable in this or that case from a human point of view, neither
01109        * of them makes really sense.
01110        * However, from an AI point of view, preserving cur_real_order_index is the most
01111        * predictable and transparent behaviour.
01112        *
01113        * With that decision it basically does not matter what we do to cur_implicit_order_index.
01114        * If we change orders between the implict- and real-index, the implicit orders are mostly likely
01115        * completely out-dated anyway. So, keep it simple and just keep cur_implicit_order_index as well.
01116        * The worst which can happen is that a lot of implicit orders are removed when reaching current_order.
01117        */
01118       if (u->cur_real_order_index == moving_order) {
01119         u->cur_real_order_index = target_order;
01120       } else if (u->cur_real_order_index > moving_order && u->cur_real_order_index <= target_order) {
01121         u->cur_real_order_index--;
01122       } else if (u->cur_real_order_index < moving_order && u->cur_real_order_index >= target_order) {
01123         u->cur_real_order_index++;
01124       }
01125 
01126       if (u->cur_implicit_order_index == moving_order) {
01127         u->cur_implicit_order_index = target_order;
01128       } else if (u->cur_implicit_order_index > moving_order && u->cur_implicit_order_index <= target_order) {
01129         u->cur_implicit_order_index--;
01130       } else if (u->cur_implicit_order_index < moving_order && u->cur_implicit_order_index >= target_order) {
01131         u->cur_implicit_order_index++;
01132       }
01133 
01134       assert(v->orders.list == u->orders.list);
01135       /* Update any possible open window of the vehicle */
01136       InvalidateVehicleOrder(u, moving_order | (target_order << 8));
01137     }
01138 
01139     /* As we move an order, the order to skip to will be 'wrong'. */
01140     Order *order;
01141     FOR_VEHICLE_ORDERS(v, order) {
01142       if (order->IsType(OT_CONDITIONAL)) {
01143         VehicleOrderID order_id = order->GetConditionSkipToOrder();
01144         if (order_id == moving_order) {
01145           order_id = target_order;
01146         } else if (order_id > moving_order && order_id <= target_order) {
01147           order_id--;
01148         } else if (order_id < moving_order && order_id >= target_order) {
01149           order_id++;
01150         }
01151         order->SetConditionSkipToOrder(order_id);
01152       }
01153     }
01154 
01155     /* Make sure to rebuild the whole list */
01156     InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
01157   }
01158 
01159   return CommandCost();
01160 }
01161 
01177 CommandCost CmdModifyOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01178 {
01179   VehicleOrderID sel_ord = GB(p1, 20,  8);
01180   VehicleID veh          = GB(p1,  0, 20);
01181   ModifyOrderFlags mof   = Extract<ModifyOrderFlags, 0, 4>(p2);
01182   uint16 data            = GB(p2,  4, 11);
01183 
01184   if (mof >= MOF_END) return CMD_ERROR;
01185 
01186   Vehicle *v = Vehicle::GetIfValid(veh);
01187   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01188 
01189   CommandCost ret = CheckOwnership(v->owner);
01190   if (ret.Failed()) return ret;
01191 
01192   /* Is it a valid order? */
01193   if (sel_ord >= v->GetNumOrders()) return CMD_ERROR;
01194 
01195   Order *order = v->GetOrder(sel_ord);
01196   switch (order->GetType()) {
01197     case OT_GOTO_STATION:
01198       if (mof == MOF_COND_VARIABLE || mof == MOF_COND_COMPARATOR || mof == MOF_DEPOT_ACTION || mof == MOF_COND_VALUE) return CMD_ERROR;
01199       break;
01200 
01201     case OT_GOTO_DEPOT:
01202       if (mof != MOF_NON_STOP && mof != MOF_DEPOT_ACTION) return CMD_ERROR;
01203       break;
01204 
01205     case OT_GOTO_WAYPOINT:
01206       if (mof != MOF_NON_STOP) return CMD_ERROR;
01207       break;
01208 
01209     case OT_CONDITIONAL:
01210       if (mof != MOF_COND_VARIABLE && mof != MOF_COND_COMPARATOR && mof != MOF_COND_VALUE && mof != MOF_COND_DESTINATION) return CMD_ERROR;
01211       break;
01212 
01213     default:
01214       return CMD_ERROR;
01215   }
01216 
01217   switch (mof) {
01218     default: NOT_REACHED();
01219 
01220     case MOF_NON_STOP:
01221       if (!v->IsGroundVehicle()) return CMD_ERROR;
01222       if (data >= ONSF_END) return CMD_ERROR;
01223       if (data == order->GetNonStopType()) return CMD_ERROR;
01224       break;
01225 
01226     case MOF_STOP_LOCATION:
01227       if (v->type != VEH_TRAIN) return CMD_ERROR;
01228       if (data >= OSL_END) return CMD_ERROR;
01229       break;
01230 
01231     case MOF_UNLOAD:
01232       if ((data & ~(OUFB_UNLOAD | OUFB_TRANSFER | OUFB_NO_UNLOAD)) != 0) return CMD_ERROR;
01233       /* Unload and no-unload are mutual exclusive and so are transfer and no unload. */
01234       if (data != 0 && ((data & (OUFB_UNLOAD | OUFB_TRANSFER)) != 0) == ((data & OUFB_NO_UNLOAD) != 0)) return CMD_ERROR;
01235       if (data == order->GetUnloadType()) return CMD_ERROR;
01236       break;
01237 
01238     case MOF_LOAD:
01239       if (data > OLFB_NO_LOAD || data == 1) return CMD_ERROR;
01240       if (data == order->GetLoadType()) return CMD_ERROR;
01241       break;
01242 
01243     case MOF_DEPOT_ACTION:
01244       if (data >= DA_END) return CMD_ERROR;
01245       break;
01246 
01247     case MOF_COND_VARIABLE:
01248       if (data >= OCV_END) return CMD_ERROR;
01249       break;
01250 
01251     case MOF_COND_COMPARATOR:
01252       if (data >= OCC_END) return CMD_ERROR;
01253       switch (order->GetConditionVariable()) {
01254         case OCV_UNCONDITIONALLY: return CMD_ERROR;
01255 
01256         case OCV_REQUIRES_SERVICE:
01257           if (data != OCC_IS_TRUE && data != OCC_IS_FALSE) return CMD_ERROR;
01258           break;
01259 
01260         default:
01261           if (data == OCC_IS_TRUE || data == OCC_IS_FALSE) return CMD_ERROR;
01262           break;
01263       }
01264       break;
01265 
01266     case MOF_COND_VALUE:
01267       switch (order->GetConditionVariable()) {
01268         case OCV_UNCONDITIONALLY: return CMD_ERROR;
01269 
01270         case OCV_LOAD_PERCENTAGE:
01271         case OCV_RELIABILITY:
01272           if (data > 100) return CMD_ERROR;
01273           break;
01274 
01275         default:
01276           if (data > 2047) return CMD_ERROR;
01277           break;
01278       }
01279       break;
01280 
01281     case MOF_COND_DESTINATION:
01282       if (data >= v->GetNumOrders()) return CMD_ERROR;
01283       break;
01284   }
01285 
01286   if (flags & DC_EXEC) {
01287     switch (mof) {
01288       case MOF_NON_STOP:
01289         order->SetNonStopType((OrderNonStopFlags)data);
01290         if (data & ONSF_NO_STOP_AT_DESTINATION_STATION) order->SetRefit(CT_NO_REFIT);
01291         break;
01292 
01293       case MOF_STOP_LOCATION:
01294         order->SetStopLocation((OrderStopLocation)data);
01295         break;
01296 
01297       case MOF_UNLOAD:
01298         order->SetUnloadType((OrderUnloadFlags)data);
01299         break;
01300 
01301       case MOF_LOAD:
01302         order->SetLoadType((OrderLoadFlags)data);
01303         if (data & OLFB_NO_LOAD) order->SetRefit(CT_NO_REFIT);
01304         break;
01305 
01306       case MOF_DEPOT_ACTION: {
01307         switch (data) {
01308           case DA_ALWAYS_GO:
01309             order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
01310             order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
01311             break;
01312 
01313           case DA_SERVICE:
01314             order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() | ODTFB_SERVICE));
01315             order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
01316             order->SetRefit(CT_NO_REFIT);
01317             break;
01318 
01319           case DA_STOP:
01320             order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
01321             order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() | ODATFB_HALT));
01322             order->SetRefit(CT_NO_REFIT);
01323             break;
01324 
01325           default:
01326             NOT_REACHED();
01327         }
01328         break;
01329       }
01330 
01331       case MOF_COND_VARIABLE: {
01332         order->SetConditionVariable((OrderConditionVariable)data);
01333 
01334         OrderConditionComparator occ = order->GetConditionComparator();
01335         switch (order->GetConditionVariable()) {
01336           case OCV_UNCONDITIONALLY:
01337             order->SetConditionComparator(OCC_EQUALS);
01338             order->SetConditionValue(0);
01339             break;
01340 
01341           case OCV_REQUIRES_SERVICE:
01342             if (occ != OCC_IS_TRUE && occ != OCC_IS_FALSE) order->SetConditionComparator(OCC_IS_TRUE);
01343             break;
01344 
01345           case OCV_LOAD_PERCENTAGE:
01346           case OCV_RELIABILITY:
01347             if (order->GetConditionValue() > 100) order->SetConditionValue(100);
01348             /* FALL THROUGH */
01349           default:
01350             if (occ == OCC_IS_TRUE || occ == OCC_IS_FALSE) order->SetConditionComparator(OCC_EQUALS);
01351             break;
01352         }
01353         break;
01354       }
01355 
01356       case MOF_COND_COMPARATOR:
01357         order->SetConditionComparator((OrderConditionComparator)data);
01358         break;
01359 
01360       case MOF_COND_VALUE:
01361         order->SetConditionValue(data);
01362         break;
01363 
01364       case MOF_COND_DESTINATION:
01365         order->SetConditionSkipToOrder(data);
01366         break;
01367 
01368       default: NOT_REACHED();
01369     }
01370 
01371     /* Update the windows and full load flags, also for vehicles that share the same order list */
01372     Vehicle *u = v->FirstShared();
01373     DeleteOrderWarnings(u);
01374     for (; u != NULL; u = u->NextShared()) {
01375       /* Toggle u->current_order "Full load" flag if it changed.
01376        * However, as the same flag is used for depot orders, check
01377        * whether we are not going to a depot as there are three
01378        * cases where the full load flag can be active and only
01379        * one case where the flag is used for depot orders. In the
01380        * other cases for the OrderTypeByte the flags are not used,
01381        * so do not care and those orders should not be active
01382        * when this function is called.
01383        */
01384       if (sel_ord == u->cur_real_order_index &&
01385           (u->current_order.IsType(OT_GOTO_STATION) || u->current_order.IsType(OT_LOADING)) &&
01386           u->current_order.GetLoadType() != order->GetLoadType()) {
01387         u->current_order.SetLoadType(order->GetLoadType());
01388       }
01389       InvalidateVehicleOrder(u, -2);
01390     }
01391   }
01392 
01393   return CommandCost();
01394 }
01395 
01402 bool CheckAircraftOrderDistance(const Aircraft *v, const Order *first)
01403 {
01404   if (first == NULL || v->acache.cached_max_range == 0) return true;
01405 
01406   /* Iterate over all orders to check the distance between all
01407    * 'goto' orders and their respective next order (of any type). */
01408   for (const Order *o = first; o != NULL; o = o->next) {
01409     switch (o->GetType()) {
01410       case OT_GOTO_STATION:
01411       case OT_GOTO_DEPOT:
01412       case OT_GOTO_WAYPOINT:
01413         /* If we don't have a next order, we've reached the end and must check the first order instead. */
01414         if (GetOrderDistance(o, o->next != NULL ? o->next : first, v) > v->acache.cached_max_range_sqr) return false;
01415         break;
01416 
01417       default: break;
01418     }
01419   }
01420 
01421   return true;
01422 }
01423 
01435 CommandCost CmdCloneOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01436 {
01437   VehicleID veh_src = GB(p2, 0, 20);
01438   VehicleID veh_dst = GB(p1, 0, 20);
01439 
01440   Vehicle *dst = Vehicle::GetIfValid(veh_dst);
01441   if (dst == NULL || !dst->IsPrimaryVehicle()) return CMD_ERROR;
01442 
01443   CommandCost ret = CheckOwnership(dst->owner);
01444   if (ret.Failed()) return ret;
01445 
01446   switch (GB(p1, 30, 2)) {
01447     case CO_SHARE: {
01448       Vehicle *src = Vehicle::GetIfValid(veh_src);
01449 
01450       /* Sanity checks */
01451       if (src == NULL || !src->IsPrimaryVehicle() || dst->type != src->type || dst == src) return CMD_ERROR;
01452 
01453       CommandCost ret = CheckOwnership(src->owner);
01454       if (ret.Failed()) return ret;
01455 
01456       /* Trucks can't share orders with busses (and visa versa) */
01457       if (src->type == VEH_ROAD && RoadVehicle::From(src)->IsBus() != RoadVehicle::From(dst)->IsBus()) {
01458         return CMD_ERROR;
01459       }
01460 
01461       /* Is the vehicle already in the shared list? */
01462       if (src->FirstShared() == dst->FirstShared()) return CMD_ERROR;
01463 
01464       const Order *order;
01465 
01466       FOR_VEHICLE_ORDERS(src, order) {
01467         if (OrderGoesToStation(dst, order) &&
01468             !CanVehicleUseStation(dst, Station::Get(order->GetDestination()))) {
01469           return_cmd_error(STR_ERROR_CAN_T_COPY_SHARE_ORDER);
01470         }
01471       }
01472 
01473       /* Check for aircraft range limits. */
01474       if (dst->type == VEH_AIRCRAFT && !CheckAircraftOrderDistance(Aircraft::From(dst), src->GetFirstOrder())) {
01475         return_cmd_error(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE);
01476       }
01477 
01478       if (src->orders.list == NULL && !OrderList::CanAllocateItem()) {
01479         return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
01480       }
01481 
01482       if (flags & DC_EXEC) {
01483         /* If the destination vehicle had a OrderList, destroy it.
01484          * We only reset the order indices, if the new orders are obviously different.
01485          * (We mainly do this to keep the order indices valid and in range.) */
01486         DeleteVehicleOrders(dst, false, dst->GetNumOrders() != src->GetNumOrders());
01487 
01488         dst->orders.list = src->orders.list;
01489 
01490         /* Link this vehicle in the shared-list */
01491         dst->AddToShared(src);
01492 
01493         InvalidateVehicleOrder(dst, -1);
01494         InvalidateVehicleOrder(src, -2);
01495 
01496         InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
01497       }
01498       break;
01499     }
01500 
01501     case CO_COPY: {
01502       Vehicle *src = Vehicle::GetIfValid(veh_src);
01503 
01504       /* Sanity checks */
01505       if (src == NULL || !src->IsPrimaryVehicle() || dst->type != src->type || dst == src) return CMD_ERROR;
01506 
01507       CommandCost ret = CheckOwnership(src->owner);
01508       if (ret.Failed()) return ret;
01509 
01510       /* Trucks can't copy all the orders from busses (and visa versa),
01511        * and neither can helicopters and aircarft. */
01512       const Order *order;
01513       FOR_VEHICLE_ORDERS(src, order) {
01514         if (OrderGoesToStation(dst, order) &&
01515             !CanVehicleUseStation(dst, Station::Get(order->GetDestination()))) {
01516           return_cmd_error(STR_ERROR_CAN_T_COPY_SHARE_ORDER);
01517         }
01518       }
01519 
01520       /* Check for aircraft range limits. */
01521       if (dst->type == VEH_AIRCRAFT && !CheckAircraftOrderDistance(Aircraft::From(dst), src->GetFirstOrder())) {
01522         return_cmd_error(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE);
01523       }
01524 
01525       /* make sure there are orders available */
01526       int delta = dst->IsOrderListShared() ? src->GetNumOrders() + 1 : src->GetNumOrders() - dst->GetNumOrders();
01527       if (!Order::CanAllocateItem(delta) ||
01528           ((dst->orders.list == NULL || dst->IsOrderListShared()) && !OrderList::CanAllocateItem())) {
01529         return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
01530       }
01531 
01532       if (flags & DC_EXEC) {
01533         const Order *order;
01534         Order *first = NULL;
01535         Order **order_dst;
01536 
01537         /* If the destination vehicle had an order list, destroy the chain but keep the OrderList.
01538          * We only reset the order indices, if the new orders are obviously different.
01539          * (We mainly do this to keep the order indices valid and in range.) */
01540         DeleteVehicleOrders(dst, true, dst->GetNumOrders() != src->GetNumOrders());
01541 
01542         order_dst = &first;
01543         FOR_VEHICLE_ORDERS(src, order) {
01544           *order_dst = new Order();
01545           (*order_dst)->AssignOrder(*order);
01546           order_dst = &(*order_dst)->next;
01547         }
01548         if (dst->orders.list == NULL) {
01549           dst->orders.list = new OrderList(first, dst);
01550         } else {
01551           assert(dst->orders.list->GetFirstOrder() == NULL);
01552           assert(!dst->orders.list->IsShared());
01553           delete dst->orders.list;
01554           assert(OrderList::CanAllocateItem());
01555           dst->orders.list = new OrderList(first, dst);
01556         }
01557 
01558         InvalidateVehicleOrder(dst, -1);
01559 
01560         InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
01561       }
01562       break;
01563     }
01564 
01565     case CO_UNSHARE: return DecloneOrder(dst, flags);
01566     default: return CMD_ERROR;
01567   }
01568 
01569   return CommandCost();
01570 }
01571 
01584 CommandCost CmdOrderRefit(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01585 {
01586   VehicleID veh = GB(p1, 0, 20);
01587   VehicleOrderID order_number  = GB(p2, 16, 8);
01588   CargoID cargo = GB(p2, 0, 8);
01589   byte subtype  = GB(p2, 8, 8);
01590 
01591   if (cargo >= NUM_CARGO && cargo != CT_NO_REFIT && cargo != CT_AUTO_REFIT) return CMD_ERROR;
01592 
01593   const Vehicle *v = Vehicle::GetIfValid(veh);
01594   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01595 
01596   CommandCost ret = CheckOwnership(v->owner);
01597   if (ret.Failed()) return ret;
01598 
01599   Order *order = v->GetOrder(order_number);
01600   if (order == NULL) return CMD_ERROR;
01601 
01602   /* Automatic refit cargo is only supported for goto station orders. */
01603   if (cargo == CT_AUTO_REFIT && !order->IsType(OT_GOTO_STATION)) return CMD_ERROR;
01604 
01605   if (flags & DC_EXEC) {
01606     order->SetRefit(cargo, subtype);
01607 
01608     /* Make the depot order an 'always go' order. */
01609     if (cargo != CT_NO_REFIT) {
01610       order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
01611       order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
01612     }
01613 
01614     for (Vehicle *u = v->FirstShared(); u != NULL; u = u->NextShared()) {
01615       /* Update any possible open window of the vehicle */
01616       InvalidateVehicleOrder(u, -2);
01617 
01618       /* If the vehicle already got the current depot set as current order, then update current order as well */
01619       if (u->cur_real_order_index == order_number && (u->current_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) {
01620         u->current_order.SetRefit(cargo, subtype);
01621       }
01622     }
01623   }
01624 
01625   return CommandCost();
01626 }
01627 
01628 
01634 void CheckOrders(const Vehicle *v)
01635 {
01636   /* Does the user wants us to check things? */
01637   if (_settings_client.gui.order_review_system == 0) return;
01638 
01639   /* Do nothing for crashed vehicles */
01640   if (v->vehstatus & VS_CRASHED) return;
01641 
01642   /* Do nothing for stopped vehicles if setting is '1' */
01643   if (_settings_client.gui.order_review_system == 1 && (v->vehstatus & VS_STOPPED)) return;
01644 
01645   /* do nothing we we're not the first vehicle in a share-chain */
01646   if (v->FirstShared() != v) return;
01647 
01648   /* Only check every 20 days, so that we don't flood the message log */
01649   if (v->owner == _local_company && v->day_counter % 20 == 0) {
01650     int n_st, problem_type = -1;
01651     const Order *order;
01652     int message = 0;
01653 
01654     /* Check the order list */
01655     n_st = 0;
01656 
01657     FOR_VEHICLE_ORDERS(v, order) {
01658       /* Dummy order? */
01659       if (order->IsType(OT_DUMMY)) {
01660         problem_type = 1;
01661         break;
01662       }
01663       /* Does station have a load-bay for this vehicle? */
01664       if (order->IsType(OT_GOTO_STATION)) {
01665         const Station *st = Station::Get(order->GetDestination());
01666 
01667         n_st++;
01668         if (!CanVehicleUseStation(v, st)) problem_type = 3;
01669       }
01670     }
01671 
01672     /* Check if the last and the first order are the same */
01673     if (v->GetNumOrders() > 1) {
01674       const Order *last = v->GetLastOrder();
01675 
01676       if (v->orders.list->GetFirstOrder()->Equals(*last)) {
01677         problem_type = 2;
01678       }
01679     }
01680 
01681     /* Do we only have 1 station in our order list? */
01682     if (n_st < 2 && problem_type == -1) problem_type = 0;
01683 
01684 #ifndef NDEBUG
01685     if (v->orders.list != NULL) v->orders.list->DebugCheckSanity();
01686 #endif
01687 
01688     /* We don't have a problem */
01689     if (problem_type < 0) return;
01690 
01691     message = STR_NEWS_VEHICLE_HAS_TOO_FEW_ORDERS + problem_type;
01692     //DEBUG(misc, 3, "Triggered News Item for vehicle %d", v->index);
01693 
01694     SetDParam(0, v->index);
01695     AddVehicleNewsItem(
01696       message,
01697       NS_ADVICE,
01698       v->index
01699     );
01700   }
01701 }
01702 
01708 void RemoveOrderFromAllVehicles(OrderType type, DestinationID destination)
01709 {
01710   Vehicle *v;
01711 
01712   /* Aircraft have StationIDs for depot orders and never use DepotIDs
01713    * This fact is handled specially below
01714    */
01715 
01716   /* Go through all vehicles */
01717   FOR_ALL_VEHICLES(v) {
01718     Order *order;
01719 
01720     order = &v->current_order;
01721     if ((v->type == VEH_AIRCRAFT && order->IsType(OT_GOTO_DEPOT) ? OT_GOTO_STATION : order->GetType()) == type &&
01722         v->current_order.GetDestination() == destination) {
01723       order->MakeDummy();
01724       SetWindowDirty(WC_VEHICLE_VIEW, v->index);
01725     }
01726 
01727     /* Clear the order from the order-list */
01728     int id = -1;
01729     FOR_VEHICLE_ORDERS(v, order) {
01730       id++;
01731 restart:
01732 
01733       OrderType ot = order->GetType();
01734       if (ot == OT_GOTO_DEPOT && (order->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0) continue;
01735       if (ot == OT_IMPLICIT || (v->type == VEH_AIRCRAFT && ot == OT_GOTO_DEPOT)) ot = OT_GOTO_STATION;
01736       if (ot == type && order->GetDestination() == destination) {
01737         /* We want to clear implicit orders, but we don't want to make them
01738          * dummy orders. They should just vanish. Also check the actual order
01739          * type as ot is currently OT_GOTO_STATION. */
01740         if (order->IsType(OT_IMPLICIT)) {
01741           order = order->next; // DeleteOrder() invalidates current order
01742           DeleteOrder(v, id);
01743           if (order != NULL) goto restart;
01744           break;
01745         }
01746 
01747         order->MakeDummy();
01748         for (const Vehicle *w = v->FirstShared(); w != NULL; w = w->NextShared()) {
01749           /* In GUI, simulate by removing the order and adding it back */
01750           InvalidateVehicleOrder(w, id | (INVALID_VEH_ORDER_ID << 8));
01751           InvalidateVehicleOrder(w, (INVALID_VEH_ORDER_ID << 8) | id);
01752         }
01753       }
01754     }
01755   }
01756 
01757   OrderBackup::RemoveOrder(type, destination);
01758 }
01759 
01764 bool Vehicle::HasDepotOrder() const
01765 {
01766   const Order *order;
01767 
01768   FOR_VEHICLE_ORDERS(this, order) {
01769     if (order->IsType(OT_GOTO_DEPOT)) return true;
01770   }
01771 
01772   return false;
01773 }
01774 
01784 void DeleteVehicleOrders(Vehicle *v, bool keep_orderlist, bool reset_order_indices)
01785 {
01786   DeleteOrderWarnings(v);
01787 
01788   if (v->IsOrderListShared()) {
01789     /* Remove ourself from the shared order list. */
01790     v->RemoveFromShared();
01791     v->orders.list = NULL;
01792   } else if (v->orders.list != NULL) {
01793     /* Remove the orders */
01794     v->orders.list->FreeChain(keep_orderlist);
01795     if (!keep_orderlist) v->orders.list = NULL;
01796   }
01797 
01798   if (reset_order_indices) {
01799     v->cur_implicit_order_index = v->cur_real_order_index = 0;
01800     if (v->current_order.IsType(OT_LOADING)) {
01801       CancelLoadingDueToDeletedOrder(v);
01802     }
01803   }
01804 }
01805 
01813 uint16 GetServiceIntervalClamped(uint interval, CompanyID company_id)
01814 {
01815   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);
01816 }
01817 
01826 static bool CheckForValidOrders(const Vehicle *v)
01827 {
01828   const Order *order;
01829 
01830   FOR_VEHICLE_ORDERS(v, order) {
01831     switch (order->GetType()) {
01832       case OT_GOTO_STATION:
01833       case OT_GOTO_DEPOT:
01834       case OT_GOTO_WAYPOINT:
01835         return true;
01836 
01837       default:
01838         break;
01839     }
01840   }
01841 
01842   return false;
01843 }
01844 
01848 static bool OrderConditionCompare(OrderConditionComparator occ, int variable, int value)
01849 {
01850   switch (occ) {
01851     case OCC_EQUALS:      return variable == value;
01852     case OCC_NOT_EQUALS:  return variable != value;
01853     case OCC_LESS_THAN:   return variable <  value;
01854     case OCC_LESS_EQUALS: return variable <= value;
01855     case OCC_MORE_THAN:   return variable >  value;
01856     case OCC_MORE_EQUALS: return variable >= value;
01857     case OCC_IS_TRUE:     return variable != 0;
01858     case OCC_IS_FALSE:    return variable == 0;
01859     default: NOT_REACHED();
01860   }
01861 }
01862 
01869 VehicleOrderID ProcessConditionalOrder(const Order *order, const Vehicle *v)
01870 {
01871   if (order->GetType() != OT_CONDITIONAL) return INVALID_VEH_ORDER_ID;
01872 
01873   bool skip_order = false;
01874   OrderConditionComparator occ = order->GetConditionComparator();
01875   uint16 value = order->GetConditionValue();
01876 
01877   switch (order->GetConditionVariable()) {
01878     case OCV_LOAD_PERCENTAGE:    skip_order = OrderConditionCompare(occ, CalcPercentVehicleFilled(v, NULL), value); break;
01879     case OCV_RELIABILITY:        skip_order = OrderConditionCompare(occ, ToPercent16(v->reliability),       value); break;
01880     case OCV_MAX_SPEED:          skip_order = OrderConditionCompare(occ, v->GetDisplayMaxSpeed() * 10 / 16, value); break;
01881     case OCV_AGE:                skip_order = OrderConditionCompare(occ, v->age / DAYS_IN_LEAP_YEAR,        value); break;
01882     case OCV_REQUIRES_SERVICE:   skip_order = OrderConditionCompare(occ, v->NeedsServicing(),               value); break;
01883     case OCV_UNCONDITIONALLY:    skip_order = true; break;
01884     case OCV_REMAINING_LIFETIME: skip_order = OrderConditionCompare(occ, max(v->max_age - v->age + DAYS_IN_LEAP_YEAR - 1, 0) / DAYS_IN_LEAP_YEAR, value); break;
01885     default: NOT_REACHED();
01886   }
01887 
01888   return skip_order ? order->GetConditionSkipToOrder() : (VehicleOrderID)INVALID_VEH_ORDER_ID;
01889 }
01890 
01898 bool UpdateOrderDest(Vehicle *v, const Order *order, int conditional_depth, bool pbs_look_ahead)
01899 {
01900   if (conditional_depth > v->GetNumOrders()) return false;
01901 
01902   switch (order->GetType()) {
01903     case OT_GOTO_STATION:
01904       v->dest_tile = v->GetOrderStationLocation(order->GetDestination());
01905       return true;
01906 
01907     case OT_GOTO_DEPOT:
01908       if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !v->NeedsServicing()) {
01909         assert(!pbs_look_ahead);
01910         UpdateVehicleTimetable(v, true);
01911         v->IncrementRealOrderIndex();
01912         break;
01913       }
01914 
01915       if (v->current_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) {
01916         /* We need to search for the nearest depot (hangar). */
01917         TileIndex location;
01918         DestinationID destination;
01919         bool reverse;
01920 
01921         if (v->FindClosestDepot(&location, &destination, &reverse)) {
01922           /* PBS reservations cannot reverse */
01923           if (pbs_look_ahead && reverse) return false;
01924 
01925           v->dest_tile = location;
01926           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());
01927 
01928           /* If there is no depot in front, reverse automatically (trains only) */
01929           if (v->type == VEH_TRAIN && reverse) DoCommand(v->tile, v->index, 0, DC_EXEC, CMD_REVERSE_TRAIN_DIRECTION);
01930 
01931           if (v->type == VEH_AIRCRAFT) {
01932             Aircraft *a = Aircraft::From(v);
01933             if (a->state == FLYING && a->targetairport != destination) {
01934               /* The aircraft is now heading for a different hangar than the next in the orders */
01935               extern void AircraftNextAirportPos_and_Order(Aircraft *a);
01936               AircraftNextAirportPos_and_Order(a);
01937             }
01938           }
01939           return true;
01940         }
01941 
01942         /* If there is no depot, we cannot help PBS either. */
01943         if (pbs_look_ahead) return false;
01944 
01945         UpdateVehicleTimetable(v, true);
01946         v->IncrementRealOrderIndex();
01947       } else {
01948         if (v->type != VEH_AIRCRAFT) {
01949           v->dest_tile = Depot::Get(order->GetDestination())->xy;
01950         }
01951         return true;
01952       }
01953       break;
01954 
01955     case OT_GOTO_WAYPOINT:
01956       v->dest_tile = Waypoint::Get(order->GetDestination())->xy;
01957       return true;
01958 
01959     case OT_CONDITIONAL: {
01960       assert(!pbs_look_ahead);
01961       VehicleOrderID next_order = ProcessConditionalOrder(order, v);
01962       if (next_order != INVALID_VEH_ORDER_ID) {
01963         /* Jump to next_order. cur_implicit_order_index becomes exactly that order,
01964          * cur_real_order_index might come after next_order. */
01965         UpdateVehicleTimetable(v, false);
01966         v->cur_implicit_order_index = v->cur_real_order_index = next_order;
01967         v->UpdateRealOrderIndex();
01968         v->current_order_time += v->GetOrder(v->cur_real_order_index)->travel_time;
01969 
01970         /* Disable creation of implicit orders.
01971          * When inserting them we do not know that we would have to make the conditional orders point to them. */
01972         if (v->IsGroundVehicle()) {
01973           uint16 &gv_flags = v->GetGroundVehicleFlags();
01974           SetBit(gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
01975         }
01976       } else {
01977         UpdateVehicleTimetable(v, true);
01978         v->IncrementRealOrderIndex();
01979       }
01980       break;
01981     }
01982 
01983     default:
01984       v->dest_tile = 0;
01985       return false;
01986   }
01987 
01988   assert(v->cur_implicit_order_index < v->GetNumOrders());
01989   assert(v->cur_real_order_index < v->GetNumOrders());
01990 
01991   /* Get the current order */
01992   order = v->GetOrder(v->cur_real_order_index);
01993   if (order != NULL && order->IsType(OT_IMPLICIT)) {
01994     assert(v->GetNumManualOrders() == 0);
01995     order = NULL;
01996   }
01997 
01998   if (order == NULL) {
01999     v->current_order.Free();
02000     v->dest_tile = 0;
02001     return false;
02002   }
02003 
02004   v->current_order = *order;
02005   return UpdateOrderDest(v, order, conditional_depth + 1, pbs_look_ahead);
02006 }
02007 
02015 bool ProcessOrders(Vehicle *v)
02016 {
02017   switch (v->current_order.GetType()) {
02018     case OT_GOTO_DEPOT:
02019       /* Let a depot order in the orderlist interrupt. */
02020       if (!(v->current_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) return false;
02021       break;
02022 
02023     case OT_LOADING:
02024       return false;
02025 
02026     case OT_LEAVESTATION:
02027       if (v->type != VEH_AIRCRAFT) return false;
02028       break;
02029 
02030     default: break;
02031   }
02032 
02040   bool may_reverse = v->current_order.IsType(OT_NOTHING);
02041 
02042   /* Check if we've reached a 'via' destination. */
02043   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)) &&
02044       IsTileType(v->tile, MP_STATION) &&
02045       v->current_order.GetDestination() == GetStationIndex(v->tile)) {
02046     v->DeleteUnreachedImplicitOrders();
02047     /* We set the last visited station here because we do not want
02048      * the train to stop at this 'via' station if the next order
02049      * is a no-non-stop order; in that case not setting the last
02050      * visited station will cause the vehicle to still stop. */
02051     v->last_station_visited = v->current_order.GetDestination();
02052     UpdateVehicleTimetable(v, true);
02053     v->IncrementImplicitOrderIndex();
02054   }
02055 
02056   /* Get the current order */
02057   assert(v->cur_implicit_order_index == 0 || v->cur_implicit_order_index < v->GetNumOrders());
02058   v->UpdateRealOrderIndex();
02059 
02060   const Order *order = v->GetOrder(v->cur_real_order_index);
02061   if (order != NULL && order->IsType(OT_IMPLICIT)) {
02062     assert(v->GetNumManualOrders() == 0);
02063     order = NULL;
02064   }
02065 
02066   /* If no order, do nothing. */
02067   if (order == NULL || (v->type == VEH_AIRCRAFT && !CheckForValidOrders(v))) {
02068     if (v->type == VEH_AIRCRAFT) {
02069       /* Aircraft do something vastly different here, so handle separately */
02070       extern void HandleMissingAircraftOrders(Aircraft *v);
02071       HandleMissingAircraftOrders(Aircraft::From(v));
02072       return false;
02073     }
02074 
02075     v->current_order.Free();
02076     v->dest_tile = 0;
02077     return false;
02078   }
02079 
02080   /* If it is unchanged, keep it. */
02081   if (order->Equals(v->current_order) && (v->type == VEH_AIRCRAFT || v->dest_tile != 0) &&
02082       (v->type != VEH_SHIP || !order->IsType(OT_GOTO_STATION) || Station::Get(order->GetDestination())->dock_tile != INVALID_TILE)) {
02083     return false;
02084   }
02085 
02086   /* Otherwise set it, and determine the destination tile. */
02087   v->current_order = *order;
02088 
02089   InvalidateVehicleOrder(v, -2);
02090   switch (v->type) {
02091     default:
02092       NOT_REACHED();
02093 
02094     case VEH_ROAD:
02095     case VEH_TRAIN:
02096       break;
02097 
02098     case VEH_AIRCRAFT:
02099     case VEH_SHIP:
02100       SetWindowClassesDirty(GetWindowClassForVehicleType(v->type));
02101       break;
02102   }
02103 
02104   return UpdateOrderDest(v, order) && may_reverse;
02105 }
02106 
02114 bool Order::ShouldStopAtStation(const Vehicle *v, StationID station) const
02115 {
02116   bool is_dest_station = this->IsType(OT_GOTO_STATION) && this->dest == station;
02117 
02118   return (!this->IsType(OT_GOTO_DEPOT) || (this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS) != 0) &&
02119       v->last_station_visited != station && // Do stop only when we've not just been there
02120       /* Finally do stop when there is no non-stop flag set for this type of station. */
02121       !(this->GetNonStopType() & (is_dest_station ? ONSF_NO_STOP_AT_DESTINATION_STATION : ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS));
02122 }