order_cmd.cpp

Go to the documentation of this file.
00001 /* $Id$ */
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 "strings_func.h"
00019 #include "timetable.h"
00020 #include "vehicle_func.h"
00021 #include "depot_base.h"
00022 #include "core/pool_func.hpp"
00023 #include "aircraft.h"
00024 #include "roadveh.h"
00025 #include "station_base.h"
00026 #include "waypoint_base.h"
00027 #include "company_base.h"
00028 #include "order_backup.h"
00029 
00030 #include "table/strings.h"
00031 
00032 /* DestinationID must be at least as large as every these below, because it can
00033  * be any of them
00034  */
00035 assert_compile(sizeof(DestinationID) >= sizeof(DepotID));
00036 assert_compile(sizeof(DestinationID) >= sizeof(StationID));
00037 
00038 OrderPool _order_pool("Order");
00039 INSTANTIATE_POOL_METHODS(Order)
00040 OrderListPool _orderlist_pool("OrderList");
00041 INSTANTIATE_POOL_METHODS(OrderList)
00042 
00044 Order::~Order()
00045 {
00046   if (CleaningPool()) return;
00047 
00048   /* We can visit oil rigs and buoys that are not our own. They will be shown in
00049    * the list of stations. So, we need to invalidate that window if needed. */
00050   if (this->IsType(OT_GOTO_STATION) || this->IsType(OT_GOTO_WAYPOINT)) {
00051     BaseStation *bs = BaseStation::GetIfValid(this->GetDestination());
00052     if (bs != NULL && bs->owner == OWNER_NONE) InvalidateWindowClassesData(WC_STATION_LIST, 0);
00053   }
00054 }
00055 
00060 void Order::Free()
00061 {
00062   this->type  = OT_NOTHING;
00063   this->flags = 0;
00064   this->dest  = 0;
00065   this->next  = NULL;
00066 }
00067 
00072 void Order::MakeGoToStation(StationID destination)
00073 {
00074   this->type = OT_GOTO_STATION;
00075   this->flags = 0;
00076   this->dest = destination;
00077 }
00078 
00088 void Order::MakeGoToDepot(DepotID destination, OrderDepotTypeFlags order, OrderNonStopFlags non_stop_type, OrderDepotActionFlags action, CargoID cargo, byte subtype)
00089 {
00090   this->type = OT_GOTO_DEPOT;
00091   this->SetDepotOrderType(order);
00092   this->SetDepotActionType(action);
00093   this->SetNonStopType(non_stop_type);
00094   this->dest = destination;
00095   this->SetRefit(cargo, subtype);
00096 }
00097 
00102 void Order::MakeGoToWaypoint(StationID destination)
00103 {
00104   this->type = OT_GOTO_WAYPOINT;
00105   this->flags = 0;
00106   this->dest = destination;
00107 }
00108 
00113 void Order::MakeLoading(bool ordered)
00114 {
00115   this->type = OT_LOADING;
00116   if (!ordered) this->flags = 0;
00117 }
00118 
00122 void Order::MakeLeaveStation()
00123 {
00124   this->type = OT_LEAVESTATION;
00125   this->flags = 0;
00126 }
00127 
00131 void Order::MakeDummy()
00132 {
00133   this->type = OT_DUMMY;
00134   this->flags = 0;
00135 }
00136 
00141 void Order::MakeConditional(VehicleOrderID order)
00142 {
00143   this->type = OT_CONDITIONAL;
00144   this->flags = order;
00145   this->dest = 0;
00146 }
00147 
00152 void Order::MakeImplicit(StationID destination)
00153 {
00154   this->type = OT_IMPLICIT;
00155   this->dest = destination;
00156 }
00157 
00164 void Order::SetRefit(CargoID cargo, byte subtype)
00165 {
00166   this->refit_cargo = cargo;
00167   this->refit_subtype = subtype;
00168 }
00169 
00175 bool Order::Equals(const Order &other) const
00176 {
00177   /* In case of go to nearest depot orders we need "only" compare the flags
00178    * with the other and not the nearest depot order bit or the actual
00179    * destination because those get clear/filled in during the order
00180    * evaluation. If we do not do this the order will continuously be seen as
00181    * a different order and it will try to find a "nearest depot" every tick. */
00182   if ((this->IsType(OT_GOTO_DEPOT) && this->type == other.type) &&
00183       ((this->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0 ||
00184        (other.GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0)) {
00185     return this->GetDepotOrderType() == other.GetDepotOrderType() &&
00186         (this->GetDepotActionType() & ~ODATFB_NEAREST_DEPOT) == (other.GetDepotActionType() & ~ODATFB_NEAREST_DEPOT);
00187   }
00188 
00189   return this->type == other.type && this->flags == other.flags && this->dest == other.dest;
00190 }
00191 
00198 uint32 Order::Pack() const
00199 {
00200   return this->dest << 16 | this->flags << 8 | this->type;
00201 }
00202 
00208 uint16 Order::MapOldOrder() const
00209 {
00210   uint16 order = this->GetType();
00211   switch (this->type) {
00212     case OT_GOTO_STATION:
00213       if (this->GetUnloadType() & OUFB_UNLOAD) SetBit(order, 5);
00214       if (this->GetLoadType() & OLFB_FULL_LOAD) SetBit(order, 6);
00215       if (this->GetNonStopType() & ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS) SetBit(order, 7);
00216       order |= GB(this->GetDestination(), 0, 8) << 8;
00217       break;
00218     case OT_GOTO_DEPOT:
00219       if (!(this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) SetBit(order, 6);
00220       SetBit(order, 7);
00221       order |= GB(this->GetDestination(), 0, 8) << 8;
00222       break;
00223     case OT_LOADING:
00224       if (this->GetLoadType() & OLFB_FULL_LOAD) SetBit(order, 6);
00225       break;
00226   }
00227   return order;
00228 }
00229 
00234 Order::Order(uint32 packed)
00235 {
00236   this->type    = (OrderType)GB(packed,  0,  8);
00237   this->flags   = GB(packed,  8,  8);
00238   this->dest    = GB(packed, 16, 16);
00239   this->next    = NULL;
00240   this->refit_cargo   = CT_NO_REFIT;
00241   this->refit_subtype = 0;
00242   this->wait_time     = 0;
00243   this->travel_time   = 0;
00244   this->max_speed     = UINT16_MAX;
00245 }
00246 
00252 void InvalidateVehicleOrder(const Vehicle *v, int data)
00253 {
00254   SetWindowDirty(WC_VEHICLE_VIEW, v->index);
00255 
00256   if (data != 0) {
00257     /* Calls SetDirty() too */
00258     InvalidateWindowData(WC_VEHICLE_ORDERS,    v->index, data);
00259     InvalidateWindowData(WC_VEHICLE_TIMETABLE, v->index, data);
00260     return;
00261   }
00262 
00263   SetWindowDirty(WC_VEHICLE_ORDERS,    v->index);
00264   SetWindowDirty(WC_VEHICLE_TIMETABLE, v->index);
00265 }
00266 
00274 void Order::AssignOrder(const Order &other)
00275 {
00276   this->type  = other.type;
00277   this->flags = other.flags;
00278   this->dest  = other.dest;
00279 
00280   this->refit_cargo   = other.refit_cargo;
00281   this->refit_subtype = other.refit_subtype;
00282 
00283   this->wait_time   = other.wait_time;
00284   this->travel_time = other.travel_time;
00285   this->max_speed   = other.max_speed;
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       /* Only special case is oilrig stations, since you can't give orders
00643        * to stations owned by other companies anyway. */
00644       if (st->head_to_head != _current_company + 1) return CMD_ERROR;
00645 
00646       if (st->owner != OWNER_NONE) {
00647         CommandCost ret = CheckOwnership(st->owner);
00648         if (ret.Failed()) return ret;
00649       }
00650 
00651       if (!CanVehicleUseStation(v, st)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
00652       for (Vehicle *u = v->FirstShared(); u != NULL; u = u->NextShared()) {
00653         if (!CanVehicleUseStation(u, st)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER_SHARED);
00654       }
00655 
00656       /* Non stop only allowed for ground vehicles. */
00657       if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && !v->IsGroundVehicle()) return CMD_ERROR;
00658 
00659       /* Filter invalid load/unload types. */
00660       switch (new_order.GetLoadType()) {
00661         case OLF_LOAD_IF_POSSIBLE: case OLFB_FULL_LOAD: case OLF_FULL_LOAD_ANY: case OLFB_NO_LOAD: break;
00662         default: return CMD_ERROR;
00663       }
00664       switch (new_order.GetUnloadType()) {
00665         case OUF_UNLOAD_IF_POSSIBLE: case OUFB_UNLOAD: case OUFB_TRANSFER: case OUFB_NO_UNLOAD: break;
00666         default: return CMD_ERROR;
00667       }
00668 
00669       /* Filter invalid stop locations */
00670       switch (new_order.GetStopLocation()) {
00671         case OSL_PLATFORM_NEAR_END:
00672         case OSL_PLATFORM_MIDDLE:
00673           if (v->type != VEH_TRAIN) return CMD_ERROR;
00674           /* FALL THROUGH */
00675         case OSL_PLATFORM_FAR_END:
00676           break;
00677 
00678         default:
00679           return CMD_ERROR;
00680       }
00681 
00682       break;
00683     }
00684 
00685     case OT_GOTO_DEPOT: {
00686       if ((new_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) == 0) {
00687         if (v->type == VEH_AIRCRAFT) {
00688           const Station *st = Station::GetIfValid(new_order.GetDestination());
00689 
00690           if (st == NULL) return CMD_ERROR;
00691 
00692           CommandCost ret = CheckOwnership(st->owner);
00693           if (ret.Failed()) return ret;
00694 
00695           if (!CanVehicleUseStation(v, st) || !st->airport.HasHangar()) {
00696             return CMD_ERROR;
00697           }
00698         } else {
00699           const Depot *dp = Depot::GetIfValid(new_order.GetDestination());
00700 
00701           if (dp == NULL) return CMD_ERROR;
00702 
00703           CommandCost ret = CheckOwnership(GetTileOwner(dp->xy));
00704           if (ret.Failed()) return ret;
00705 
00706           switch (v->type) {
00707             case VEH_TRAIN:
00708               if (!IsRailDepotTile(dp->xy)) return CMD_ERROR;
00709               break;
00710 
00711             case VEH_ROAD:
00712               if (!IsRoadDepotTile(dp->xy)) return CMD_ERROR;
00713               break;
00714 
00715             case VEH_SHIP:
00716               if (!IsShipDepotTile(dp->xy)) return CMD_ERROR;
00717               break;
00718 
00719             default: return CMD_ERROR;
00720           }
00721         }
00722       }
00723 
00724       if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && !v->IsGroundVehicle()) return CMD_ERROR;
00725       if (new_order.GetDepotOrderType() & ~(ODTFB_PART_OF_ORDERS | ((new_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS) != 0 ? ODTFB_SERVICE : 0))) return CMD_ERROR;
00726       if (new_order.GetDepotActionType() & ~(ODATFB_HALT | ODATFB_NEAREST_DEPOT)) return CMD_ERROR;
00727       if ((new_order.GetDepotOrderType() & ODTFB_SERVICE) && (new_order.GetDepotActionType() & ODATFB_HALT)) return CMD_ERROR;
00728       break;
00729     }
00730 
00731     case OT_GOTO_WAYPOINT: {
00732       const Waypoint *wp = Waypoint::GetIfValid(new_order.GetDestination());
00733       if (wp == NULL) return CMD_ERROR;
00734 
00735       switch (v->type) {
00736         default: return CMD_ERROR;
00737 
00738         case VEH_TRAIN: {
00739           if (!(wp->facilities & FACIL_TRAIN)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
00740 
00741           CommandCost ret = CheckOwnership(wp->owner);
00742           if (ret.Failed()) return ret;
00743           break;
00744         }
00745 
00746         case VEH_SHIP:
00747           if (!(wp->facilities & FACIL_DOCK)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
00748           if (wp->owner != OWNER_NONE) {
00749             CommandCost ret = CheckOwnership(wp->owner);
00750             if (ret.Failed()) return ret;
00751           }
00752           break;
00753       }
00754 
00755       /* Order flags can be any of the following for waypoints:
00756        * [non-stop]
00757        * non-stop orders (if any) are only valid for trains */
00758       if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && v->type != VEH_TRAIN) return CMD_ERROR;
00759       break;
00760     }
00761 
00762     case OT_CONDITIONAL: {
00763       VehicleOrderID skip_to = new_order.GetConditionSkipToOrder();
00764       if (skip_to != 0 && skip_to >= v->GetNumOrders()) return CMD_ERROR; // Always allow jumping to the first (even when there is no order).
00765       if (new_order.GetConditionVariable() >= OCV_END) return CMD_ERROR;
00766 
00767       OrderConditionComparator occ = new_order.GetConditionComparator();
00768       if (occ >= OCC_END) return CMD_ERROR;
00769       switch (new_order.GetConditionVariable()) {
00770         case OCV_REQUIRES_SERVICE:
00771           if (occ != OCC_IS_TRUE && occ != OCC_IS_FALSE) return CMD_ERROR;
00772           break;
00773 
00774         case OCV_UNCONDITIONALLY:
00775           if (occ != OCC_EQUALS) return CMD_ERROR;
00776           if (new_order.GetConditionValue() != 0) return CMD_ERROR;
00777           break;
00778 
00779         case OCV_LOAD_PERCENTAGE:
00780         case OCV_RELIABILITY:
00781           if (new_order.GetConditionValue() > 100) return CMD_ERROR;
00782           /* FALL THROUGH */
00783         default:
00784           if (occ == OCC_IS_TRUE || occ == OCC_IS_FALSE) return CMD_ERROR;
00785           break;
00786       }
00787       break;
00788     }
00789 
00790     default: return CMD_ERROR;
00791   }
00792 
00793   if (sel_ord > v->GetNumOrders()) return CMD_ERROR;
00794 
00795   if (v->GetNumOrders() >= MAX_VEH_ORDER_ID) return_cmd_error(STR_ERROR_TOO_MANY_ORDERS);
00796   if (!Order::CanAllocateItem()) return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
00797   if (v->orders.list == NULL && !OrderList::CanAllocateItem()) return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
00798 
00799   if (v->type == VEH_SHIP && _settings_game.pf.pathfinder_for_ships != VPF_NPF) {
00800     /* Make sure the new destination is not too far away from the previous */
00801     const Order *prev = NULL;
00802     uint n = 0;
00803 
00804     /* Find the last goto station or depot order before the insert location.
00805      * If the order is to be inserted at the beginning of the order list this
00806      * finds the last order in the list. */
00807     const Order *o;
00808     FOR_VEHICLE_ORDERS(v, o) {
00809       switch (o->GetType()) {
00810         case OT_GOTO_STATION:
00811         case OT_GOTO_DEPOT:
00812         case OT_GOTO_WAYPOINT:
00813           prev = o;
00814           break;
00815 
00816         default: break;
00817       }
00818       if (++n == sel_ord && prev != NULL) break;
00819     }
00820     if (prev != NULL) {
00821       uint dist;
00822       if (new_order.IsType(OT_CONDITIONAL)) {
00823         /* The order is not yet inserted, so we have to do the first iteration here. */
00824         dist = GetOrderDistance(prev, v->GetOrder(new_order.GetConditionSkipToOrder()), v);
00825       } else {
00826         dist = GetOrderDistance(prev, &new_order, v);
00827       }
00828 
00829       if (dist >= 130) {
00830         return_cmd_error(STR_ERROR_TOO_FAR_FROM_PREVIOUS_DESTINATION);
00831       }
00832     }
00833   }
00834 
00835   if (flags & DC_EXEC) {
00836     Order *new_o = new Order();
00837     new_o->AssignOrder(new_order);
00838     InsertOrder(v, new_o, sel_ord);
00839   }
00840 
00841   return CommandCost();
00842 }
00843 
00850 void InsertOrder(Vehicle *v, Order *new_o, VehicleOrderID sel_ord)
00851 {
00852   /* Create new order and link in list */
00853   if (v->orders.list == NULL) {
00854     v->orders.list = new OrderList(new_o, v);
00855   } else {
00856     v->orders.list->InsertOrderAt(new_o, sel_ord);
00857   }
00858 
00859   Vehicle *u = v->FirstShared();
00860   DeleteOrderWarnings(u);
00861   for (; u != NULL; u = u->NextShared()) {
00862     assert(v->orders.list == u->orders.list);
00863 
00864     /* If there is added an order before the current one, we need
00865      * to update the selected order. We do not change implicit/real order indices though.
00866      * If the new order is between the current implicit order and real order, the implicit order will
00867      * later skip the inserted order. */
00868     if (sel_ord <= u->cur_real_order_index) {
00869       uint cur = u->cur_real_order_index + 1;
00870       /* Check if we don't go out of bound */
00871       if (cur < u->GetNumOrders()) {
00872         u->cur_real_order_index = cur;
00873       }
00874     }
00875     if (sel_ord == u->cur_implicit_order_index && u->IsGroundVehicle()) {
00876       /* We are inserting an order just before the current implicit order.
00877        * We do not know whether we will reach current implicit or the newly inserted order first.
00878        * So, disable creation of implicit orders until we are on track again. */
00879       uint16 &gv_flags = u->GetGroundVehicleFlags();
00880       SetBit(gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
00881     }
00882     if (sel_ord <= u->cur_implicit_order_index) {
00883       uint cur = u->cur_implicit_order_index + 1;
00884       /* Check if we don't go out of bound */
00885       if (cur < u->GetNumOrders()) {
00886         u->cur_implicit_order_index = cur;
00887       }
00888     }
00889     /* Update any possible open window of the vehicle */
00890     InvalidateVehicleOrder(u, INVALID_VEH_ORDER_ID | (sel_ord << 8));
00891   }
00892 
00893   /* As we insert an order, the order to skip to will be 'wrong'. */
00894   VehicleOrderID cur_order_id = 0;
00895   Order *order;
00896   FOR_VEHICLE_ORDERS(v, order) {
00897     if (order->IsType(OT_CONDITIONAL)) {
00898       VehicleOrderID order_id = order->GetConditionSkipToOrder();
00899       if (order_id >= sel_ord) {
00900         order->SetConditionSkipToOrder(order_id + 1);
00901       }
00902       if (order_id == cur_order_id) {
00903         order->SetConditionSkipToOrder((order_id + 1) % v->GetNumOrders());
00904       }
00905     }
00906     cur_order_id++;
00907   }
00908 
00909   /* Make sure to rebuild the whole list */
00910   InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
00911 }
00912 
00918 static CommandCost DecloneOrder(Vehicle *dst, DoCommandFlag flags)
00919 {
00920   if (flags & DC_EXEC) {
00921     DeleteVehicleOrders(dst);
00922     InvalidateVehicleOrder(dst, -1);
00923     InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
00924   }
00925   return CommandCost();
00926 }
00927 
00937 CommandCost CmdDeleteOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00938 {
00939   VehicleID veh_id = GB(p1, 0, 20);
00940   VehicleOrderID sel_ord = GB(p2, 0, 8);
00941 
00942   Vehicle *v = Vehicle::GetIfValid(veh_id);
00943 
00944   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
00945 
00946   CommandCost ret = CheckOwnership(v->owner);
00947   if (ret.Failed()) return ret;
00948 
00949   /* If we did not select an order, we maybe want to de-clone the orders */
00950   if (sel_ord >= v->GetNumOrders()) return DecloneOrder(v, flags);
00951 
00952   if (v->GetOrder(sel_ord) == NULL) return CMD_ERROR;
00953 
00954   if (flags & DC_EXEC) DeleteOrder(v, sel_ord);
00955   return CommandCost();
00956 }
00957 
00962 static void CancelLoadingDueToDeletedOrder(Vehicle *v)
00963 {
00964   assert(v->current_order.IsType(OT_LOADING));
00965   /* NON-stop flag is misused to see if a train is in a station that is
00966    * on his order list or not */
00967   v->current_order.SetNonStopType(ONSF_STOP_EVERYWHERE);
00968   /* When full loading, "cancel" that order so the vehicle doesn't
00969    * stay indefinitely at this station anymore. */
00970   if (v->current_order.GetLoadType() & OLFB_FULL_LOAD) v->current_order.SetLoadType(OLF_LOAD_IF_POSSIBLE);
00971 }
00972 
00978 void DeleteOrder(Vehicle *v, VehicleOrderID sel_ord)
00979 {
00980   v->orders.list->DeleteOrderAt(sel_ord);
00981 
00982   Vehicle *u = v->FirstShared();
00983   DeleteOrderWarnings(u);
00984   for (; u != NULL; u = u->NextShared()) {
00985     assert(v->orders.list == u->orders.list);
00986 
00987     if (sel_ord == u->cur_real_order_index && u->current_order.IsType(OT_LOADING)) {
00988       CancelLoadingDueToDeletedOrder(u);
00989     }
00990 
00991     if (sel_ord < u->cur_real_order_index) {
00992       u->cur_real_order_index--;
00993     } else if (sel_ord == u->cur_real_order_index) {
00994       u->UpdateRealOrderIndex();
00995     }
00996 
00997     if (sel_ord < u->cur_implicit_order_index) {
00998       u->cur_implicit_order_index--;
00999     } else if (sel_ord == u->cur_implicit_order_index) {
01000       /* Make sure the index is valid */
01001       if (u->cur_implicit_order_index >= u->GetNumOrders()) u->cur_implicit_order_index = 0;
01002 
01003       /* Skip non-implicit orders for the implicit-order-index (e.g. if the current implicit order was deleted */
01004       while (u->cur_implicit_order_index != u->cur_real_order_index && !u->GetOrder(u->cur_implicit_order_index)->IsType(OT_IMPLICIT)) {
01005         u->cur_implicit_order_index++;
01006         if (u->cur_implicit_order_index >= u->GetNumOrders()) u->cur_implicit_order_index = 0;
01007       }
01008     }
01009 
01010     /* Update any possible open window of the vehicle */
01011     InvalidateVehicleOrder(u, sel_ord | (INVALID_VEH_ORDER_ID << 8));
01012   }
01013 
01014   /* As we delete an order, the order to skip to will be 'wrong'. */
01015   VehicleOrderID cur_order_id = 0;
01016   Order *order = NULL;
01017   FOR_VEHICLE_ORDERS(v, order) {
01018     if (order->IsType(OT_CONDITIONAL)) {
01019       VehicleOrderID order_id = order->GetConditionSkipToOrder();
01020       if (order_id >= sel_ord) {
01021         order_id = max(order_id - 1, 0);
01022       }
01023       if (order_id == cur_order_id) {
01024         order_id = (order_id + 1) % v->GetNumOrders();
01025       }
01026       order->SetConditionSkipToOrder(order_id);
01027     }
01028     cur_order_id++;
01029   }
01030 
01031   InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
01032 }
01033 
01043 CommandCost CmdSkipToOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01044 {
01045   VehicleID veh_id = GB(p1, 0, 20);
01046   VehicleOrderID sel_ord = GB(p2, 0, 8);
01047 
01048   Vehicle *v = Vehicle::GetIfValid(veh_id);
01049 
01050   if (v == NULL || !v->IsPrimaryVehicle() || sel_ord == v->cur_implicit_order_index || sel_ord >= v->GetNumOrders() || v->GetNumOrders() < 2) return CMD_ERROR;
01051 
01052   CommandCost ret = CheckOwnership(v->owner);
01053   if (ret.Failed()) return ret;
01054 
01055   if (flags & DC_EXEC) {
01056     v->cur_implicit_order_index = v->cur_real_order_index = sel_ord;
01057     v->UpdateRealOrderIndex();
01058 
01059     if (v->current_order.IsType(OT_LOADING)) v->LeaveStation();
01060 
01061     InvalidateVehicleOrder(v, -2);
01062   }
01063 
01064   /* We have an aircraft/ship, they have a mini-schedule, so update them all */
01065   if (v->type == VEH_AIRCRAFT) SetWindowClassesDirty(WC_AIRCRAFT_LIST);
01066   if (v->type == VEH_SHIP) SetWindowClassesDirty(WC_SHIPS_LIST);
01067 
01068   return CommandCost();
01069 }
01070 
01084 CommandCost CmdMoveOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01085 {
01086   VehicleID veh = GB(p1, 0, 20);
01087   VehicleOrderID moving_order = GB(p2,  0, 16);
01088   VehicleOrderID target_order = GB(p2, 16, 16);
01089 
01090   Vehicle *v = Vehicle::GetIfValid(veh);
01091   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01092 
01093   CommandCost ret = CheckOwnership(v->owner);
01094   if (ret.Failed()) return ret;
01095 
01096   /* Don't make senseless movements */
01097   if (moving_order >= v->GetNumOrders() || target_order >= v->GetNumOrders() ||
01098       moving_order == target_order || v->GetNumOrders() <= 1) return CMD_ERROR;
01099 
01100   Order *moving_one = v->GetOrder(moving_order);
01101   /* Don't move an empty order */
01102   if (moving_one == NULL) return CMD_ERROR;
01103 
01104   if (flags & DC_EXEC) {
01105     v->orders.list->MoveOrder(moving_order, target_order);
01106 
01107     /* Update shared list */
01108     Vehicle *u = v->FirstShared();
01109 
01110     DeleteOrderWarnings(u);
01111 
01112     for (; u != NULL; u = u->NextShared()) {
01113       /* Update the current order.
01114        * There are multiple ways to move orders, which result in cur_implicit_order_index
01115        * and cur_real_order_index to not longer make any sense. E.g. moving another
01116        * real order between them.
01117        *
01118        * Basically one could choose to preserve either of them, but not both.
01119        * While both ways are suitable in this or that case from a human point of view, neither
01120        * of them makes really sense.
01121        * However, from an AI point of view, preserving cur_real_order_index is the most
01122        * predictable and transparent behaviour.
01123        *
01124        * With that decision it basically does not matter what we do to cur_implicit_order_index.
01125        * If we change orders between the implict- and real-index, the implicit orders are mostly likely
01126        * completely out-dated anyway. So, keep it simple and just keep cur_implicit_order_index as well.
01127        * The worst which can happen is that a lot of implicit orders are removed when reaching current_order.
01128        */
01129       if (u->cur_real_order_index == moving_order) {
01130         u->cur_real_order_index = target_order;
01131       } else if (u->cur_real_order_index > moving_order && u->cur_real_order_index <= target_order) {
01132         u->cur_real_order_index--;
01133       } else if (u->cur_real_order_index < moving_order && u->cur_real_order_index >= target_order) {
01134         u->cur_real_order_index++;
01135       }
01136 
01137       if (u->cur_implicit_order_index == moving_order) {
01138         u->cur_implicit_order_index = target_order;
01139       } else if (u->cur_implicit_order_index > moving_order && u->cur_implicit_order_index <= target_order) {
01140         u->cur_implicit_order_index--;
01141       } else if (u->cur_implicit_order_index < moving_order && u->cur_implicit_order_index >= target_order) {
01142         u->cur_implicit_order_index++;
01143       }
01144 
01145       assert(v->orders.list == u->orders.list);
01146       /* Update any possible open window of the vehicle */
01147       InvalidateVehicleOrder(u, moving_order | (target_order << 8));
01148     }
01149 
01150     /* As we move an order, the order to skip to will be 'wrong'. */
01151     Order *order;
01152     FOR_VEHICLE_ORDERS(v, order) {
01153       if (order->IsType(OT_CONDITIONAL)) {
01154         VehicleOrderID order_id = order->GetConditionSkipToOrder();
01155         if (order_id == moving_order) {
01156           order_id = target_order;
01157         } else if (order_id > moving_order && order_id <= target_order) {
01158           order_id--;
01159         } else if (order_id < moving_order && order_id >= target_order) {
01160           order_id++;
01161         }
01162         order->SetConditionSkipToOrder(order_id);
01163       }
01164     }
01165 
01166     /* Make sure to rebuild the whole list */
01167     InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
01168   }
01169 
01170   return CommandCost();
01171 }
01172 
01188 CommandCost CmdModifyOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01189 {
01190   VehicleOrderID sel_ord = GB(p1, 20,  8);
01191   VehicleID veh          = GB(p1,  0, 20);
01192   ModifyOrderFlags mof   = Extract<ModifyOrderFlags, 0, 4>(p2);
01193   uint16 data            = GB(p2,  4, 11);
01194 
01195   if (mof >= MOF_END) return CMD_ERROR;
01196 
01197   Vehicle *v = Vehicle::GetIfValid(veh);
01198   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01199 
01200   CommandCost ret = CheckOwnership(v->owner);
01201   if (ret.Failed()) return ret;
01202 
01203   /* Is it a valid order? */
01204   if (sel_ord >= v->GetNumOrders()) return CMD_ERROR;
01205 
01206   Order *order = v->GetOrder(sel_ord);
01207   switch (order->GetType()) {
01208     case OT_GOTO_STATION:
01209       if (mof == MOF_COND_VARIABLE || mof == MOF_COND_COMPARATOR || mof == MOF_DEPOT_ACTION || mof == MOF_COND_VALUE) return CMD_ERROR;
01210       break;
01211 
01212     case OT_GOTO_DEPOT:
01213       if (mof != MOF_NON_STOP && mof != MOF_DEPOT_ACTION) return CMD_ERROR;
01214       break;
01215 
01216     case OT_GOTO_WAYPOINT:
01217       if (mof != MOF_NON_STOP) return CMD_ERROR;
01218       break;
01219 
01220     case OT_CONDITIONAL:
01221       if (mof != MOF_COND_VARIABLE && mof != MOF_COND_COMPARATOR && mof != MOF_COND_VALUE && mof != MOF_COND_DESTINATION) return CMD_ERROR;
01222       break;
01223 
01224     default:
01225       return CMD_ERROR;
01226   }
01227 
01228   switch (mof) {
01229     default: NOT_REACHED();
01230 
01231     case MOF_NON_STOP:
01232       if (!v->IsGroundVehicle()) return CMD_ERROR;
01233       if (data >= ONSF_END) return CMD_ERROR;
01234       if (data == order->GetNonStopType()) return CMD_ERROR;
01235       break;
01236 
01237     case MOF_STOP_LOCATION:
01238       if (v->type != VEH_TRAIN) return CMD_ERROR;
01239       if (data >= OSL_END) return CMD_ERROR;
01240       break;
01241 
01242     case MOF_UNLOAD:
01243       if ((data & ~(OUFB_UNLOAD | OUFB_TRANSFER | OUFB_NO_UNLOAD)) != 0) return CMD_ERROR;
01244       /* Unload and no-unload are mutual exclusive and so are transfer and no unload. */
01245       if (data != 0 && ((data & (OUFB_UNLOAD | OUFB_TRANSFER)) != 0) == ((data & OUFB_NO_UNLOAD) != 0)) return CMD_ERROR;
01246       if (data == order->GetUnloadType()) return CMD_ERROR;
01247       break;
01248 
01249     case MOF_LOAD:
01250       if (data > OLFB_NO_LOAD || data == 1) return CMD_ERROR;
01251       if (data == order->GetLoadType()) return CMD_ERROR;
01252       break;
01253 
01254     case MOF_DEPOT_ACTION:
01255       if (data >= DA_END) return CMD_ERROR;
01256       break;
01257 
01258     case MOF_COND_VARIABLE:
01259       if (data >= OCV_END) return CMD_ERROR;
01260       break;
01261 
01262     case MOF_COND_COMPARATOR:
01263       if (data >= OCC_END) return CMD_ERROR;
01264       switch (order->GetConditionVariable()) {
01265         case OCV_UNCONDITIONALLY: return CMD_ERROR;
01266 
01267         case OCV_REQUIRES_SERVICE:
01268           if (data != OCC_IS_TRUE && data != OCC_IS_FALSE) return CMD_ERROR;
01269           break;
01270 
01271         default:
01272           if (data == OCC_IS_TRUE || data == OCC_IS_FALSE) return CMD_ERROR;
01273           break;
01274       }
01275       break;
01276 
01277     case MOF_COND_VALUE:
01278       switch (order->GetConditionVariable()) {
01279         case OCV_UNCONDITIONALLY: return CMD_ERROR;
01280 
01281         case OCV_LOAD_PERCENTAGE:
01282         case OCV_RELIABILITY:
01283           if (data > 100) return CMD_ERROR;
01284           break;
01285 
01286         default:
01287           if (data > 2047) return CMD_ERROR;
01288           break;
01289       }
01290       break;
01291 
01292     case MOF_COND_DESTINATION:
01293       if (data >= v->GetNumOrders()) return CMD_ERROR;
01294       break;
01295   }
01296 
01297   if (flags & DC_EXEC) {
01298     switch (mof) {
01299       case MOF_NON_STOP:
01300         order->SetNonStopType((OrderNonStopFlags)data);
01301         if (data & ONSF_NO_STOP_AT_DESTINATION_STATION) order->SetRefit(CT_NO_REFIT);
01302         break;
01303 
01304       case MOF_STOP_LOCATION:
01305         order->SetStopLocation((OrderStopLocation)data);
01306         break;
01307 
01308       case MOF_UNLOAD:
01309         order->SetUnloadType((OrderUnloadFlags)data);
01310         break;
01311 
01312       case MOF_LOAD:
01313         order->SetLoadType((OrderLoadFlags)data);
01314         if (data & OLFB_NO_LOAD) order->SetRefit(CT_NO_REFIT);
01315         break;
01316 
01317       case MOF_DEPOT_ACTION: {
01318         switch (data) {
01319           case DA_ALWAYS_GO:
01320             order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
01321             order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
01322             break;
01323 
01324           case DA_SERVICE:
01325             order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() | ODTFB_SERVICE));
01326             order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
01327             order->SetRefit(CT_NO_REFIT);
01328             break;
01329 
01330           case DA_STOP:
01331             order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
01332             order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() | ODATFB_HALT));
01333             order->SetRefit(CT_NO_REFIT);
01334             break;
01335 
01336           default:
01337             NOT_REACHED();
01338         }
01339         break;
01340       }
01341 
01342       case MOF_COND_VARIABLE: {
01343         order->SetConditionVariable((OrderConditionVariable)data);
01344 
01345         OrderConditionComparator occ = order->GetConditionComparator();
01346         switch (order->GetConditionVariable()) {
01347           case OCV_UNCONDITIONALLY:
01348             order->SetConditionComparator(OCC_EQUALS);
01349             order->SetConditionValue(0);
01350             break;
01351 
01352           case OCV_REQUIRES_SERVICE:
01353             if (occ != OCC_IS_TRUE && occ != OCC_IS_FALSE) order->SetConditionComparator(OCC_IS_TRUE);
01354             break;
01355 
01356           case OCV_LOAD_PERCENTAGE:
01357           case OCV_RELIABILITY:
01358             if (order->GetConditionValue() > 100) order->SetConditionValue(100);
01359             /* FALL THROUGH */
01360           default:
01361             if (occ == OCC_IS_TRUE || occ == OCC_IS_FALSE) order->SetConditionComparator(OCC_EQUALS);
01362             break;
01363         }
01364         break;
01365       }
01366 
01367       case MOF_COND_COMPARATOR:
01368         order->SetConditionComparator((OrderConditionComparator)data);
01369         break;
01370 
01371       case MOF_COND_VALUE:
01372         order->SetConditionValue(data);
01373         break;
01374 
01375       case MOF_COND_DESTINATION:
01376         order->SetConditionSkipToOrder(data);
01377         break;
01378 
01379       default: NOT_REACHED();
01380     }
01381 
01382     /* Update the windows and full load flags, also for vehicles that share the same order list */
01383     Vehicle *u = v->FirstShared();
01384     DeleteOrderWarnings(u);
01385     for (; u != NULL; u = u->NextShared()) {
01386       /* Toggle u->current_order "Full load" flag if it changed.
01387        * However, as the same flag is used for depot orders, check
01388        * whether we are not going to a depot as there are three
01389        * cases where the full load flag can be active and only
01390        * one case where the flag is used for depot orders. In the
01391        * other cases for the OrderTypeByte the flags are not used,
01392        * so do not care and those orders should not be active
01393        * when this function is called.
01394        */
01395       if (sel_ord == u->cur_real_order_index &&
01396           (u->current_order.IsType(OT_GOTO_STATION) || u->current_order.IsType(OT_LOADING)) &&
01397           u->current_order.GetLoadType() != order->GetLoadType()) {
01398         u->current_order.SetLoadType(order->GetLoadType());
01399       }
01400       InvalidateVehicleOrder(u, -2);
01401     }
01402   }
01403 
01404   return CommandCost();
01405 }
01406 
01414 static bool CheckAircraftOrderDistance(const Aircraft *v_new, const Vehicle *v_order, const Order *first)
01415 {
01416   if (first == NULL || v_new->acache.cached_max_range == 0) return true;
01417 
01418   /* Iterate over all orders to check the distance between all
01419    * 'goto' orders and their respective next order (of any type). */
01420   for (const Order *o = first; o != NULL; o = o->next) {
01421     switch (o->GetType()) {
01422       case OT_GOTO_STATION:
01423       case OT_GOTO_DEPOT:
01424       case OT_GOTO_WAYPOINT:
01425         /* If we don't have a next order, we've reached the end and must check the first order instead. */
01426         if (GetOrderDistance(o, o->next != NULL ? o->next : first, v_order) > v_new->acache.cached_max_range_sqr) return false;
01427         break;
01428 
01429       default: break;
01430     }
01431   }
01432 
01433   return true;
01434 }
01435 
01447 CommandCost CmdCloneOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01448 {
01449   VehicleID veh_src = GB(p2, 0, 20);
01450   VehicleID veh_dst = GB(p1, 0, 20);
01451 
01452   Vehicle *dst = Vehicle::GetIfValid(veh_dst);
01453   if (dst == NULL || !dst->IsPrimaryVehicle()) return CMD_ERROR;
01454 
01455   CommandCost ret = CheckOwnership(dst->owner);
01456   if (ret.Failed()) return ret;
01457 
01458   switch (GB(p1, 30, 2)) {
01459     case CO_SHARE: {
01460       Vehicle *src = Vehicle::GetIfValid(veh_src);
01461 
01462       /* Sanity checks */
01463       if (src == NULL || !src->IsPrimaryVehicle() || dst->type != src->type || dst == src) return CMD_ERROR;
01464 
01465       CommandCost ret = CheckOwnership(src->owner);
01466       if (ret.Failed()) return ret;
01467 
01468       /* Trucks can't share orders with busses (and visa versa) */
01469       if (src->type == VEH_ROAD && RoadVehicle::From(src)->IsBus() != RoadVehicle::From(dst)->IsBus()) {
01470         return CMD_ERROR;
01471       }
01472 
01473       /* Is the vehicle already in the shared list? */
01474       if (src->FirstShared() == dst->FirstShared()) return CMD_ERROR;
01475 
01476       const Order *order;
01477 
01478       FOR_VEHICLE_ORDERS(src, order) {
01479         if (!OrderGoesToStation(dst, order)) continue;
01480 
01481         /* Allow copying unreachable destinations if they were already unreachable for the source.
01482          * This is basically to allow cloning / autorenewing / autoreplacing vehicles, while the stations
01483          * are temporarily invalid due to reconstruction. */
01484         const Station *st = Station::Get(order->GetDestination());
01485         if (CanVehicleUseStation(src, st) && !CanVehicleUseStation(dst, st)) {
01486           return_cmd_error(STR_ERROR_CAN_T_COPY_SHARE_ORDER);
01487         }
01488       }
01489 
01490       /* Check for aircraft range limits. */
01491       if (dst->type == VEH_AIRCRAFT && !CheckAircraftOrderDistance(Aircraft::From(dst), src, src->GetFirstOrder())) {
01492         return_cmd_error(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE);
01493       }
01494 
01495       if (src->orders.list == NULL && !OrderList::CanAllocateItem()) {
01496         return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
01497       }
01498 
01499       if (flags & DC_EXEC) {
01500         /* If the destination vehicle had a OrderList, destroy it.
01501          * We only reset the order indices, if the new orders are obviously different.
01502          * (We mainly do this to keep the order indices valid and in range.) */
01503         DeleteVehicleOrders(dst, false, dst->GetNumOrders() != src->GetNumOrders());
01504 
01505         dst->orders.list = src->orders.list;
01506 
01507         /* Link this vehicle in the shared-list */
01508         dst->AddToShared(src);
01509 
01510         InvalidateVehicleOrder(dst, -1);
01511         InvalidateVehicleOrder(src, -2);
01512 
01513         InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
01514       }
01515       break;
01516     }
01517 
01518     case CO_COPY: {
01519       Vehicle *src = Vehicle::GetIfValid(veh_src);
01520 
01521       /* Sanity checks */
01522       if (src == NULL || !src->IsPrimaryVehicle() || dst->type != src->type || dst == src) return CMD_ERROR;
01523 
01524       CommandCost ret = CheckOwnership(src->owner);
01525       if (ret.Failed()) return ret;
01526 
01527       /* Trucks can't copy all the orders from busses (and visa versa),
01528        * and neither can helicopters and aircarft. */
01529       const Order *order;
01530       FOR_VEHICLE_ORDERS(src, order) {
01531         if (OrderGoesToStation(dst, order) &&
01532             !CanVehicleUseStation(dst, Station::Get(order->GetDestination()))) {
01533           return_cmd_error(STR_ERROR_CAN_T_COPY_SHARE_ORDER);
01534         }
01535       }
01536 
01537       /* Check for aircraft range limits. */
01538       if (dst->type == VEH_AIRCRAFT && !CheckAircraftOrderDistance(Aircraft::From(dst), src, src->GetFirstOrder())) {
01539         return_cmd_error(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE);
01540       }
01541 
01542       /* make sure there are orders available */
01543       if (!Order::CanAllocateItem(src->GetNumOrders()) || !OrderList::CanAllocateItem()) {
01544         return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
01545       }
01546 
01547       if (flags & DC_EXEC) {
01548         const Order *order;
01549         Order *first = NULL;
01550         Order **order_dst;
01551 
01552         /* If the destination vehicle had an order list, destroy the chain but keep the OrderList.
01553          * We only reset the order indices, if the new orders are obviously different.
01554          * (We mainly do this to keep the order indices valid and in range.) */
01555         DeleteVehicleOrders(dst, true, dst->GetNumOrders() != src->GetNumOrders());
01556 
01557         order_dst = &first;
01558         FOR_VEHICLE_ORDERS(src, order) {
01559           *order_dst = new Order();
01560           (*order_dst)->AssignOrder(*order);
01561           order_dst = &(*order_dst)->next;
01562         }
01563         if (dst->orders.list == NULL) {
01564           dst->orders.list = new OrderList(first, dst);
01565         } else {
01566           assert(dst->orders.list->GetFirstOrder() == NULL);
01567           assert(!dst->orders.list->IsShared());
01568           delete dst->orders.list;
01569           assert(OrderList::CanAllocateItem());
01570           dst->orders.list = new OrderList(first, dst);
01571         }
01572 
01573         InvalidateVehicleOrder(dst, -1);
01574 
01575         InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
01576       }
01577       break;
01578     }
01579 
01580     case CO_UNSHARE: return DecloneOrder(dst, flags);
01581     default: return CMD_ERROR;
01582   }
01583 
01584   return CommandCost();
01585 }
01586 
01599 CommandCost CmdOrderRefit(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01600 {
01601   VehicleID veh = GB(p1, 0, 20);
01602   VehicleOrderID order_number  = GB(p2, 16, 8);
01603   CargoID cargo = GB(p2, 0, 8);
01604   byte subtype  = GB(p2, 8, 8);
01605 
01606   if (cargo >= NUM_CARGO && cargo != CT_NO_REFIT && cargo != CT_AUTO_REFIT) return CMD_ERROR;
01607 
01608   const Vehicle *v = Vehicle::GetIfValid(veh);
01609   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01610 
01611   CommandCost ret = CheckOwnership(v->owner);
01612   if (ret.Failed()) return ret;
01613 
01614   Order *order = v->GetOrder(order_number);
01615   if (order == NULL) return CMD_ERROR;
01616 
01617   /* Automatic refit cargo is only supported for goto station orders. */
01618   if (cargo == CT_AUTO_REFIT && !order->IsType(OT_GOTO_STATION)) return CMD_ERROR;
01619 
01620   if (flags & DC_EXEC) {
01621     order->SetRefit(cargo, subtype);
01622 
01623     /* Make the depot order an 'always go' order. */
01624     if (cargo != CT_NO_REFIT && order->IsType(OT_GOTO_DEPOT)) {
01625       order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
01626       order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
01627     }
01628 
01629     for (Vehicle *u = v->FirstShared(); u != NULL; u = u->NextShared()) {
01630       /* Update any possible open window of the vehicle */
01631       InvalidateVehicleOrder(u, -2);
01632 
01633       /* If the vehicle already got the current depot set as current order, then update current order as well */
01634       if (u->cur_real_order_index == order_number && (u->current_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) {
01635         u->current_order.SetRefit(cargo, subtype);
01636       }
01637     }
01638   }
01639 
01640   return CommandCost();
01641 }
01642 
01643 
01649 void CheckOrders(const Vehicle *v)
01650 {
01651   /* Does the user wants us to check things? */
01652   if (_settings_client.gui.order_review_system == 0) return;
01653 
01654   /* Do nothing for crashed vehicles */
01655   if (v->vehstatus & VS_CRASHED) return;
01656 
01657   /* Do nothing for stopped vehicles if setting is '1' */
01658   if (_settings_client.gui.order_review_system == 1 && (v->vehstatus & VS_STOPPED)) return;
01659 
01660   /* do nothing we we're not the first vehicle in a share-chain */
01661   if (v->FirstShared() != v) return;
01662 
01663   /* Only check every 20 days, so that we don't flood the message log */
01664   if (v->owner == _local_company && v->day_counter % 20 == 0) {
01665     int n_st, problem_type = -1;
01666     const Order *order;
01667     int message = 0;
01668 
01669     /* Check the order list */
01670     n_st = 0;
01671 
01672     FOR_VEHICLE_ORDERS(v, order) {
01673       /* Dummy order? */
01674       if (order->IsType(OT_DUMMY)) {
01675         problem_type = 1;
01676         break;
01677       }
01678       /* Does station have a load-bay for this vehicle? */
01679       if (order->IsType(OT_GOTO_STATION)) {
01680         const Station *st = Station::Get(order->GetDestination());
01681 
01682         n_st++;
01683         if (!CanVehicleUseStation(v, st)) problem_type = 3;
01684       }
01685     }
01686 
01687     /* Check if the last and the first order are the same */
01688     if (v->GetNumOrders() > 1) {
01689       const Order *last = v->GetLastOrder();
01690 
01691       if (v->orders.list->GetFirstOrder()->Equals(*last)) {
01692         problem_type = 2;
01693       }
01694     }
01695 
01696     /* Do we only have 1 station in our order list? */
01697     if (n_st < 2 && problem_type == -1) problem_type = 0;
01698 
01699 #ifndef NDEBUG
01700     if (v->orders.list != NULL) v->orders.list->DebugCheckSanity();
01701 #endif
01702 
01703     /* We don't have a problem */
01704     if (problem_type < 0) return;
01705 
01706     message = STR_NEWS_VEHICLE_HAS_TOO_FEW_ORDERS + problem_type;
01707     //DEBUG(misc, 3, "Triggered News Item for vehicle %d", v->index);
01708 
01709     SetDParam(0, v->index);
01710     AddVehicleAdviceNewsItem(message, v->index);
01711   }
01712 }
01713 
01719 void RemoveOrderFromAllVehicles(OrderType type, DestinationID destination)
01720 {
01721   Vehicle *v;
01722 
01723   /* Aircraft have StationIDs for depot orders and never use DepotIDs
01724    * This fact is handled specially below
01725    */
01726 
01727   /* Go through all vehicles */
01728   FOR_ALL_VEHICLES(v) {
01729     Order *order;
01730 
01731     order = &v->current_order;
01732     if ((v->type == VEH_AIRCRAFT && order->IsType(OT_GOTO_DEPOT) ? OT_GOTO_STATION : order->GetType()) == type &&
01733         v->current_order.GetDestination() == destination) {
01734       order->MakeDummy();
01735       SetWindowDirty(WC_VEHICLE_VIEW, v->index);
01736     }
01737 
01738     /* Clear the order from the order-list */
01739     int id = -1;
01740     FOR_VEHICLE_ORDERS(v, order) {
01741       id++;
01742 restart:
01743 
01744       OrderType ot = order->GetType();
01745       if (ot == OT_GOTO_DEPOT && (order->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0) continue;
01746       if (ot == OT_IMPLICIT || (v->type == VEH_AIRCRAFT && ot == OT_GOTO_DEPOT)) ot = OT_GOTO_STATION;
01747       if (ot == type && order->GetDestination() == destination) {
01748         /* We want to clear implicit orders, but we don't want to make them
01749          * dummy orders. They should just vanish. Also check the actual order
01750          * type as ot is currently OT_GOTO_STATION. */
01751         if (order->IsType(OT_IMPLICIT)) {
01752           order = order->next; // DeleteOrder() invalidates current order
01753           DeleteOrder(v, id);
01754           if (order != NULL) goto restart;
01755           break;
01756         }
01757 
01758         order->MakeDummy();
01759         for (const Vehicle *w = v->FirstShared(); w != NULL; w = w->NextShared()) {
01760           /* In GUI, simulate by removing the order and adding it back */
01761           InvalidateVehicleOrder(w, id | (INVALID_VEH_ORDER_ID << 8));
01762           InvalidateVehicleOrder(w, (INVALID_VEH_ORDER_ID << 8) | id);
01763         }
01764       }
01765     }
01766   }
01767 
01768   OrderBackup::RemoveOrder(type, destination);
01769 }
01770 
01775 bool Vehicle::HasDepotOrder() const
01776 {
01777   const Order *order;
01778 
01779   FOR_VEHICLE_ORDERS(this, order) {
01780     if (order->IsType(OT_GOTO_DEPOT)) return true;
01781   }
01782 
01783   return false;
01784 }
01785 
01795 void DeleteVehicleOrders(Vehicle *v, bool keep_orderlist, bool reset_order_indices)
01796 {
01797   DeleteOrderWarnings(v);
01798 
01799   if (v->IsOrderListShared()) {
01800     /* Remove ourself from the shared order list. */
01801     v->RemoveFromShared();
01802     v->orders.list = NULL;
01803   } else if (v->orders.list != NULL) {
01804     /* Remove the orders */
01805     v->orders.list->FreeChain(keep_orderlist);
01806     if (!keep_orderlist) v->orders.list = NULL;
01807   }
01808 
01809   if (reset_order_indices) {
01810     v->cur_implicit_order_index = v->cur_real_order_index = 0;
01811     if (v->current_order.IsType(OT_LOADING)) {
01812       CancelLoadingDueToDeletedOrder(v);
01813     }
01814   }
01815 }
01816 
01824 uint16 GetServiceIntervalClamped(uint interval, CompanyID company_id)
01825 {
01826   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);
01827 }
01828 
01837 static bool CheckForValidOrders(const Vehicle *v)
01838 {
01839   const Order *order;
01840 
01841   FOR_VEHICLE_ORDERS(v, order) {
01842     switch (order->GetType()) {
01843       case OT_GOTO_STATION:
01844       case OT_GOTO_DEPOT:
01845       case OT_GOTO_WAYPOINT:
01846         return true;
01847 
01848       default:
01849         break;
01850     }
01851   }
01852 
01853   return false;
01854 }
01855 
01859 static bool OrderConditionCompare(OrderConditionComparator occ, int variable, int value)
01860 {
01861   switch (occ) {
01862     case OCC_EQUALS:      return variable == value;
01863     case OCC_NOT_EQUALS:  return variable != value;
01864     case OCC_LESS_THAN:   return variable <  value;
01865     case OCC_LESS_EQUALS: return variable <= value;
01866     case OCC_MORE_THAN:   return variable >  value;
01867     case OCC_MORE_EQUALS: return variable >= value;
01868     case OCC_IS_TRUE:     return variable != 0;
01869     case OCC_IS_FALSE:    return variable == 0;
01870     default: NOT_REACHED();
01871   }
01872 }
01873 
01880 VehicleOrderID ProcessConditionalOrder(const Order *order, const Vehicle *v)
01881 {
01882   if (order->GetType() != OT_CONDITIONAL) return INVALID_VEH_ORDER_ID;
01883 
01884   bool skip_order = false;
01885   OrderConditionComparator occ = order->GetConditionComparator();
01886   uint16 value = order->GetConditionValue();
01887 
01888   switch (order->GetConditionVariable()) {
01889     case OCV_LOAD_PERCENTAGE:    skip_order = OrderConditionCompare(occ, CalcPercentVehicleFilled(v, NULL), value); break;
01890     case OCV_RELIABILITY:        skip_order = OrderConditionCompare(occ, ToPercent16(v->reliability),       value); break;
01891     case OCV_MAX_SPEED:          skip_order = OrderConditionCompare(occ, v->GetDisplayMaxSpeed() * 10 / 16, value); break;
01892     case OCV_AGE:                skip_order = OrderConditionCompare(occ, v->age / DAYS_IN_LEAP_YEAR,        value); break;
01893     case OCV_REQUIRES_SERVICE:   skip_order = OrderConditionCompare(occ, v->NeedsServicing(),               value); break;
01894     case OCV_UNCONDITIONALLY:    skip_order = true; break;
01895     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;
01896     default: NOT_REACHED();
01897   }
01898 
01899   return skip_order ? order->GetConditionSkipToOrder() : (VehicleOrderID)INVALID_VEH_ORDER_ID;
01900 }
01901 
01909 bool UpdateOrderDest(Vehicle *v, const Order *order, int conditional_depth, bool pbs_look_ahead)
01910 {
01911   if (conditional_depth > v->GetNumOrders()) return false;
01912 
01913   switch (order->GetType()) {
01914     case OT_GOTO_STATION:
01915       v->dest_tile = v->GetOrderStationLocation(order->GetDestination());
01916       return true;
01917 
01918     case OT_GOTO_DEPOT:
01919       if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !v->NeedsServicing()) {
01920         assert(!pbs_look_ahead);
01921         UpdateVehicleTimetable(v, true);
01922         v->IncrementRealOrderIndex();
01923         break;
01924       }
01925 
01926       if (v->current_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) {
01927         /* We need to search for the nearest depot (hangar). */
01928         TileIndex location;
01929         DestinationID destination;
01930         bool reverse;
01931 
01932         if (v->FindClosestDepot(&location, &destination, &reverse)) {
01933           /* PBS reservations cannot reverse */
01934           if (pbs_look_ahead && reverse) return false;
01935 
01936           v->dest_tile = location;
01937           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());
01938 
01939           /* If there is no depot in front, reverse automatically (trains only) */
01940           if (v->type == VEH_TRAIN && reverse) DoCommand(v->tile, v->index, 0, DC_EXEC, CMD_REVERSE_TRAIN_DIRECTION);
01941 
01942           if (v->type == VEH_AIRCRAFT) {
01943             Aircraft *a = Aircraft::From(v);
01944             if (a->state == FLYING && a->targetairport != destination) {
01945               /* The aircraft is now heading for a different hangar than the next in the orders */
01946               extern void AircraftNextAirportPos_and_Order(Aircraft *a);
01947               AircraftNextAirportPos_and_Order(a);
01948             }
01949           }
01950           return true;
01951         }
01952 
01953         /* If there is no depot, we cannot help PBS either. */
01954         if (pbs_look_ahead) return false;
01955 
01956         UpdateVehicleTimetable(v, true);
01957         v->IncrementRealOrderIndex();
01958       } else {
01959         if (v->type != VEH_AIRCRAFT) {
01960           v->dest_tile = Depot::Get(order->GetDestination())->xy;
01961         }
01962         return true;
01963       }
01964       break;
01965 
01966     case OT_GOTO_WAYPOINT:
01967       v->dest_tile = Waypoint::Get(order->GetDestination())->xy;
01968       return true;
01969 
01970     case OT_CONDITIONAL: {
01971       assert(!pbs_look_ahead);
01972       VehicleOrderID next_order = ProcessConditionalOrder(order, v);
01973       if (next_order != INVALID_VEH_ORDER_ID) {
01974         /* Jump to next_order. cur_implicit_order_index becomes exactly that order,
01975          * cur_real_order_index might come after next_order. */
01976         UpdateVehicleTimetable(v, false);
01977         v->cur_implicit_order_index = v->cur_real_order_index = next_order;
01978         v->UpdateRealOrderIndex();
01979         v->current_order_time += v->GetOrder(v->cur_real_order_index)->travel_time;
01980 
01981         /* Disable creation of implicit orders.
01982          * When inserting them we do not know that we would have to make the conditional orders point to them. */
01983         if (v->IsGroundVehicle()) {
01984           uint16 &gv_flags = v->GetGroundVehicleFlags();
01985           SetBit(gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
01986         }
01987       } else {
01988         UpdateVehicleTimetable(v, true);
01989         v->IncrementRealOrderIndex();
01990       }
01991       break;
01992     }
01993 
01994     default:
01995       v->dest_tile = 0;
01996       return false;
01997   }
01998 
01999   assert(v->cur_implicit_order_index < v->GetNumOrders());
02000   assert(v->cur_real_order_index < v->GetNumOrders());
02001 
02002   /* Get the current order */
02003   order = v->GetOrder(v->cur_real_order_index);
02004   if (order != NULL && order->IsType(OT_IMPLICIT)) {
02005     assert(v->GetNumManualOrders() == 0);
02006     order = NULL;
02007   }
02008 
02009   if (order == NULL) {
02010     v->current_order.Free();
02011     v->dest_tile = 0;
02012     return false;
02013   }
02014 
02015   v->current_order = *order;
02016   return UpdateOrderDest(v, order, conditional_depth + 1, pbs_look_ahead);
02017 }
02018 
02026 bool ProcessOrders(Vehicle *v)
02027 {
02028   switch (v->current_order.GetType()) {
02029     case OT_GOTO_DEPOT:
02030       /* Let a depot order in the orderlist interrupt. */
02031       if (!(v->current_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) return false;
02032       break;
02033 
02034     case OT_LOADING:
02035       return false;
02036 
02037     case OT_LEAVESTATION:
02038       if (v->type != VEH_AIRCRAFT) return false;
02039       break;
02040 
02041     default: break;
02042   }
02043 
02051   bool may_reverse = v->current_order.IsType(OT_NOTHING);
02052 
02053   /* Check if we've reached a 'via' destination. */
02054   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)) &&
02055       IsTileType(v->tile, MP_STATION) &&
02056       v->current_order.GetDestination() == GetStationIndex(v->tile)) {
02057     v->DeleteUnreachedImplicitOrders();
02058     /* We set the last visited station here because we do not want
02059      * the train to stop at this 'via' station if the next order
02060      * is a no-non-stop order; in that case not setting the last
02061      * visited station will cause the vehicle to still stop. */
02062     v->last_station_visited = v->current_order.GetDestination();
02063     UpdateVehicleTimetable(v, true);
02064     v->IncrementImplicitOrderIndex();
02065   }
02066 
02067   /* Get the current order */
02068   assert(v->cur_implicit_order_index == 0 || v->cur_implicit_order_index < v->GetNumOrders());
02069   v->UpdateRealOrderIndex();
02070 
02071   const Order *order = v->GetOrder(v->cur_real_order_index);
02072   if (order != NULL && order->IsType(OT_IMPLICIT)) {
02073     assert(v->GetNumManualOrders() == 0);
02074     order = NULL;
02075   }
02076 
02077   /* If no order, do nothing. */
02078   if (order == NULL || (v->type == VEH_AIRCRAFT && !CheckForValidOrders(v))) {
02079     if (v->type == VEH_AIRCRAFT) {
02080       /* Aircraft do something vastly different here, so handle separately */
02081       extern void HandleMissingAircraftOrders(Aircraft *v);
02082       HandleMissingAircraftOrders(Aircraft::From(v));
02083       return false;
02084     }
02085 
02086     v->current_order.Free();
02087     v->dest_tile = 0;
02088     return false;
02089   }
02090 
02091   /* If it is unchanged, keep it. */
02092   if (order->Equals(v->current_order) && (v->type == VEH_AIRCRAFT || v->dest_tile != 0) &&
02093       (v->type != VEH_SHIP || !order->IsType(OT_GOTO_STATION) || Station::Get(order->GetDestination())->dock_tile != INVALID_TILE)) {
02094     return false;
02095   }
02096 
02097   /* Otherwise set it, and determine the destination tile. */
02098   v->current_order = *order;
02099 
02100   InvalidateVehicleOrder(v, -2);
02101   switch (v->type) {
02102     default:
02103       NOT_REACHED();
02104 
02105     case VEH_ROAD:
02106     case VEH_TRAIN:
02107       break;
02108 
02109     case VEH_AIRCRAFT:
02110     case VEH_SHIP:
02111       SetWindowClassesDirty(GetWindowClassForVehicleType(v->type));
02112       break;
02113   }
02114 
02115   return UpdateOrderDest(v, order) && may_reverse;
02116 }
02117 
02125 bool Order::ShouldStopAtStation(const Vehicle *v, StationID station) const
02126 {
02127   bool is_dest_station = this->IsType(OT_GOTO_STATION) && this->dest == station;
02128 
02129   return (!this->IsType(OT_GOTO_DEPOT) || (this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS) != 0) &&
02130       v->last_station_visited != station && // Do stop only when we've not just been there
02131       /* Finally do stop when there is no non-stop flag set for this type of station. */
02132       !(this->GetNonStopType() & (is_dest_station ? ONSF_NO_STOP_AT_DESTINATION_STATION : ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS));
02133 }