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 "core/random_func.hpp"
00024 #include "aircraft.h"
00025 #include "roadveh.h"
00026 #include "station_base.h"
00027 #include "waypoint_base.h"
00028 #include "company_base.h"
00029 #include "order_backup.h"
00030 
00031 #include "table/strings.h"
00032 
00033 /* DestinationID must be at least as large as every these below, because it can
00034  * be any of them
00035  */
00036 assert_compile(sizeof(DestinationID) >= sizeof(DepotID));
00037 assert_compile(sizeof(DestinationID) >= sizeof(StationID));
00038 
00039 OrderPool _order_pool("Order");
00040 INSTANTIATE_POOL_METHODS(Order)
00041 OrderListPool _orderlist_pool("OrderList");
00042 INSTANTIATE_POOL_METHODS(OrderList)
00043 
00045 Order::~Order()
00046 {
00047   if (CleaningPool()) return;
00048 
00049   /* We can visit oil rigs and buoys that are not our own. They will be shown in
00050    * the list of stations. So, we need to invalidate that window if needed. */
00051   if (this->IsType(OT_GOTO_STATION) || this->IsType(OT_GOTO_WAYPOINT)) {
00052     BaseStation *bs = BaseStation::GetIfValid(this->GetDestination());
00053     if (bs != NULL && bs->owner == OWNER_NONE) InvalidateWindowClassesData(WC_STATION_LIST, 0);
00054   }
00055 }
00056 
00061 void Order::Free()
00062 {
00063   this->type  = OT_NOTHING;
00064   this->flags = 0;
00065   this->dest  = 0;
00066   this->next  = NULL;
00067 }
00068 
00073 void Order::MakeGoToStation(StationID destination)
00074 {
00075   this->type = OT_GOTO_STATION;
00076   this->flags = 0;
00077   this->dest = destination;
00078 }
00079 
00089 void Order::MakeGoToDepot(DepotID destination, OrderDepotTypeFlags order, OrderNonStopFlags non_stop_type, OrderDepotActionFlags action, CargoID cargo, byte subtype)
00090 {
00091   this->type = OT_GOTO_DEPOT;
00092   this->SetDepotOrderType(order);
00093   this->SetDepotActionType(action);
00094   this->SetNonStopType(non_stop_type);
00095   this->dest = destination;
00096   this->SetRefit(cargo, subtype);
00097 }
00098 
00103 void Order::MakeGoToWaypoint(StationID destination)
00104 {
00105   this->type = OT_GOTO_WAYPOINT;
00106   this->flags = 0;
00107   this->dest = destination;
00108 }
00109 
00114 void Order::MakeLoading(bool ordered)
00115 {
00116   this->type = OT_LOADING;
00117   if (!ordered) this->flags = 0;
00118 }
00119 
00123 void Order::MakeLeaveStation()
00124 {
00125   this->type = OT_LEAVESTATION;
00126   this->flags = 0;
00127 }
00128 
00132 void Order::MakeDummy()
00133 {
00134   this->type = OT_DUMMY;
00135   this->flags = 0;
00136 }
00137 
00142 void Order::MakeConditional(VehicleOrderID order)
00143 {
00144   this->type = OT_CONDITIONAL;
00145   this->flags = order;
00146   this->dest = 0;
00147 }
00148 
00153 void Order::MakeImplicit(StationID destination)
00154 {
00155   this->type = OT_IMPLICIT;
00156   this->dest = destination;
00157 }
00158 
00165 void Order::SetRefit(CargoID cargo, byte subtype)
00166 {
00167   this->refit_cargo = cargo;
00168   this->refit_subtype = subtype;
00169 }
00170 
00176 bool Order::Equals(const Order &other) const
00177 {
00178   /* In case of go to nearest depot orders we need "only" compare the flags
00179    * with the other and not the nearest depot order bit or the actual
00180    * destination because those get clear/filled in during the order
00181    * evaluation. If we do not do this the order will continuously be seen as
00182    * a different order and it will try to find a "nearest depot" every tick. */
00183   if ((this->IsType(OT_GOTO_DEPOT) && this->type == other.type) &&
00184       ((this->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0 ||
00185        (other.GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0)) {
00186     return this->GetDepotOrderType() == other.GetDepotOrderType() &&
00187         (this->GetDepotActionType() & ~ODATFB_NEAREST_DEPOT) == (other.GetDepotActionType() & ~ODATFB_NEAREST_DEPOT);
00188   }
00189 
00190   return this->type == other.type && this->flags == other.flags && this->dest == other.dest;
00191 }
00192 
00199 uint32 Order::Pack() const
00200 {
00201   return this->dest << 16 | this->flags << 8 | this->type;
00202 }
00203 
00209 uint16 Order::MapOldOrder() const
00210 {
00211   uint16 order = this->GetType();
00212   switch (this->type) {
00213     case OT_GOTO_STATION:
00214       if (this->GetUnloadType() & OUFB_UNLOAD) SetBit(order, 5);
00215       if (this->GetLoadType() & OLFB_FULL_LOAD) SetBit(order, 6);
00216       if (this->GetNonStopType() & ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS) SetBit(order, 7);
00217       order |= GB(this->GetDestination(), 0, 8) << 8;
00218       break;
00219     case OT_GOTO_DEPOT:
00220       if (!(this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) SetBit(order, 6);
00221       SetBit(order, 7);
00222       order |= GB(this->GetDestination(), 0, 8) << 8;
00223       break;
00224     case OT_LOADING:
00225       if (this->GetLoadType() & OLFB_FULL_LOAD) SetBit(order, 6);
00226       break;
00227   }
00228   return order;
00229 }
00230 
00235 Order::Order(uint32 packed)
00236 {
00237   this->type    = (OrderType)GB(packed,  0,  8);
00238   this->flags   = GB(packed,  8,  8);
00239   this->dest    = GB(packed, 16, 16);
00240   this->next    = NULL;
00241   this->refit_cargo   = CT_NO_REFIT;
00242   this->refit_subtype = 0;
00243   this->wait_time     = 0;
00244   this->travel_time   = 0;
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 }
00286 
00292 void OrderList::Initialize(Order *chain, Vehicle *v)
00293 {
00294   this->first = chain;
00295   this->first_shared = v;
00296 
00297   this->num_orders = 0;
00298   this->num_manual_orders = 0;
00299   this->num_vehicles = 1;
00300   this->timetable_duration = 0;
00301 
00302   for (Order *o = this->first; o != NULL; o = o->next) {
00303     ++this->num_orders;
00304     if (!o->IsType(OT_IMPLICIT)) ++this->num_manual_orders;
00305     this->timetable_duration += o->wait_time + o->travel_time;
00306   }
00307 
00308   for (Vehicle *u = this->first_shared->PreviousShared(); u != NULL; u = u->PreviousShared()) {
00309     ++this->num_vehicles;
00310     this->first_shared = u;
00311   }
00312 
00313   for (const Vehicle *u = v->NextShared(); u != NULL; u = u->NextShared()) ++this->num_vehicles;
00314 }
00315 
00321 void OrderList::FreeChain(bool keep_orderlist)
00322 {
00323   Order *next;
00324   for (Order *o = this->first; o != NULL; o = next) {
00325     next = o->next;
00326     delete o;
00327   }
00328 
00329   if (keep_orderlist) {
00330     this->first = NULL;
00331     this->num_orders = 0;
00332     this->num_manual_orders = 0;
00333     this->timetable_duration = 0;
00334   } else {
00335     delete this;
00336   }
00337 }
00338 
00344 Order *OrderList::GetOrderAt(int index) const
00345 {
00346   if (index < 0) return NULL;
00347 
00348   Order *order = this->first;
00349 
00350   while (order != NULL && index-- > 0) {
00351     order = order->next;
00352   }
00353   return order;
00354 }
00355 
00365 const Order *OrderList::GetBestLoadableNext(const Vehicle *v, const Order *o2, const Order *o1) const
00366 {
00367   SmallMap<CargoID, uint> capacities;
00368   v->GetConsistFreeCapacities(capacities);
00369   uint loadable1 = 0;
00370   uint loadable2 = 0;
00371   StationID st1 = o1->GetDestination();
00372   StationID st2 = o2->GetDestination();
00373   const Station *cur_station = Station::Get(v->last_station_visited);
00374   for (SmallPair<CargoID, uint> *i = capacities.Begin(); i != capacities.End(); ++i) {
00375     const StationCargoPacketMap *loadable_packets = cur_station->goods[i->first].cargo.Packets();
00376     uint loadable_cargo = 0;
00377     std::pair<StationCargoPacketMap::const_iterator, StationCargoPacketMap::const_iterator> p =
00378       loadable_packets->equal_range(st1);
00379     for (StationCargoPacketMap::const_iterator j = p.first; j != p.second; ++j) {
00380       loadable_cargo = (*j)->Count();
00381     }
00382     loadable1 += min(i->second, loadable_cargo);
00383 
00384     loadable_cargo = 0;
00385     p = loadable_packets->equal_range(st2);
00386     for (StationCargoPacketMap::const_iterator j = p.first; j != p.second; ++j) {
00387       loadable_cargo = (*j)->Count();
00388     }
00389     loadable2 += min(i->second, loadable_cargo);
00390   }
00391   if (loadable1 == loadable2) return RandomRange(2) == 0 ? o1 : o2;
00392   return loadable1 > loadable2 ? o1 : o2;
00393 }
00394 
00406 const Order *OrderList::GetNextStoppingOrder(const Vehicle *v, const Order *next, uint hops, bool is_loading) const
00407 {
00408   if (hops > this->GetNumOrders() || next == NULL) return NULL;
00409 
00410   if (next->IsType(OT_CONDITIONAL)) {
00411     if (is_loading && next->GetConditionVariable() == OCV_LOAD_PERCENTAGE) {
00412       /* If the condition is based on load percentage we can't
00413        * tell what it will do. So we choose randomly.
00414        */
00415       const Order *skip_to = this->GetNextStoppingOrder(v,
00416           this->GetOrderAt(next->GetConditionSkipToOrder()),
00417           hops + 1);
00418       const Order *advance = this->GetNextStoppingOrder(v,
00419           this->GetNext(next), hops + 1);
00420       if (advance == NULL) {
00421         return skip_to;
00422       } else if (skip_to == NULL) {
00423         return advance;
00424       } else {
00425         return this->GetBestLoadableNext(v, skip_to, advance);
00426       }
00427     } else {
00428       /* Otherwise we're optimistic and expect that the
00429        * condition value won't change until it's evaluated.
00430        */
00431       VehicleOrderID skip_to = ProcessConditionalOrder(next, v);
00432       if (skip_to != INVALID_VEH_ORDER_ID) {
00433         return this->GetNextStoppingOrder(v,
00434             this->GetOrderAt(skip_to), hops + 1);
00435       } else {
00436         return this->GetNextStoppingOrder(v,
00437             this->GetNext(next), hops + 1);
00438       }
00439     }
00440   }
00441 
00442   if (next->IsType(OT_GOTO_DEPOT)) {
00443     if (next->GetDepotActionType() == ODATFB_HALT) return NULL;
00444     if (next->IsRefit()) return next;
00445   }
00446 
00447   if (!next->CanLoadOrUnload()) {
00448     return this->GetNextStoppingOrder(v, this->GetNext(next), hops + 1);
00449   }
00450 
00451   return next;
00452 }
00453 
00461 StationID OrderList::GetNextStoppingStation(const Vehicle *v) const
00462 {
00463 
00464   const Order *next = this->GetOrderAt(v->cur_implicit_order_index);
00465   if (next == NULL) {
00466     next = this->GetFirstOrder();
00467     if (next == NULL) return INVALID_STATION;
00468   } else {
00469     next = this->GetNext(next);
00470   }
00471 
00472   uint hops = 0;
00473   do {
00474     next = this->GetNextStoppingOrder(v, next, ++hops, true);
00475     /* Don't return a next stop if the vehicle has to unload everything. */
00476     if (next == NULL || (next->GetDestination() == v->last_station_visited &&
00477         (next->GetUnloadType() & (OUFB_TRANSFER | OUFB_UNLOAD)) == 0)) {
00478       return INVALID_STATION;
00479     }
00480   } while (next->IsType(OT_GOTO_DEPOT) || next->GetDestination() == v->last_station_visited);
00481 
00482   return next->GetDestination();
00483 }
00484 
00490 void OrderList::InsertOrderAt(Order *new_order, int index)
00491 {
00492   if (this->first == NULL) {
00493     this->first = new_order;
00494   } else {
00495     if (index == 0) {
00496       /* Insert as first or only order */
00497       new_order->next = this->first;
00498       this->first = new_order;
00499     } else if (index >= this->num_orders) {
00500       /* index is after the last order, add it to the end */
00501       this->GetLastOrder()->next = new_order;
00502     } else {
00503       /* Put the new order in between */
00504       Order *order = this->GetOrderAt(index - 1);
00505       new_order->next = order->next;
00506       order->next = new_order;
00507     }
00508   }
00509   ++this->num_orders;
00510   if (!new_order->IsType(OT_IMPLICIT)) ++this->num_manual_orders;
00511   this->timetable_duration += new_order->wait_time + new_order->travel_time;
00512 
00513   /* We can visit oil rigs and buoys that are not our own. They will be shown in
00514    * the list of stations. So, we need to invalidate that window if needed. */
00515   if (new_order->IsType(OT_GOTO_STATION) || new_order->IsType(OT_GOTO_WAYPOINT)) {
00516     BaseStation *bs = BaseStation::Get(new_order->GetDestination());
00517     if (bs->owner == OWNER_NONE) InvalidateWindowClassesData(WC_STATION_LIST, 0);
00518   }
00519 
00520 }
00521 
00522 
00527 void OrderList::DeleteOrderAt(int index)
00528 {
00529   if (index >= this->num_orders) return;
00530 
00531   Order *to_remove;
00532 
00533   if (index == 0) {
00534     to_remove = this->first;
00535     this->first = to_remove->next;
00536   } else {
00537     Order *prev = GetOrderAt(index - 1);
00538     to_remove = prev->next;
00539     prev->next = to_remove->next;
00540   }
00541   --this->num_orders;
00542   if (!to_remove->IsType(OT_IMPLICIT)) --this->num_manual_orders;
00543   this->timetable_duration -= (to_remove->wait_time + to_remove->travel_time);
00544   delete to_remove;
00545 }
00546 
00552 void OrderList::MoveOrder(int from, int to)
00553 {
00554   if (from >= this->num_orders || to >= this->num_orders || from == to) return;
00555 
00556   Order *moving_one;
00557 
00558   /* Take the moving order out of the pointer-chain */
00559   if (from == 0) {
00560     moving_one = this->first;
00561     this->first = moving_one->next;
00562   } else {
00563     Order *one_before = GetOrderAt(from - 1);
00564     moving_one = one_before->next;
00565     one_before->next = moving_one->next;
00566   }
00567 
00568   /* Insert the moving_order again in the pointer-chain */
00569   if (to == 0) {
00570     moving_one->next = this->first;
00571     this->first = moving_one;
00572   } else {
00573     Order *one_before = GetOrderAt(to - 1);
00574     moving_one->next = one_before->next;
00575     one_before->next = moving_one;
00576   }
00577 }
00578 
00584 void OrderList::RemoveVehicle(Vehicle *v)
00585 {
00586   --this->num_vehicles;
00587   if (v == this->first_shared) this->first_shared = v->NextShared();
00588 }
00589 
00594 bool OrderList::IsVehicleInSharedOrdersList(const Vehicle *v) const
00595 {
00596   for (const Vehicle *v_shared = this->first_shared; v_shared != NULL; v_shared = v_shared->NextShared()) {
00597     if (v_shared == v) return true;
00598   }
00599 
00600   return false;
00601 }
00602 
00608 int OrderList::GetPositionInSharedOrderList(const Vehicle *v) const
00609 {
00610   int count = 0;
00611   for (const Vehicle *v_shared = v->PreviousShared(); v_shared != NULL; v_shared = v_shared->PreviousShared()) count++;
00612   return count;
00613 }
00614 
00619 bool OrderList::IsCompleteTimetable() const
00620 {
00621   for (Order *o = this->first; o != NULL; o = o->next) {
00622     /* Implicit orders are, by definition, not timetabled. */
00623     if (o->IsType(OT_IMPLICIT)) continue;
00624     if (!o->IsCompletelyTimetabled()) return false;
00625   }
00626   return true;
00627 }
00628 
00632 void OrderList::DebugCheckSanity() const
00633 {
00634   VehicleOrderID check_num_orders = 0;
00635   VehicleOrderID check_num_manual_orders = 0;
00636   uint check_num_vehicles = 0;
00637   Ticks check_timetable_duration = 0;
00638 
00639   DEBUG(misc, 6, "Checking OrderList %hu for sanity...", this->index);
00640 
00641   for (const Order *o = this->first; o != NULL; o = o->next) {
00642     ++check_num_orders;
00643     if (!o->IsType(OT_IMPLICIT)) ++check_num_manual_orders;
00644     check_timetable_duration += o->wait_time + o->travel_time;
00645   }
00646   assert(this->num_orders == check_num_orders);
00647   assert(this->num_manual_orders == check_num_manual_orders);
00648   assert(this->timetable_duration == check_timetable_duration);
00649 
00650   for (const Vehicle *v = this->first_shared; v != NULL; v = v->NextShared()) {
00651     ++check_num_vehicles;
00652     assert(v->orders.list == this);
00653   }
00654   assert(this->num_vehicles == check_num_vehicles);
00655   DEBUG(misc, 6, "... detected %u orders (%u manual), %u vehicles, %i ticks",
00656       (uint)this->num_orders, (uint)this->num_manual_orders,
00657       this->num_vehicles, this->timetable_duration);
00658 }
00659 
00667 static inline bool OrderGoesToStation(const Vehicle *v, const Order *o)
00668 {
00669   return o->IsType(OT_GOTO_STATION) ||
00670       (v->type == VEH_AIRCRAFT && o->IsType(OT_GOTO_DEPOT) && !(o->GetDepotActionType() & ODATFB_NEAREST_DEPOT));
00671 }
00672 
00679 static void DeleteOrderWarnings(const Vehicle *v)
00680 {
00681   DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_TOO_FEW_ORDERS);
00682   DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_VOID_ORDER);
00683   DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_DUPLICATE_ENTRY);
00684   DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_INVALID_ENTRY);
00685 }
00686 
00693 TileIndex Order::GetLocation(const Vehicle *v, bool airport) const
00694 {
00695   switch (this->GetType()) {
00696     case OT_GOTO_WAYPOINT:
00697     case OT_GOTO_STATION:
00698     case OT_IMPLICIT:
00699       if (airport && v->type == VEH_AIRCRAFT) return Station::Get(this->GetDestination())->airport.tile;
00700       return BaseStation::Get(this->GetDestination())->xy;
00701 
00702     case OT_GOTO_DEPOT:
00703       if ((this->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0) return INVALID_TILE;
00704       return (v->type == VEH_AIRCRAFT) ? Station::Get(this->GetDestination())->xy : Depot::Get(this->GetDestination())->xy;
00705 
00706     default:
00707       return INVALID_TILE;
00708   }
00709 }
00710 
00720 uint GetOrderDistance(const Order *prev, const Order *cur, const Vehicle *v, int conditional_depth)
00721 {
00722   if (cur->IsType(OT_CONDITIONAL)) {
00723     if (conditional_depth > v->GetNumOrders()) return 0;
00724 
00725     conditional_depth++;
00726 
00727     int dist1 = GetOrderDistance(prev, v->GetOrder(cur->GetConditionSkipToOrder()), v, conditional_depth);
00728     int dist2 = GetOrderDistance(prev, cur->next == NULL ? v->orders.list->GetFirstOrder() : cur->next, v, conditional_depth);
00729     return max(dist1, dist2);
00730   }
00731 
00732   TileIndex prev_tile = prev->GetLocation(v, true);
00733   TileIndex cur_tile = cur->GetLocation(v, true);
00734   if (prev_tile == INVALID_TILE || cur_tile == INVALID_TILE) return 0;
00735   return v->type == VEH_AIRCRAFT ? DistanceSquare(prev_tile, cur_tile) : DistanceManhattan(prev_tile, cur_tile);
00736 }
00737 
00751 CommandCost CmdInsertOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00752 {
00753   VehicleID veh          = GB(p1,  0, 20);
00754   VehicleOrderID sel_ord = GB(p1, 20, 8);
00755   Order new_order(p2);
00756 
00757   Vehicle *v = Vehicle::GetIfValid(veh);
00758   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
00759 
00760   CommandCost ret = CheckOwnership(v->owner);
00761   if (ret.Failed()) return ret;
00762 
00763   /* Check if the inserted order is to the correct destination (owner, type),
00764    * and has the correct flags if any */
00765   switch (new_order.GetType()) {
00766     case OT_GOTO_STATION: {
00767       const Station *st = Station::GetIfValid(new_order.GetDestination());
00768       if (st == NULL) return CMD_ERROR;
00769 
00770       if (st->owner != OWNER_NONE) {
00771         CommandCost ret = CheckOwnership(st->owner);
00772         if (ret.Failed()) return ret;
00773       }
00774 
00775       if (!CanVehicleUseStation(v, st)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
00776       for (Vehicle *u = v->FirstShared(); u != NULL; u = u->NextShared()) {
00777         if (!CanVehicleUseStation(u, st)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER_SHARED);
00778       }
00779 
00780       /* Non stop only allowed for ground vehicles. */
00781       if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && !v->IsGroundVehicle()) return CMD_ERROR;
00782 
00783       /* Filter invalid load/unload types. */
00784       switch (new_order.GetLoadType()) {
00785         case OLF_LOAD_IF_POSSIBLE: case OLFB_FULL_LOAD: case OLF_FULL_LOAD_ANY: case OLFB_NO_LOAD: break;
00786         default: return CMD_ERROR;
00787       }
00788       switch (new_order.GetUnloadType()) {
00789         case OUF_UNLOAD_IF_POSSIBLE: case OUFB_UNLOAD: case OUFB_TRANSFER: case OUFB_NO_UNLOAD: break;
00790         default: return CMD_ERROR;
00791       }
00792 
00793       /* Filter invalid stop locations */
00794       switch (new_order.GetStopLocation()) {
00795         case OSL_PLATFORM_NEAR_END:
00796         case OSL_PLATFORM_MIDDLE:
00797           if (v->type != VEH_TRAIN) return CMD_ERROR;
00798           /* FALL THROUGH */
00799         case OSL_PLATFORM_FAR_END:
00800           break;
00801 
00802         default:
00803           return CMD_ERROR;
00804       }
00805 
00806       break;
00807     }
00808 
00809     case OT_GOTO_DEPOT: {
00810       if ((new_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) == 0) {
00811         if (v->type == VEH_AIRCRAFT) {
00812           const Station *st = Station::GetIfValid(new_order.GetDestination());
00813 
00814           if (st == NULL) return CMD_ERROR;
00815 
00816           CommandCost ret = CheckOwnership(st->owner);
00817           if (ret.Failed()) return ret;
00818 
00819           if (!CanVehicleUseStation(v, st) || !st->airport.HasHangar()) {
00820             return CMD_ERROR;
00821           }
00822         } else {
00823           const Depot *dp = Depot::GetIfValid(new_order.GetDestination());
00824 
00825           if (dp == NULL) return CMD_ERROR;
00826 
00827           CommandCost ret = CheckOwnership(GetTileOwner(dp->xy));
00828           if (ret.Failed()) return ret;
00829 
00830           switch (v->type) {
00831             case VEH_TRAIN:
00832               if (!IsRailDepotTile(dp->xy)) return CMD_ERROR;
00833               break;
00834 
00835             case VEH_ROAD:
00836               if (!IsRoadDepotTile(dp->xy)) return CMD_ERROR;
00837               break;
00838 
00839             case VEH_SHIP:
00840               if (!IsShipDepotTile(dp->xy)) return CMD_ERROR;
00841               break;
00842 
00843             default: return CMD_ERROR;
00844           }
00845         }
00846       }
00847 
00848       if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && !v->IsGroundVehicle()) return CMD_ERROR;
00849       if (new_order.GetDepotOrderType() & ~(ODTFB_PART_OF_ORDERS | ((new_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS) != 0 ? ODTFB_SERVICE : 0))) return CMD_ERROR;
00850       if (new_order.GetDepotActionType() & ~(ODATFB_HALT | ODATFB_NEAREST_DEPOT)) return CMD_ERROR;
00851       if ((new_order.GetDepotOrderType() & ODTFB_SERVICE) && (new_order.GetDepotActionType() & ODATFB_HALT)) return CMD_ERROR;
00852       break;
00853     }
00854 
00855     case OT_GOTO_WAYPOINT: {
00856       const Waypoint *wp = Waypoint::GetIfValid(new_order.GetDestination());
00857       if (wp == NULL) return CMD_ERROR;
00858 
00859       switch (v->type) {
00860         default: return CMD_ERROR;
00861 
00862         case VEH_TRAIN: {
00863           if (!(wp->facilities & FACIL_TRAIN)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
00864 
00865           CommandCost ret = CheckOwnership(wp->owner);
00866           if (ret.Failed()) return ret;
00867           break;
00868         }
00869 
00870         case VEH_SHIP:
00871           if (!(wp->facilities & FACIL_DOCK)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
00872           if (wp->owner != OWNER_NONE) {
00873             CommandCost ret = CheckOwnership(wp->owner);
00874             if (ret.Failed()) return ret;
00875           }
00876           break;
00877       }
00878 
00879       /* Order flags can be any of the following for waypoints:
00880        * [non-stop]
00881        * non-stop orders (if any) are only valid for trains */
00882       if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && v->type != VEH_TRAIN) return CMD_ERROR;
00883       break;
00884     }
00885 
00886     case OT_CONDITIONAL: {
00887       VehicleOrderID skip_to = new_order.GetConditionSkipToOrder();
00888       if (skip_to != 0 && skip_to >= v->GetNumOrders()) return CMD_ERROR; // Always allow jumping to the first (even when there is no order).
00889       if (new_order.GetConditionVariable() >= OCV_END) return CMD_ERROR;
00890 
00891       OrderConditionComparator occ = new_order.GetConditionComparator();
00892       if (occ >= OCC_END) return CMD_ERROR;
00893       switch (new_order.GetConditionVariable()) {
00894         case OCV_REQUIRES_SERVICE:
00895           if (occ != OCC_IS_TRUE && occ != OCC_IS_FALSE) return CMD_ERROR;
00896           break;
00897 
00898         case OCV_UNCONDITIONALLY:
00899           if (occ != OCC_EQUALS) return CMD_ERROR;
00900           if (new_order.GetConditionValue() != 0) return CMD_ERROR;
00901           break;
00902 
00903         case OCV_LOAD_PERCENTAGE:
00904         case OCV_RELIABILITY:
00905           if (new_order.GetConditionValue() > 100) return CMD_ERROR;
00906           /* FALL THROUGH */
00907         default:
00908           if (occ == OCC_IS_TRUE || occ == OCC_IS_FALSE) return CMD_ERROR;
00909           break;
00910       }
00911       break;
00912     }
00913 
00914     default: return CMD_ERROR;
00915   }
00916 
00917   if (sel_ord > v->GetNumOrders()) return CMD_ERROR;
00918 
00919   if (v->GetNumOrders() >= MAX_VEH_ORDER_ID) return_cmd_error(STR_ERROR_TOO_MANY_ORDERS);
00920   if (!Order::CanAllocateItem()) return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
00921   if (v->orders.list == NULL && !OrderList::CanAllocateItem()) return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
00922 
00923   if (v->type == VEH_SHIP && _settings_game.pf.pathfinder_for_ships != VPF_NPF) {
00924     /* Make sure the new destination is not too far away from the previous */
00925     const Order *prev = NULL;
00926     uint n = 0;
00927 
00928     /* Find the last goto station or depot order before the insert location.
00929      * If the order is to be inserted at the beginning of the order list this
00930      * finds the last order in the list. */
00931     const Order *o;
00932     FOR_VEHICLE_ORDERS(v, o) {
00933       switch (o->GetType()) {
00934         case OT_GOTO_STATION:
00935         case OT_GOTO_DEPOT:
00936         case OT_GOTO_WAYPOINT:
00937           prev = o;
00938           break;
00939 
00940         default: break;
00941       }
00942       if (++n == sel_ord && prev != NULL) break;
00943     }
00944     if (prev != NULL) {
00945       uint dist;
00946       if (new_order.IsType(OT_CONDITIONAL)) {
00947         /* The order is not yet inserted, so we have to do the first iteration here. */
00948         dist = GetOrderDistance(prev, v->GetOrder(new_order.GetConditionSkipToOrder()), v);
00949       } else {
00950         dist = GetOrderDistance(prev, &new_order, v);
00951       }
00952 
00953       if (dist >= 130) {
00954         return_cmd_error(STR_ERROR_TOO_FAR_FROM_PREVIOUS_DESTINATION);
00955       }
00956     }
00957   }
00958 
00959   if (flags & DC_EXEC) {
00960     Order *new_o = new Order();
00961     new_o->AssignOrder(new_order);
00962     InsertOrder(v, new_o, sel_ord);
00963   }
00964 
00965   return CommandCost();
00966 }
00967 
00974 void InsertOrder(Vehicle *v, Order *new_o, VehicleOrderID sel_ord)
00975 {
00976   /* Create new order and link in list */
00977   if (v->orders.list == NULL) {
00978     v->orders.list = new OrderList(new_o, v);
00979   } else {
00980     v->orders.list->InsertOrderAt(new_o, sel_ord);
00981   }
00982 
00983   Vehicle *u = v->FirstShared();
00984   DeleteOrderWarnings(u);
00985   for (; u != NULL; u = u->NextShared()) {
00986     assert(v->orders.list == u->orders.list);
00987 
00988     /* If there is added an order before the current one, we need
00989      * to update the selected order. We do not change implicit/real order indices though.
00990      * If the new order is between the current implicit order and real order, the implicit order will
00991      * later skip the inserted order. */
00992     if (sel_ord <= u->cur_real_order_index) {
00993       uint cur = u->cur_real_order_index + 1;
00994       /* Check if we don't go out of bound */
00995       if (cur < u->GetNumOrders()) {
00996         u->cur_real_order_index = cur;
00997       }
00998     }
00999     if (sel_ord == u->cur_implicit_order_index && u->IsGroundVehicle()) {
01000       /* We are inserting an order just before the current implicit order.
01001        * We do not know whether we will reach current implicit or the newly inserted order first.
01002        * So, disable creation of implicit orders until we are on track again. */
01003       uint16 &gv_flags = u->GetGroundVehicleFlags();
01004       SetBit(gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
01005     }
01006     if (sel_ord <= u->cur_implicit_order_index) {
01007       uint cur = u->cur_implicit_order_index + 1;
01008       /* Check if we don't go out of bound */
01009       if (cur < u->GetNumOrders()) {
01010         u->cur_implicit_order_index = cur;
01011       }
01012     }
01013     /* Update any possible open window of the vehicle */
01014     InvalidateVehicleOrder(u, INVALID_VEH_ORDER_ID | (sel_ord << 8));
01015   }
01016 
01017   /* As we insert an order, the order to skip to will be 'wrong'. */
01018   VehicleOrderID cur_order_id = 0;
01019   Order *order;
01020   FOR_VEHICLE_ORDERS(v, order) {
01021     if (order->IsType(OT_CONDITIONAL)) {
01022       VehicleOrderID order_id = order->GetConditionSkipToOrder();
01023       if (order_id >= sel_ord) {
01024         order->SetConditionSkipToOrder(order_id + 1);
01025       }
01026       if (order_id == cur_order_id) {
01027         order->SetConditionSkipToOrder((order_id + 1) % v->GetNumOrders());
01028       }
01029     }
01030     cur_order_id++;
01031   }
01032 
01033   /* Make sure to rebuild the whole list */
01034   InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
01035 }
01036 
01042 static CommandCost DecloneOrder(Vehicle *dst, DoCommandFlag flags)
01043 {
01044   if (flags & DC_EXEC) {
01045     DeleteVehicleOrders(dst);
01046     InvalidateVehicleOrder(dst, -1);
01047 
01048     InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
01049   }
01050   return CommandCost();
01051 }
01052 
01062 CommandCost CmdDeleteOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01063 {
01064   VehicleID veh_id = GB(p1, 0, 20);
01065   VehicleOrderID sel_ord = GB(p2, 0, 8);
01066 
01067   Vehicle *v = Vehicle::GetIfValid(veh_id);
01068 
01069   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01070 
01071   CommandCost ret = CheckOwnership(v->owner);
01072   if (ret.Failed()) return ret;
01073 
01074   /* If we did not select an order, we maybe want to de-clone the orders */
01075   if (sel_ord >= v->GetNumOrders()) return DecloneOrder(v, flags);
01076 
01077   if (v->GetOrder(sel_ord) == NULL) return CMD_ERROR;
01078 
01079   if (flags & DC_EXEC) DeleteOrder(v, sel_ord);
01080   return CommandCost();
01081 }
01082 
01087 static void CancelLoadingDueToDeletedOrder(Vehicle *v)
01088 {
01089   assert(v->current_order.IsType(OT_LOADING));
01090   /* NON-stop flag is misused to see if a train is in a station that is
01091    * on his order list or not */
01092   v->current_order.SetNonStopType(ONSF_STOP_EVERYWHERE);
01093   /* When full loading, "cancel" that order so the vehicle doesn't
01094    * stay indefinitely at this station anymore. */
01095   if (v->current_order.GetLoadType() & OLFB_FULL_LOAD) v->current_order.SetLoadType(OLF_LOAD_IF_POSSIBLE);
01096 }
01097 
01103 void DeleteOrder(Vehicle *v, VehicleOrderID sel_ord)
01104 {
01105   v->orders.list->DeleteOrderAt(sel_ord);
01106 
01107   Vehicle *u = v->FirstShared();
01108   DeleteOrderWarnings(u);
01109   for (; u != NULL; u = u->NextShared()) {
01110     assert(v->orders.list == u->orders.list);
01111 
01112     if (sel_ord == u->cur_real_order_index && u->current_order.IsType(OT_LOADING)) {
01113       CancelLoadingDueToDeletedOrder(u);
01114     }
01115 
01116     if (sel_ord < u->cur_real_order_index) {
01117       u->cur_real_order_index--;
01118     } else if (sel_ord == u->cur_real_order_index) {
01119       u->UpdateRealOrderIndex();
01120     }
01121 
01122     if (sel_ord < u->cur_implicit_order_index) {
01123       u->cur_implicit_order_index--;
01124     } else if (sel_ord == u->cur_implicit_order_index) {
01125       /* Make sure the index is valid */
01126       if (u->cur_implicit_order_index >= u->GetNumOrders()) u->cur_implicit_order_index = 0;
01127 
01128       /* Skip non-implicit orders for the implicit-order-index (e.g. if the current implicit order was deleted */
01129       while (u->cur_implicit_order_index != u->cur_real_order_index && !u->GetOrder(u->cur_implicit_order_index)->IsType(OT_IMPLICIT)) {
01130         u->cur_implicit_order_index++;
01131         if (u->cur_implicit_order_index >= u->GetNumOrders()) u->cur_implicit_order_index = 0;
01132       }
01133     }
01134 
01135     /* Update any possible open window of the vehicle */
01136     InvalidateVehicleOrder(u, sel_ord | (INVALID_VEH_ORDER_ID << 8));
01137   }
01138 
01139   /* As we delete an order, the order to skip to will be 'wrong'. */
01140   VehicleOrderID cur_order_id = 0;
01141   Order *order = NULL;
01142   FOR_VEHICLE_ORDERS(v, order) {
01143     if (order->IsType(OT_CONDITIONAL)) {
01144       VehicleOrderID order_id = order->GetConditionSkipToOrder();
01145       if (order_id >= sel_ord) {
01146         order_id = max(order_id - 1, 0);
01147       }
01148       if (order_id == cur_order_id) {
01149         order_id = (order_id + 1) % v->GetNumOrders();
01150       }
01151       order->SetConditionSkipToOrder(order_id);
01152     }
01153     cur_order_id++;
01154   }
01155 
01156   InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
01157 }
01158 
01168 CommandCost CmdSkipToOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01169 {
01170   VehicleID veh_id = GB(p1, 0, 20);
01171   VehicleOrderID sel_ord = GB(p2, 0, 8);
01172 
01173   Vehicle *v = Vehicle::GetIfValid(veh_id);
01174 
01175   if (v == NULL || !v->IsPrimaryVehicle() || sel_ord == v->cur_implicit_order_index || sel_ord >= v->GetNumOrders() || v->GetNumOrders() < 2) return CMD_ERROR;
01176 
01177   CommandCost ret = CheckOwnership(v->owner);
01178   if (ret.Failed()) return ret;
01179 
01180   if (flags & DC_EXEC) {
01181     if (v->current_order.IsType(OT_LOADING)) v->LeaveStation();
01182 
01183     v->cur_implicit_order_index = v->cur_real_order_index = sel_ord;
01184     v->UpdateRealOrderIndex();
01185 
01186     InvalidateVehicleOrder(v, -2);
01187   }
01188 
01189   /* We have an aircraft/ship, they have a mini-schedule, so update them all */
01190   if (v->type == VEH_AIRCRAFT) SetWindowClassesDirty(WC_AIRCRAFT_LIST);
01191   if (v->type == VEH_SHIP) SetWindowClassesDirty(WC_SHIPS_LIST);
01192 
01193   return CommandCost();
01194 }
01195 
01209 CommandCost CmdMoveOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01210 {
01211   VehicleID veh = GB(p1, 0, 20);
01212   VehicleOrderID moving_order = GB(p2,  0, 16);
01213   VehicleOrderID target_order = GB(p2, 16, 16);
01214 
01215   Vehicle *v = Vehicle::GetIfValid(veh);
01216   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01217 
01218   CommandCost ret = CheckOwnership(v->owner);
01219   if (ret.Failed()) return ret;
01220 
01221   /* Don't make senseless movements */
01222   if (moving_order >= v->GetNumOrders() || target_order >= v->GetNumOrders() ||
01223       moving_order == target_order || v->GetNumOrders() <= 1) return CMD_ERROR;
01224 
01225   Order *moving_one = v->GetOrder(moving_order);
01226   /* Don't move an empty order */
01227   if (moving_one == NULL) return CMD_ERROR;
01228 
01229   if (flags & DC_EXEC) {
01230     v->orders.list->MoveOrder(moving_order, target_order);
01231 
01232     /* Update shared list */
01233     Vehicle *u = v->FirstShared();
01234 
01235     DeleteOrderWarnings(u);
01236 
01237     for (; u != NULL; u = u->NextShared()) {
01238       /* Update the current order.
01239        * There are multiple ways to move orders, which result in cur_implicit_order_index
01240        * and cur_real_order_index to not longer make any sense. E.g. moving another
01241        * real order between them.
01242        *
01243        * Basically one could choose to preserve either of them, but not both.
01244        * While both ways are suitable in this or that case from a human point of view, neither
01245        * of them makes really sense.
01246        * However, from an AI point of view, preserving cur_real_order_index is the most
01247        * predictable and transparent behaviour.
01248        *
01249        * With that decision it basically does not matter what we do to cur_implicit_order_index.
01250        * If we change orders between the implict- and real-index, the implicit orders are mostly likely
01251        * completely out-dated anyway. So, keep it simple and just keep cur_implicit_order_index as well.
01252        * The worst which can happen is that a lot of implicit orders are removed when reaching current_order.
01253        */
01254       if (u->cur_real_order_index == moving_order) {
01255         u->cur_real_order_index = target_order;
01256       } else if (u->cur_real_order_index > moving_order && u->cur_real_order_index <= target_order) {
01257         u->cur_real_order_index--;
01258       } else if (u->cur_real_order_index < moving_order && u->cur_real_order_index >= target_order) {
01259         u->cur_real_order_index++;
01260       }
01261 
01262       if (u->cur_implicit_order_index == moving_order) {
01263         u->cur_implicit_order_index = target_order;
01264       } else if (u->cur_implicit_order_index > moving_order && u->cur_implicit_order_index <= target_order) {
01265         u->cur_implicit_order_index--;
01266       } else if (u->cur_implicit_order_index < moving_order && u->cur_implicit_order_index >= target_order) {
01267         u->cur_implicit_order_index++;
01268       }
01269 
01270       assert(v->orders.list == u->orders.list);
01271       /* Update any possible open window of the vehicle */
01272       InvalidateVehicleOrder(u, moving_order | (target_order << 8));
01273     }
01274 
01275     /* As we move an order, the order to skip to will be 'wrong'. */
01276     Order *order;
01277     FOR_VEHICLE_ORDERS(v, order) {
01278       if (order->IsType(OT_CONDITIONAL)) {
01279         VehicleOrderID order_id = order->GetConditionSkipToOrder();
01280         if (order_id == moving_order) {
01281           order_id = target_order;
01282         } else if (order_id > moving_order && order_id <= target_order) {
01283           order_id--;
01284         } else if (order_id < moving_order && order_id >= target_order) {
01285           order_id++;
01286         }
01287         order->SetConditionSkipToOrder(order_id);
01288       }
01289     }
01290 
01291     /* Make sure to rebuild the whole list */
01292     InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
01293   }
01294 
01295   return CommandCost();
01296 }
01297 
01313 CommandCost CmdModifyOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01314 {
01315   VehicleOrderID sel_ord = GB(p1, 20,  8);
01316   VehicleID veh          = GB(p1,  0, 20);
01317   ModifyOrderFlags mof   = Extract<ModifyOrderFlags, 0, 4>(p2);
01318   uint16 data            = GB(p2,  4, 11);
01319 
01320   if (mof >= MOF_END) return CMD_ERROR;
01321 
01322   Vehicle *v = Vehicle::GetIfValid(veh);
01323   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01324 
01325   CommandCost ret = CheckOwnership(v->owner);
01326   if (ret.Failed()) return ret;
01327 
01328   /* Is it a valid order? */
01329   if (sel_ord >= v->GetNumOrders()) return CMD_ERROR;
01330 
01331   Order *order = v->GetOrder(sel_ord);
01332   switch (order->GetType()) {
01333     case OT_GOTO_STATION:
01334       if (mof == MOF_COND_VARIABLE || mof == MOF_COND_COMPARATOR || mof == MOF_DEPOT_ACTION || mof == MOF_COND_VALUE) return CMD_ERROR;
01335       break;
01336 
01337     case OT_GOTO_DEPOT:
01338       if (mof != MOF_NON_STOP && mof != MOF_DEPOT_ACTION) return CMD_ERROR;
01339       break;
01340 
01341     case OT_GOTO_WAYPOINT:
01342       if (mof != MOF_NON_STOP) return CMD_ERROR;
01343       break;
01344 
01345     case OT_CONDITIONAL:
01346       if (mof != MOF_COND_VARIABLE && mof != MOF_COND_COMPARATOR && mof != MOF_COND_VALUE && mof != MOF_COND_DESTINATION) return CMD_ERROR;
01347       break;
01348 
01349     default:
01350       return CMD_ERROR;
01351   }
01352 
01353   switch (mof) {
01354     default: NOT_REACHED();
01355 
01356     case MOF_NON_STOP:
01357       if (!v->IsGroundVehicle()) return CMD_ERROR;
01358       if (data >= ONSF_END) return CMD_ERROR;
01359       if (data == order->GetNonStopType()) return CMD_ERROR;
01360       break;
01361 
01362     case MOF_STOP_LOCATION:
01363       if (v->type != VEH_TRAIN) return CMD_ERROR;
01364       if (data >= OSL_END) return CMD_ERROR;
01365       break;
01366 
01367     case MOF_UNLOAD:
01368       if ((data & ~(OUFB_UNLOAD | OUFB_TRANSFER | OUFB_NO_UNLOAD)) != 0) return CMD_ERROR;
01369       /* Unload and no-unload are mutual exclusive and so are transfer and no unload. */
01370       if (data != 0 && ((data & (OUFB_UNLOAD | OUFB_TRANSFER)) != 0) == ((data & OUFB_NO_UNLOAD) != 0)) return CMD_ERROR;
01371       if (data == order->GetUnloadType()) return CMD_ERROR;
01372       break;
01373 
01374     case MOF_LOAD:
01375       if (data > OLFB_NO_LOAD || data == 1) return CMD_ERROR;
01376       if (data == order->GetLoadType()) return CMD_ERROR;
01377       break;
01378 
01379     case MOF_DEPOT_ACTION:
01380       if (data >= DA_END) return CMD_ERROR;
01381       break;
01382 
01383     case MOF_COND_VARIABLE:
01384       if (data >= OCV_END) return CMD_ERROR;
01385       break;
01386 
01387     case MOF_COND_COMPARATOR:
01388       if (data >= OCC_END) return CMD_ERROR;
01389       switch (order->GetConditionVariable()) {
01390         case OCV_UNCONDITIONALLY: return CMD_ERROR;
01391 
01392         case OCV_REQUIRES_SERVICE:
01393           if (data != OCC_IS_TRUE && data != OCC_IS_FALSE) return CMD_ERROR;
01394           break;
01395 
01396         default:
01397           if (data == OCC_IS_TRUE || data == OCC_IS_FALSE) return CMD_ERROR;
01398           break;
01399       }
01400       break;
01401 
01402     case MOF_COND_VALUE:
01403       switch (order->GetConditionVariable()) {
01404         case OCV_UNCONDITIONALLY: return CMD_ERROR;
01405 
01406         case OCV_LOAD_PERCENTAGE:
01407         case OCV_RELIABILITY:
01408           if (data > 100) return CMD_ERROR;
01409           break;
01410 
01411         default:
01412           if (data > 2047) return CMD_ERROR;
01413           break;
01414       }
01415       break;
01416 
01417     case MOF_COND_DESTINATION:
01418       if (data >= v->GetNumOrders()) return CMD_ERROR;
01419       break;
01420   }
01421 
01422   if (flags & DC_EXEC) {
01423     switch (mof) {
01424       case MOF_NON_STOP:
01425         order->SetNonStopType((OrderNonStopFlags)data);
01426         if (data & ONSF_NO_STOP_AT_DESTINATION_STATION) order->SetRefit(CT_NO_REFIT);
01427         break;
01428 
01429       case MOF_STOP_LOCATION:
01430         order->SetStopLocation((OrderStopLocation)data);
01431         break;
01432 
01433       case MOF_UNLOAD:
01434         order->SetUnloadType((OrderUnloadFlags)data);
01435         break;
01436 
01437       case MOF_LOAD:
01438         order->SetLoadType((OrderLoadFlags)data);
01439         if (data & OLFB_NO_LOAD) order->SetRefit(CT_NO_REFIT);
01440         break;
01441 
01442       case MOF_DEPOT_ACTION: {
01443         switch (data) {
01444           case DA_ALWAYS_GO:
01445             order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
01446             order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
01447             break;
01448 
01449           case DA_SERVICE:
01450             order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() | ODTFB_SERVICE));
01451             order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
01452             order->SetRefit(CT_NO_REFIT);
01453             break;
01454 
01455           case DA_STOP:
01456             order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
01457             order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() | ODATFB_HALT));
01458             order->SetRefit(CT_NO_REFIT);
01459             break;
01460 
01461           default:
01462             NOT_REACHED();
01463         }
01464         break;
01465       }
01466 
01467       case MOF_COND_VARIABLE: {
01468         order->SetConditionVariable((OrderConditionVariable)data);
01469 
01470         OrderConditionComparator occ = order->GetConditionComparator();
01471         switch (order->GetConditionVariable()) {
01472           case OCV_UNCONDITIONALLY:
01473             order->SetConditionComparator(OCC_EQUALS);
01474             order->SetConditionValue(0);
01475             break;
01476 
01477           case OCV_REQUIRES_SERVICE:
01478             if (occ != OCC_IS_TRUE && occ != OCC_IS_FALSE) order->SetConditionComparator(OCC_IS_TRUE);
01479             break;
01480 
01481           case OCV_LOAD_PERCENTAGE:
01482           case OCV_RELIABILITY:
01483             if (order->GetConditionValue() > 100) order->SetConditionValue(100);
01484             /* FALL THROUGH */
01485           default:
01486             if (occ == OCC_IS_TRUE || occ == OCC_IS_FALSE) order->SetConditionComparator(OCC_EQUALS);
01487             break;
01488         }
01489         break;
01490       }
01491 
01492       case MOF_COND_COMPARATOR:
01493         order->SetConditionComparator((OrderConditionComparator)data);
01494         break;
01495 
01496       case MOF_COND_VALUE:
01497         order->SetConditionValue(data);
01498         break;
01499 
01500       case MOF_COND_DESTINATION:
01501         order->SetConditionSkipToOrder(data);
01502         break;
01503 
01504       default: NOT_REACHED();
01505     }
01506 
01507     /* Update the windows and full load flags, also for vehicles that share the same order list */
01508     Vehicle *u = v->FirstShared();
01509     DeleteOrderWarnings(u);
01510     for (; u != NULL; u = u->NextShared()) {
01511       /* Toggle u->current_order "Full load" flag if it changed.
01512        * However, as the same flag is used for depot orders, check
01513        * whether we are not going to a depot as there are three
01514        * cases where the full load flag can be active and only
01515        * one case where the flag is used for depot orders. In the
01516        * other cases for the OrderTypeByte the flags are not used,
01517        * so do not care and those orders should not be active
01518        * when this function is called.
01519        */
01520       if (sel_ord == u->cur_real_order_index &&
01521           (u->current_order.IsType(OT_GOTO_STATION) || u->current_order.IsType(OT_LOADING)) &&
01522           u->current_order.GetLoadType() != order->GetLoadType()) {
01523         u->current_order.SetLoadType(order->GetLoadType());
01524       }
01525       InvalidateVehicleOrder(u, -2);
01526     }
01527   }
01528 
01529   return CommandCost();
01530 }
01531 
01538 bool CheckAircraftOrderDistance(const Aircraft *v, const Order *first)
01539 {
01540   if (first == NULL || v->acache.cached_max_range == 0) return true;
01541 
01542   /* Iterate over all orders to check the distance between all
01543    * 'goto' orders and their respective next order (of any type). */
01544   for (const Order *o = first; o != NULL; o = o->next) {
01545     switch (o->GetType()) {
01546       case OT_GOTO_STATION:
01547       case OT_GOTO_DEPOT:
01548       case OT_GOTO_WAYPOINT:
01549         /* If we don't have a next order, we've reached the end and must check the first order instead. */
01550         if (GetOrderDistance(o, o->next != NULL ? o->next : first, v) > v->acache.cached_max_range_sqr) return false;
01551         break;
01552 
01553       default: break;
01554     }
01555   }
01556 
01557   return true;
01558 }
01559 
01571 CommandCost CmdCloneOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01572 {
01573   VehicleID veh_src = GB(p2, 0, 20);
01574   VehicleID veh_dst = GB(p1, 0, 20);
01575 
01576   Vehicle *dst = Vehicle::GetIfValid(veh_dst);
01577   if (dst == NULL || !dst->IsPrimaryVehicle()) return CMD_ERROR;
01578 
01579   CommandCost ret = CheckOwnership(dst->owner);
01580   if (ret.Failed()) return ret;
01581 
01582   switch (GB(p1, 30, 2)) {
01583     case CO_SHARE: {
01584       Vehicle *src = Vehicle::GetIfValid(veh_src);
01585 
01586       /* Sanity checks */
01587       if (src == NULL || !src->IsPrimaryVehicle() || dst->type != src->type || dst == src) return CMD_ERROR;
01588 
01589       CommandCost ret = CheckOwnership(src->owner);
01590       if (ret.Failed()) return ret;
01591 
01592       /* Trucks can't share orders with busses (and visa versa) */
01593       if (src->type == VEH_ROAD && RoadVehicle::From(src)->IsBus() != RoadVehicle::From(dst)->IsBus()) {
01594         return CMD_ERROR;
01595       }
01596 
01597       /* Is the vehicle already in the shared list? */
01598       if (src->FirstShared() == dst->FirstShared()) return CMD_ERROR;
01599 
01600       const Order *order;
01601 
01602       FOR_VEHICLE_ORDERS(src, order) {
01603         if (OrderGoesToStation(dst, order) &&
01604             !CanVehicleUseStation(dst, Station::Get(order->GetDestination()))) {
01605           return_cmd_error(STR_ERROR_CAN_T_COPY_SHARE_ORDER);
01606         }
01607       }
01608 
01609       /* Check for aircraft range limits. */
01610       if (dst->type == VEH_AIRCRAFT && !CheckAircraftOrderDistance(Aircraft::From(dst), src->GetFirstOrder())) {
01611         return_cmd_error(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE);
01612       }
01613 
01614       if (src->orders.list == NULL && !OrderList::CanAllocateItem()) {
01615         return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
01616       }
01617 
01618       if (flags & DC_EXEC) {
01619         /* If the destination vehicle had a OrderList, destroy it.
01620          * We only reset the order indices, if the new orders are obviously different.
01621          * (We mainly do this to keep the order indices valid and in range.) */
01622         DeleteVehicleOrders(dst, false, dst->GetNumOrders() != src->GetNumOrders());
01623 
01624         dst->orders.list = src->orders.list;
01625 
01626         /* Link this vehicle in the shared-list */
01627         dst->AddToShared(src);
01628 
01629         InvalidateVehicleOrder(dst, -1);
01630         InvalidateVehicleOrder(src, -2);
01631 
01632         InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
01633       }
01634       break;
01635     }
01636 
01637     case CO_COPY: {
01638       Vehicle *src = Vehicle::GetIfValid(veh_src);
01639 
01640       /* Sanity checks */
01641       if (src == NULL || !src->IsPrimaryVehicle() || dst->type != src->type || dst == src) return CMD_ERROR;
01642 
01643       CommandCost ret = CheckOwnership(src->owner);
01644       if (ret.Failed()) return ret;
01645 
01646       /* Trucks can't copy all the orders from busses (and visa versa),
01647        * and neither can helicopters and aircarft. */
01648       const Order *order;
01649       FOR_VEHICLE_ORDERS(src, order) {
01650         if (OrderGoesToStation(dst, order) &&
01651             !CanVehicleUseStation(dst, Station::Get(order->GetDestination()))) {
01652           return_cmd_error(STR_ERROR_CAN_T_COPY_SHARE_ORDER);
01653         }
01654       }
01655 
01656       /* Check for aircraft range limits. */
01657       if (dst->type == VEH_AIRCRAFT && !CheckAircraftOrderDistance(Aircraft::From(dst), src->GetFirstOrder())) {
01658         return_cmd_error(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE);
01659       }
01660 
01661       /* make sure there are orders available */
01662       if (!Order::CanAllocateItem(src->GetNumOrders()) || !OrderList::CanAllocateItem()) {
01663         return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
01664       }
01665 
01666       if (flags & DC_EXEC) {
01667         const Order *order;
01668         Order *first = NULL;
01669         Order **order_dst;
01670 
01671         /* If the destination vehicle had an order list, destroy the chain but keep the OrderList.
01672          * We only reset the order indices, if the new orders are obviously different.
01673          * (We mainly do this to keep the order indices valid and in range.) */
01674         DeleteVehicleOrders(dst, true, dst->GetNumOrders() != src->GetNumOrders());
01675 
01676         order_dst = &first;
01677         FOR_VEHICLE_ORDERS(src, order) {
01678           *order_dst = new Order();
01679           (*order_dst)->AssignOrder(*order);
01680           order_dst = &(*order_dst)->next;
01681         }
01682         if (dst->orders.list == NULL) {
01683           dst->orders.list = new OrderList(first, dst);
01684         } else {
01685           assert(dst->orders.list->GetFirstOrder() == NULL);
01686           assert(!dst->orders.list->IsShared());
01687           delete dst->orders.list;
01688           assert(OrderList::CanAllocateItem());
01689           dst->orders.list = new OrderList(first, dst);
01690         }
01691 
01692         InvalidateVehicleOrder(dst, -1);
01693 
01694         InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
01695       }
01696       break;
01697     }
01698 
01699     case CO_UNSHARE: return DecloneOrder(dst, flags);
01700     default: return CMD_ERROR;
01701   }
01702 
01703   return CommandCost();
01704 }
01705 
01718 CommandCost CmdOrderRefit(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01719 {
01720   VehicleID veh = GB(p1, 0, 20);
01721   VehicleOrderID order_number  = GB(p2, 16, 8);
01722   CargoID cargo = GB(p2, 0, 8);
01723   byte subtype  = GB(p2, 8, 8);
01724 
01725   if (cargo >= NUM_CARGO && cargo != CT_NO_REFIT && cargo != CT_AUTO_REFIT) return CMD_ERROR;
01726 
01727   const Vehicle *v = Vehicle::GetIfValid(veh);
01728   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01729 
01730   CommandCost ret = CheckOwnership(v->owner);
01731   if (ret.Failed()) return ret;
01732 
01733   Order *order = v->GetOrder(order_number);
01734   if (order == NULL) return CMD_ERROR;
01735 
01736   /* Automatic refit cargo is only supported for goto station orders. */
01737   if (cargo == CT_AUTO_REFIT && !order->IsType(OT_GOTO_STATION)) return CMD_ERROR;
01738 
01739   if (flags & DC_EXEC) {
01740     order->SetRefit(cargo, subtype);
01741 
01742     /* Make the depot order an 'always go' order. */
01743     if (cargo != CT_NO_REFIT) {
01744       order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
01745       order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
01746     }
01747 
01748     for (Vehicle *u = v->FirstShared(); u != NULL; u = u->NextShared()) {
01749       /* Update any possible open window of the vehicle */
01750       InvalidateVehicleOrder(u, -2);
01751 
01752       /* If the vehicle already got the current depot set as current order, then update current order as well */
01753       if (u->cur_real_order_index == order_number && (u->current_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) {
01754         u->current_order.SetRefit(cargo, subtype);
01755       }
01756     }
01757   }
01758 
01759   return CommandCost();
01760 }
01761 
01762 
01768 void CheckOrders(const Vehicle *v)
01769 {
01770   /* Does the user wants us to check things? */
01771   if (_settings_client.gui.order_review_system == 0) return;
01772 
01773   /* Do nothing for crashed vehicles */
01774   if (v->vehstatus & VS_CRASHED) return;
01775 
01776   /* Do nothing for stopped vehicles if setting is '1' */
01777   if (_settings_client.gui.order_review_system == 1 && (v->vehstatus & VS_STOPPED)) return;
01778 
01779   /* do nothing we we're not the first vehicle in a share-chain */
01780   if (v->FirstShared() != v) return;
01781 
01782   /* Only check every 20 days, so that we don't flood the message log */
01783   if (v->owner == _local_company && v->day_counter % 20 == 0) {
01784     int n_st, problem_type = -1;
01785     const Order *order;
01786     int message = 0;
01787 
01788     /* Check the order list */
01789     n_st = 0;
01790 
01791     FOR_VEHICLE_ORDERS(v, order) {
01792       /* Dummy order? */
01793       if (order->IsType(OT_DUMMY)) {
01794         problem_type = 1;
01795         break;
01796       }
01797       /* Does station have a load-bay for this vehicle? */
01798       if (order->IsType(OT_GOTO_STATION)) {
01799         const Station *st = Station::Get(order->GetDestination());
01800 
01801         n_st++;
01802         if (!CanVehicleUseStation(v, st)) problem_type = 3;
01803       }
01804     }
01805 
01806     /* Check if the last and the first order are the same */
01807     if (v->GetNumOrders() > 1) {
01808       const Order *last = v->GetLastOrder();
01809 
01810       if (v->orders.list->GetFirstOrder()->Equals(*last)) {
01811         problem_type = 2;
01812       }
01813     }
01814 
01815     /* Do we only have 1 station in our order list? */
01816     if (n_st < 2 && problem_type == -1) problem_type = 0;
01817 
01818 #ifndef NDEBUG
01819     if (v->orders.list != NULL) v->orders.list->DebugCheckSanity();
01820 #endif
01821 
01822     /* We don't have a problem */
01823     if (problem_type < 0) return;
01824 
01825     message = STR_NEWS_VEHICLE_HAS_TOO_FEW_ORDERS + problem_type;
01826     //DEBUG(misc, 3, "Triggered News Item for vehicle %d", v->index);
01827 
01828     SetDParam(0, v->index);
01829     AddVehicleNewsItem(
01830       message,
01831       NS_ADVICE,
01832       v->index
01833     );
01834   }
01835 }
01836 
01842 void RemoveOrderFromAllVehicles(OrderType type, DestinationID destination)
01843 {
01844   Vehicle *v;
01845 
01846   /* Aircraft have StationIDs for depot orders and never use DepotIDs
01847    * This fact is handled specially below
01848    */
01849 
01850   /* Go through all vehicles */
01851   FOR_ALL_VEHICLES(v) {
01852     Order *order;
01853 
01854     order = &v->current_order;
01855     if ((v->type == VEH_AIRCRAFT && order->IsType(OT_GOTO_DEPOT) ? OT_GOTO_STATION : order->GetType()) == type &&
01856         v->current_order.GetDestination() == destination) {
01857       order->MakeDummy();
01858       SetWindowDirty(WC_VEHICLE_VIEW, v->index);
01859     }
01860 
01861     /* Clear the order from the order-list */
01862     int id = -1;
01863     FOR_VEHICLE_ORDERS(v, order) {
01864       id++;
01865 restart:
01866 
01867       OrderType ot = order->GetType();
01868       if (ot == OT_GOTO_DEPOT && (order->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0) continue;
01869       if (ot == OT_IMPLICIT || (v->type == VEH_AIRCRAFT && ot == OT_GOTO_DEPOT)) ot = OT_GOTO_STATION;
01870       if (ot == type && order->GetDestination() == destination) {
01871         /* We want to clear implicit orders, but we don't want to make them
01872          * dummy orders. They should just vanish. Also check the actual order
01873          * type as ot is currently OT_GOTO_STATION. */
01874         if (order->IsType(OT_IMPLICIT)) {
01875           order = order->next; // DeleteOrder() invalidates current order
01876           DeleteOrder(v, id);
01877           if (order != NULL) goto restart;
01878           break;
01879         }
01880 
01881         order->MakeDummy();
01882         for (const Vehicle *w = v->FirstShared(); w != NULL; w = w->NextShared()) {
01883           /* In GUI, simulate by removing the order and adding it back */
01884           InvalidateVehicleOrder(w, id | (INVALID_VEH_ORDER_ID << 8));
01885           InvalidateVehicleOrder(w, (INVALID_VEH_ORDER_ID << 8) | id);
01886         }
01887       }
01888     }
01889   }
01890 
01891   OrderBackup::RemoveOrder(type, destination);
01892 }
01893 
01898 bool Vehicle::HasDepotOrder() const
01899 {
01900   const Order *order;
01901 
01902   FOR_VEHICLE_ORDERS(this, order) {
01903     if (order->IsType(OT_GOTO_DEPOT)) return true;
01904   }
01905 
01906   return false;
01907 }
01908 
01918 void DeleteVehicleOrders(Vehicle *v, bool keep_orderlist, bool reset_order_indices)
01919 {
01920   DeleteOrderWarnings(v);
01921 
01922   if (v->IsOrderListShared()) {
01923     /* Remove ourself from the shared order list. */
01924     v->RemoveFromShared();
01925     v->orders.list = NULL;
01926   } else if (v->orders.list != NULL) {
01927     /* Remove the orders */
01928     v->orders.list->FreeChain(keep_orderlist);
01929     if (!keep_orderlist) v->orders.list = NULL;
01930   }
01931 
01932   if (reset_order_indices) {
01933     v->cur_implicit_order_index = v->cur_real_order_index = 0;
01934     if (v->current_order.IsType(OT_LOADING)) {
01935       CancelLoadingDueToDeletedOrder(v);
01936     }
01937   }
01938 }
01939 
01947 uint16 GetServiceIntervalClamped(uint interval, CompanyID company_id)
01948 {
01949   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);
01950 }
01951 
01960 static bool CheckForValidOrders(const Vehicle *v)
01961 {
01962   const Order *order;
01963 
01964   FOR_VEHICLE_ORDERS(v, order) {
01965     switch (order->GetType()) {
01966       case OT_GOTO_STATION:
01967       case OT_GOTO_DEPOT:
01968       case OT_GOTO_WAYPOINT:
01969         return true;
01970 
01971       default:
01972         break;
01973     }
01974   }
01975 
01976   return false;
01977 }
01978 
01982 static bool OrderConditionCompare(OrderConditionComparator occ, int variable, int value)
01983 {
01984   switch (occ) {
01985     case OCC_EQUALS:      return variable == value;
01986     case OCC_NOT_EQUALS:  return variable != value;
01987     case OCC_LESS_THAN:   return variable <  value;
01988     case OCC_LESS_EQUALS: return variable <= value;
01989     case OCC_MORE_THAN:   return variable >  value;
01990     case OCC_MORE_EQUALS: return variable >= value;
01991     case OCC_IS_TRUE:     return variable != 0;
01992     case OCC_IS_FALSE:    return variable == 0;
01993     default: NOT_REACHED();
01994   }
01995 }
01996 
02003 VehicleOrderID ProcessConditionalOrder(const Order *order, const Vehicle *v)
02004 {
02005   if (order->GetType() != OT_CONDITIONAL) return INVALID_VEH_ORDER_ID;
02006 
02007   bool skip_order = false;
02008   OrderConditionComparator occ = order->GetConditionComparator();
02009   uint16 value = order->GetConditionValue();
02010 
02011   switch (order->GetConditionVariable()) {
02012     case OCV_LOAD_PERCENTAGE:    skip_order = OrderConditionCompare(occ, CalcPercentVehicleFilled(v, NULL), value); break;
02013     case OCV_RELIABILITY:        skip_order = OrderConditionCompare(occ, ToPercent16(v->reliability),       value); break;
02014     case OCV_MAX_SPEED:          skip_order = OrderConditionCompare(occ, v->GetDisplayMaxSpeed() * 10 / 16, value); break;
02015     case OCV_AGE:                skip_order = OrderConditionCompare(occ, v->age / DAYS_IN_LEAP_YEAR,        value); break;
02016     case OCV_REQUIRES_SERVICE:   skip_order = OrderConditionCompare(occ, v->NeedsServicing(),               value); break;
02017     case OCV_UNCONDITIONALLY:    skip_order = true; break;
02018     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;
02019     default: NOT_REACHED();
02020   }
02021 
02022   return skip_order ? order->GetConditionSkipToOrder() : (VehicleOrderID)INVALID_VEH_ORDER_ID;
02023 }
02024 
02032 bool UpdateOrderDest(Vehicle *v, const Order *order, int conditional_depth, bool pbs_look_ahead)
02033 {
02034   if (conditional_depth > v->GetNumOrders()) return false;
02035 
02036   switch (order->GetType()) {
02037     case OT_GOTO_STATION:
02038       v->dest_tile = v->GetOrderStationLocation(order->GetDestination());
02039       return true;
02040 
02041     case OT_GOTO_DEPOT:
02042       if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !v->NeedsServicing()) {
02043         assert(!pbs_look_ahead);
02044         UpdateVehicleTimetable(v, true);
02045         v->IncrementRealOrderIndex();
02046         break;
02047       }
02048 
02049       if (v->current_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) {
02050         /* We need to search for the nearest depot (hangar). */
02051         TileIndex location;
02052         DestinationID destination;
02053         bool reverse;
02054 
02055         if (v->FindClosestDepot(&location, &destination, &reverse)) {
02056           /* PBS reservations cannot reverse */
02057           if (pbs_look_ahead && reverse) return false;
02058 
02059           v->dest_tile = location;
02060           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());
02061 
02062           /* If there is no depot in front, reverse automatically (trains only) */
02063           if (v->type == VEH_TRAIN && reverse) DoCommand(v->tile, v->index, 0, DC_EXEC, CMD_REVERSE_TRAIN_DIRECTION);
02064 
02065           if (v->type == VEH_AIRCRAFT) {
02066             Aircraft *a = Aircraft::From(v);
02067             if (a->state == FLYING && a->targetairport != destination) {
02068               /* The aircraft is now heading for a different hangar than the next in the orders */
02069               extern void AircraftNextAirportPos_and_Order(Aircraft *a);
02070               AircraftNextAirportPos_and_Order(a);
02071             }
02072           }
02073           return true;
02074         }
02075 
02076         /* If there is no depot, we cannot help PBS either. */
02077         if (pbs_look_ahead) return false;
02078 
02079         UpdateVehicleTimetable(v, true);
02080         v->IncrementRealOrderIndex();
02081       } else {
02082         if (v->type != VEH_AIRCRAFT) {
02083           v->dest_tile = Depot::Get(order->GetDestination())->xy;
02084         }
02085         return true;
02086       }
02087       break;
02088 
02089     case OT_GOTO_WAYPOINT:
02090       v->dest_tile = Waypoint::Get(order->GetDestination())->xy;
02091       return true;
02092 
02093     case OT_CONDITIONAL: {
02094       assert(!pbs_look_ahead);
02095       VehicleOrderID next_order = ProcessConditionalOrder(order, v);
02096       if (next_order != INVALID_VEH_ORDER_ID) {
02097         /* Jump to next_order. cur_implicit_order_index becomes exactly that order,
02098          * cur_real_order_index might come after next_order. */
02099         UpdateVehicleTimetable(v, false);
02100         v->cur_implicit_order_index = v->cur_real_order_index = next_order;
02101         v->UpdateRealOrderIndex();
02102         v->current_order_time += v->GetOrder(v->cur_real_order_index)->travel_time;
02103 
02104         /* Disable creation of implicit orders.
02105          * When inserting them we do not know that we would have to make the conditional orders point to them. */
02106         if (v->IsGroundVehicle()) {
02107           uint16 &gv_flags = v->GetGroundVehicleFlags();
02108           SetBit(gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
02109         }
02110       } else {
02111         UpdateVehicleTimetable(v, true);
02112         v->IncrementRealOrderIndex();
02113       }
02114       break;
02115     }
02116 
02117     default:
02118       v->dest_tile = 0;
02119       return false;
02120   }
02121 
02122   assert(v->cur_implicit_order_index < v->GetNumOrders());
02123   assert(v->cur_real_order_index < v->GetNumOrders());
02124 
02125   /* Get the current order */
02126   order = v->GetOrder(v->cur_real_order_index);
02127   if (order != NULL && order->IsType(OT_IMPLICIT)) {
02128     assert(v->GetNumManualOrders() == 0);
02129     order = NULL;
02130   }
02131 
02132   if (order == NULL) {
02133     v->current_order.Free();
02134     v->dest_tile = 0;
02135     return false;
02136   }
02137 
02138   v->current_order = *order;
02139   return UpdateOrderDest(v, order, conditional_depth + 1, pbs_look_ahead);
02140 }
02141 
02149 bool ProcessOrders(Vehicle *v)
02150 {
02151   switch (v->current_order.GetType()) {
02152     case OT_GOTO_DEPOT:
02153       /* Let a depot order in the orderlist interrupt. */
02154       if (!(v->current_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) return false;
02155       break;
02156 
02157     case OT_LOADING:
02158       return false;
02159 
02160     case OT_LEAVESTATION:
02161       if (v->type != VEH_AIRCRAFT) return false;
02162       break;
02163 
02164     default: break;
02165   }
02166 
02174   bool may_reverse = v->current_order.IsType(OT_NOTHING);
02175 
02176   /* Check if we've reached a 'via' destination. */
02177   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)) &&
02178       IsTileType(v->tile, MP_STATION) &&
02179       v->current_order.GetDestination() == GetStationIndex(v->tile)) {
02180     v->DeleteUnreachedImplicitOrders();
02181     /* We set the last visited station here because we do not want
02182      * the train to stop at this 'via' station if the next order
02183      * is a no-non-stop order; in that case not setting the last
02184      * visited station will cause the vehicle to still stop. */
02185     v->last_station_visited = v->current_order.GetDestination();
02186     UpdateVehicleTimetable(v, true);
02187     v->IncrementImplicitOrderIndex();
02188   }
02189 
02190   /* Get the current order */
02191   assert(v->cur_implicit_order_index == 0 || v->cur_implicit_order_index < v->GetNumOrders());
02192   v->UpdateRealOrderIndex();
02193 
02194   const Order *order = v->GetOrder(v->cur_real_order_index);
02195   if (order != NULL && order->IsType(OT_IMPLICIT)) {
02196     assert(v->GetNumManualOrders() == 0);
02197     order = NULL;
02198   }
02199 
02200   /* If no order, do nothing. */
02201   if (order == NULL || (v->type == VEH_AIRCRAFT && !CheckForValidOrders(v))) {
02202     if (v->type == VEH_AIRCRAFT) {
02203       /* Aircraft do something vastly different here, so handle separately */
02204       extern void HandleMissingAircraftOrders(Aircraft *v);
02205       HandleMissingAircraftOrders(Aircraft::From(v));
02206       return false;
02207     }
02208 
02209     v->current_order.Free();
02210     v->dest_tile = 0;
02211     return false;
02212   }
02213 
02214   /* If it is unchanged, keep it. */
02215   if (order->Equals(v->current_order) && (v->type == VEH_AIRCRAFT || v->dest_tile != 0) &&
02216       (v->type != VEH_SHIP || !order->IsType(OT_GOTO_STATION) || Station::Get(order->GetDestination())->dock_tile != INVALID_TILE)) {
02217     return false;
02218   }
02219 
02220   /* Otherwise set it, and determine the destination tile. */
02221   v->current_order = *order;
02222 
02223   InvalidateVehicleOrder(v, -2);
02224   switch (v->type) {
02225     default:
02226       NOT_REACHED();
02227 
02228     case VEH_ROAD:
02229     case VEH_TRAIN:
02230       break;
02231 
02232     case VEH_AIRCRAFT:
02233     case VEH_SHIP:
02234       SetWindowClassesDirty(GetWindowClassForVehicleType(v->type));
02235       break;
02236   }
02237 
02238   return UpdateOrderDest(v, order) && may_reverse;
02239 }
02240 
02248 bool Order::ShouldStopAtStation(const Vehicle *v, StationID station) const
02249 {
02250   bool is_dest_station = this->IsType(OT_GOTO_STATION) && this->dest == station;
02251 
02252   return (!this->IsType(OT_GOTO_DEPOT) || (this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS) != 0) &&
02253       v->last_station_visited != station && // Do stop only when we've not just been there
02254       /* Finally do stop when there is no non-stop flag set for this type of station. */
02255       !(this->GetNonStopType() & (is_dest_station ? ONSF_NO_STOP_AT_DESTINATION_STATION : ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS));
02256 }
02257 
02258 bool Order::CanLoadOrUnload() const
02259 {
02260   return (this->IsType(OT_GOTO_STATION) || this->IsType(OT_IMPLICIT)) &&
02261       (this->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) == 0 &&
02262       ((this->GetLoadType() & OLFB_NO_LOAD) == 0 ||
02263       (this->GetUnloadType() & OUFB_NO_UNLOAD) == 0);
02264 }
02265 
02272 bool Order::CanLeaveWithCargo(bool has_cargo) const
02273 {
02274   return (this->GetLoadType() & OLFB_NO_LOAD) == 0 || (has_cargo &&
02275       (this->GetUnloadType() & (OUFB_UNLOAD | OUFB_TRANSFER)) == 0);
02276 }