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