order_cmd.cpp

Go to the documentation of this file.
00001 /* $Id: order_cmd.cpp 26267 2014-01-19 09:27:44Z fonsinchen $ */
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 
00088 void Order::MakeGoToDepot(DepotID destination, OrderDepotTypeFlags order, OrderNonStopFlags non_stop_type, OrderDepotActionFlags action, CargoID cargo)
00089 {
00090   this->type = OT_GOTO_DEPOT;
00091   this->SetDepotOrderType(order);
00092   this->SetDepotActionType(action);
00093   this->SetNonStopType(non_stop_type);
00094   this->dest = destination;
00095   this->SetRefit(cargo);
00096 }
00097 
00102 void Order::MakeGoToWaypoint(StationID destination)
00103 {
00104   this->type = OT_GOTO_WAYPOINT;
00105   this->flags = 0;
00106   this->dest = destination;
00107 }
00108 
00113 void Order::MakeLoading(bool ordered)
00114 {
00115   this->type = OT_LOADING;
00116   if (!ordered) this->flags = 0;
00117 }
00118 
00122 void Order::MakeLeaveStation()
00123 {
00124   this->type = OT_LEAVESTATION;
00125   this->flags = 0;
00126 }
00127 
00131 void Order::MakeDummy()
00132 {
00133   this->type = OT_DUMMY;
00134   this->flags = 0;
00135 }
00136 
00141 void Order::MakeConditional(VehicleOrderID order)
00142 {
00143   this->type = OT_CONDITIONAL;
00144   this->flags = order;
00145   this->dest = 0;
00146 }
00147 
00152 void Order::MakeImplicit(StationID destination)
00153 {
00154   this->type = OT_IMPLICIT;
00155   this->dest = destination;
00156 }
00157 
00163 void Order::SetRefit(CargoID cargo)
00164 {
00165   this->refit_cargo = cargo;
00166 }
00167 
00173 bool Order::Equals(const Order &other) const
00174 {
00175   /* In case of go to nearest depot orders we need "only" compare the flags
00176    * with the other and not the nearest depot order bit or the actual
00177    * destination because those get clear/filled in during the order
00178    * evaluation. If we do not do this the order will continuously be seen as
00179    * a different order and it will try to find a "nearest depot" every tick. */
00180   if ((this->IsType(OT_GOTO_DEPOT) && this->type == other.type) &&
00181       ((this->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0 ||
00182        (other.GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0)) {
00183     return this->GetDepotOrderType() == other.GetDepotOrderType() &&
00184         (this->GetDepotActionType() & ~ODATFB_NEAREST_DEPOT) == (other.GetDepotActionType() & ~ODATFB_NEAREST_DEPOT);
00185   }
00186 
00187   return this->type == other.type && this->flags == other.flags && this->dest == other.dest;
00188 }
00189 
00196 uint32 Order::Pack() const
00197 {
00198   return this->dest << 16 | this->flags << 8 | this->type;
00199 }
00200 
00206 uint16 Order::MapOldOrder() const
00207 {
00208   uint16 order = this->GetType();
00209   switch (this->type) {
00210     case OT_GOTO_STATION:
00211       if (this->GetUnloadType() & OUFB_UNLOAD) SetBit(order, 5);
00212       if (this->GetLoadType() & OLFB_FULL_LOAD) SetBit(order, 6);
00213       if (this->GetNonStopType() & ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS) SetBit(order, 7);
00214       order |= GB(this->GetDestination(), 0, 8) << 8;
00215       break;
00216     case OT_GOTO_DEPOT:
00217       if (!(this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) SetBit(order, 6);
00218       SetBit(order, 7);
00219       order |= GB(this->GetDestination(), 0, 8) << 8;
00220       break;
00221     case OT_LOADING:
00222       if (this->GetLoadType() & OLFB_FULL_LOAD) SetBit(order, 6);
00223       break;
00224   }
00225   return order;
00226 }
00227 
00232 Order::Order(uint32 packed)
00233 {
00234   this->type    = (OrderType)GB(packed,  0,  8);
00235   this->flags   = GB(packed,  8,  8);
00236   this->dest    = GB(packed, 16, 16);
00237   this->next    = NULL;
00238   this->refit_cargo   = CT_NO_REFIT;
00239   this->wait_time     = 0;
00240   this->travel_time   = 0;
00241   this->max_speed     = UINT16_MAX;
00242 }
00243 
00249 void InvalidateVehicleOrder(const Vehicle *v, int data)
00250 {
00251   SetWindowDirty(WC_VEHICLE_VIEW, v->index);
00252 
00253   if (data != 0) {
00254     /* Calls SetDirty() too */
00255     InvalidateWindowData(WC_VEHICLE_ORDERS,    v->index, data);
00256     InvalidateWindowData(WC_VEHICLE_TIMETABLE, v->index, data);
00257     return;
00258   }
00259 
00260   SetWindowDirty(WC_VEHICLE_ORDERS,    v->index);
00261   SetWindowDirty(WC_VEHICLE_TIMETABLE, v->index);
00262 }
00263 
00271 void Order::AssignOrder(const Order &other)
00272 {
00273   this->type  = other.type;
00274   this->flags = other.flags;
00275   this->dest  = other.dest;
00276 
00277   this->refit_cargo   = other.refit_cargo;
00278 
00279   this->wait_time   = other.wait_time;
00280   this->travel_time = other.travel_time;
00281   this->max_speed   = other.max_speed;
00282 }
00283 
00289 void OrderList::Initialize(Order *chain, Vehicle *v)
00290 {
00291   this->first = chain;
00292   this->first_shared = v;
00293 
00294   this->num_orders = 0;
00295   this->num_manual_orders = 0;
00296   this->num_vehicles = 1;
00297   this->timetable_duration = 0;
00298 
00299   for (Order *o = this->first; o != NULL; o = o->next) {
00300     ++this->num_orders;
00301     if (!o->IsType(OT_IMPLICIT)) ++this->num_manual_orders;
00302     this->timetable_duration += o->wait_time + o->travel_time;
00303   }
00304 
00305   for (Vehicle *u = this->first_shared->PreviousShared(); u != NULL; u = u->PreviousShared()) {
00306     ++this->num_vehicles;
00307     this->first_shared = u;
00308   }
00309 
00310   for (const Vehicle *u = v->NextShared(); u != NULL; u = u->NextShared()) ++this->num_vehicles;
00311 }
00312 
00318 void OrderList::FreeChain(bool keep_orderlist)
00319 {
00320   Order *next;
00321   for (Order *o = this->first; o != NULL; o = next) {
00322     next = o->next;
00323     delete o;
00324   }
00325 
00326   if (keep_orderlist) {
00327     this->first = NULL;
00328     this->num_orders = 0;
00329     this->num_manual_orders = 0;
00330     this->timetable_duration = 0;
00331   } else {
00332     delete this;
00333   }
00334 }
00335 
00341 Order *OrderList::GetOrderAt(int index) const
00342 {
00343   if (index < 0) return NULL;
00344 
00345   Order *order = this->first;
00346 
00347   while (order != NULL && index-- > 0) {
00348     order = order->next;
00349   }
00350   return order;
00351 }
00352 
00364 const Order *OrderList::GetNextDecisionNode(const Order *next, uint hops) const
00365 {
00366   if (hops > this->GetNumOrders() || next == NULL) return NULL;
00367 
00368   if (next->IsType(OT_CONDITIONAL)) {
00369     if (next->GetConditionVariable() != OCV_UNCONDITIONALLY) return next;
00370 
00371     /* We can evaluate trivial conditions right away. They're conceptually
00372      * the same as regular order progression. */
00373     return this->GetNextDecisionNode(
00374         this->GetOrderAt(next->GetConditionSkipToOrder()),
00375         hops + 1);
00376   }
00377 
00378   if (next->IsType(OT_GOTO_DEPOT)) {
00379     if (next->GetDepotActionType() == ODATFB_HALT) return NULL;
00380     if (next->IsRefit()) return next;
00381   }
00382 
00383   if (!next->CanLoadOrUnload()) {
00384     return this->GetNextDecisionNode(this->GetNext(next), hops + 1);
00385   }
00386 
00387   return next;
00388 }
00389 
00399 StationIDStack OrderList::GetNextStoppingStation(const Vehicle *v, const Order *first, uint hops) const
00400 {
00401 
00402   const Order *next = first;
00403   if (first == NULL) {
00404     next = this->GetOrderAt(v->cur_implicit_order_index);
00405     if (next == NULL) {
00406       next = this->GetFirstOrder();
00407       if (next == NULL) return INVALID_STATION;
00408     } else {
00409       /* GetNext never returns NULL if there is a valid station in the list.
00410        * As the given "next" is already valid and a station in the list, we
00411        * don't have to check for NULL here. */
00412       next = this->GetNext(next);
00413       assert(next != NULL);
00414     }
00415   }
00416 
00417   do {
00418     next = this->GetNextDecisionNode(next, ++hops);
00419 
00420     /* Resolve possibly nested conditionals by estimation. */
00421     while (next != NULL && next->IsType(OT_CONDITIONAL)) {
00422       /* We return both options of conditional orders. */
00423       const Order *skip_to = this->GetNextDecisionNode(
00424           this->GetOrderAt(next->GetConditionSkipToOrder()), hops);
00425       const Order *advance = this->GetNextDecisionNode(
00426           this->GetNext(next), hops);
00427       if (advance == NULL || advance == first || skip_to == advance) {
00428         next = (skip_to == first) ? NULL : skip_to;
00429       } else if (skip_to == NULL || skip_to == first) {
00430         next = (advance == first) ? NULL : advance;
00431       } else {
00432         StationIDStack st1 = this->GetNextStoppingStation(v, skip_to, hops);
00433         StationIDStack st2 = this->GetNextStoppingStation(v, advance, hops);
00434         while (!st2.IsEmpty()) st1.Push(st2.Pop());
00435         return st1;
00436       }
00437       ++hops;
00438     }
00439 
00440     /* Don't return a next stop if the vehicle has to unload everything. */
00441     if (next == NULL || ((next->IsType(OT_GOTO_STATION) || next->IsType(OT_IMPLICIT)) &&
00442         next->GetDestination() == v->last_station_visited &&
00443         (next->GetUnloadType() & (OUFB_TRANSFER | OUFB_UNLOAD)) != 0)) {
00444       return INVALID_STATION;
00445     }
00446   } while (next->IsType(OT_GOTO_DEPOT) || next->GetDestination() == v->last_station_visited);
00447 
00448   return next->GetDestination();
00449 }
00450 
00456 void OrderList::InsertOrderAt(Order *new_order, int index)
00457 {
00458   if (this->first == NULL) {
00459     this->first = new_order;
00460   } else {
00461     if (index == 0) {
00462       /* Insert as first or only order */
00463       new_order->next = this->first;
00464       this->first = new_order;
00465     } else if (index >= this->num_orders) {
00466       /* index is after the last order, add it to the end */
00467       this->GetLastOrder()->next = new_order;
00468     } else {
00469       /* Put the new order in between */
00470       Order *order = this->GetOrderAt(index - 1);
00471       new_order->next = order->next;
00472       order->next = new_order;
00473     }
00474   }
00475   ++this->num_orders;
00476   if (!new_order->IsType(OT_IMPLICIT)) ++this->num_manual_orders;
00477   this->timetable_duration += new_order->wait_time + new_order->travel_time;
00478 
00479   /* We can visit oil rigs and buoys that are not our own. They will be shown in
00480    * the list of stations. So, we need to invalidate that window if needed. */
00481   if (new_order->IsType(OT_GOTO_STATION) || new_order->IsType(OT_GOTO_WAYPOINT)) {
00482     BaseStation *bs = BaseStation::Get(new_order->GetDestination());
00483     if (bs->owner == OWNER_NONE) InvalidateWindowClassesData(WC_STATION_LIST, 0);
00484   }
00485 
00486 }
00487 
00488 
00493 void OrderList::DeleteOrderAt(int index)
00494 {
00495   if (index >= this->num_orders) return;
00496 
00497   Order *to_remove;
00498 
00499   if (index == 0) {
00500     to_remove = this->first;
00501     this->first = to_remove->next;
00502   } else {
00503     Order *prev = GetOrderAt(index - 1);
00504     to_remove = prev->next;
00505     prev->next = to_remove->next;
00506   }
00507   --this->num_orders;
00508   if (!to_remove->IsType(OT_IMPLICIT)) --this->num_manual_orders;
00509   this->timetable_duration -= (to_remove->wait_time + to_remove->travel_time);
00510   delete to_remove;
00511 }
00512 
00518 void OrderList::MoveOrder(int from, int to)
00519 {
00520   if (from >= this->num_orders || to >= this->num_orders || from == to) return;
00521 
00522   Order *moving_one;
00523 
00524   /* Take the moving order out of the pointer-chain */
00525   if (from == 0) {
00526     moving_one = this->first;
00527     this->first = moving_one->next;
00528   } else {
00529     Order *one_before = GetOrderAt(from - 1);
00530     moving_one = one_before->next;
00531     one_before->next = moving_one->next;
00532   }
00533 
00534   /* Insert the moving_order again in the pointer-chain */
00535   if (to == 0) {
00536     moving_one->next = this->first;
00537     this->first = moving_one;
00538   } else {
00539     Order *one_before = GetOrderAt(to - 1);
00540     moving_one->next = one_before->next;
00541     one_before->next = moving_one;
00542   }
00543 }
00544 
00550 void OrderList::RemoveVehicle(Vehicle *v)
00551 {
00552   --this->num_vehicles;
00553   if (v == this->first_shared) this->first_shared = v->NextShared();
00554 }
00555 
00560 bool OrderList::IsVehicleInSharedOrdersList(const Vehicle *v) const
00561 {
00562   for (const Vehicle *v_shared = this->first_shared; v_shared != NULL; v_shared = v_shared->NextShared()) {
00563     if (v_shared == v) return true;
00564   }
00565 
00566   return false;
00567 }
00568 
00574 int OrderList::GetPositionInSharedOrderList(const Vehicle *v) const
00575 {
00576   int count = 0;
00577   for (const Vehicle *v_shared = v->PreviousShared(); v_shared != NULL; v_shared = v_shared->PreviousShared()) count++;
00578   return count;
00579 }
00580 
00585 bool OrderList::IsCompleteTimetable() const
00586 {
00587   for (Order *o = this->first; o != NULL; o = o->next) {
00588     /* Implicit orders are, by definition, not timetabled. */
00589     if (o->IsType(OT_IMPLICIT)) continue;
00590     if (!o->IsCompletelyTimetabled()) return false;
00591   }
00592   return true;
00593 }
00594 
00598 void OrderList::DebugCheckSanity() const
00599 {
00600   VehicleOrderID check_num_orders = 0;
00601   VehicleOrderID check_num_manual_orders = 0;
00602   uint check_num_vehicles = 0;
00603   Ticks check_timetable_duration = 0;
00604 
00605   DEBUG(misc, 6, "Checking OrderList %hu for sanity...", this->index);
00606 
00607   for (const Order *o = this->first; o != NULL; o = o->next) {
00608     ++check_num_orders;
00609     if (!o->IsType(OT_IMPLICIT)) ++check_num_manual_orders;
00610     check_timetable_duration += o->wait_time + o->travel_time;
00611   }
00612   assert(this->num_orders == check_num_orders);
00613   assert(this->num_manual_orders == check_num_manual_orders);
00614   assert(this->timetable_duration == check_timetable_duration);
00615 
00616   for (const Vehicle *v = this->first_shared; v != NULL; v = v->NextShared()) {
00617     ++check_num_vehicles;
00618     assert(v->orders.list == this);
00619   }
00620   assert(this->num_vehicles == check_num_vehicles);
00621   DEBUG(misc, 6, "... detected %u orders (%u manual), %u vehicles, %i ticks",
00622       (uint)this->num_orders, (uint)this->num_manual_orders,
00623       this->num_vehicles, this->timetable_duration);
00624 }
00625 
00633 static inline bool OrderGoesToStation(const Vehicle *v, const Order *o)
00634 {
00635   return o->IsType(OT_GOTO_STATION) ||
00636       (v->type == VEH_AIRCRAFT && o->IsType(OT_GOTO_DEPOT) && !(o->GetDepotActionType() & ODATFB_NEAREST_DEPOT));
00637 }
00638 
00645 static void DeleteOrderWarnings(const Vehicle *v)
00646 {
00647   DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_TOO_FEW_ORDERS);
00648   DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_VOID_ORDER);
00649   DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_DUPLICATE_ENTRY);
00650   DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_INVALID_ENTRY);
00651 }
00652 
00659 TileIndex Order::GetLocation(const Vehicle *v, bool airport) const
00660 {
00661   switch (this->GetType()) {
00662     case OT_GOTO_WAYPOINT:
00663     case OT_GOTO_STATION:
00664     case OT_IMPLICIT:
00665       if (airport && v->type == VEH_AIRCRAFT) return Station::Get(this->GetDestination())->airport.tile;
00666       return BaseStation::Get(this->GetDestination())->xy;
00667 
00668     case OT_GOTO_DEPOT:
00669       if ((this->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0) return INVALID_TILE;
00670       return (v->type == VEH_AIRCRAFT) ? Station::Get(this->GetDestination())->xy : Depot::Get(this->GetDestination())->xy;
00671 
00672     default:
00673       return INVALID_TILE;
00674   }
00675 }
00676 
00686 uint GetOrderDistance(const Order *prev, const Order *cur, const Vehicle *v, int conditional_depth)
00687 {
00688   if (cur->IsType(OT_CONDITIONAL)) {
00689     if (conditional_depth > v->GetNumOrders()) return 0;
00690 
00691     conditional_depth++;
00692 
00693     int dist1 = GetOrderDistance(prev, v->GetOrder(cur->GetConditionSkipToOrder()), v, conditional_depth);
00694     int dist2 = GetOrderDistance(prev, cur->next == NULL ? v->orders.list->GetFirstOrder() : cur->next, v, conditional_depth);
00695     return max(dist1, dist2);
00696   }
00697 
00698   TileIndex prev_tile = prev->GetLocation(v, true);
00699   TileIndex cur_tile = cur->GetLocation(v, true);
00700   if (prev_tile == INVALID_TILE || cur_tile == INVALID_TILE) return 0;
00701   return v->type == VEH_AIRCRAFT ? DistanceSquare(prev_tile, cur_tile) : DistanceManhattan(prev_tile, cur_tile);
00702 }
00703 
00717 CommandCost CmdInsertOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00718 {
00719   VehicleID veh          = GB(p1,  0, 20);
00720   VehicleOrderID sel_ord = GB(p1, 20, 8);
00721   Order new_order(p2);
00722 
00723   Vehicle *v = Vehicle::GetIfValid(veh);
00724   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
00725 
00726   CommandCost ret = CheckOwnership(v->owner);
00727   if (ret.Failed()) return ret;
00728 
00729   /* Check if the inserted order is to the correct destination (owner, type),
00730    * and has the correct flags if any */
00731   switch (new_order.GetType()) {
00732     case OT_GOTO_STATION: {
00733       const Station *st = Station::GetIfValid(new_order.GetDestination());
00734       if (st == NULL) return CMD_ERROR;
00735 
00736       if (st->owner != OWNER_NONE) {
00737         CommandCost ret = CheckOwnership(st->owner);
00738         if (ret.Failed()) return ret;
00739       }
00740 
00741       if (!CanVehicleUseStation(v, st)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
00742       for (Vehicle *u = v->FirstShared(); u != NULL; u = u->NextShared()) {
00743         if (!CanVehicleUseStation(u, st)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER_SHARED);
00744       }
00745 
00746       /* Non stop only allowed for ground vehicles. */
00747       if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && !v->IsGroundVehicle()) return CMD_ERROR;
00748 
00749       /* Filter invalid load/unload types. */
00750       switch (new_order.GetLoadType()) {
00751         case OLF_LOAD_IF_POSSIBLE: case OLFB_FULL_LOAD: case OLF_FULL_LOAD_ANY: case OLFB_NO_LOAD: break;
00752         default: return CMD_ERROR;
00753       }
00754       switch (new_order.GetUnloadType()) {
00755         case OUF_UNLOAD_IF_POSSIBLE: case OUFB_UNLOAD: case OUFB_TRANSFER: case OUFB_NO_UNLOAD: break;
00756         default: return CMD_ERROR;
00757       }
00758 
00759       /* Filter invalid stop locations */
00760       switch (new_order.GetStopLocation()) {
00761         case OSL_PLATFORM_NEAR_END:
00762         case OSL_PLATFORM_MIDDLE:
00763           if (v->type != VEH_TRAIN) return CMD_ERROR;
00764           /* FALL THROUGH */
00765         case OSL_PLATFORM_FAR_END:
00766           break;
00767 
00768         default:
00769           return CMD_ERROR;
00770       }
00771 
00772       break;
00773     }
00774 
00775     case OT_GOTO_DEPOT: {
00776       if ((new_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) == 0) {
00777         if (v->type == VEH_AIRCRAFT) {
00778           const Station *st = Station::GetIfValid(new_order.GetDestination());
00779 
00780           if (st == NULL) return CMD_ERROR;
00781 
00782           CommandCost ret = CheckOwnership(st->owner);
00783           if (ret.Failed()) return ret;
00784 
00785           if (!CanVehicleUseStation(v, st) || !st->airport.HasHangar()) {
00786             return CMD_ERROR;
00787           }
00788         } else {
00789           const Depot *dp = Depot::GetIfValid(new_order.GetDestination());
00790 
00791           if (dp == NULL) return CMD_ERROR;
00792 
00793           CommandCost ret = CheckOwnership(GetTileOwner(dp->xy));
00794           if (ret.Failed()) return ret;
00795 
00796           switch (v->type) {
00797             case VEH_TRAIN:
00798               if (!IsRailDepotTile(dp->xy)) return CMD_ERROR;
00799               break;
00800 
00801             case VEH_ROAD:
00802               if (!IsRoadDepotTile(dp->xy)) return CMD_ERROR;
00803               break;
00804 
00805             case VEH_SHIP:
00806               if (!IsShipDepotTile(dp->xy)) return CMD_ERROR;
00807               break;
00808 
00809             default: return CMD_ERROR;
00810           }
00811         }
00812       }
00813 
00814       if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && !v->IsGroundVehicle()) return CMD_ERROR;
00815       if (new_order.GetDepotOrderType() & ~(ODTFB_PART_OF_ORDERS | ((new_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS) != 0 ? ODTFB_SERVICE : 0))) return CMD_ERROR;
00816       if (new_order.GetDepotActionType() & ~(ODATFB_HALT | ODATFB_NEAREST_DEPOT)) return CMD_ERROR;
00817       if ((new_order.GetDepotOrderType() & ODTFB_SERVICE) && (new_order.GetDepotActionType() & ODATFB_HALT)) return CMD_ERROR;
00818       break;
00819     }
00820 
00821     case OT_GOTO_WAYPOINT: {
00822       const Waypoint *wp = Waypoint::GetIfValid(new_order.GetDestination());
00823       if (wp == NULL) return CMD_ERROR;
00824 
00825       switch (v->type) {
00826         default: return CMD_ERROR;
00827 
00828         case VEH_TRAIN: {
00829           if (!(wp->facilities & FACIL_TRAIN)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
00830 
00831           CommandCost ret = CheckOwnership(wp->owner);
00832           if (ret.Failed()) return ret;
00833           break;
00834         }
00835 
00836         case VEH_SHIP:
00837           if (!(wp->facilities & FACIL_DOCK)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
00838           if (wp->owner != OWNER_NONE) {
00839             CommandCost ret = CheckOwnership(wp->owner);
00840             if (ret.Failed()) return ret;
00841           }
00842           break;
00843       }
00844 
00845       /* Order flags can be any of the following for waypoints:
00846        * [non-stop]
00847        * non-stop orders (if any) are only valid for trains */
00848       if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && v->type != VEH_TRAIN) return CMD_ERROR;
00849       break;
00850     }
00851 
00852     case OT_CONDITIONAL: {
00853       VehicleOrderID skip_to = new_order.GetConditionSkipToOrder();
00854       if (skip_to != 0 && skip_to >= v->GetNumOrders()) return CMD_ERROR; // Always allow jumping to the first (even when there is no order).
00855       if (new_order.GetConditionVariable() >= OCV_END) return CMD_ERROR;
00856 
00857       OrderConditionComparator occ = new_order.GetConditionComparator();
00858       if (occ >= OCC_END) return CMD_ERROR;
00859       switch (new_order.GetConditionVariable()) {
00860         case OCV_REQUIRES_SERVICE:
00861           if (occ != OCC_IS_TRUE && occ != OCC_IS_FALSE) return CMD_ERROR;
00862           break;
00863 
00864         case OCV_UNCONDITIONALLY:
00865           if (occ != OCC_EQUALS) return CMD_ERROR;
00866           if (new_order.GetConditionValue() != 0) return CMD_ERROR;
00867           break;
00868 
00869         case OCV_LOAD_PERCENTAGE:
00870         case OCV_RELIABILITY:
00871           if (new_order.GetConditionValue() > 100) return CMD_ERROR;
00872           /* FALL THROUGH */
00873         default:
00874           if (occ == OCC_IS_TRUE || occ == OCC_IS_FALSE) return CMD_ERROR;
00875           break;
00876       }
00877       break;
00878     }
00879 
00880     default: return CMD_ERROR;
00881   }
00882 
00883   if (sel_ord > v->GetNumOrders()) return CMD_ERROR;
00884 
00885   if (v->GetNumOrders() >= MAX_VEH_ORDER_ID) return_cmd_error(STR_ERROR_TOO_MANY_ORDERS);
00886   if (!Order::CanAllocateItem()) return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
00887   if (v->orders.list == NULL && !OrderList::CanAllocateItem()) return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
00888 
00889   if (v->type == VEH_SHIP && _settings_game.pf.pathfinder_for_ships != VPF_NPF) {
00890     /* Make sure the new destination is not too far away from the previous */
00891     const Order *prev = NULL;
00892     uint n = 0;
00893 
00894     /* Find the last goto station or depot order before the insert location.
00895      * If the order is to be inserted at the beginning of the order list this
00896      * finds the last order in the list. */
00897     const Order *o;
00898     FOR_VEHICLE_ORDERS(v, o) {
00899       switch (o->GetType()) {
00900         case OT_GOTO_STATION:
00901         case OT_GOTO_DEPOT:
00902         case OT_GOTO_WAYPOINT:
00903           prev = o;
00904           break;
00905 
00906         default: break;
00907       }
00908       if (++n == sel_ord && prev != NULL) break;
00909     }
00910     if (prev != NULL) {
00911       uint dist;
00912       if (new_order.IsType(OT_CONDITIONAL)) {
00913         /* The order is not yet inserted, so we have to do the first iteration here. */
00914         dist = GetOrderDistance(prev, v->GetOrder(new_order.GetConditionSkipToOrder()), v);
00915       } else {
00916         dist = GetOrderDistance(prev, &new_order, v);
00917       }
00918 
00919       if (dist >= 130) {
00920         return_cmd_error(STR_ERROR_TOO_FAR_FROM_PREVIOUS_DESTINATION);
00921       }
00922     }
00923   }
00924 
00925   if (flags & DC_EXEC) {
00926     Order *new_o = new Order();
00927     new_o->AssignOrder(new_order);
00928     InsertOrder(v, new_o, sel_ord);
00929   }
00930 
00931   return CommandCost();
00932 }
00933 
00940 void InsertOrder(Vehicle *v, Order *new_o, VehicleOrderID sel_ord)
00941 {
00942   /* Create new order and link in list */
00943   if (v->orders.list == NULL) {
00944     v->orders.list = new OrderList(new_o, v);
00945   } else {
00946     v->orders.list->InsertOrderAt(new_o, sel_ord);
00947   }
00948 
00949   Vehicle *u = v->FirstShared();
00950   DeleteOrderWarnings(u);
00951   for (; u != NULL; u = u->NextShared()) {
00952     assert(v->orders.list == u->orders.list);
00953 
00954     /* If there is added an order before the current one, we need
00955      * to update the selected order. We do not change implicit/real order indices though.
00956      * If the new order is between the current implicit order and real order, the implicit order will
00957      * later skip the inserted order. */
00958     if (sel_ord <= u->cur_real_order_index) {
00959       uint cur = u->cur_real_order_index + 1;
00960       /* Check if we don't go out of bound */
00961       if (cur < u->GetNumOrders()) {
00962         u->cur_real_order_index = cur;
00963       }
00964     }
00965     if (sel_ord == u->cur_implicit_order_index && u->IsGroundVehicle()) {
00966       /* We are inserting an order just before the current implicit order.
00967        * We do not know whether we will reach current implicit or the newly inserted order first.
00968        * So, disable creation of implicit orders until we are on track again. */
00969       uint16 &gv_flags = u->GetGroundVehicleFlags();
00970       SetBit(gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
00971     }
00972     if (sel_ord <= u->cur_implicit_order_index) {
00973       uint cur = u->cur_implicit_order_index + 1;
00974       /* Check if we don't go out of bound */
00975       if (cur < u->GetNumOrders()) {
00976         u->cur_implicit_order_index = cur;
00977       }
00978     }
00979     /* Update any possible open window of the vehicle */
00980     InvalidateVehicleOrder(u, INVALID_VEH_ORDER_ID | (sel_ord << 8));
00981   }
00982 
00983   /* As we insert an order, the order to skip to will be 'wrong'. */
00984   VehicleOrderID cur_order_id = 0;
00985   Order *order;
00986   FOR_VEHICLE_ORDERS(v, order) {
00987     if (order->IsType(OT_CONDITIONAL)) {
00988       VehicleOrderID order_id = order->GetConditionSkipToOrder();
00989       if (order_id >= sel_ord) {
00990         order->SetConditionSkipToOrder(order_id + 1);
00991       }
00992       if (order_id == cur_order_id) {
00993         order->SetConditionSkipToOrder((order_id + 1) % v->GetNumOrders());
00994       }
00995     }
00996     cur_order_id++;
00997   }
00998 
00999   /* Make sure to rebuild the whole list */
01000   InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
01001 }
01002 
01008 static CommandCost DecloneOrder(Vehicle *dst, DoCommandFlag flags)
01009 {
01010   if (flags & DC_EXEC) {
01011     DeleteVehicleOrders(dst);
01012     InvalidateVehicleOrder(dst, VIWD_REMOVE_ALL_ORDERS);
01013     InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
01014   }
01015   return CommandCost();
01016 }
01017 
01027 CommandCost CmdDeleteOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01028 {
01029   VehicleID veh_id = GB(p1, 0, 20);
01030   VehicleOrderID sel_ord = GB(p2, 0, 8);
01031 
01032   Vehicle *v = Vehicle::GetIfValid(veh_id);
01033 
01034   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01035 
01036   CommandCost ret = CheckOwnership(v->owner);
01037   if (ret.Failed()) return ret;
01038 
01039   /* If we did not select an order, we maybe want to de-clone the orders */
01040   if (sel_ord >= v->GetNumOrders()) return DecloneOrder(v, flags);
01041 
01042   if (v->GetOrder(sel_ord) == NULL) return CMD_ERROR;
01043 
01044   if (flags & DC_EXEC) DeleteOrder(v, sel_ord);
01045   return CommandCost();
01046 }
01047 
01052 static void CancelLoadingDueToDeletedOrder(Vehicle *v)
01053 {
01054   assert(v->current_order.IsType(OT_LOADING));
01055   /* NON-stop flag is misused to see if a train is in a station that is
01056    * on his order list or not */
01057   v->current_order.SetNonStopType(ONSF_STOP_EVERYWHERE);
01058   /* When full loading, "cancel" that order so the vehicle doesn't
01059    * stay indefinitely at this station anymore. */
01060   if (v->current_order.GetLoadType() & OLFB_FULL_LOAD) v->current_order.SetLoadType(OLF_LOAD_IF_POSSIBLE);
01061 }
01062 
01068 void DeleteOrder(Vehicle *v, VehicleOrderID sel_ord)
01069 {
01070   v->orders.list->DeleteOrderAt(sel_ord);
01071 
01072   Vehicle *u = v->FirstShared();
01073   DeleteOrderWarnings(u);
01074   for (; u != NULL; u = u->NextShared()) {
01075     assert(v->orders.list == u->orders.list);
01076 
01077     if (sel_ord == u->cur_real_order_index && u->current_order.IsType(OT_LOADING)) {
01078       CancelLoadingDueToDeletedOrder(u);
01079     }
01080 
01081     if (sel_ord < u->cur_real_order_index) {
01082       u->cur_real_order_index--;
01083     } else if (sel_ord == u->cur_real_order_index) {
01084       u->UpdateRealOrderIndex();
01085     }
01086 
01087     if (sel_ord < u->cur_implicit_order_index) {
01088       u->cur_implicit_order_index--;
01089     } else if (sel_ord == u->cur_implicit_order_index) {
01090       /* Make sure the index is valid */
01091       if (u->cur_implicit_order_index >= u->GetNumOrders()) u->cur_implicit_order_index = 0;
01092 
01093       /* Skip non-implicit orders for the implicit-order-index (e.g. if the current implicit order was deleted */
01094       while (u->cur_implicit_order_index != u->cur_real_order_index && !u->GetOrder(u->cur_implicit_order_index)->IsType(OT_IMPLICIT)) {
01095         u->cur_implicit_order_index++;
01096         if (u->cur_implicit_order_index >= u->GetNumOrders()) u->cur_implicit_order_index = 0;
01097       }
01098     }
01099 
01100     /* Update any possible open window of the vehicle */
01101     InvalidateVehicleOrder(u, sel_ord | (INVALID_VEH_ORDER_ID << 8));
01102   }
01103 
01104   /* As we delete an order, the order to skip to will be 'wrong'. */
01105   VehicleOrderID cur_order_id = 0;
01106   Order *order = NULL;
01107   FOR_VEHICLE_ORDERS(v, order) {
01108     if (order->IsType(OT_CONDITIONAL)) {
01109       VehicleOrderID order_id = order->GetConditionSkipToOrder();
01110       if (order_id >= sel_ord) {
01111         order_id = max(order_id - 1, 0);
01112       }
01113       if (order_id == cur_order_id) {
01114         order_id = (order_id + 1) % v->GetNumOrders();
01115       }
01116       order->SetConditionSkipToOrder(order_id);
01117     }
01118     cur_order_id++;
01119   }
01120 
01121   InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
01122 }
01123 
01133 CommandCost CmdSkipToOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01134 {
01135   VehicleID veh_id = GB(p1, 0, 20);
01136   VehicleOrderID sel_ord = GB(p2, 0, 8);
01137 
01138   Vehicle *v = Vehicle::GetIfValid(veh_id);
01139 
01140   if (v == NULL || !v->IsPrimaryVehicle() || sel_ord == v->cur_implicit_order_index || sel_ord >= v->GetNumOrders() || v->GetNumOrders() < 2) return CMD_ERROR;
01141 
01142   CommandCost ret = CheckOwnership(v->owner);
01143   if (ret.Failed()) return ret;
01144 
01145   if (flags & DC_EXEC) {
01146     if (v->current_order.IsType(OT_LOADING)) v->LeaveStation();
01147 
01148     v->cur_implicit_order_index = v->cur_real_order_index = sel_ord;
01149     v->UpdateRealOrderIndex();
01150 
01151     InvalidateVehicleOrder(v, VIWD_MODIFY_ORDERS);
01152   }
01153 
01154   /* We have an aircraft/ship, they have a mini-schedule, so update them all */
01155   if (v->type == VEH_AIRCRAFT) SetWindowClassesDirty(WC_AIRCRAFT_LIST);
01156   if (v->type == VEH_SHIP) SetWindowClassesDirty(WC_SHIPS_LIST);
01157 
01158   return CommandCost();
01159 }
01160 
01174 CommandCost CmdMoveOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01175 {
01176   VehicleID veh = GB(p1, 0, 20);
01177   VehicleOrderID moving_order = GB(p2,  0, 16);
01178   VehicleOrderID target_order = GB(p2, 16, 16);
01179 
01180   Vehicle *v = Vehicle::GetIfValid(veh);
01181   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01182 
01183   CommandCost ret = CheckOwnership(v->owner);
01184   if (ret.Failed()) return ret;
01185 
01186   /* Don't make senseless movements */
01187   if (moving_order >= v->GetNumOrders() || target_order >= v->GetNumOrders() ||
01188       moving_order == target_order || v->GetNumOrders() <= 1) return CMD_ERROR;
01189 
01190   Order *moving_one = v->GetOrder(moving_order);
01191   /* Don't move an empty order */
01192   if (moving_one == NULL) return CMD_ERROR;
01193 
01194   if (flags & DC_EXEC) {
01195     v->orders.list->MoveOrder(moving_order, target_order);
01196 
01197     /* Update shared list */
01198     Vehicle *u = v->FirstShared();
01199 
01200     DeleteOrderWarnings(u);
01201 
01202     for (; u != NULL; u = u->NextShared()) {
01203       /* Update the current order.
01204        * There are multiple ways to move orders, which result in cur_implicit_order_index
01205        * and cur_real_order_index to not longer make any sense. E.g. moving another
01206        * real order between them.
01207        *
01208        * Basically one could choose to preserve either of them, but not both.
01209        * While both ways are suitable in this or that case from a human point of view, neither
01210        * of them makes really sense.
01211        * However, from an AI point of view, preserving cur_real_order_index is the most
01212        * predictable and transparent behaviour.
01213        *
01214        * With that decision it basically does not matter what we do to cur_implicit_order_index.
01215        * If we change orders between the implicit- and real-index, the implicit orders are mostly likely
01216        * completely out-dated anyway. So, keep it simple and just keep cur_implicit_order_index as well.
01217        * The worst which can happen is that a lot of implicit orders are removed when reaching current_order.
01218        */
01219       if (u->cur_real_order_index == moving_order) {
01220         u->cur_real_order_index = target_order;
01221       } else if (u->cur_real_order_index > moving_order && u->cur_real_order_index <= target_order) {
01222         u->cur_real_order_index--;
01223       } else if (u->cur_real_order_index < moving_order && u->cur_real_order_index >= target_order) {
01224         u->cur_real_order_index++;
01225       }
01226 
01227       if (u->cur_implicit_order_index == moving_order) {
01228         u->cur_implicit_order_index = target_order;
01229       } else if (u->cur_implicit_order_index > moving_order && u->cur_implicit_order_index <= target_order) {
01230         u->cur_implicit_order_index--;
01231       } else if (u->cur_implicit_order_index < moving_order && u->cur_implicit_order_index >= target_order) {
01232         u->cur_implicit_order_index++;
01233       }
01234 
01235       assert(v->orders.list == u->orders.list);
01236       /* Update any possible open window of the vehicle */
01237       InvalidateVehicleOrder(u, moving_order | (target_order << 8));
01238     }
01239 
01240     /* As we move an order, the order to skip to will be 'wrong'. */
01241     Order *order;
01242     FOR_VEHICLE_ORDERS(v, order) {
01243       if (order->IsType(OT_CONDITIONAL)) {
01244         VehicleOrderID order_id = order->GetConditionSkipToOrder();
01245         if (order_id == moving_order) {
01246           order_id = target_order;
01247         } else if (order_id > moving_order && order_id <= target_order) {
01248           order_id--;
01249         } else if (order_id < moving_order && order_id >= target_order) {
01250           order_id++;
01251         }
01252         order->SetConditionSkipToOrder(order_id);
01253       }
01254     }
01255 
01256     /* Make sure to rebuild the whole list */
01257     InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
01258   }
01259 
01260   return CommandCost();
01261 }
01262 
01278 CommandCost CmdModifyOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01279 {
01280   VehicleOrderID sel_ord = GB(p1, 20,  8);
01281   VehicleID veh          = GB(p1,  0, 20);
01282   ModifyOrderFlags mof   = Extract<ModifyOrderFlags, 0, 4>(p2);
01283   uint16 data            = GB(p2,  4, 11);
01284 
01285   if (mof >= MOF_END) return CMD_ERROR;
01286 
01287   Vehicle *v = Vehicle::GetIfValid(veh);
01288   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01289 
01290   CommandCost ret = CheckOwnership(v->owner);
01291   if (ret.Failed()) return ret;
01292 
01293   /* Is it a valid order? */
01294   if (sel_ord >= v->GetNumOrders()) return CMD_ERROR;
01295 
01296   Order *order = v->GetOrder(sel_ord);
01297   switch (order->GetType()) {
01298     case OT_GOTO_STATION:
01299       if (mof == MOF_COND_VARIABLE || mof == MOF_COND_COMPARATOR || mof == MOF_DEPOT_ACTION || mof == MOF_COND_VALUE) return CMD_ERROR;
01300       break;
01301 
01302     case OT_GOTO_DEPOT:
01303       if (mof != MOF_NON_STOP && mof != MOF_DEPOT_ACTION) return CMD_ERROR;
01304       break;
01305 
01306     case OT_GOTO_WAYPOINT:
01307       if (mof != MOF_NON_STOP) return CMD_ERROR;
01308       break;
01309 
01310     case OT_CONDITIONAL:
01311       if (mof != MOF_COND_VARIABLE && mof != MOF_COND_COMPARATOR && mof != MOF_COND_VALUE && mof != MOF_COND_DESTINATION) return CMD_ERROR;
01312       break;
01313 
01314     default:
01315       return CMD_ERROR;
01316   }
01317 
01318   switch (mof) {
01319     default: NOT_REACHED();
01320 
01321     case MOF_NON_STOP:
01322       if (!v->IsGroundVehicle()) return CMD_ERROR;
01323       if (data >= ONSF_END) return CMD_ERROR;
01324       if (data == order->GetNonStopType()) return CMD_ERROR;
01325       break;
01326 
01327     case MOF_STOP_LOCATION:
01328       if (v->type != VEH_TRAIN) return CMD_ERROR;
01329       if (data >= OSL_END) return CMD_ERROR;
01330       break;
01331 
01332     case MOF_UNLOAD:
01333       if ((data & ~(OUFB_UNLOAD | OUFB_TRANSFER | OUFB_NO_UNLOAD)) != 0) return CMD_ERROR;
01334       /* Unload and no-unload are mutual exclusive and so are transfer and no unload. */
01335       if (data != 0 && ((data & (OUFB_UNLOAD | OUFB_TRANSFER)) != 0) == ((data & OUFB_NO_UNLOAD) != 0)) return CMD_ERROR;
01336       if (data == order->GetUnloadType()) return CMD_ERROR;
01337       break;
01338 
01339     case MOF_LOAD:
01340       if (data > OLFB_NO_LOAD || data == 1) return CMD_ERROR;
01341       if (data == order->GetLoadType()) return CMD_ERROR;
01342       break;
01343 
01344     case MOF_DEPOT_ACTION:
01345       if (data >= DA_END) return CMD_ERROR;
01346       break;
01347 
01348     case MOF_COND_VARIABLE:
01349       if (data >= OCV_END) return CMD_ERROR;
01350       break;
01351 
01352     case MOF_COND_COMPARATOR:
01353       if (data >= OCC_END) return CMD_ERROR;
01354       switch (order->GetConditionVariable()) {
01355         case OCV_UNCONDITIONALLY: return CMD_ERROR;
01356 
01357         case OCV_REQUIRES_SERVICE:
01358           if (data != OCC_IS_TRUE && data != OCC_IS_FALSE) return CMD_ERROR;
01359           break;
01360 
01361         default:
01362           if (data == OCC_IS_TRUE || data == OCC_IS_FALSE) return CMD_ERROR;
01363           break;
01364       }
01365       break;
01366 
01367     case MOF_COND_VALUE:
01368       switch (order->GetConditionVariable()) {
01369         case OCV_UNCONDITIONALLY: return CMD_ERROR;
01370 
01371         case OCV_LOAD_PERCENTAGE:
01372         case OCV_RELIABILITY:
01373           if (data > 100) return CMD_ERROR;
01374           break;
01375 
01376         default:
01377           if (data > 2047) return CMD_ERROR;
01378           break;
01379       }
01380       break;
01381 
01382     case MOF_COND_DESTINATION:
01383       if (data >= v->GetNumOrders()) return CMD_ERROR;
01384       break;
01385   }
01386 
01387   if (flags & DC_EXEC) {
01388     switch (mof) {
01389       case MOF_NON_STOP:
01390         order->SetNonStopType((OrderNonStopFlags)data);
01391         if (data & ONSF_NO_STOP_AT_DESTINATION_STATION) order->SetRefit(CT_NO_REFIT);
01392         break;
01393 
01394       case MOF_STOP_LOCATION:
01395         order->SetStopLocation((OrderStopLocation)data);
01396         break;
01397 
01398       case MOF_UNLOAD:
01399         order->SetUnloadType((OrderUnloadFlags)data);
01400         break;
01401 
01402       case MOF_LOAD:
01403         order->SetLoadType((OrderLoadFlags)data);
01404         if (data & OLFB_NO_LOAD) order->SetRefit(CT_NO_REFIT);
01405         break;
01406 
01407       case MOF_DEPOT_ACTION: {
01408         switch (data) {
01409           case DA_ALWAYS_GO:
01410             order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
01411             order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
01412             break;
01413 
01414           case DA_SERVICE:
01415             order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() | ODTFB_SERVICE));
01416             order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
01417             order->SetRefit(CT_NO_REFIT);
01418             break;
01419 
01420           case DA_STOP:
01421             order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
01422             order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() | ODATFB_HALT));
01423             order->SetRefit(CT_NO_REFIT);
01424             break;
01425 
01426           default:
01427             NOT_REACHED();
01428         }
01429         break;
01430       }
01431 
01432       case MOF_COND_VARIABLE: {
01433         order->SetConditionVariable((OrderConditionVariable)data);
01434 
01435         OrderConditionComparator occ = order->GetConditionComparator();
01436         switch (order->GetConditionVariable()) {
01437           case OCV_UNCONDITIONALLY:
01438             order->SetConditionComparator(OCC_EQUALS);
01439             order->SetConditionValue(0);
01440             break;
01441 
01442           case OCV_REQUIRES_SERVICE:
01443             if (occ != OCC_IS_TRUE && occ != OCC_IS_FALSE) order->SetConditionComparator(OCC_IS_TRUE);
01444             break;
01445 
01446           case OCV_LOAD_PERCENTAGE:
01447           case OCV_RELIABILITY:
01448             if (order->GetConditionValue() > 100) order->SetConditionValue(100);
01449             /* FALL THROUGH */
01450           default:
01451             if (occ == OCC_IS_TRUE || occ == OCC_IS_FALSE) order->SetConditionComparator(OCC_EQUALS);
01452             break;
01453         }
01454         break;
01455       }
01456 
01457       case MOF_COND_COMPARATOR:
01458         order->SetConditionComparator((OrderConditionComparator)data);
01459         break;
01460 
01461       case MOF_COND_VALUE:
01462         order->SetConditionValue(data);
01463         break;
01464 
01465       case MOF_COND_DESTINATION:
01466         order->SetConditionSkipToOrder(data);
01467         break;
01468 
01469       default: NOT_REACHED();
01470     }
01471 
01472     /* Update the windows and full load flags, also for vehicles that share the same order list */
01473     Vehicle *u = v->FirstShared();
01474     DeleteOrderWarnings(u);
01475     for (; u != NULL; u = u->NextShared()) {
01476       /* Toggle u->current_order "Full load" flag if it changed.
01477        * However, as the same flag is used for depot orders, check
01478        * whether we are not going to a depot as there are three
01479        * cases where the full load flag can be active and only
01480        * one case where the flag is used for depot orders. In the
01481        * other cases for the OrderTypeByte the flags are not used,
01482        * so do not care and those orders should not be active
01483        * when this function is called.
01484        */
01485       if (sel_ord == u->cur_real_order_index &&
01486           (u->current_order.IsType(OT_GOTO_STATION) || u->current_order.IsType(OT_LOADING)) &&
01487           u->current_order.GetLoadType() != order->GetLoadType()) {
01488         u->current_order.SetLoadType(order->GetLoadType());
01489       }
01490       InvalidateVehicleOrder(u, VIWD_MODIFY_ORDERS);
01491     }
01492   }
01493 
01494   return CommandCost();
01495 }
01496 
01504 static bool CheckAircraftOrderDistance(const Aircraft *v_new, const Vehicle *v_order, const Order *first)
01505 {
01506   if (first == NULL || v_new->acache.cached_max_range == 0) return true;
01507 
01508   /* Iterate over all orders to check the distance between all
01509    * 'goto' orders and their respective next order (of any type). */
01510   for (const Order *o = first; o != NULL; o = o->next) {
01511     switch (o->GetType()) {
01512       case OT_GOTO_STATION:
01513       case OT_GOTO_DEPOT:
01514       case OT_GOTO_WAYPOINT:
01515         /* If we don't have a next order, we've reached the end and must check the first order instead. */
01516         if (GetOrderDistance(o, o->next != NULL ? o->next : first, v_order) > v_new->acache.cached_max_range_sqr) return false;
01517         break;
01518 
01519       default: break;
01520     }
01521   }
01522 
01523   return true;
01524 }
01525 
01537 CommandCost CmdCloneOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01538 {
01539   VehicleID veh_src = GB(p2, 0, 20);
01540   VehicleID veh_dst = GB(p1, 0, 20);
01541 
01542   Vehicle *dst = Vehicle::GetIfValid(veh_dst);
01543   if (dst == NULL || !dst->IsPrimaryVehicle()) return CMD_ERROR;
01544 
01545   CommandCost ret = CheckOwnership(dst->owner);
01546   if (ret.Failed()) return ret;
01547 
01548   switch (GB(p1, 30, 2)) {
01549     case CO_SHARE: {
01550       Vehicle *src = Vehicle::GetIfValid(veh_src);
01551 
01552       /* Sanity checks */
01553       if (src == NULL || !src->IsPrimaryVehicle() || dst->type != src->type || dst == src) return CMD_ERROR;
01554 
01555       CommandCost ret = CheckOwnership(src->owner);
01556       if (ret.Failed()) return ret;
01557 
01558       /* Trucks can't share orders with busses (and visa versa) */
01559       if (src->type == VEH_ROAD && RoadVehicle::From(src)->IsBus() != RoadVehicle::From(dst)->IsBus()) {
01560         return CMD_ERROR;
01561       }
01562 
01563       /* Is the vehicle already in the shared list? */
01564       if (src->FirstShared() == dst->FirstShared()) return CMD_ERROR;
01565 
01566       const Order *order;
01567 
01568       FOR_VEHICLE_ORDERS(src, order) {
01569         if (!OrderGoesToStation(dst, order)) continue;
01570 
01571         /* Allow copying unreachable destinations if they were already unreachable for the source.
01572          * This is basically to allow cloning / autorenewing / autoreplacing vehicles, while the stations
01573          * are temporarily invalid due to reconstruction. */
01574         const Station *st = Station::Get(order->GetDestination());
01575         if (CanVehicleUseStation(src, st) && !CanVehicleUseStation(dst, st)) {
01576           return_cmd_error(STR_ERROR_CAN_T_COPY_SHARE_ORDER);
01577         }
01578       }
01579 
01580       /* Check for aircraft range limits. */
01581       if (dst->type == VEH_AIRCRAFT && !CheckAircraftOrderDistance(Aircraft::From(dst), src, src->GetFirstOrder())) {
01582         return_cmd_error(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE);
01583       }
01584 
01585       if (src->orders.list == NULL && !OrderList::CanAllocateItem()) {
01586         return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
01587       }
01588 
01589       if (flags & DC_EXEC) {
01590         /* If the destination vehicle had a OrderList, destroy it.
01591          * We only reset the order indices, if the new orders are obviously different.
01592          * (We mainly do this to keep the order indices valid and in range.) */
01593         DeleteVehicleOrders(dst, false, dst->GetNumOrders() != src->GetNumOrders());
01594 
01595         dst->orders.list = src->orders.list;
01596 
01597         /* Link this vehicle in the shared-list */
01598         dst->AddToShared(src);
01599 
01600         InvalidateVehicleOrder(dst, VIWD_REMOVE_ALL_ORDERS);
01601         InvalidateVehicleOrder(src, VIWD_MODIFY_ORDERS);
01602 
01603         InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
01604       }
01605       break;
01606     }
01607 
01608     case CO_COPY: {
01609       Vehicle *src = Vehicle::GetIfValid(veh_src);
01610 
01611       /* Sanity checks */
01612       if (src == NULL || !src->IsPrimaryVehicle() || dst->type != src->type || dst == src) return CMD_ERROR;
01613 
01614       CommandCost ret = CheckOwnership(src->owner);
01615       if (ret.Failed()) return ret;
01616 
01617       /* Trucks can't copy all the orders from busses (and visa versa),
01618        * and neither can helicopters and aircraft. */
01619       const Order *order;
01620       FOR_VEHICLE_ORDERS(src, order) {
01621         if (OrderGoesToStation(dst, order) &&
01622             !CanVehicleUseStation(dst, Station::Get(order->GetDestination()))) {
01623           return_cmd_error(STR_ERROR_CAN_T_COPY_SHARE_ORDER);
01624         }
01625       }
01626 
01627       /* Check for aircraft range limits. */
01628       if (dst->type == VEH_AIRCRAFT && !CheckAircraftOrderDistance(Aircraft::From(dst), src, src->GetFirstOrder())) {
01629         return_cmd_error(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE);
01630       }
01631 
01632       /* make sure there are orders available */
01633       if (!Order::CanAllocateItem(src->GetNumOrders()) || !OrderList::CanAllocateItem()) {
01634         return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
01635       }
01636 
01637       if (flags & DC_EXEC) {
01638         const Order *order;
01639         Order *first = NULL;
01640         Order **order_dst;
01641 
01642         /* If the destination vehicle had an order list, destroy the chain but keep the OrderList.
01643          * We only reset the order indices, if the new orders are obviously different.
01644          * (We mainly do this to keep the order indices valid and in range.) */
01645         DeleteVehicleOrders(dst, true, dst->GetNumOrders() != src->GetNumOrders());
01646 
01647         order_dst = &first;
01648         FOR_VEHICLE_ORDERS(src, order) {
01649           *order_dst = new Order();
01650           (*order_dst)->AssignOrder(*order);
01651           order_dst = &(*order_dst)->next;
01652         }
01653         if (dst->orders.list == NULL) {
01654           dst->orders.list = new OrderList(first, dst);
01655         } else {
01656           assert(dst->orders.list->GetFirstOrder() == NULL);
01657           assert(!dst->orders.list->IsShared());
01658           delete dst->orders.list;
01659           assert(OrderList::CanAllocateItem());
01660           dst->orders.list = new OrderList(first, dst);
01661         }
01662 
01663         InvalidateVehicleOrder(dst, VIWD_REMOVE_ALL_ORDERS);
01664 
01665         InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
01666       }
01667       break;
01668     }
01669 
01670     case CO_UNSHARE: return DecloneOrder(dst, flags);
01671     default: return CMD_ERROR;
01672   }
01673 
01674   return CommandCost();
01675 }
01676 
01688 CommandCost CmdOrderRefit(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01689 {
01690   VehicleID veh = GB(p1, 0, 20);
01691   VehicleOrderID order_number  = GB(p2, 16, 8);
01692   CargoID cargo = GB(p2, 0, 8);
01693 
01694   if (cargo >= NUM_CARGO && cargo != CT_NO_REFIT && cargo != CT_AUTO_REFIT) return CMD_ERROR;
01695 
01696   const Vehicle *v = Vehicle::GetIfValid(veh);
01697   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01698 
01699   CommandCost ret = CheckOwnership(v->owner);
01700   if (ret.Failed()) return ret;
01701 
01702   Order *order = v->GetOrder(order_number);
01703   if (order == NULL) return CMD_ERROR;
01704 
01705   /* Automatic refit cargo is only supported for goto station orders. */
01706   if (cargo == CT_AUTO_REFIT && !order->IsType(OT_GOTO_STATION)) return CMD_ERROR;
01707 
01708   if (order->GetLoadType() & OLFB_NO_LOAD) return CMD_ERROR;
01709 
01710   if (flags & DC_EXEC) {
01711     order->SetRefit(cargo);
01712 
01713     /* Make the depot order an 'always go' order. */
01714     if (cargo != CT_NO_REFIT && order->IsType(OT_GOTO_DEPOT)) {
01715       order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
01716       order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
01717     }
01718 
01719     for (Vehicle *u = v->FirstShared(); u != NULL; u = u->NextShared()) {
01720       /* Update any possible open window of the vehicle */
01721       InvalidateVehicleOrder(u, VIWD_MODIFY_ORDERS);
01722 
01723       /* If the vehicle already got the current depot set as current order, then update current order as well */
01724       if (u->cur_real_order_index == order_number && (u->current_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) {
01725         u->current_order.SetRefit(cargo);
01726       }
01727     }
01728   }
01729 
01730   return CommandCost();
01731 }
01732 
01733 
01739 void CheckOrders(const Vehicle *v)
01740 {
01741   /* Does the user wants us to check things? */
01742   if (_settings_client.gui.order_review_system == 0) return;
01743 
01744   /* Do nothing for crashed vehicles */
01745   if (v->vehstatus & VS_CRASHED) return;
01746 
01747   /* Do nothing for stopped vehicles if setting is '1' */
01748   if (_settings_client.gui.order_review_system == 1 && (v->vehstatus & VS_STOPPED)) return;
01749 
01750   /* do nothing we we're not the first vehicle in a share-chain */
01751   if (v->FirstShared() != v) return;
01752 
01753   /* Only check every 20 days, so that we don't flood the message log */
01754   if (v->owner == _local_company && v->day_counter % 20 == 0) {
01755     int n_st, problem_type = -1;
01756     const Order *order;
01757     int message = 0;
01758 
01759     /* Check the order list */
01760     n_st = 0;
01761 
01762     FOR_VEHICLE_ORDERS(v, order) {
01763       /* Dummy order? */
01764       if (order->IsType(OT_DUMMY)) {
01765         problem_type = 1;
01766         break;
01767       }
01768       /* Does station have a load-bay for this vehicle? */
01769       if (order->IsType(OT_GOTO_STATION)) {
01770         const Station *st = Station::Get(order->GetDestination());
01771 
01772         n_st++;
01773         if (!CanVehicleUseStation(v, st)) problem_type = 3;
01774       }
01775     }
01776 
01777     /* Check if the last and the first order are the same */
01778     if (v->GetNumOrders() > 1) {
01779       const Order *last = v->GetLastOrder();
01780 
01781       if (v->orders.list->GetFirstOrder()->Equals(*last)) {
01782         problem_type = 2;
01783       }
01784     }
01785 
01786     /* Do we only have 1 station in our order list? */
01787     if (n_st < 2 && problem_type == -1) problem_type = 0;
01788 
01789 #ifndef NDEBUG
01790     if (v->orders.list != NULL) v->orders.list->DebugCheckSanity();
01791 #endif
01792 
01793     /* We don't have a problem */
01794     if (problem_type < 0) return;
01795 
01796     message = STR_NEWS_VEHICLE_HAS_TOO_FEW_ORDERS + problem_type;
01797     //DEBUG(misc, 3, "Triggered News Item for vehicle %d", v->index);
01798 
01799     SetDParam(0, v->index);
01800     AddVehicleAdviceNewsItem(message, v->index);
01801   }
01802 }
01803 
01809 void RemoveOrderFromAllVehicles(OrderType type, DestinationID destination)
01810 {
01811   Vehicle *v;
01812 
01813   /* Aircraft have StationIDs for depot orders and never use DepotIDs
01814    * This fact is handled specially below
01815    */
01816 
01817   /* Go through all vehicles */
01818   FOR_ALL_VEHICLES(v) {
01819     Order *order;
01820 
01821     order = &v->current_order;
01822     if ((v->type == VEH_AIRCRAFT && order->IsType(OT_GOTO_DEPOT) ? OT_GOTO_STATION : order->GetType()) == type &&
01823         v->current_order.GetDestination() == destination) {
01824       order->MakeDummy();
01825       SetWindowDirty(WC_VEHICLE_VIEW, v->index);
01826     }
01827 
01828     /* Clear the order from the order-list */
01829     int id = -1;
01830     FOR_VEHICLE_ORDERS(v, order) {
01831       id++;
01832 restart:
01833 
01834       OrderType ot = order->GetType();
01835       if (ot == OT_GOTO_DEPOT && (order->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0) continue;
01836       if (ot == OT_IMPLICIT || (v->type == VEH_AIRCRAFT && ot == OT_GOTO_DEPOT)) ot = OT_GOTO_STATION;
01837       if (ot == type && order->GetDestination() == destination) {
01838         /* We want to clear implicit orders, but we don't want to make them
01839          * dummy orders. They should just vanish. Also check the actual order
01840          * type as ot is currently OT_GOTO_STATION. */
01841         if (order->IsType(OT_IMPLICIT)) {
01842           order = order->next; // DeleteOrder() invalidates current order
01843           DeleteOrder(v, id);
01844           if (order != NULL) goto restart;
01845           break;
01846         }
01847 
01848         order->MakeDummy();
01849         for (const Vehicle *w = v->FirstShared(); w != NULL; w = w->NextShared()) {
01850           /* In GUI, simulate by removing the order and adding it back */
01851           InvalidateVehicleOrder(w, id | (INVALID_VEH_ORDER_ID << 8));
01852           InvalidateVehicleOrder(w, (INVALID_VEH_ORDER_ID << 8) | id);
01853         }
01854       }
01855     }
01856   }
01857 
01858   OrderBackup::RemoveOrder(type, destination);
01859 }
01860 
01865 bool Vehicle::HasDepotOrder() const
01866 {
01867   const Order *order;
01868 
01869   FOR_VEHICLE_ORDERS(this, order) {
01870     if (order->IsType(OT_GOTO_DEPOT)) return true;
01871   }
01872 
01873   return false;
01874 }
01875 
01885 void DeleteVehicleOrders(Vehicle *v, bool keep_orderlist, bool reset_order_indices)
01886 {
01887   DeleteOrderWarnings(v);
01888 
01889   if (v->IsOrderListShared()) {
01890     /* Remove ourself from the shared order list. */
01891     v->RemoveFromShared();
01892     v->orders.list = NULL;
01893   } else if (v->orders.list != NULL) {
01894     /* Remove the orders */
01895     v->orders.list->FreeChain(keep_orderlist);
01896     if (!keep_orderlist) v->orders.list = NULL;
01897   }
01898 
01899   if (reset_order_indices) {
01900     v->cur_implicit_order_index = v->cur_real_order_index = 0;
01901     if (v->current_order.IsType(OT_LOADING)) {
01902       CancelLoadingDueToDeletedOrder(v);
01903     }
01904   }
01905 }
01906 
01914 uint16 GetServiceIntervalClamped(uint interval, bool ispercent)
01915 {
01916   return ispercent ? Clamp(interval, MIN_SERVINT_PERCENT, MAX_SERVINT_PERCENT) : Clamp(interval, MIN_SERVINT_DAYS, MAX_SERVINT_DAYS);
01917 }
01918 
01927 static bool CheckForValidOrders(const Vehicle *v)
01928 {
01929   const Order *order;
01930 
01931   FOR_VEHICLE_ORDERS(v, order) {
01932     switch (order->GetType()) {
01933       case OT_GOTO_STATION:
01934       case OT_GOTO_DEPOT:
01935       case OT_GOTO_WAYPOINT:
01936         return true;
01937 
01938       default:
01939         break;
01940     }
01941   }
01942 
01943   return false;
01944 }
01945 
01949 static bool OrderConditionCompare(OrderConditionComparator occ, int variable, int value)
01950 {
01951   switch (occ) {
01952     case OCC_EQUALS:      return variable == value;
01953     case OCC_NOT_EQUALS:  return variable != value;
01954     case OCC_LESS_THAN:   return variable <  value;
01955     case OCC_LESS_EQUALS: return variable <= value;
01956     case OCC_MORE_THAN:   return variable >  value;
01957     case OCC_MORE_EQUALS: return variable >= value;
01958     case OCC_IS_TRUE:     return variable != 0;
01959     case OCC_IS_FALSE:    return variable == 0;
01960     default: NOT_REACHED();
01961   }
01962 }
01963 
01970 VehicleOrderID ProcessConditionalOrder(const Order *order, const Vehicle *v)
01971 {
01972   if (order->GetType() != OT_CONDITIONAL) return INVALID_VEH_ORDER_ID;
01973 
01974   bool skip_order = false;
01975   OrderConditionComparator occ = order->GetConditionComparator();
01976   uint16 value = order->GetConditionValue();
01977 
01978   switch (order->GetConditionVariable()) {
01979     case OCV_LOAD_PERCENTAGE:    skip_order = OrderConditionCompare(occ, CalcPercentVehicleFilled(v, NULL), value); break;
01980     case OCV_RELIABILITY:        skip_order = OrderConditionCompare(occ, ToPercent16(v->reliability),       value); break;
01981     case OCV_MAX_SPEED:          skip_order = OrderConditionCompare(occ, v->GetDisplayMaxSpeed() * 10 / 16, value); break;
01982     case OCV_AGE:                skip_order = OrderConditionCompare(occ, v->age / DAYS_IN_LEAP_YEAR,        value); break;
01983     case OCV_REQUIRES_SERVICE:   skip_order = OrderConditionCompare(occ, v->NeedsServicing(),               value); break;
01984     case OCV_UNCONDITIONALLY:    skip_order = true; break;
01985     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;
01986     default: NOT_REACHED();
01987   }
01988 
01989   return skip_order ? order->GetConditionSkipToOrder() : (VehicleOrderID)INVALID_VEH_ORDER_ID;
01990 }
01991 
01999 bool UpdateOrderDest(Vehicle *v, const Order *order, int conditional_depth, bool pbs_look_ahead)
02000 {
02001   if (conditional_depth > v->GetNumOrders()) {
02002     v->current_order.Free();
02003     v->dest_tile = 0;
02004     return false;
02005   }
02006 
02007   switch (order->GetType()) {
02008     case OT_GOTO_STATION:
02009       v->dest_tile = v->GetOrderStationLocation(order->GetDestination());
02010       return true;
02011 
02012     case OT_GOTO_DEPOT:
02013       if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !v->NeedsServicing()) {
02014         assert(!pbs_look_ahead);
02015         UpdateVehicleTimetable(v, true);
02016         v->IncrementRealOrderIndex();
02017         break;
02018       }
02019 
02020       if (v->current_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) {
02021         /* We need to search for the nearest depot (hangar). */
02022         TileIndex location;
02023         DestinationID destination;
02024         bool reverse;
02025 
02026         if (v->FindClosestDepot(&location, &destination, &reverse)) {
02027           /* PBS reservations cannot reverse */
02028           if (pbs_look_ahead && reverse) return false;
02029 
02030           v->dest_tile = location;
02031           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());
02032 
02033           /* If there is no depot in front, reverse automatically (trains only) */
02034           if (v->type == VEH_TRAIN && reverse) DoCommand(v->tile, v->index, 0, DC_EXEC, CMD_REVERSE_TRAIN_DIRECTION);
02035 
02036           if (v->type == VEH_AIRCRAFT) {
02037             Aircraft *a = Aircraft::From(v);
02038             if (a->state == FLYING && a->targetairport != destination) {
02039               /* The aircraft is now heading for a different hangar than the next in the orders */
02040               extern void AircraftNextAirportPos_and_Order(Aircraft *a);
02041               AircraftNextAirportPos_and_Order(a);
02042             }
02043           }
02044           return true;
02045         }
02046 
02047         /* If there is no depot, we cannot help PBS either. */
02048         if (pbs_look_ahead) return false;
02049 
02050         UpdateVehicleTimetable(v, true);
02051         v->IncrementRealOrderIndex();
02052       } else {
02053         if (v->type != VEH_AIRCRAFT) {
02054           v->dest_tile = Depot::Get(order->GetDestination())->xy;
02055         }
02056         return true;
02057       }
02058       break;
02059 
02060     case OT_GOTO_WAYPOINT:
02061       v->dest_tile = Waypoint::Get(order->GetDestination())->xy;
02062       return true;
02063 
02064     case OT_CONDITIONAL: {
02065       assert(!pbs_look_ahead);
02066       VehicleOrderID next_order = ProcessConditionalOrder(order, v);
02067       if (next_order != INVALID_VEH_ORDER_ID) {
02068         /* Jump to next_order. cur_implicit_order_index becomes exactly that order,
02069          * cur_real_order_index might come after next_order. */
02070         UpdateVehicleTimetable(v, false);
02071         v->cur_implicit_order_index = v->cur_real_order_index = next_order;
02072         v->UpdateRealOrderIndex();
02073         v->current_order_time += v->GetOrder(v->cur_real_order_index)->travel_time;
02074 
02075         /* Disable creation of implicit orders.
02076          * When inserting them we do not know that we would have to make the conditional orders point to them. */
02077         if (v->IsGroundVehicle()) {
02078           uint16 &gv_flags = v->GetGroundVehicleFlags();
02079           SetBit(gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
02080         }
02081       } else {
02082         UpdateVehicleTimetable(v, true);
02083         v->IncrementRealOrderIndex();
02084       }
02085       break;
02086     }
02087 
02088     default:
02089       v->dest_tile = 0;
02090       return false;
02091   }
02092 
02093   assert(v->cur_implicit_order_index < v->GetNumOrders());
02094   assert(v->cur_real_order_index < v->GetNumOrders());
02095 
02096   /* Get the current order */
02097   order = v->GetOrder(v->cur_real_order_index);
02098   if (order != NULL && order->IsType(OT_IMPLICIT)) {
02099     assert(v->GetNumManualOrders() == 0);
02100     order = NULL;
02101   }
02102 
02103   if (order == NULL) {
02104     v->current_order.Free();
02105     v->dest_tile = 0;
02106     return false;
02107   }
02108 
02109   v->current_order = *order;
02110   return UpdateOrderDest(v, order, conditional_depth + 1, pbs_look_ahead);
02111 }
02112 
02120 bool ProcessOrders(Vehicle *v)
02121 {
02122   switch (v->current_order.GetType()) {
02123     case OT_GOTO_DEPOT:
02124       /* Let a depot order in the orderlist interrupt. */
02125       if (!(v->current_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) return false;
02126       break;
02127 
02128     case OT_LOADING:
02129       return false;
02130 
02131     case OT_LEAVESTATION:
02132       if (v->type != VEH_AIRCRAFT) return false;
02133       break;
02134 
02135     default: break;
02136   }
02137 
02145   bool may_reverse = v->current_order.IsType(OT_NOTHING);
02146 
02147   /* Check if we've reached a 'via' destination. */
02148   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)) &&
02149       IsTileType(v->tile, MP_STATION) &&
02150       v->current_order.GetDestination() == GetStationIndex(v->tile)) {
02151     v->DeleteUnreachedImplicitOrders();
02152     /* We set the last visited station here because we do not want
02153      * the train to stop at this 'via' station if the next order
02154      * is a no-non-stop order; in that case not setting the last
02155      * visited station will cause the vehicle to still stop. */
02156     v->last_station_visited = v->current_order.GetDestination();
02157     UpdateVehicleTimetable(v, true);
02158     v->IncrementImplicitOrderIndex();
02159   }
02160 
02161   /* Get the current order */
02162   assert(v->cur_implicit_order_index == 0 || v->cur_implicit_order_index < v->GetNumOrders());
02163   v->UpdateRealOrderIndex();
02164 
02165   const Order *order = v->GetOrder(v->cur_real_order_index);
02166   if (order != NULL && order->IsType(OT_IMPLICIT)) {
02167     assert(v->GetNumManualOrders() == 0);
02168     order = NULL;
02169   }
02170 
02171   /* If no order, do nothing. */
02172   if (order == NULL || (v->type == VEH_AIRCRAFT && !CheckForValidOrders(v))) {
02173     if (v->type == VEH_AIRCRAFT) {
02174       /* Aircraft do something vastly different here, so handle separately */
02175       extern void HandleMissingAircraftOrders(Aircraft *v);
02176       HandleMissingAircraftOrders(Aircraft::From(v));
02177       return false;
02178     }
02179 
02180     v->current_order.Free();
02181     v->dest_tile = 0;
02182     return false;
02183   }
02184 
02185   /* If it is unchanged, keep it. */
02186   if (order->Equals(v->current_order) && (v->type == VEH_AIRCRAFT || v->dest_tile != 0) &&
02187       (v->type != VEH_SHIP || !order->IsType(OT_GOTO_STATION) || Station::Get(order->GetDestination())->dock_tile != INVALID_TILE)) {
02188     return false;
02189   }
02190 
02191   /* Otherwise set it, and determine the destination tile. */
02192   v->current_order = *order;
02193 
02194   InvalidateVehicleOrder(v, VIWD_MODIFY_ORDERS);
02195   switch (v->type) {
02196     default:
02197       NOT_REACHED();
02198 
02199     case VEH_ROAD:
02200     case VEH_TRAIN:
02201       break;
02202 
02203     case VEH_AIRCRAFT:
02204     case VEH_SHIP:
02205       SetWindowClassesDirty(GetWindowClassForVehicleType(v->type));
02206       break;
02207   }
02208 
02209   return UpdateOrderDest(v, order) && may_reverse;
02210 }
02211 
02219 bool Order::ShouldStopAtStation(const Vehicle *v, StationID station) const
02220 {
02221   bool is_dest_station = this->IsType(OT_GOTO_STATION) && this->dest == station;
02222 
02223   return (!this->IsType(OT_GOTO_DEPOT) || (this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS) != 0) &&
02224       v->last_station_visited != station && // Do stop only when we've not just been there
02225       /* Finally do stop when there is no non-stop flag set for this type of station. */
02226       !(this->GetNonStopType() & (is_dest_station ? ONSF_NO_STOP_AT_DESTINATION_STATION : ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS));
02227 }
02228 
02229 bool Order::CanLoadOrUnload() const
02230 {
02231   return (this->IsType(OT_GOTO_STATION) || this->IsType(OT_IMPLICIT)) &&
02232       (this->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) == 0 &&
02233       ((this->GetLoadType() & OLFB_NO_LOAD) == 0 ||
02234       (this->GetUnloadType() & OUFB_NO_UNLOAD) == 0);
02235 }
02236 
02243 bool Order::CanLeaveWithCargo(bool has_cargo) const
02244 {
02245   return (this->GetLoadType() & OLFB_NO_LOAD) == 0 || (has_cargo &&
02246       (this->GetUnloadType() & (OUFB_UNLOAD | OUFB_TRANSFER)) == 0);
02247 }