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   this->max_speed     = UINT16_MAX;
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   this->max_speed   = other.max_speed;
00287 }
00288 
00294 void OrderList::Initialize(Order *chain, Vehicle *v)
00295 {
00296   this->first = chain;
00297   this->first_shared = v;
00298 
00299   this->num_orders = 0;
00300   this->num_manual_orders = 0;
00301   this->num_vehicles = 1;
00302   this->timetable_duration = 0;
00303 
00304   for (Order *o = this->first; o != NULL; o = o->next) {
00305     ++this->num_orders;
00306     if (!o->IsType(OT_IMPLICIT)) ++this->num_manual_orders;
00307     this->timetable_duration += o->wait_time + o->travel_time;
00308   }
00309 
00310   for (Vehicle *u = this->first_shared->PreviousShared(); u != NULL; u = u->PreviousShared()) {
00311     ++this->num_vehicles;
00312     this->first_shared = u;
00313   }
00314 
00315   for (const Vehicle *u = v->NextShared(); u != NULL; u = u->NextShared()) ++this->num_vehicles;
00316 }
00317 
00323 void OrderList::FreeChain(bool keep_orderlist)
00324 {
00325   Order *next;
00326   for (Order *o = this->first; o != NULL; o = next) {
00327     next = o->next;
00328     delete o;
00329   }
00330 
00331   if (keep_orderlist) {
00332     this->first = NULL;
00333     this->num_orders = 0;
00334     this->num_manual_orders = 0;
00335     this->timetable_duration = 0;
00336   } else {
00337     delete this;
00338   }
00339 }
00340 
00346 Order *OrderList::GetOrderAt(int index) const
00347 {
00348   if (index < 0) return NULL;
00349 
00350   Order *order = this->first;
00351 
00352   while (order != NULL && index-- > 0) {
00353     order = order->next;
00354   }
00355   return order;
00356 }
00357 
00367 const Order *OrderList::GetBestLoadableNext(const Vehicle *v, const Order *o2, const Order *o1) const
00368 {
00369   SmallMap<CargoID, uint> capacities;
00370   v->GetConsistFreeCapacities(capacities);
00371   uint loadable1 = 0;
00372   uint loadable2 = 0;
00373   StationID st1 = o1->GetDestination();
00374   StationID st2 = o2->GetDestination();
00375   const Station *cur_station = Station::Get(v->last_station_visited);
00376   for (SmallPair<CargoID, uint> *i = capacities.Begin(); i != capacities.End(); ++i) {
00377     const StationCargoPacketMap *loadable_packets = cur_station->goods[i->first].cargo.Packets();
00378     uint loadable_cargo = 0;
00379     std::pair<StationCargoPacketMap::const_iterator, StationCargoPacketMap::const_iterator> p =
00380       loadable_packets->equal_range(st1);
00381     for (StationCargoPacketMap::const_iterator j = p.first; j != p.second; ++j) {
00382       loadable_cargo = (*j)->Count();
00383     }
00384     loadable1 += min(i->second, loadable_cargo);
00385 
00386     loadable_cargo = 0;
00387     p = loadable_packets->equal_range(st2);
00388     for (StationCargoPacketMap::const_iterator j = p.first; j != p.second; ++j) {
00389       loadable_cargo = (*j)->Count();
00390     }
00391     loadable2 += min(i->second, loadable_cargo);
00392   }
00393   if (loadable1 == loadable2) return RandomRange(2) == 0 ? o1 : o2;
00394   return loadable1 > loadable2 ? o1 : o2;
00395 }
00396 
00408 const Order *OrderList::GetNextStoppingOrder(const Vehicle *v, const Order *next, uint hops, bool is_loading) const
00409 {
00410   if (hops > this->GetNumOrders() || next == NULL) return NULL;
00411 
00412   if (next->IsType(OT_CONDITIONAL)) {
00413     if (is_loading && next->GetConditionVariable() == OCV_LOAD_PERCENTAGE) {
00414       /* If the condition is based on load percentage we can't
00415        * tell what it will do. So we choose randomly. */
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       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 
01539 static bool CheckAircraftOrderDistance(const Aircraft *v_new, const Vehicle *v_order, const Order *first)
01540 {
01541   if (first == NULL || v_new->acache.cached_max_range == 0) return true;
01542 
01543   /* Iterate over all orders to check the distance between all
01544    * 'goto' orders and their respective next order (of any type). */
01545   for (const Order *o = first; o != NULL; o = o->next) {
01546     switch (o->GetType()) {
01547       case OT_GOTO_STATION:
01548       case OT_GOTO_DEPOT:
01549       case OT_GOTO_WAYPOINT:
01550         /* If we don't have a next order, we've reached the end and must check the first order instead. */
01551         if (GetOrderDistance(o, o->next != NULL ? o->next : first, v_order) > v_new->acache.cached_max_range_sqr) return false;
01552         break;
01553 
01554       default: break;
01555     }
01556   }
01557 
01558   return true;
01559 }
01560 
01572 CommandCost CmdCloneOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01573 {
01574   VehicleID veh_src = GB(p2, 0, 20);
01575   VehicleID veh_dst = GB(p1, 0, 20);
01576 
01577   Vehicle *dst = Vehicle::GetIfValid(veh_dst);
01578   if (dst == NULL || !dst->IsPrimaryVehicle()) return CMD_ERROR;
01579 
01580   CommandCost ret = CheckOwnership(dst->owner);
01581   if (ret.Failed()) return ret;
01582 
01583   switch (GB(p1, 30, 2)) {
01584     case CO_SHARE: {
01585       Vehicle *src = Vehicle::GetIfValid(veh_src);
01586 
01587       /* Sanity checks */
01588       if (src == NULL || !src->IsPrimaryVehicle() || dst->type != src->type || dst == src) return CMD_ERROR;
01589 
01590       CommandCost ret = CheckOwnership(src->owner);
01591       if (ret.Failed()) return ret;
01592 
01593       /* Trucks can't share orders with busses (and visa versa) */
01594       if (src->type == VEH_ROAD && RoadVehicle::From(src)->IsBus() != RoadVehicle::From(dst)->IsBus()) {
01595         return CMD_ERROR;
01596       }
01597 
01598       /* Is the vehicle already in the shared list? */
01599       if (src->FirstShared() == dst->FirstShared()) return CMD_ERROR;
01600 
01601       const Order *order;
01602 
01603       FOR_VEHICLE_ORDERS(src, order) {
01604         if (!OrderGoesToStation(dst, order)) continue;
01605 
01606         /* Allow copying unreachable destinations if they were already unreachable for the source.
01607          * This is basically to allow cloning / autorenewing / autoreplacing vehicles, while the stations
01608          * are temporarily invalid due to reconstruction. */
01609         const Station *st = Station::Get(order->GetDestination());
01610         if (CanVehicleUseStation(src, st) && !CanVehicleUseStation(dst, st)) {
01611           return_cmd_error(STR_ERROR_CAN_T_COPY_SHARE_ORDER);
01612         }
01613       }
01614 
01615       /* Check for aircraft range limits. */
01616       if (dst->type == VEH_AIRCRAFT && !CheckAircraftOrderDistance(Aircraft::From(dst), src, src->GetFirstOrder())) {
01617         return_cmd_error(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE);
01618       }
01619 
01620       if (src->orders.list == NULL && !OrderList::CanAllocateItem()) {
01621         return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
01622       }
01623 
01624       if (flags & DC_EXEC) {
01625         /* If the destination vehicle had a OrderList, destroy it.
01626          * We only reset the order indices, if the new orders are obviously different.
01627          * (We mainly do this to keep the order indices valid and in range.) */
01628         DeleteVehicleOrders(dst, false, dst->GetNumOrders() != src->GetNumOrders());
01629 
01630         dst->orders.list = src->orders.list;
01631 
01632         /* Link this vehicle in the shared-list */
01633         dst->AddToShared(src);
01634 
01635         InvalidateVehicleOrder(dst, -1);
01636         InvalidateVehicleOrder(src, -2);
01637 
01638         InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
01639       }
01640       break;
01641     }
01642 
01643     case CO_COPY: {
01644       Vehicle *src = Vehicle::GetIfValid(veh_src);
01645 
01646       /* Sanity checks */
01647       if (src == NULL || !src->IsPrimaryVehicle() || dst->type != src->type || dst == src) return CMD_ERROR;
01648 
01649       CommandCost ret = CheckOwnership(src->owner);
01650       if (ret.Failed()) return ret;
01651 
01652       /* Trucks can't copy all the orders from busses (and visa versa),
01653        * and neither can helicopters and aircarft. */
01654       const Order *order;
01655       FOR_VEHICLE_ORDERS(src, order) {
01656         if (OrderGoesToStation(dst, order) &&
01657             !CanVehicleUseStation(dst, Station::Get(order->GetDestination()))) {
01658           return_cmd_error(STR_ERROR_CAN_T_COPY_SHARE_ORDER);
01659         }
01660       }
01661 
01662       /* Check for aircraft range limits. */
01663       if (dst->type == VEH_AIRCRAFT && !CheckAircraftOrderDistance(Aircraft::From(dst), src, src->GetFirstOrder())) {
01664         return_cmd_error(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE);
01665       }
01666 
01667       /* make sure there are orders available */
01668       if (!Order::CanAllocateItem(src->GetNumOrders()) || !OrderList::CanAllocateItem()) {
01669         return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
01670       }
01671 
01672       if (flags & DC_EXEC) {
01673         const Order *order;
01674         Order *first = NULL;
01675         Order **order_dst;
01676 
01677         /* If the destination vehicle had an order list, destroy the chain but keep the OrderList.
01678          * We only reset the order indices, if the new orders are obviously different.
01679          * (We mainly do this to keep the order indices valid and in range.) */
01680         DeleteVehicleOrders(dst, true, dst->GetNumOrders() != src->GetNumOrders());
01681 
01682         order_dst = &first;
01683         FOR_VEHICLE_ORDERS(src, order) {
01684           *order_dst = new Order();
01685           (*order_dst)->AssignOrder(*order);
01686           order_dst = &(*order_dst)->next;
01687         }
01688         if (dst->orders.list == NULL) {
01689           dst->orders.list = new OrderList(first, dst);
01690         } else {
01691           assert(dst->orders.list->GetFirstOrder() == NULL);
01692           assert(!dst->orders.list->IsShared());
01693           delete dst->orders.list;
01694           assert(OrderList::CanAllocateItem());
01695           dst->orders.list = new OrderList(first, dst);
01696         }
01697 
01698         InvalidateVehicleOrder(dst, -1);
01699 
01700         InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
01701       }
01702       break;
01703     }
01704 
01705     case CO_UNSHARE: return DecloneOrder(dst, flags);
01706     default: return CMD_ERROR;
01707   }
01708 
01709   return CommandCost();
01710 }
01711 
01724 CommandCost CmdOrderRefit(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01725 {
01726   VehicleID veh = GB(p1, 0, 20);
01727   VehicleOrderID order_number  = GB(p2, 16, 8);
01728   CargoID cargo = GB(p2, 0, 8);
01729   byte subtype  = GB(p2, 8, 8);
01730 
01731   if (cargo >= NUM_CARGO && cargo != CT_NO_REFIT && cargo != CT_AUTO_REFIT) return CMD_ERROR;
01732 
01733   const Vehicle *v = Vehicle::GetIfValid(veh);
01734   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01735 
01736   CommandCost ret = CheckOwnership(v->owner);
01737   if (ret.Failed()) return ret;
01738 
01739   Order *order = v->GetOrder(order_number);
01740   if (order == NULL) return CMD_ERROR;
01741 
01742   /* Automatic refit cargo is only supported for goto station orders. */
01743   if (cargo == CT_AUTO_REFIT && !order->IsType(OT_GOTO_STATION)) return CMD_ERROR;
01744 
01745   if (flags & DC_EXEC) {
01746     order->SetRefit(cargo, subtype);
01747 
01748     /* Make the depot order an 'always go' order. */
01749     if (cargo != CT_NO_REFIT && order->IsType(OT_GOTO_DEPOT)) {
01750       order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
01751       order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
01752     }
01753 
01754     for (Vehicle *u = v->FirstShared(); u != NULL; u = u->NextShared()) {
01755       /* Update any possible open window of the vehicle */
01756       InvalidateVehicleOrder(u, -2);
01757 
01758       /* If the vehicle already got the current depot set as current order, then update current order as well */
01759       if (u->cur_real_order_index == order_number && (u->current_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) {
01760         u->current_order.SetRefit(cargo, subtype);
01761       }
01762     }
01763   }
01764 
01765   return CommandCost();
01766 }
01767 
01768 
01774 void CheckOrders(const Vehicle *v)
01775 {
01776   /* Does the user wants us to check things? */
01777   if (_settings_client.gui.order_review_system == 0) return;
01778 
01779   /* Do nothing for crashed vehicles */
01780   if (v->vehstatus & VS_CRASHED) return;
01781 
01782   /* Do nothing for stopped vehicles if setting is '1' */
01783   if (_settings_client.gui.order_review_system == 1 && (v->vehstatus & VS_STOPPED)) return;
01784 
01785   /* do nothing we we're not the first vehicle in a share-chain */
01786   if (v->FirstShared() != v) return;
01787 
01788   /* Only check every 20 days, so that we don't flood the message log */
01789   if (v->owner == _local_company && v->day_counter % 20 == 0) {
01790     int n_st, problem_type = -1;
01791     const Order *order;
01792     int message = 0;
01793 
01794     /* Check the order list */
01795     n_st = 0;
01796 
01797     FOR_VEHICLE_ORDERS(v, order) {
01798       /* Dummy order? */
01799       if (order->IsType(OT_DUMMY)) {
01800         problem_type = 1;
01801         break;
01802       }
01803       /* Does station have a load-bay for this vehicle? */
01804       if (order->IsType(OT_GOTO_STATION)) {
01805         const Station *st = Station::Get(order->GetDestination());
01806 
01807         n_st++;
01808         if (!CanVehicleUseStation(v, st)) problem_type = 3;
01809       }
01810     }
01811 
01812     /* Check if the last and the first order are the same */
01813     if (v->GetNumOrders() > 1) {
01814       const Order *last = v->GetLastOrder();
01815 
01816       if (v->orders.list->GetFirstOrder()->Equals(*last)) {
01817         problem_type = 2;
01818       }
01819     }
01820 
01821     /* Do we only have 1 station in our order list? */
01822     if (n_st < 2 && problem_type == -1) problem_type = 0;
01823 
01824 #ifndef NDEBUG
01825     if (v->orders.list != NULL) v->orders.list->DebugCheckSanity();
01826 #endif
01827 
01828     /* We don't have a problem */
01829     if (problem_type < 0) return;
01830 
01831     message = STR_NEWS_VEHICLE_HAS_TOO_FEW_ORDERS + problem_type;
01832     //DEBUG(misc, 3, "Triggered News Item for vehicle %d", v->index);
01833 
01834     SetDParam(0, v->index);
01835     AddVehicleAdviceNewsItem(message, v->index);
01836   }
01837 }
01838 
01844 void RemoveOrderFromAllVehicles(OrderType type, DestinationID destination)
01845 {
01846   Vehicle *v;
01847 
01848   /* Aircraft have StationIDs for depot orders and never use DepotIDs
01849    * This fact is handled specially below
01850    */
01851 
01852   /* Go through all vehicles */
01853   FOR_ALL_VEHICLES(v) {
01854     Order *order;
01855 
01856     order = &v->current_order;
01857     if ((v->type == VEH_AIRCRAFT && order->IsType(OT_GOTO_DEPOT) ? OT_GOTO_STATION : order->GetType()) == type &&
01858         v->current_order.GetDestination() == destination) {
01859       order->MakeDummy();
01860       SetWindowDirty(WC_VEHICLE_VIEW, v->index);
01861     }
01862 
01863     /* Clear the order from the order-list */
01864     int id = -1;
01865     FOR_VEHICLE_ORDERS(v, order) {
01866       id++;
01867 restart:
01868 
01869       OrderType ot = order->GetType();
01870       if (ot == OT_GOTO_DEPOT && (order->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0) continue;
01871       if (ot == OT_IMPLICIT || (v->type == VEH_AIRCRAFT && ot == OT_GOTO_DEPOT)) ot = OT_GOTO_STATION;
01872       if (ot == type && order->GetDestination() == destination) {
01873         /* We want to clear implicit orders, but we don't want to make them
01874          * dummy orders. They should just vanish. Also check the actual order
01875          * type as ot is currently OT_GOTO_STATION. */
01876         if (order->IsType(OT_IMPLICIT)) {
01877           order = order->next; // DeleteOrder() invalidates current order
01878           DeleteOrder(v, id);
01879           if (order != NULL) goto restart;
01880           break;
01881         }
01882 
01883         order->MakeDummy();
01884         for (const Vehicle *w = v->FirstShared(); w != NULL; w = w->NextShared()) {
01885           /* In GUI, simulate by removing the order and adding it back */
01886           InvalidateVehicleOrder(w, id | (INVALID_VEH_ORDER_ID << 8));
01887           InvalidateVehicleOrder(w, (INVALID_VEH_ORDER_ID << 8) | id);
01888         }
01889       }
01890     }
01891   }
01892 
01893   OrderBackup::RemoveOrder(type, destination);
01894 }
01895 
01900 bool Vehicle::HasDepotOrder() const
01901 {
01902   const Order *order;
01903 
01904   FOR_VEHICLE_ORDERS(this, order) {
01905     if (order->IsType(OT_GOTO_DEPOT)) return true;
01906   }
01907 
01908   return false;
01909 }
01910 
01920 void DeleteVehicleOrders(Vehicle *v, bool keep_orderlist, bool reset_order_indices)
01921 {
01922   DeleteOrderWarnings(v);
01923 
01924   if (v->IsOrderListShared()) {
01925     /* Remove ourself from the shared order list. */
01926     v->RemoveFromShared();
01927     v->orders.list = NULL;
01928   } else if (v->orders.list != NULL) {
01929     /* Remove the orders */
01930     v->orders.list->FreeChain(keep_orderlist);
01931     if (!keep_orderlist) v->orders.list = NULL;
01932   }
01933 
01934   if (reset_order_indices) {
01935     v->cur_implicit_order_index = v->cur_real_order_index = 0;
01936     if (v->current_order.IsType(OT_LOADING)) {
01937       CancelLoadingDueToDeletedOrder(v);
01938     }
01939   }
01940 }
01941 
01949 uint16 GetServiceIntervalClamped(uint interval, CompanyID company_id)
01950 {
01951   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);
01952 }
01953 
01962 static bool CheckForValidOrders(const Vehicle *v)
01963 {
01964   const Order *order;
01965 
01966   FOR_VEHICLE_ORDERS(v, order) {
01967     switch (order->GetType()) {
01968       case OT_GOTO_STATION:
01969       case OT_GOTO_DEPOT:
01970       case OT_GOTO_WAYPOINT:
01971         return true;
01972 
01973       default:
01974         break;
01975     }
01976   }
01977 
01978   return false;
01979 }
01980 
01984 static bool OrderConditionCompare(OrderConditionComparator occ, int variable, int value)
01985 {
01986   switch (occ) {
01987     case OCC_EQUALS:      return variable == value;
01988     case OCC_NOT_EQUALS:  return variable != value;
01989     case OCC_LESS_THAN:   return variable <  value;
01990     case OCC_LESS_EQUALS: return variable <= value;
01991     case OCC_MORE_THAN:   return variable >  value;
01992     case OCC_MORE_EQUALS: return variable >= value;
01993     case OCC_IS_TRUE:     return variable != 0;
01994     case OCC_IS_FALSE:    return variable == 0;
01995     default: NOT_REACHED();
01996   }
01997 }
01998 
02005 VehicleOrderID ProcessConditionalOrder(const Order *order, const Vehicle *v)
02006 {
02007   if (order->GetType() != OT_CONDITIONAL) return INVALID_VEH_ORDER_ID;
02008 
02009   bool skip_order = false;
02010   OrderConditionComparator occ = order->GetConditionComparator();
02011   uint16 value = order->GetConditionValue();
02012 
02013   switch (order->GetConditionVariable()) {
02014     case OCV_LOAD_PERCENTAGE:    skip_order = OrderConditionCompare(occ, CalcPercentVehicleFilled(v, NULL), value); break;
02015     case OCV_RELIABILITY:        skip_order = OrderConditionCompare(occ, ToPercent16(v->reliability),       value); break;
02016     case OCV_MAX_SPEED:          skip_order = OrderConditionCompare(occ, v->GetDisplayMaxSpeed() * 10 / 16, value); break;
02017     case OCV_AGE:                skip_order = OrderConditionCompare(occ, v->age / DAYS_IN_LEAP_YEAR,        value); break;
02018     case OCV_REQUIRES_SERVICE:   skip_order = OrderConditionCompare(occ, v->NeedsServicing(),               value); break;
02019     case OCV_UNCONDITIONALLY:    skip_order = true; break;
02020     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;
02021     default: NOT_REACHED();
02022   }
02023 
02024   return skip_order ? order->GetConditionSkipToOrder() : (VehicleOrderID)INVALID_VEH_ORDER_ID;
02025 }
02026 
02034 bool UpdateOrderDest(Vehicle *v, const Order *order, int conditional_depth, bool pbs_look_ahead)
02035 {
02036   if (conditional_depth > v->GetNumOrders()) return false;
02037 
02038   switch (order->GetType()) {
02039     case OT_GOTO_STATION:
02040       v->dest_tile = v->GetOrderStationLocation(order->GetDestination());
02041       return true;
02042 
02043     case OT_GOTO_DEPOT:
02044       if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !v->NeedsServicing()) {
02045         assert(!pbs_look_ahead);
02046         UpdateVehicleTimetable(v, true);
02047         v->IncrementRealOrderIndex();
02048         break;
02049       }
02050 
02051       if (v->current_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) {
02052         /* We need to search for the nearest depot (hangar). */
02053         TileIndex location;
02054         DestinationID destination;
02055         bool reverse;
02056 
02057         if (v->FindClosestDepot(&location, &destination, &reverse)) {
02058           /* PBS reservations cannot reverse */
02059           if (pbs_look_ahead && reverse) return false;
02060 
02061           v->dest_tile = location;
02062           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());
02063 
02064           /* If there is no depot in front, reverse automatically (trains only) */
02065           if (v->type == VEH_TRAIN && reverse) DoCommand(v->tile, v->index, 0, DC_EXEC, CMD_REVERSE_TRAIN_DIRECTION);
02066 
02067           if (v->type == VEH_AIRCRAFT) {
02068             Aircraft *a = Aircraft::From(v);
02069             if (a->state == FLYING && a->targetairport != destination) {
02070               /* The aircraft is now heading for a different hangar than the next in the orders */
02071               extern void AircraftNextAirportPos_and_Order(Aircraft *a);
02072               AircraftNextAirportPos_and_Order(a);
02073             }
02074           }
02075           return true;
02076         }
02077 
02078         /* If there is no depot, we cannot help PBS either. */
02079         if (pbs_look_ahead) return false;
02080 
02081         UpdateVehicleTimetable(v, true);
02082         v->IncrementRealOrderIndex();
02083       } else {
02084         if (v->type != VEH_AIRCRAFT) {
02085           v->dest_tile = Depot::Get(order->GetDestination())->xy;
02086         }
02087         return true;
02088       }
02089       break;
02090 
02091     case OT_GOTO_WAYPOINT:
02092       v->dest_tile = Waypoint::Get(order->GetDestination())->xy;
02093       return true;
02094 
02095     case OT_CONDITIONAL: {
02096       assert(!pbs_look_ahead);
02097       VehicleOrderID next_order = ProcessConditionalOrder(order, v);
02098       if (next_order != INVALID_VEH_ORDER_ID) {
02099         /* Jump to next_order. cur_implicit_order_index becomes exactly that order,
02100          * cur_real_order_index might come after next_order. */
02101         UpdateVehicleTimetable(v, false);
02102         v->cur_implicit_order_index = v->cur_real_order_index = next_order;
02103         v->UpdateRealOrderIndex();
02104         v->current_order_time += v->GetOrder(v->cur_real_order_index)->travel_time;
02105 
02106         /* Disable creation of implicit orders.
02107          * When inserting them we do not know that we would have to make the conditional orders point to them. */
02108         if (v->IsGroundVehicle()) {
02109           uint16 &gv_flags = v->GetGroundVehicleFlags();
02110           SetBit(gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
02111         }
02112       } else {
02113         UpdateVehicleTimetable(v, true);
02114         v->IncrementRealOrderIndex();
02115       }
02116       break;
02117     }
02118 
02119     default:
02120       v->dest_tile = 0;
02121       return false;
02122   }
02123 
02124   assert(v->cur_implicit_order_index < v->GetNumOrders());
02125   assert(v->cur_real_order_index < v->GetNumOrders());
02126 
02127   /* Get the current order */
02128   order = v->GetOrder(v->cur_real_order_index);
02129   if (order != NULL && order->IsType(OT_IMPLICIT)) {
02130     assert(v->GetNumManualOrders() == 0);
02131     order = NULL;
02132   }
02133 
02134   if (order == NULL) {
02135     v->current_order.Free();
02136     v->dest_tile = 0;
02137     return false;
02138   }
02139 
02140   v->current_order = *order;
02141   return UpdateOrderDest(v, order, conditional_depth + 1, pbs_look_ahead);
02142 }
02143 
02151 bool ProcessOrders(Vehicle *v)
02152 {
02153   switch (v->current_order.GetType()) {
02154     case OT_GOTO_DEPOT:
02155       /* Let a depot order in the orderlist interrupt. */
02156       if (!(v->current_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) return false;
02157       break;
02158 
02159     case OT_LOADING:
02160       return false;
02161 
02162     case OT_LEAVESTATION:
02163       if (v->type != VEH_AIRCRAFT) return false;
02164       break;
02165 
02166     default: break;
02167   }
02168 
02176   bool may_reverse = v->current_order.IsType(OT_NOTHING);
02177 
02178   /* Check if we've reached a 'via' destination. */
02179   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)) &&
02180       IsTileType(v->tile, MP_STATION) &&
02181       v->current_order.GetDestination() == GetStationIndex(v->tile)) {
02182     v->DeleteUnreachedImplicitOrders();
02183     /* We set the last visited station here because we do not want
02184      * the train to stop at this 'via' station if the next order
02185      * is a no-non-stop order; in that case not setting the last
02186      * visited station will cause the vehicle to still stop. */
02187     v->last_station_visited = v->current_order.GetDestination();
02188     UpdateVehicleTimetable(v, true);
02189     v->IncrementImplicitOrderIndex();
02190   }
02191 
02192   /* Get the current order */
02193   assert(v->cur_implicit_order_index == 0 || v->cur_implicit_order_index < v->GetNumOrders());
02194   v->UpdateRealOrderIndex();
02195 
02196   const Order *order = v->GetOrder(v->cur_real_order_index);
02197   if (order != NULL && order->IsType(OT_IMPLICIT)) {
02198     assert(v->GetNumManualOrders() == 0);
02199     order = NULL;
02200   }
02201 
02202   /* If no order, do nothing. */
02203   if (order == NULL || (v->type == VEH_AIRCRAFT && !CheckForValidOrders(v))) {
02204     if (v->type == VEH_AIRCRAFT) {
02205       /* Aircraft do something vastly different here, so handle separately */
02206       extern void HandleMissingAircraftOrders(Aircraft *v);
02207       HandleMissingAircraftOrders(Aircraft::From(v));
02208       return false;
02209     }
02210 
02211     v->current_order.Free();
02212     v->dest_tile = 0;
02213     return false;
02214   }
02215 
02216   /* If it is unchanged, keep it. */
02217   if (order->Equals(v->current_order) && (v->type == VEH_AIRCRAFT || v->dest_tile != 0) &&
02218       (v->type != VEH_SHIP || !order->IsType(OT_GOTO_STATION) || Station::Get(order->GetDestination())->dock_tile != INVALID_TILE)) {
02219     return false;
02220   }
02221 
02222   /* Otherwise set it, and determine the destination tile. */
02223   v->current_order = *order;
02224 
02225   InvalidateVehicleOrder(v, -2);
02226   switch (v->type) {
02227     default:
02228       NOT_REACHED();
02229 
02230     case VEH_ROAD:
02231     case VEH_TRAIN:
02232       break;
02233 
02234     case VEH_AIRCRAFT:
02235     case VEH_SHIP:
02236       SetWindowClassesDirty(GetWindowClassForVehicleType(v->type));
02237       break;
02238   }
02239 
02240   return UpdateOrderDest(v, order) && may_reverse;
02241 }
02242 
02250 bool Order::ShouldStopAtStation(const Vehicle *v, StationID station) const
02251 {
02252   bool is_dest_station = this->IsType(OT_GOTO_STATION) && this->dest == station;
02253 
02254   return (!this->IsType(OT_GOTO_DEPOT) || (this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS) != 0) &&
02255       v->last_station_visited != station && // Do stop only when we've not just been there
02256       /* Finally do stop when there is no non-stop flag set for this type of station. */
02257       !(this->GetNonStopType() & (is_dest_station ? ONSF_NO_STOP_AT_DESTINATION_STATION : ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS));
02258 }
02259 
02260 bool Order::CanLoadOrUnload() const
02261 {
02262   return (this->IsType(OT_GOTO_STATION) || this->IsType(OT_IMPLICIT)) &&
02263       (this->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) == 0 &&
02264       ((this->GetLoadType() & OLFB_NO_LOAD) == 0 ||
02265       (this->GetUnloadType() & OUFB_NO_UNLOAD) == 0);
02266 }
02267 
02274 bool Order::CanLeaveWithCargo(bool has_cargo) const
02275 {
02276   return (this->GetLoadType() & OLFB_NO_LOAD) == 0 || (has_cargo &&
02277       (this->GetUnloadType() & (OUFB_UNLOAD | OUFB_TRANSFER)) == 0);
02278 }