order_cmd.cpp

Go to the documentation of this file.
00001 /* $Id: order_cmd.cpp 24600 2012-10-17 18:43:23Z rubidium $ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
00006  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
00007  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
00008  */
00009 
00012 #include "stdafx.h"
00013 #include "debug.h"
00014 #include "cmd_helper.h"
00015 #include "command_func.h"
00016 #include "company_func.h"
00017 #include "news_func.h"
00018 #include "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       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;
00818       if (new_order.IsType(OT_CONDITIONAL)) {
00819         /* The order is not yet inserted, so we have to do the first iteration here. */
00820         dist = GetOrderDistance(prev, v->GetOrder(new_order.GetConditionSkipToOrder()), v);
00821       } else {
00822         dist = GetOrderDistance(prev, &new_order, v);
00823       }
00824 
00825       if (dist >= 130) {
00826         return_cmd_error(STR_ERROR_TOO_FAR_FROM_PREVIOUS_DESTINATION);
00827       }
00828     }
00829   }
00830 
00831   if (flags & DC_EXEC) {
00832     Order *new_o = new Order();
00833     new_o->AssignOrder(new_order);
00834     InsertOrder(v, new_o, sel_ord);
00835   }
00836 
00837   return CommandCost();
00838 }
00839 
00846 void InsertOrder(Vehicle *v, Order *new_o, VehicleOrderID sel_ord)
00847 {
00848   /* Create new order and link in list */
00849   if (v->orders.list == NULL) {
00850     v->orders.list = new OrderList(new_o, v);
00851   } else {
00852     v->orders.list->InsertOrderAt(new_o, sel_ord);
00853   }
00854 
00855   Vehicle *u = v->FirstShared();
00856   DeleteOrderWarnings(u);
00857   for (; u != NULL; u = u->NextShared()) {
00858     assert(v->orders.list == u->orders.list);
00859 
00860     /* If there is added an order before the current one, we need
00861      * to update the selected order. We do not change implicit/real order indices though.
00862      * If the new order is between the current implicit order and real order, the implicit order will
00863      * later skip the inserted order. */
00864     if (sel_ord <= u->cur_real_order_index) {
00865       uint cur = u->cur_real_order_index + 1;
00866       /* Check if we don't go out of bound */
00867       if (cur < u->GetNumOrders()) {
00868         u->cur_real_order_index = cur;
00869       }
00870     }
00871     if (sel_ord == u->cur_implicit_order_index && u->IsGroundVehicle()) {
00872       /* We are inserting an order just before the current implicit order.
00873        * We do not know whether we will reach current implicit or the newly inserted order first.
00874        * So, disable creation of implicit orders until we are on track again. */
00875       uint16 &gv_flags = u->GetGroundVehicleFlags();
00876       SetBit(gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
00877     }
00878     if (sel_ord <= u->cur_implicit_order_index) {
00879       uint cur = u->cur_implicit_order_index + 1;
00880       /* Check if we don't go out of bound */
00881       if (cur < u->GetNumOrders()) {
00882         u->cur_implicit_order_index = cur;
00883       }
00884     }
00885     /* Update any possible open window of the vehicle */
00886     InvalidateVehicleOrder(u, INVALID_VEH_ORDER_ID | (sel_ord << 8));
00887   }
00888 
00889   /* As we insert an order, the order to skip to will be 'wrong'. */
00890   VehicleOrderID cur_order_id = 0;
00891   Order *order;
00892   FOR_VEHICLE_ORDERS(v, order) {
00893     if (order->IsType(OT_CONDITIONAL)) {
00894       VehicleOrderID order_id = order->GetConditionSkipToOrder();
00895       if (order_id >= sel_ord) {
00896         order->SetConditionSkipToOrder(order_id + 1);
00897       }
00898       if (order_id == cur_order_id) {
00899         order->SetConditionSkipToOrder((order_id + 1) % v->GetNumOrders());
00900       }
00901     }
00902     cur_order_id++;
00903   }
00904 
00905   /* Make sure to rebuild the whole list */
00906   InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
00907 }
00908 
00914 static CommandCost DecloneOrder(Vehicle *dst, DoCommandFlag flags)
00915 {
00916   if (flags & DC_EXEC) {
00917     DeleteVehicleOrders(dst);
00918     InvalidateVehicleOrder(dst, -1);
00919     InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
00920   }
00921   return CommandCost();
00922 }
00923 
00933 CommandCost CmdDeleteOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00934 {
00935   VehicleID veh_id = GB(p1, 0, 20);
00936   VehicleOrderID sel_ord = GB(p2, 0, 8);
00937 
00938   Vehicle *v = Vehicle::GetIfValid(veh_id);
00939 
00940   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
00941 
00942   CommandCost ret = CheckOwnership(v->owner);
00943   if (ret.Failed()) return ret;
00944 
00945   /* If we did not select an order, we maybe want to de-clone the orders */
00946   if (sel_ord >= v->GetNumOrders()) return DecloneOrder(v, flags);
00947 
00948   if (v->GetOrder(sel_ord) == NULL) return CMD_ERROR;
00949 
00950   if (flags & DC_EXEC) DeleteOrder(v, sel_ord);
00951   return CommandCost();
00952 }
00953 
00958 static void CancelLoadingDueToDeletedOrder(Vehicle *v)
00959 {
00960   assert(v->current_order.IsType(OT_LOADING));
00961   /* NON-stop flag is misused to see if a train is in a station that is
00962    * on his order list or not */
00963   v->current_order.SetNonStopType(ONSF_STOP_EVERYWHERE);
00964   /* When full loading, "cancel" that order so the vehicle doesn't
00965    * stay indefinitely at this station anymore. */
00966   if (v->current_order.GetLoadType() & OLFB_FULL_LOAD) v->current_order.SetLoadType(OLF_LOAD_IF_POSSIBLE);
00967 }
00968 
00974 void DeleteOrder(Vehicle *v, VehicleOrderID sel_ord)
00975 {
00976   v->orders.list->DeleteOrderAt(sel_ord);
00977 
00978   Vehicle *u = v->FirstShared();
00979   DeleteOrderWarnings(u);
00980   for (; u != NULL; u = u->NextShared()) {
00981     assert(v->orders.list == u->orders.list);
00982 
00983     if (sel_ord == u->cur_real_order_index && u->current_order.IsType(OT_LOADING)) {
00984       CancelLoadingDueToDeletedOrder(u);
00985     }
00986 
00987     if (sel_ord < u->cur_real_order_index) {
00988       u->cur_real_order_index--;
00989     } else if (sel_ord == u->cur_real_order_index) {
00990       u->UpdateRealOrderIndex();
00991     }
00992 
00993     if (sel_ord < u->cur_implicit_order_index) {
00994       u->cur_implicit_order_index--;
00995     } else if (sel_ord == u->cur_implicit_order_index) {
00996       /* Make sure the index is valid */
00997       if (u->cur_implicit_order_index >= u->GetNumOrders()) u->cur_implicit_order_index = 0;
00998 
00999       /* Skip non-implicit orders for the implicit-order-index (e.g. if the current implicit order was deleted */
01000       while (u->cur_implicit_order_index != u->cur_real_order_index && !u->GetOrder(u->cur_implicit_order_index)->IsType(OT_IMPLICIT)) {
01001         u->cur_implicit_order_index++;
01002         if (u->cur_implicit_order_index >= u->GetNumOrders()) u->cur_implicit_order_index = 0;
01003       }
01004     }
01005 
01006     /* Update any possible open window of the vehicle */
01007     InvalidateVehicleOrder(u, sel_ord | (INVALID_VEH_ORDER_ID << 8));
01008   }
01009 
01010   /* As we delete an order, the order to skip to will be 'wrong'. */
01011   VehicleOrderID cur_order_id = 0;
01012   Order *order = NULL;
01013   FOR_VEHICLE_ORDERS(v, order) {
01014     if (order->IsType(OT_CONDITIONAL)) {
01015       VehicleOrderID order_id = order->GetConditionSkipToOrder();
01016       if (order_id >= sel_ord) {
01017         order_id = max(order_id - 1, 0);
01018       }
01019       if (order_id == cur_order_id) {
01020         order_id = (order_id + 1) % v->GetNumOrders();
01021       }
01022       order->SetConditionSkipToOrder(order_id);
01023     }
01024     cur_order_id++;
01025   }
01026 
01027   InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
01028 }
01029 
01039 CommandCost CmdSkipToOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01040 {
01041   VehicleID veh_id = GB(p1, 0, 20);
01042   VehicleOrderID sel_ord = GB(p2, 0, 8);
01043 
01044   Vehicle *v = Vehicle::GetIfValid(veh_id);
01045 
01046   if (v == NULL || !v->IsPrimaryVehicle() || sel_ord == v->cur_implicit_order_index || sel_ord >= v->GetNumOrders() || v->GetNumOrders() < 2) return CMD_ERROR;
01047 
01048   CommandCost ret = CheckOwnership(v->owner);
01049   if (ret.Failed()) return ret;
01050 
01051   if (flags & DC_EXEC) {
01052     v->cur_implicit_order_index = v->cur_real_order_index = sel_ord;
01053     v->UpdateRealOrderIndex();
01054 
01055     if (v->current_order.IsType(OT_LOADING)) v->LeaveStation();
01056 
01057     InvalidateVehicleOrder(v, -2);
01058   }
01059 
01060   /* We have an aircraft/ship, they have a mini-schedule, so update them all */
01061   if (v->type == VEH_AIRCRAFT) SetWindowClassesDirty(WC_AIRCRAFT_LIST);
01062   if (v->type == VEH_SHIP) SetWindowClassesDirty(WC_SHIPS_LIST);
01063 
01064   return CommandCost();
01065 }
01066 
01080 CommandCost CmdMoveOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01081 {
01082   VehicleID veh = GB(p1, 0, 20);
01083   VehicleOrderID moving_order = GB(p2,  0, 16);
01084   VehicleOrderID target_order = GB(p2, 16, 16);
01085 
01086   Vehicle *v = Vehicle::GetIfValid(veh);
01087   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01088 
01089   CommandCost ret = CheckOwnership(v->owner);
01090   if (ret.Failed()) return ret;
01091 
01092   /* Don't make senseless movements */
01093   if (moving_order >= v->GetNumOrders() || target_order >= v->GetNumOrders() ||
01094       moving_order == target_order || v->GetNumOrders() <= 1) return CMD_ERROR;
01095 
01096   Order *moving_one = v->GetOrder(moving_order);
01097   /* Don't move an empty order */
01098   if (moving_one == NULL) return CMD_ERROR;
01099 
01100   if (flags & DC_EXEC) {
01101     v->orders.list->MoveOrder(moving_order, target_order);
01102 
01103     /* Update shared list */
01104     Vehicle *u = v->FirstShared();
01105 
01106     DeleteOrderWarnings(u);
01107 
01108     for (; u != NULL; u = u->NextShared()) {
01109       /* Update the current order.
01110        * There are multiple ways to move orders, which result in cur_implicit_order_index
01111        * and cur_real_order_index to not longer make any sense. E.g. moving another
01112        * real order between them.
01113        *
01114        * Basically one could choose to preserve either of them, but not both.
01115        * While both ways are suitable in this or that case from a human point of view, neither
01116        * of them makes really sense.
01117        * However, from an AI point of view, preserving cur_real_order_index is the most
01118        * predictable and transparent behaviour.
01119        *
01120        * With that decision it basically does not matter what we do to cur_implicit_order_index.
01121        * If we change orders between the implict- and real-index, the implicit orders are mostly likely
01122        * completely out-dated anyway. So, keep it simple and just keep cur_implicit_order_index as well.
01123        * The worst which can happen is that a lot of implicit orders are removed when reaching current_order.
01124        */
01125       if (u->cur_real_order_index == moving_order) {
01126         u->cur_real_order_index = target_order;
01127       } else if (u->cur_real_order_index > moving_order && u->cur_real_order_index <= target_order) {
01128         u->cur_real_order_index--;
01129       } else if (u->cur_real_order_index < moving_order && u->cur_real_order_index >= target_order) {
01130         u->cur_real_order_index++;
01131       }
01132 
01133       if (u->cur_implicit_order_index == moving_order) {
01134         u->cur_implicit_order_index = target_order;
01135       } else if (u->cur_implicit_order_index > moving_order && u->cur_implicit_order_index <= target_order) {
01136         u->cur_implicit_order_index--;
01137       } else if (u->cur_implicit_order_index < moving_order && u->cur_implicit_order_index >= target_order) {
01138         u->cur_implicit_order_index++;
01139       }
01140 
01141       assert(v->orders.list == u->orders.list);
01142       /* Update any possible open window of the vehicle */
01143       InvalidateVehicleOrder(u, moving_order | (target_order << 8));
01144     }
01145 
01146     /* As we move an order, the order to skip to will be 'wrong'. */
01147     Order *order;
01148     FOR_VEHICLE_ORDERS(v, order) {
01149       if (order->IsType(OT_CONDITIONAL)) {
01150         VehicleOrderID order_id = order->GetConditionSkipToOrder();
01151         if (order_id == moving_order) {
01152           order_id = target_order;
01153         } else if (order_id > moving_order && order_id <= target_order) {
01154           order_id--;
01155         } else if (order_id < moving_order && order_id >= target_order) {
01156           order_id++;
01157         }
01158         order->SetConditionSkipToOrder(order_id);
01159       }
01160     }
01161 
01162     /* Make sure to rebuild the whole list */
01163     InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
01164   }
01165 
01166   return CommandCost();
01167 }
01168 
01184 CommandCost CmdModifyOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01185 {
01186   VehicleOrderID sel_ord = GB(p1, 20,  8);
01187   VehicleID veh          = GB(p1,  0, 20);
01188   ModifyOrderFlags mof   = Extract<ModifyOrderFlags, 0, 4>(p2);
01189   uint16 data            = GB(p2,  4, 11);
01190 
01191   if (mof >= MOF_END) return CMD_ERROR;
01192 
01193   Vehicle *v = Vehicle::GetIfValid(veh);
01194   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01195 
01196   CommandCost ret = CheckOwnership(v->owner);
01197   if (ret.Failed()) return ret;
01198 
01199   /* Is it a valid order? */
01200   if (sel_ord >= v->GetNumOrders()) return CMD_ERROR;
01201 
01202   Order *order = v->GetOrder(sel_ord);
01203   switch (order->GetType()) {
01204     case OT_GOTO_STATION:
01205       if (mof == MOF_COND_VARIABLE || mof == MOF_COND_COMPARATOR || mof == MOF_DEPOT_ACTION || mof == MOF_COND_VALUE) return CMD_ERROR;
01206       break;
01207 
01208     case OT_GOTO_DEPOT:
01209       if (mof != MOF_NON_STOP && mof != MOF_DEPOT_ACTION) return CMD_ERROR;
01210       break;
01211 
01212     case OT_GOTO_WAYPOINT:
01213       if (mof != MOF_NON_STOP) return CMD_ERROR;
01214       break;
01215 
01216     case OT_CONDITIONAL:
01217       if (mof != MOF_COND_VARIABLE && mof != MOF_COND_COMPARATOR && mof != MOF_COND_VALUE && mof != MOF_COND_DESTINATION) return CMD_ERROR;
01218       break;
01219 
01220     default:
01221       return CMD_ERROR;
01222   }
01223 
01224   switch (mof) {
01225     default: NOT_REACHED();
01226 
01227     case MOF_NON_STOP:
01228       if (!v->IsGroundVehicle()) return CMD_ERROR;
01229       if (data >= ONSF_END) return CMD_ERROR;
01230       if (data == order->GetNonStopType()) return CMD_ERROR;
01231       break;
01232 
01233     case MOF_STOP_LOCATION:
01234       if (v->type != VEH_TRAIN) return CMD_ERROR;
01235       if (data >= OSL_END) return CMD_ERROR;
01236       break;
01237 
01238     case MOF_UNLOAD:
01239       if ((data & ~(OUFB_UNLOAD | OUFB_TRANSFER | OUFB_NO_UNLOAD)) != 0) return CMD_ERROR;
01240       /* Unload and no-unload are mutual exclusive and so are transfer and no unload. */
01241       if (data != 0 && ((data & (OUFB_UNLOAD | OUFB_TRANSFER)) != 0) == ((data & OUFB_NO_UNLOAD) != 0)) return CMD_ERROR;
01242       if (data == order->GetUnloadType()) return CMD_ERROR;
01243       break;
01244 
01245     case MOF_LOAD:
01246       if (data > OLFB_NO_LOAD || data == 1) return CMD_ERROR;
01247       if (data == order->GetLoadType()) return CMD_ERROR;
01248       break;
01249 
01250     case MOF_DEPOT_ACTION:
01251       if (data >= DA_END) return CMD_ERROR;
01252       break;
01253 
01254     case MOF_COND_VARIABLE:
01255       if (data >= OCV_END) return CMD_ERROR;
01256       break;
01257 
01258     case MOF_COND_COMPARATOR:
01259       if (data >= OCC_END) return CMD_ERROR;
01260       switch (order->GetConditionVariable()) {
01261         case OCV_UNCONDITIONALLY: return CMD_ERROR;
01262 
01263         case OCV_REQUIRES_SERVICE:
01264           if (data != OCC_IS_TRUE && data != OCC_IS_FALSE) return CMD_ERROR;
01265           break;
01266 
01267         default:
01268           if (data == OCC_IS_TRUE || data == OCC_IS_FALSE) return CMD_ERROR;
01269           break;
01270       }
01271       break;
01272 
01273     case MOF_COND_VALUE:
01274       switch (order->GetConditionVariable()) {
01275         case OCV_UNCONDITIONALLY: return CMD_ERROR;
01276 
01277         case OCV_LOAD_PERCENTAGE:
01278         case OCV_RELIABILITY:
01279           if (data > 100) return CMD_ERROR;
01280           break;
01281 
01282         default:
01283           if (data > 2047) return CMD_ERROR;
01284           break;
01285       }
01286       break;
01287 
01288     case MOF_COND_DESTINATION:
01289       if (data >= v->GetNumOrders()) return CMD_ERROR;
01290       break;
01291   }
01292 
01293   if (flags & DC_EXEC) {
01294     switch (mof) {
01295       case MOF_NON_STOP:
01296         order->SetNonStopType((OrderNonStopFlags)data);
01297         if (data & ONSF_NO_STOP_AT_DESTINATION_STATION) order->SetRefit(CT_NO_REFIT);
01298         break;
01299 
01300       case MOF_STOP_LOCATION:
01301         order->SetStopLocation((OrderStopLocation)data);
01302         break;
01303 
01304       case MOF_UNLOAD:
01305         order->SetUnloadType((OrderUnloadFlags)data);
01306         break;
01307 
01308       case MOF_LOAD:
01309         order->SetLoadType((OrderLoadFlags)data);
01310         if (data & OLFB_NO_LOAD) order->SetRefit(CT_NO_REFIT);
01311         break;
01312 
01313       case MOF_DEPOT_ACTION: {
01314         switch (data) {
01315           case DA_ALWAYS_GO:
01316             order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
01317             order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
01318             break;
01319 
01320           case DA_SERVICE:
01321             order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() | ODTFB_SERVICE));
01322             order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
01323             order->SetRefit(CT_NO_REFIT);
01324             break;
01325 
01326           case DA_STOP:
01327             order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
01328             order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() | ODATFB_HALT));
01329             order->SetRefit(CT_NO_REFIT);
01330             break;
01331 
01332           default:
01333             NOT_REACHED();
01334         }
01335         break;
01336       }
01337 
01338       case MOF_COND_VARIABLE: {
01339         order->SetConditionVariable((OrderConditionVariable)data);
01340 
01341         OrderConditionComparator occ = order->GetConditionComparator();
01342         switch (order->GetConditionVariable()) {
01343           case OCV_UNCONDITIONALLY:
01344             order->SetConditionComparator(OCC_EQUALS);
01345             order->SetConditionValue(0);
01346             break;
01347 
01348           case OCV_REQUIRES_SERVICE:
01349             if (occ != OCC_IS_TRUE && occ != OCC_IS_FALSE) order->SetConditionComparator(OCC_IS_TRUE);
01350             break;
01351 
01352           case OCV_LOAD_PERCENTAGE:
01353           case OCV_RELIABILITY:
01354             if (order->GetConditionValue() > 100) order->SetConditionValue(100);
01355             /* FALL THROUGH */
01356           default:
01357             if (occ == OCC_IS_TRUE || occ == OCC_IS_FALSE) order->SetConditionComparator(OCC_EQUALS);
01358             break;
01359         }
01360         break;
01361       }
01362 
01363       case MOF_COND_COMPARATOR:
01364         order->SetConditionComparator((OrderConditionComparator)data);
01365         break;
01366 
01367       case MOF_COND_VALUE:
01368         order->SetConditionValue(data);
01369         break;
01370 
01371       case MOF_COND_DESTINATION:
01372         order->SetConditionSkipToOrder(data);
01373         break;
01374 
01375       default: NOT_REACHED();
01376     }
01377 
01378     /* Update the windows and full load flags, also for vehicles that share the same order list */
01379     Vehicle *u = v->FirstShared();
01380     DeleteOrderWarnings(u);
01381     for (; u != NULL; u = u->NextShared()) {
01382       /* Toggle u->current_order "Full load" flag if it changed.
01383        * However, as the same flag is used for depot orders, check
01384        * whether we are not going to a depot as there are three
01385        * cases where the full load flag can be active and only
01386        * one case where the flag is used for depot orders. In the
01387        * other cases for the OrderTypeByte the flags are not used,
01388        * so do not care and those orders should not be active
01389        * when this function is called.
01390        */
01391       if (sel_ord == u->cur_real_order_index &&
01392           (u->current_order.IsType(OT_GOTO_STATION) || u->current_order.IsType(OT_LOADING)) &&
01393           u->current_order.GetLoadType() != order->GetLoadType()) {
01394         u->current_order.SetLoadType(order->GetLoadType());
01395       }
01396       InvalidateVehicleOrder(u, -2);
01397     }
01398   }
01399 
01400   return CommandCost();
01401 }
01402 
01410 static bool CheckAircraftOrderDistance(const Aircraft *v_new, const Vehicle *v_order, const Order *first)
01411 {
01412   if (first == NULL || v_new->acache.cached_max_range == 0) return true;
01413 
01414   /* Iterate over all orders to check the distance between all
01415    * 'goto' orders and their respective next order (of any type). */
01416   for (const Order *o = first; o != NULL; o = o->next) {
01417     switch (o->GetType()) {
01418       case OT_GOTO_STATION:
01419       case OT_GOTO_DEPOT:
01420       case OT_GOTO_WAYPOINT:
01421         /* If we don't have a next order, we've reached the end and must check the first order instead. */
01422         if (GetOrderDistance(o, o->next != NULL ? o->next : first, v_order) > v_new->acache.cached_max_range_sqr) return false;
01423         break;
01424 
01425       default: break;
01426     }
01427   }
01428 
01429   return true;
01430 }
01431 
01443 CommandCost CmdCloneOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01444 {
01445   VehicleID veh_src = GB(p2, 0, 20);
01446   VehicleID veh_dst = GB(p1, 0, 20);
01447 
01448   Vehicle *dst = Vehicle::GetIfValid(veh_dst);
01449   if (dst == NULL || !dst->IsPrimaryVehicle()) return CMD_ERROR;
01450 
01451   CommandCost ret = CheckOwnership(dst->owner);
01452   if (ret.Failed()) return ret;
01453 
01454   switch (GB(p1, 30, 2)) {
01455     case CO_SHARE: {
01456       Vehicle *src = Vehicle::GetIfValid(veh_src);
01457 
01458       /* Sanity checks */
01459       if (src == NULL || !src->IsPrimaryVehicle() || dst->type != src->type || dst == src) return CMD_ERROR;
01460 
01461       CommandCost ret = CheckOwnership(src->owner);
01462       if (ret.Failed()) return ret;
01463 
01464       /* Trucks can't share orders with busses (and visa versa) */
01465       if (src->type == VEH_ROAD && RoadVehicle::From(src)->IsBus() != RoadVehicle::From(dst)->IsBus()) {
01466         return CMD_ERROR;
01467       }
01468 
01469       /* Is the vehicle already in the shared list? */
01470       if (src->FirstShared() == dst->FirstShared()) return CMD_ERROR;
01471 
01472       const Order *order;
01473 
01474       FOR_VEHICLE_ORDERS(src, order) {
01475         if (OrderGoesToStation(dst, order) &&
01476             !CanVehicleUseStation(dst, Station::Get(order->GetDestination()))) {
01477           return_cmd_error(STR_ERROR_CAN_T_COPY_SHARE_ORDER);
01478         }
01479       }
01480 
01481       /* Check for aircraft range limits. */
01482       if (dst->type == VEH_AIRCRAFT && !CheckAircraftOrderDistance(Aircraft::From(dst), src, src->GetFirstOrder())) {
01483         return_cmd_error(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE);
01484       }
01485 
01486       if (src->orders.list == NULL && !OrderList::CanAllocateItem()) {
01487         return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
01488       }
01489 
01490       if (flags & DC_EXEC) {
01491         /* If the destination vehicle had a OrderList, destroy it.
01492          * We only reset the order indices, if the new orders are obviously different.
01493          * (We mainly do this to keep the order indices valid and in range.) */
01494         DeleteVehicleOrders(dst, false, dst->GetNumOrders() != src->GetNumOrders());
01495 
01496         dst->orders.list = src->orders.list;
01497 
01498         /* Link this vehicle in the shared-list */
01499         dst->AddToShared(src);
01500 
01501         InvalidateVehicleOrder(dst, -1);
01502         InvalidateVehicleOrder(src, -2);
01503 
01504         InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
01505       }
01506       break;
01507     }
01508 
01509     case CO_COPY: {
01510       Vehicle *src = Vehicle::GetIfValid(veh_src);
01511 
01512       /* Sanity checks */
01513       if (src == NULL || !src->IsPrimaryVehicle() || dst->type != src->type || dst == src) return CMD_ERROR;
01514 
01515       CommandCost ret = CheckOwnership(src->owner);
01516       if (ret.Failed()) return ret;
01517 
01518       /* Trucks can't copy all the orders from busses (and visa versa),
01519        * and neither can helicopters and aircarft. */
01520       const Order *order;
01521       FOR_VEHICLE_ORDERS(src, order) {
01522         if (OrderGoesToStation(dst, order) &&
01523             !CanVehicleUseStation(dst, Station::Get(order->GetDestination()))) {
01524           return_cmd_error(STR_ERROR_CAN_T_COPY_SHARE_ORDER);
01525         }
01526       }
01527 
01528       /* Check for aircraft range limits. */
01529       if (dst->type == VEH_AIRCRAFT && !CheckAircraftOrderDistance(Aircraft::From(dst), src, src->GetFirstOrder())) {
01530         return_cmd_error(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE);
01531       }
01532 
01533       /* make sure there are orders available */
01534       if (!Order::CanAllocateItem(src->GetNumOrders()) || !OrderList::CanAllocateItem()) {
01535         return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
01536       }
01537 
01538       if (flags & DC_EXEC) {
01539         const Order *order;
01540         Order *first = NULL;
01541         Order **order_dst;
01542 
01543         /* If the destination vehicle had an order list, destroy the chain but keep the OrderList.
01544          * We only reset the order indices, if the new orders are obviously different.
01545          * (We mainly do this to keep the order indices valid and in range.) */
01546         DeleteVehicleOrders(dst, true, dst->GetNumOrders() != src->GetNumOrders());
01547 
01548         order_dst = &first;
01549         FOR_VEHICLE_ORDERS(src, order) {
01550           *order_dst = new Order();
01551           (*order_dst)->AssignOrder(*order);
01552           order_dst = &(*order_dst)->next;
01553         }
01554         if (dst->orders.list == NULL) {
01555           dst->orders.list = new OrderList(first, dst);
01556         } else {
01557           assert(dst->orders.list->GetFirstOrder() == NULL);
01558           assert(!dst->orders.list->IsShared());
01559           delete dst->orders.list;
01560           assert(OrderList::CanAllocateItem());
01561           dst->orders.list = new OrderList(first, dst);
01562         }
01563 
01564         InvalidateVehicleOrder(dst, -1);
01565 
01566         InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
01567       }
01568       break;
01569     }
01570 
01571     case CO_UNSHARE: return DecloneOrder(dst, flags);
01572     default: return CMD_ERROR;
01573   }
01574 
01575   return CommandCost();
01576 }
01577 
01590 CommandCost CmdOrderRefit(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01591 {
01592   VehicleID veh = GB(p1, 0, 20);
01593   VehicleOrderID order_number  = GB(p2, 16, 8);
01594   CargoID cargo = GB(p2, 0, 8);
01595   byte subtype  = GB(p2, 8, 8);
01596 
01597   if (cargo >= NUM_CARGO && cargo != CT_NO_REFIT && cargo != CT_AUTO_REFIT) return CMD_ERROR;
01598 
01599   const Vehicle *v = Vehicle::GetIfValid(veh);
01600   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01601 
01602   CommandCost ret = CheckOwnership(v->owner);
01603   if (ret.Failed()) return ret;
01604 
01605   Order *order = v->GetOrder(order_number);
01606   if (order == NULL) return CMD_ERROR;
01607 
01608   /* Automatic refit cargo is only supported for goto station orders. */
01609   if (cargo == CT_AUTO_REFIT && !order->IsType(OT_GOTO_STATION)) return CMD_ERROR;
01610 
01611   if (flags & DC_EXEC) {
01612     order->SetRefit(cargo, subtype);
01613 
01614     /* Make the depot order an 'always go' order. */
01615     if (cargo != CT_NO_REFIT && order->IsType(OT_GOTO_DEPOT)) {
01616       order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
01617       order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
01618     }
01619 
01620     for (Vehicle *u = v->FirstShared(); u != NULL; u = u->NextShared()) {
01621       /* Update any possible open window of the vehicle */
01622       InvalidateVehicleOrder(u, -2);
01623 
01624       /* If the vehicle already got the current depot set as current order, then update current order as well */
01625       if (u->cur_real_order_index == order_number && (u->current_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) {
01626         u->current_order.SetRefit(cargo, subtype);
01627       }
01628     }
01629   }
01630 
01631   return CommandCost();
01632 }
01633 
01634 
01640 void CheckOrders(const Vehicle *v)
01641 {
01642   /* Does the user wants us to check things? */
01643   if (_settings_client.gui.order_review_system == 0) return;
01644 
01645   /* Do nothing for crashed vehicles */
01646   if (v->vehstatus & VS_CRASHED) return;
01647 
01648   /* Do nothing for stopped vehicles if setting is '1' */
01649   if (_settings_client.gui.order_review_system == 1 && (v->vehstatus & VS_STOPPED)) return;
01650 
01651   /* do nothing we we're not the first vehicle in a share-chain */
01652   if (v->FirstShared() != v) return;
01653 
01654   /* Only check every 20 days, so that we don't flood the message log */
01655   if (v->owner == _local_company && v->day_counter % 20 == 0) {
01656     int n_st, problem_type = -1;
01657     const Order *order;
01658     int message = 0;
01659 
01660     /* Check the order list */
01661     n_st = 0;
01662 
01663     FOR_VEHICLE_ORDERS(v, order) {
01664       /* Dummy order? */
01665       if (order->IsType(OT_DUMMY)) {
01666         problem_type = 1;
01667         break;
01668       }
01669       /* Does station have a load-bay for this vehicle? */
01670       if (order->IsType(OT_GOTO_STATION)) {
01671         const Station *st = Station::Get(order->GetDestination());
01672 
01673         n_st++;
01674         if (!CanVehicleUseStation(v, st)) problem_type = 3;
01675       }
01676     }
01677 
01678     /* Check if the last and the first order are the same */
01679     if (v->GetNumOrders() > 1) {
01680       const Order *last = v->GetLastOrder();
01681 
01682       if (v->orders.list->GetFirstOrder()->Equals(*last)) {
01683         problem_type = 2;
01684       }
01685     }
01686 
01687     /* Do we only have 1 station in our order list? */
01688     if (n_st < 2 && problem_type == -1) problem_type = 0;
01689 
01690 #ifndef NDEBUG
01691     if (v->orders.list != NULL) v->orders.list->DebugCheckSanity();
01692 #endif
01693 
01694     /* We don't have a problem */
01695     if (problem_type < 0) return;
01696 
01697     message = STR_NEWS_VEHICLE_HAS_TOO_FEW_ORDERS + problem_type;
01698     //DEBUG(misc, 3, "Triggered News Item for vehicle %d", v->index);
01699 
01700     SetDParam(0, v->index);
01701     AddVehicleNewsItem(
01702       message,
01703       NS_ADVICE,
01704       v->index
01705     );
01706   }
01707 }
01708 
01714 void RemoveOrderFromAllVehicles(OrderType type, DestinationID destination)
01715 {
01716   Vehicle *v;
01717 
01718   /* Aircraft have StationIDs for depot orders and never use DepotIDs
01719    * This fact is handled specially below
01720    */
01721 
01722   /* Go through all vehicles */
01723   FOR_ALL_VEHICLES(v) {
01724     Order *order;
01725 
01726     order = &v->current_order;
01727     if ((v->type == VEH_AIRCRAFT && order->IsType(OT_GOTO_DEPOT) ? OT_GOTO_STATION : order->GetType()) == type &&
01728         v->current_order.GetDestination() == destination) {
01729       order->MakeDummy();
01730       SetWindowDirty(WC_VEHICLE_VIEW, v->index);
01731     }
01732 
01733     /* Clear the order from the order-list */
01734     int id = -1;
01735     FOR_VEHICLE_ORDERS(v, order) {
01736       id++;
01737 restart:
01738 
01739       OrderType ot = order->GetType();
01740       if (ot == OT_GOTO_DEPOT && (order->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0) continue;
01741       if (ot == OT_IMPLICIT || (v->type == VEH_AIRCRAFT && ot == OT_GOTO_DEPOT)) ot = OT_GOTO_STATION;
01742       if (ot == type && order->GetDestination() == destination) {
01743         /* We want to clear implicit orders, but we don't want to make them
01744          * dummy orders. They should just vanish. Also check the actual order
01745          * type as ot is currently OT_GOTO_STATION. */
01746         if (order->IsType(OT_IMPLICIT)) {
01747           order = order->next; // DeleteOrder() invalidates current order
01748           DeleteOrder(v, id);
01749           if (order != NULL) goto restart;
01750           break;
01751         }
01752 
01753         order->MakeDummy();
01754         for (const Vehicle *w = v->FirstShared(); w != NULL; w = w->NextShared()) {
01755           /* In GUI, simulate by removing the order and adding it back */
01756           InvalidateVehicleOrder(w, id | (INVALID_VEH_ORDER_ID << 8));
01757           InvalidateVehicleOrder(w, (INVALID_VEH_ORDER_ID << 8) | id);
01758         }
01759       }
01760     }
01761   }
01762 
01763   OrderBackup::RemoveOrder(type, destination);
01764 }
01765 
01770 bool Vehicle::HasDepotOrder() const
01771 {
01772   const Order *order;
01773 
01774   FOR_VEHICLE_ORDERS(this, order) {
01775     if (order->IsType(OT_GOTO_DEPOT)) return true;
01776   }
01777 
01778   return false;
01779 }
01780 
01790 void DeleteVehicleOrders(Vehicle *v, bool keep_orderlist, bool reset_order_indices)
01791 {
01792   DeleteOrderWarnings(v);
01793 
01794   if (v->IsOrderListShared()) {
01795     /* Remove ourself from the shared order list. */
01796     v->RemoveFromShared();
01797     v->orders.list = NULL;
01798   } else if (v->orders.list != NULL) {
01799     /* Remove the orders */
01800     v->orders.list->FreeChain(keep_orderlist);
01801     if (!keep_orderlist) v->orders.list = NULL;
01802   }
01803 
01804   if (reset_order_indices) {
01805     v->cur_implicit_order_index = v->cur_real_order_index = 0;
01806     if (v->current_order.IsType(OT_LOADING)) {
01807       CancelLoadingDueToDeletedOrder(v);
01808     }
01809   }
01810 }
01811 
01819 uint16 GetServiceIntervalClamped(uint interval, CompanyID company_id)
01820 {
01821   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);
01822 }
01823 
01832 static bool CheckForValidOrders(const Vehicle *v)
01833 {
01834   const Order *order;
01835 
01836   FOR_VEHICLE_ORDERS(v, order) {
01837     switch (order->GetType()) {
01838       case OT_GOTO_STATION:
01839       case OT_GOTO_DEPOT:
01840       case OT_GOTO_WAYPOINT:
01841         return true;
01842 
01843       default:
01844         break;
01845     }
01846   }
01847 
01848   return false;
01849 }
01850 
01854 static bool OrderConditionCompare(OrderConditionComparator occ, int variable, int value)
01855 {
01856   switch (occ) {
01857     case OCC_EQUALS:      return variable == value;
01858     case OCC_NOT_EQUALS:  return variable != value;
01859     case OCC_LESS_THAN:   return variable <  value;
01860     case OCC_LESS_EQUALS: return variable <= value;
01861     case OCC_MORE_THAN:   return variable >  value;
01862     case OCC_MORE_EQUALS: return variable >= value;
01863     case OCC_IS_TRUE:     return variable != 0;
01864     case OCC_IS_FALSE:    return variable == 0;
01865     default: NOT_REACHED();
01866   }
01867 }
01868 
01875 VehicleOrderID ProcessConditionalOrder(const Order *order, const Vehicle *v)
01876 {
01877   if (order->GetType() != OT_CONDITIONAL) return INVALID_VEH_ORDER_ID;
01878 
01879   bool skip_order = false;
01880   OrderConditionComparator occ = order->GetConditionComparator();
01881   uint16 value = order->GetConditionValue();
01882 
01883   switch (order->GetConditionVariable()) {
01884     case OCV_LOAD_PERCENTAGE:    skip_order = OrderConditionCompare(occ, CalcPercentVehicleFilled(v, NULL), value); break;
01885     case OCV_RELIABILITY:        skip_order = OrderConditionCompare(occ, ToPercent16(v->reliability),       value); break;
01886     case OCV_MAX_SPEED:          skip_order = OrderConditionCompare(occ, v->GetDisplayMaxSpeed() * 10 / 16, value); break;
01887     case OCV_AGE:                skip_order = OrderConditionCompare(occ, v->age / DAYS_IN_LEAP_YEAR,        value); break;
01888     case OCV_REQUIRES_SERVICE:   skip_order = OrderConditionCompare(occ, v->NeedsServicing(),               value); break;
01889     case OCV_UNCONDITIONALLY:    skip_order = true; break;
01890     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;
01891     default: NOT_REACHED();
01892   }
01893 
01894   return skip_order ? order->GetConditionSkipToOrder() : (VehicleOrderID)INVALID_VEH_ORDER_ID;
01895 }
01896 
01904 bool UpdateOrderDest(Vehicle *v, const Order *order, int conditional_depth, bool pbs_look_ahead)
01905 {
01906   if (conditional_depth > v->GetNumOrders()) return false;
01907 
01908   switch (order->GetType()) {
01909     case OT_GOTO_STATION:
01910       v->dest_tile = v->GetOrderStationLocation(order->GetDestination());
01911       return true;
01912 
01913     case OT_GOTO_DEPOT:
01914       if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !v->NeedsServicing()) {
01915         assert(!pbs_look_ahead);
01916         UpdateVehicleTimetable(v, true);
01917         v->IncrementRealOrderIndex();
01918         break;
01919       }
01920 
01921       if (v->current_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) {
01922         /* We need to search for the nearest depot (hangar). */
01923         TileIndex location;
01924         DestinationID destination;
01925         bool reverse;
01926 
01927         if (v->FindClosestDepot(&location, &destination, &reverse)) {
01928           /* PBS reservations cannot reverse */
01929           if (pbs_look_ahead && reverse) return false;
01930 
01931           v->dest_tile = location;
01932           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());
01933 
01934           /* If there is no depot in front, reverse automatically (trains only) */
01935           if (v->type == VEH_TRAIN && reverse) DoCommand(v->tile, v->index, 0, DC_EXEC, CMD_REVERSE_TRAIN_DIRECTION);
01936 
01937           if (v->type == VEH_AIRCRAFT) {
01938             Aircraft *a = Aircraft::From(v);
01939             if (a->state == FLYING && a->targetairport != destination) {
01940               /* The aircraft is now heading for a different hangar than the next in the orders */
01941               extern void AircraftNextAirportPos_and_Order(Aircraft *a);
01942               AircraftNextAirportPos_and_Order(a);
01943             }
01944           }
01945           return true;
01946         }
01947 
01948         /* If there is no depot, we cannot help PBS either. */
01949         if (pbs_look_ahead) return false;
01950 
01951         UpdateVehicleTimetable(v, true);
01952         v->IncrementRealOrderIndex();
01953       } else {
01954         if (v->type != VEH_AIRCRAFT) {
01955           v->dest_tile = Depot::Get(order->GetDestination())->xy;
01956         }
01957         return true;
01958       }
01959       break;
01960 
01961     case OT_GOTO_WAYPOINT:
01962       v->dest_tile = Waypoint::Get(order->GetDestination())->xy;
01963       return true;
01964 
01965     case OT_CONDITIONAL: {
01966       assert(!pbs_look_ahead);
01967       VehicleOrderID next_order = ProcessConditionalOrder(order, v);
01968       if (next_order != INVALID_VEH_ORDER_ID) {
01969         /* Jump to next_order. cur_implicit_order_index becomes exactly that order,
01970          * cur_real_order_index might come after next_order. */
01971         UpdateVehicleTimetable(v, false);
01972         v->cur_implicit_order_index = v->cur_real_order_index = next_order;
01973         v->UpdateRealOrderIndex();
01974         v->current_order_time += v->GetOrder(v->cur_real_order_index)->travel_time;
01975 
01976         /* Disable creation of implicit orders.
01977          * When inserting them we do not know that we would have to make the conditional orders point to them. */
01978         if (v->IsGroundVehicle()) {
01979           uint16 &gv_flags = v->GetGroundVehicleFlags();
01980           SetBit(gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
01981         }
01982       } else {
01983         UpdateVehicleTimetable(v, true);
01984         v->IncrementRealOrderIndex();
01985       }
01986       break;
01987     }
01988 
01989     default:
01990       v->dest_tile = 0;
01991       return false;
01992   }
01993 
01994   assert(v->cur_implicit_order_index < v->GetNumOrders());
01995   assert(v->cur_real_order_index < v->GetNumOrders());
01996 
01997   /* Get the current order */
01998   order = v->GetOrder(v->cur_real_order_index);
01999   if (order != NULL && order->IsType(OT_IMPLICIT)) {
02000     assert(v->GetNumManualOrders() == 0);
02001     order = NULL;
02002   }
02003 
02004   if (order == NULL) {
02005     v->current_order.Free();
02006     v->dest_tile = 0;
02007     return false;
02008   }
02009 
02010   v->current_order = *order;
02011   return UpdateOrderDest(v, order, conditional_depth + 1, pbs_look_ahead);
02012 }
02013 
02021 bool ProcessOrders(Vehicle *v)
02022 {
02023   switch (v->current_order.GetType()) {
02024     case OT_GOTO_DEPOT:
02025       /* Let a depot order in the orderlist interrupt. */
02026       if (!(v->current_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) return false;
02027       break;
02028 
02029     case OT_LOADING:
02030       return false;
02031 
02032     case OT_LEAVESTATION:
02033       if (v->type != VEH_AIRCRAFT) return false;
02034       break;
02035 
02036     default: break;
02037   }
02038 
02046   bool may_reverse = v->current_order.IsType(OT_NOTHING);
02047 
02048   /* Check if we've reached a 'via' destination. */
02049   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)) &&
02050       IsTileType(v->tile, MP_STATION) &&
02051       v->current_order.GetDestination() == GetStationIndex(v->tile)) {
02052     v->DeleteUnreachedImplicitOrders();
02053     /* We set the last visited station here because we do not want
02054      * the train to stop at this 'via' station if the next order
02055      * is a no-non-stop order; in that case not setting the last
02056      * visited station will cause the vehicle to still stop. */
02057     v->last_station_visited = v->current_order.GetDestination();
02058     UpdateVehicleTimetable(v, true);
02059     v->IncrementImplicitOrderIndex();
02060   }
02061 
02062   /* Get the current order */
02063   assert(v->cur_implicit_order_index == 0 || v->cur_implicit_order_index < v->GetNumOrders());
02064   v->UpdateRealOrderIndex();
02065 
02066   const Order *order = v->GetOrder(v->cur_real_order_index);
02067   if (order != NULL && order->IsType(OT_IMPLICIT)) {
02068     assert(v->GetNumManualOrders() == 0);
02069     order = NULL;
02070   }
02071 
02072   /* If no order, do nothing. */
02073   if (order == NULL || (v->type == VEH_AIRCRAFT && !CheckForValidOrders(v))) {
02074     if (v->type == VEH_AIRCRAFT) {
02075       /* Aircraft do something vastly different here, so handle separately */
02076       extern void HandleMissingAircraftOrders(Aircraft *v);
02077       HandleMissingAircraftOrders(Aircraft::From(v));
02078       return false;
02079     }
02080 
02081     v->current_order.Free();
02082     v->dest_tile = 0;
02083     return false;
02084   }
02085 
02086   /* If it is unchanged, keep it. */
02087   if (order->Equals(v->current_order) && (v->type == VEH_AIRCRAFT || v->dest_tile != 0) &&
02088       (v->type != VEH_SHIP || !order->IsType(OT_GOTO_STATION) || Station::Get(order->GetDestination())->dock_tile != INVALID_TILE)) {
02089     return false;
02090   }
02091 
02092   /* Otherwise set it, and determine the destination tile. */
02093   v->current_order = *order;
02094 
02095   InvalidateVehicleOrder(v, -2);
02096   switch (v->type) {
02097     default:
02098       NOT_REACHED();
02099 
02100     case VEH_ROAD:
02101     case VEH_TRAIN:
02102       break;
02103 
02104     case VEH_AIRCRAFT:
02105     case VEH_SHIP:
02106       SetWindowClassesDirty(GetWindowClassForVehicleType(v->type));
02107       break;
02108   }
02109 
02110   return UpdateOrderDest(v, order) && may_reverse;
02111 }
02112 
02120 bool Order::ShouldStopAtStation(const Vehicle *v, StationID station) const
02121 {
02122   bool is_dest_station = this->IsType(OT_GOTO_STATION) && this->dest == station;
02123 
02124   return (!this->IsType(OT_GOTO_DEPOT) || (this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS) != 0) &&
02125       v->last_station_visited != station && // Do stop only when we've not just been there
02126       /* Finally do stop when there is no non-stop flag set for this type of station. */
02127       !(this->GetNonStopType() & (is_dest_station ? ONSF_NO_STOP_AT_DESTINATION_STATION : ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS));
02128 }