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, VIWD_REMOVE_ALL_ORDERS);
01047     InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
01048   }
01049   return CommandCost();
01050 }
01051 
01061 CommandCost CmdDeleteOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01062 {
01063   VehicleID veh_id = GB(p1, 0, 20);
01064   VehicleOrderID sel_ord = GB(p2, 0, 8);
01065 
01066   Vehicle *v = Vehicle::GetIfValid(veh_id);
01067 
01068   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01069 
01070   CommandCost ret = CheckOwnership(v->owner);
01071   if (ret.Failed()) return ret;
01072 
01073   /* If we did not select an order, we maybe want to de-clone the orders */
01074   if (sel_ord >= v->GetNumOrders()) return DecloneOrder(v, flags);
01075 
01076   if (v->GetOrder(sel_ord) == NULL) return CMD_ERROR;
01077 
01078   if (flags & DC_EXEC) DeleteOrder(v, sel_ord);
01079   return CommandCost();
01080 }
01081 
01086 static void CancelLoadingDueToDeletedOrder(Vehicle *v)
01087 {
01088   assert(v->current_order.IsType(OT_LOADING));
01089   /* NON-stop flag is misused to see if a train is in a station that is
01090    * on his order list or not */
01091   v->current_order.SetNonStopType(ONSF_STOP_EVERYWHERE);
01092   /* When full loading, "cancel" that order so the vehicle doesn't
01093    * stay indefinitely at this station anymore. */
01094   if (v->current_order.GetLoadType() & OLFB_FULL_LOAD) v->current_order.SetLoadType(OLF_LOAD_IF_POSSIBLE);
01095 }
01096 
01102 void DeleteOrder(Vehicle *v, VehicleOrderID sel_ord)
01103 {
01104   v->orders.list->DeleteOrderAt(sel_ord);
01105 
01106   Vehicle *u = v->FirstShared();
01107   DeleteOrderWarnings(u);
01108   for (; u != NULL; u = u->NextShared()) {
01109     assert(v->orders.list == u->orders.list);
01110 
01111     if (sel_ord == u->cur_real_order_index && u->current_order.IsType(OT_LOADING)) {
01112       CancelLoadingDueToDeletedOrder(u);
01113     }
01114 
01115     if (sel_ord < u->cur_real_order_index) {
01116       u->cur_real_order_index--;
01117     } else if (sel_ord == u->cur_real_order_index) {
01118       u->UpdateRealOrderIndex();
01119     }
01120 
01121     if (sel_ord < u->cur_implicit_order_index) {
01122       u->cur_implicit_order_index--;
01123     } else if (sel_ord == u->cur_implicit_order_index) {
01124       /* Make sure the index is valid */
01125       if (u->cur_implicit_order_index >= u->GetNumOrders()) u->cur_implicit_order_index = 0;
01126 
01127       /* Skip non-implicit orders for the implicit-order-index (e.g. if the current implicit order was deleted */
01128       while (u->cur_implicit_order_index != u->cur_real_order_index && !u->GetOrder(u->cur_implicit_order_index)->IsType(OT_IMPLICIT)) {
01129         u->cur_implicit_order_index++;
01130         if (u->cur_implicit_order_index >= u->GetNumOrders()) u->cur_implicit_order_index = 0;
01131       }
01132     }
01133 
01134     /* Update any possible open window of the vehicle */
01135     InvalidateVehicleOrder(u, sel_ord | (INVALID_VEH_ORDER_ID << 8));
01136   }
01137 
01138   /* As we delete an order, the order to skip to will be 'wrong'. */
01139   VehicleOrderID cur_order_id = 0;
01140   Order *order = NULL;
01141   FOR_VEHICLE_ORDERS(v, order) {
01142     if (order->IsType(OT_CONDITIONAL)) {
01143       VehicleOrderID order_id = order->GetConditionSkipToOrder();
01144       if (order_id >= sel_ord) {
01145         order_id = max(order_id - 1, 0);
01146       }
01147       if (order_id == cur_order_id) {
01148         order_id = (order_id + 1) % v->GetNumOrders();
01149       }
01150       order->SetConditionSkipToOrder(order_id);
01151     }
01152     cur_order_id++;
01153   }
01154 
01155   InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
01156 }
01157 
01167 CommandCost CmdSkipToOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01168 {
01169   VehicleID veh_id = GB(p1, 0, 20);
01170   VehicleOrderID sel_ord = GB(p2, 0, 8);
01171 
01172   Vehicle *v = Vehicle::GetIfValid(veh_id);
01173 
01174   if (v == NULL || !v->IsPrimaryVehicle() || sel_ord == v->cur_implicit_order_index || sel_ord >= v->GetNumOrders() || v->GetNumOrders() < 2) return CMD_ERROR;
01175 
01176   CommandCost ret = CheckOwnership(v->owner);
01177   if (ret.Failed()) return ret;
01178 
01179   if (flags & DC_EXEC) {
01180     if (v->current_order.IsType(OT_LOADING)) v->LeaveStation();
01181 
01182     v->cur_implicit_order_index = v->cur_real_order_index = sel_ord;
01183     v->UpdateRealOrderIndex();
01184 
01185     InvalidateVehicleOrder(v, VIWD_MODIFY_ORDERS);
01186   }
01187 
01188   /* We have an aircraft/ship, they have a mini-schedule, so update them all */
01189   if (v->type == VEH_AIRCRAFT) SetWindowClassesDirty(WC_AIRCRAFT_LIST);
01190   if (v->type == VEH_SHIP) SetWindowClassesDirty(WC_SHIPS_LIST);
01191 
01192   return CommandCost();
01193 }
01194 
01208 CommandCost CmdMoveOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01209 {
01210   VehicleID veh = GB(p1, 0, 20);
01211   VehicleOrderID moving_order = GB(p2,  0, 16);
01212   VehicleOrderID target_order = GB(p2, 16, 16);
01213 
01214   Vehicle *v = Vehicle::GetIfValid(veh);
01215   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01216 
01217   CommandCost ret = CheckOwnership(v->owner);
01218   if (ret.Failed()) return ret;
01219 
01220   /* Don't make senseless movements */
01221   if (moving_order >= v->GetNumOrders() || target_order >= v->GetNumOrders() ||
01222       moving_order == target_order || v->GetNumOrders() <= 1) return CMD_ERROR;
01223 
01224   Order *moving_one = v->GetOrder(moving_order);
01225   /* Don't move an empty order */
01226   if (moving_one == NULL) return CMD_ERROR;
01227 
01228   if (flags & DC_EXEC) {
01229     v->orders.list->MoveOrder(moving_order, target_order);
01230 
01231     /* Update shared list */
01232     Vehicle *u = v->FirstShared();
01233 
01234     DeleteOrderWarnings(u);
01235 
01236     for (; u != NULL; u = u->NextShared()) {
01237       /* Update the current order.
01238        * There are multiple ways to move orders, which result in cur_implicit_order_index
01239        * and cur_real_order_index to not longer make any sense. E.g. moving another
01240        * real order between them.
01241        *
01242        * Basically one could choose to preserve either of them, but not both.
01243        * While both ways are suitable in this or that case from a human point of view, neither
01244        * of them makes really sense.
01245        * However, from an AI point of view, preserving cur_real_order_index is the most
01246        * predictable and transparent behaviour.
01247        *
01248        * With that decision it basically does not matter what we do to cur_implicit_order_index.
01249        * If we change orders between the implict- and real-index, the implicit orders are mostly likely
01250        * completely out-dated anyway. So, keep it simple and just keep cur_implicit_order_index as well.
01251        * The worst which can happen is that a lot of implicit orders are removed when reaching current_order.
01252        */
01253       if (u->cur_real_order_index == moving_order) {
01254         u->cur_real_order_index = target_order;
01255       } else if (u->cur_real_order_index > moving_order && u->cur_real_order_index <= target_order) {
01256         u->cur_real_order_index--;
01257       } else if (u->cur_real_order_index < moving_order && u->cur_real_order_index >= target_order) {
01258         u->cur_real_order_index++;
01259       }
01260 
01261       if (u->cur_implicit_order_index == moving_order) {
01262         u->cur_implicit_order_index = target_order;
01263       } else if (u->cur_implicit_order_index > moving_order && u->cur_implicit_order_index <= target_order) {
01264         u->cur_implicit_order_index--;
01265       } else if (u->cur_implicit_order_index < moving_order && u->cur_implicit_order_index >= target_order) {
01266         u->cur_implicit_order_index++;
01267       }
01268 
01269       assert(v->orders.list == u->orders.list);
01270       /* Update any possible open window of the vehicle */
01271       InvalidateVehicleOrder(u, moving_order | (target_order << 8));
01272     }
01273 
01274     /* As we move an order, the order to skip to will be 'wrong'. */
01275     Order *order;
01276     FOR_VEHICLE_ORDERS(v, order) {
01277       if (order->IsType(OT_CONDITIONAL)) {
01278         VehicleOrderID order_id = order->GetConditionSkipToOrder();
01279         if (order_id == moving_order) {
01280           order_id = target_order;
01281         } else if (order_id > moving_order && order_id <= target_order) {
01282           order_id--;
01283         } else if (order_id < moving_order && order_id >= target_order) {
01284           order_id++;
01285         }
01286         order->SetConditionSkipToOrder(order_id);
01287       }
01288     }
01289 
01290     /* Make sure to rebuild the whole list */
01291     InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
01292   }
01293 
01294   return CommandCost();
01295 }
01296 
01312 CommandCost CmdModifyOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01313 {
01314   VehicleOrderID sel_ord = GB(p1, 20,  8);
01315   VehicleID veh          = GB(p1,  0, 20);
01316   ModifyOrderFlags mof   = Extract<ModifyOrderFlags, 0, 4>(p2);
01317   uint16 data            = GB(p2,  4, 11);
01318 
01319   if (mof >= MOF_END) return CMD_ERROR;
01320 
01321   Vehicle *v = Vehicle::GetIfValid(veh);
01322   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01323 
01324   CommandCost ret = CheckOwnership(v->owner);
01325   if (ret.Failed()) return ret;
01326 
01327   /* Is it a valid order? */
01328   if (sel_ord >= v->GetNumOrders()) return CMD_ERROR;
01329 
01330   Order *order = v->GetOrder(sel_ord);
01331   switch (order->GetType()) {
01332     case OT_GOTO_STATION:
01333       if (mof == MOF_COND_VARIABLE || mof == MOF_COND_COMPARATOR || mof == MOF_DEPOT_ACTION || mof == MOF_COND_VALUE) return CMD_ERROR;
01334       break;
01335 
01336     case OT_GOTO_DEPOT:
01337       if (mof != MOF_NON_STOP && mof != MOF_DEPOT_ACTION) return CMD_ERROR;
01338       break;
01339 
01340     case OT_GOTO_WAYPOINT:
01341       if (mof != MOF_NON_STOP) return CMD_ERROR;
01342       break;
01343 
01344     case OT_CONDITIONAL:
01345       if (mof != MOF_COND_VARIABLE && mof != MOF_COND_COMPARATOR && mof != MOF_COND_VALUE && mof != MOF_COND_DESTINATION) return CMD_ERROR;
01346       break;
01347 
01348     default:
01349       return CMD_ERROR;
01350   }
01351 
01352   switch (mof) {
01353     default: NOT_REACHED();
01354 
01355     case MOF_NON_STOP:
01356       if (!v->IsGroundVehicle()) return CMD_ERROR;
01357       if (data >= ONSF_END) return CMD_ERROR;
01358       if (data == order->GetNonStopType()) return CMD_ERROR;
01359       break;
01360 
01361     case MOF_STOP_LOCATION:
01362       if (v->type != VEH_TRAIN) return CMD_ERROR;
01363       if (data >= OSL_END) return CMD_ERROR;
01364       break;
01365 
01366     case MOF_UNLOAD:
01367       if ((data & ~(OUFB_UNLOAD | OUFB_TRANSFER | OUFB_NO_UNLOAD)) != 0) return CMD_ERROR;
01368       /* Unload and no-unload are mutual exclusive and so are transfer and no unload. */
01369       if (data != 0 && ((data & (OUFB_UNLOAD | OUFB_TRANSFER)) != 0) == ((data & OUFB_NO_UNLOAD) != 0)) return CMD_ERROR;
01370       if (data == order->GetUnloadType()) return CMD_ERROR;
01371       break;
01372 
01373     case MOF_LOAD:
01374       if (data > OLFB_NO_LOAD || data == 1) return CMD_ERROR;
01375       if (data == order->GetLoadType()) return CMD_ERROR;
01376       break;
01377 
01378     case MOF_DEPOT_ACTION:
01379       if (data >= DA_END) return CMD_ERROR;
01380       break;
01381 
01382     case MOF_COND_VARIABLE:
01383       if (data >= OCV_END) return CMD_ERROR;
01384       break;
01385 
01386     case MOF_COND_COMPARATOR:
01387       if (data >= OCC_END) return CMD_ERROR;
01388       switch (order->GetConditionVariable()) {
01389         case OCV_UNCONDITIONALLY: return CMD_ERROR;
01390 
01391         case OCV_REQUIRES_SERVICE:
01392           if (data != OCC_IS_TRUE && data != OCC_IS_FALSE) return CMD_ERROR;
01393           break;
01394 
01395         default:
01396           if (data == OCC_IS_TRUE || data == OCC_IS_FALSE) return CMD_ERROR;
01397           break;
01398       }
01399       break;
01400 
01401     case MOF_COND_VALUE:
01402       switch (order->GetConditionVariable()) {
01403         case OCV_UNCONDITIONALLY: return CMD_ERROR;
01404 
01405         case OCV_LOAD_PERCENTAGE:
01406         case OCV_RELIABILITY:
01407           if (data > 100) return CMD_ERROR;
01408           break;
01409 
01410         default:
01411           if (data > 2047) return CMD_ERROR;
01412           break;
01413       }
01414       break;
01415 
01416     case MOF_COND_DESTINATION:
01417       if (data >= v->GetNumOrders()) return CMD_ERROR;
01418       break;
01419   }
01420 
01421   if (flags & DC_EXEC) {
01422     switch (mof) {
01423       case MOF_NON_STOP:
01424         order->SetNonStopType((OrderNonStopFlags)data);
01425         if (data & ONSF_NO_STOP_AT_DESTINATION_STATION) order->SetRefit(CT_NO_REFIT);
01426         break;
01427 
01428       case MOF_STOP_LOCATION:
01429         order->SetStopLocation((OrderStopLocation)data);
01430         break;
01431 
01432       case MOF_UNLOAD:
01433         order->SetUnloadType((OrderUnloadFlags)data);
01434         break;
01435 
01436       case MOF_LOAD:
01437         order->SetLoadType((OrderLoadFlags)data);
01438         if (data & OLFB_NO_LOAD) order->SetRefit(CT_NO_REFIT);
01439         break;
01440 
01441       case MOF_DEPOT_ACTION: {
01442         switch (data) {
01443           case DA_ALWAYS_GO:
01444             order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
01445             order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
01446             break;
01447 
01448           case DA_SERVICE:
01449             order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() | ODTFB_SERVICE));
01450             order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
01451             order->SetRefit(CT_NO_REFIT);
01452             break;
01453 
01454           case DA_STOP:
01455             order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
01456             order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() | ODATFB_HALT));
01457             order->SetRefit(CT_NO_REFIT);
01458             break;
01459 
01460           default:
01461             NOT_REACHED();
01462         }
01463         break;
01464       }
01465 
01466       case MOF_COND_VARIABLE: {
01467         order->SetConditionVariable((OrderConditionVariable)data);
01468 
01469         OrderConditionComparator occ = order->GetConditionComparator();
01470         switch (order->GetConditionVariable()) {
01471           case OCV_UNCONDITIONALLY:
01472             order->SetConditionComparator(OCC_EQUALS);
01473             order->SetConditionValue(0);
01474             break;
01475 
01476           case OCV_REQUIRES_SERVICE:
01477             if (occ != OCC_IS_TRUE && occ != OCC_IS_FALSE) order->SetConditionComparator(OCC_IS_TRUE);
01478             break;
01479 
01480           case OCV_LOAD_PERCENTAGE:
01481           case OCV_RELIABILITY:
01482             if (order->GetConditionValue() > 100) order->SetConditionValue(100);
01483             /* FALL THROUGH */
01484           default:
01485             if (occ == OCC_IS_TRUE || occ == OCC_IS_FALSE) order->SetConditionComparator(OCC_EQUALS);
01486             break;
01487         }
01488         break;
01489       }
01490 
01491       case MOF_COND_COMPARATOR:
01492         order->SetConditionComparator((OrderConditionComparator)data);
01493         break;
01494 
01495       case MOF_COND_VALUE:
01496         order->SetConditionValue(data);
01497         break;
01498 
01499       case MOF_COND_DESTINATION:
01500         order->SetConditionSkipToOrder(data);
01501         break;
01502 
01503       default: NOT_REACHED();
01504     }
01505 
01506     /* Update the windows and full load flags, also for vehicles that share the same order list */
01507     Vehicle *u = v->FirstShared();
01508     DeleteOrderWarnings(u);
01509     for (; u != NULL; u = u->NextShared()) {
01510       /* Toggle u->current_order "Full load" flag if it changed.
01511        * However, as the same flag is used for depot orders, check
01512        * whether we are not going to a depot as there are three
01513        * cases where the full load flag can be active and only
01514        * one case where the flag is used for depot orders. In the
01515        * other cases for the OrderTypeByte the flags are not used,
01516        * so do not care and those orders should not be active
01517        * when this function is called.
01518        */
01519       if (sel_ord == u->cur_real_order_index &&
01520           (u->current_order.IsType(OT_GOTO_STATION) || u->current_order.IsType(OT_LOADING)) &&
01521           u->current_order.GetLoadType() != order->GetLoadType()) {
01522         u->current_order.SetLoadType(order->GetLoadType());
01523       }
01524       InvalidateVehicleOrder(u, VIWD_MODIFY_ORDERS);
01525     }
01526   }
01527 
01528   return CommandCost();
01529 }
01530 
01538 static bool CheckAircraftOrderDistance(const Aircraft *v_new, const Vehicle *v_order, const Order *first)
01539 {
01540   if (first == NULL || v_new->acache.cached_max_range == 0) return true;
01541 
01542   /* Iterate over all orders to check the distance between all
01543    * 'goto' orders and their respective next order (of any type). */
01544   for (const Order *o = first; o != NULL; o = o->next) {
01545     switch (o->GetType()) {
01546       case OT_GOTO_STATION:
01547       case OT_GOTO_DEPOT:
01548       case OT_GOTO_WAYPOINT:
01549         /* If we don't have a next order, we've reached the end and must check the first order instead. */
01550         if (GetOrderDistance(o, o->next != NULL ? o->next : first, v_order) > v_new->acache.cached_max_range_sqr) return false;
01551         break;
01552 
01553       default: break;
01554     }
01555   }
01556 
01557   return true;
01558 }
01559 
01571 CommandCost CmdCloneOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01572 {
01573   VehicleID veh_src = GB(p2, 0, 20);
01574   VehicleID veh_dst = GB(p1, 0, 20);
01575 
01576   Vehicle *dst = Vehicle::GetIfValid(veh_dst);
01577   if (dst == NULL || !dst->IsPrimaryVehicle()) return CMD_ERROR;
01578 
01579   CommandCost ret = CheckOwnership(dst->owner);
01580   if (ret.Failed()) return ret;
01581 
01582   switch (GB(p1, 30, 2)) {
01583     case CO_SHARE: {
01584       Vehicle *src = Vehicle::GetIfValid(veh_src);
01585 
01586       /* Sanity checks */
01587       if (src == NULL || !src->IsPrimaryVehicle() || dst->type != src->type || dst == src) return CMD_ERROR;
01588 
01589       CommandCost ret = CheckOwnership(src->owner);
01590       if (ret.Failed()) return ret;
01591 
01592       /* Trucks can't share orders with busses (and visa versa) */
01593       if (src->type == VEH_ROAD && RoadVehicle::From(src)->IsBus() != RoadVehicle::From(dst)->IsBus()) {
01594         return CMD_ERROR;
01595       }
01596 
01597       /* Is the vehicle already in the shared list? */
01598       if (src->FirstShared() == dst->FirstShared()) return CMD_ERROR;
01599 
01600       const Order *order;
01601 
01602       FOR_VEHICLE_ORDERS(src, order) {
01603         if (!OrderGoesToStation(dst, order)) continue;
01604 
01605         /* Allow copying unreachable destinations if they were already unreachable for the source.
01606          * This is basically to allow cloning / autorenewing / autoreplacing vehicles, while the stations
01607          * are temporarily invalid due to reconstruction. */
01608         const Station *st = Station::Get(order->GetDestination());
01609         if (CanVehicleUseStation(src, st) && !CanVehicleUseStation(dst, st)) {
01610           return_cmd_error(STR_ERROR_CAN_T_COPY_SHARE_ORDER);
01611         }
01612       }
01613 
01614       /* Check for aircraft range limits. */
01615       if (dst->type == VEH_AIRCRAFT && !CheckAircraftOrderDistance(Aircraft::From(dst), src, src->GetFirstOrder())) {
01616         return_cmd_error(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE);
01617       }
01618 
01619       if (src->orders.list == NULL && !OrderList::CanAllocateItem()) {
01620         return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
01621       }
01622 
01623       if (flags & DC_EXEC) {
01624         /* If the destination vehicle had a OrderList, destroy it.
01625          * We only reset the order indices, if the new orders are obviously different.
01626          * (We mainly do this to keep the order indices valid and in range.) */
01627         DeleteVehicleOrders(dst, false, dst->GetNumOrders() != src->GetNumOrders());
01628 
01629         dst->orders.list = src->orders.list;
01630 
01631         /* Link this vehicle in the shared-list */
01632         dst->AddToShared(src);
01633 
01634         InvalidateVehicleOrder(dst, VIWD_REMOVE_ALL_ORDERS);
01635         InvalidateVehicleOrder(src, VIWD_MODIFY_ORDERS);
01636 
01637         InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
01638       }
01639       break;
01640     }
01641 
01642     case CO_COPY: {
01643       Vehicle *src = Vehicle::GetIfValid(veh_src);
01644 
01645       /* Sanity checks */
01646       if (src == NULL || !src->IsPrimaryVehicle() || dst->type != src->type || dst == src) return CMD_ERROR;
01647 
01648       CommandCost ret = CheckOwnership(src->owner);
01649       if (ret.Failed()) return ret;
01650 
01651       /* Trucks can't copy all the orders from busses (and visa versa),
01652        * and neither can helicopters and aircarft. */
01653       const Order *order;
01654       FOR_VEHICLE_ORDERS(src, order) {
01655         if (OrderGoesToStation(dst, order) &&
01656             !CanVehicleUseStation(dst, Station::Get(order->GetDestination()))) {
01657           return_cmd_error(STR_ERROR_CAN_T_COPY_SHARE_ORDER);
01658         }
01659       }
01660 
01661       /* Check for aircraft range limits. */
01662       if (dst->type == VEH_AIRCRAFT && !CheckAircraftOrderDistance(Aircraft::From(dst), src, src->GetFirstOrder())) {
01663         return_cmd_error(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE);
01664       }
01665 
01666       /* make sure there are orders available */
01667       if (!Order::CanAllocateItem(src->GetNumOrders()) || !OrderList::CanAllocateItem()) {
01668         return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
01669       }
01670 
01671       if (flags & DC_EXEC) {
01672         const Order *order;
01673         Order *first = NULL;
01674         Order **order_dst;
01675 
01676         /* If the destination vehicle had an order list, destroy the chain but keep the OrderList.
01677          * We only reset the order indices, if the new orders are obviously different.
01678          * (We mainly do this to keep the order indices valid and in range.) */
01679         DeleteVehicleOrders(dst, true, dst->GetNumOrders() != src->GetNumOrders());
01680 
01681         order_dst = &first;
01682         FOR_VEHICLE_ORDERS(src, order) {
01683           *order_dst = new Order();
01684           (*order_dst)->AssignOrder(*order);
01685           order_dst = &(*order_dst)->next;
01686         }
01687         if (dst->orders.list == NULL) {
01688           dst->orders.list = new OrderList(first, dst);
01689         } else {
01690           assert(dst->orders.list->GetFirstOrder() == NULL);
01691           assert(!dst->orders.list->IsShared());
01692           delete dst->orders.list;
01693           assert(OrderList::CanAllocateItem());
01694           dst->orders.list = new OrderList(first, dst);
01695         }
01696 
01697         InvalidateVehicleOrder(dst, VIWD_REMOVE_ALL_ORDERS);
01698 
01699         InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
01700       }
01701       break;
01702     }
01703 
01704     case CO_UNSHARE: return DecloneOrder(dst, flags);
01705     default: return CMD_ERROR;
01706   }
01707 
01708   return CommandCost();
01709 }
01710 
01723 CommandCost CmdOrderRefit(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01724 {
01725   VehicleID veh = GB(p1, 0, 20);
01726   VehicleOrderID order_number  = GB(p2, 16, 8);
01727   CargoID cargo = GB(p2, 0, 8);
01728   byte subtype  = GB(p2, 8, 8);
01729 
01730   if (cargo >= NUM_CARGO && cargo != CT_NO_REFIT && cargo != CT_AUTO_REFIT) return CMD_ERROR;
01731 
01732   const Vehicle *v = Vehicle::GetIfValid(veh);
01733   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01734 
01735   CommandCost ret = CheckOwnership(v->owner);
01736   if (ret.Failed()) return ret;
01737 
01738   Order *order = v->GetOrder(order_number);
01739   if (order == NULL) return CMD_ERROR;
01740 
01741   /* Automatic refit cargo is only supported for goto station orders. */
01742   if (cargo == CT_AUTO_REFIT && !order->IsType(OT_GOTO_STATION)) return CMD_ERROR;
01743 
01744   if (flags & DC_EXEC) {
01745     order->SetRefit(cargo, subtype);
01746 
01747     /* Make the depot order an 'always go' order. */
01748     if (cargo != CT_NO_REFIT && order->IsType(OT_GOTO_DEPOT)) {
01749       order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
01750       order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
01751     }
01752 
01753     for (Vehicle *u = v->FirstShared(); u != NULL; u = u->NextShared()) {
01754       /* Update any possible open window of the vehicle */
01755       InvalidateVehicleOrder(u, VIWD_MODIFY_ORDERS);
01756 
01757       /* If the vehicle already got the current depot set as current order, then update current order as well */
01758       if (u->cur_real_order_index == order_number && (u->current_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) {
01759         u->current_order.SetRefit(cargo, subtype);
01760       }
01761     }
01762   }
01763 
01764   return CommandCost();
01765 }
01766 
01767 
01773 void CheckOrders(const Vehicle *v)
01774 {
01775   /* Does the user wants us to check things? */
01776   if (_settings_client.gui.order_review_system == 0) return;
01777 
01778   /* Do nothing for crashed vehicles */
01779   if (v->vehstatus & VS_CRASHED) return;
01780 
01781   /* Do nothing for stopped vehicles if setting is '1' */
01782   if (_settings_client.gui.order_review_system == 1 && (v->vehstatus & VS_STOPPED)) return;
01783 
01784   /* do nothing we we're not the first vehicle in a share-chain */
01785   if (v->FirstShared() != v) return;
01786 
01787   /* Only check every 20 days, so that we don't flood the message log */
01788   if (v->owner == _local_company && v->day_counter % 20 == 0) {
01789     int n_st, problem_type = -1;
01790     const Order *order;
01791     int message = 0;
01792 
01793     /* Check the order list */
01794     n_st = 0;
01795 
01796     FOR_VEHICLE_ORDERS(v, order) {
01797       /* Dummy order? */
01798       if (order->IsType(OT_DUMMY)) {
01799         problem_type = 1;
01800         break;
01801       }
01802       /* Does station have a load-bay for this vehicle? */
01803       if (order->IsType(OT_GOTO_STATION)) {
01804         const Station *st = Station::Get(order->GetDestination());
01805 
01806         n_st++;
01807         if (!CanVehicleUseStation(v, st)) problem_type = 3;
01808       }
01809     }
01810 
01811     /* Check if the last and the first order are the same */
01812     if (v->GetNumOrders() > 1) {
01813       const Order *last = v->GetLastOrder();
01814 
01815       if (v->orders.list->GetFirstOrder()->Equals(*last)) {
01816         problem_type = 2;
01817       }
01818     }
01819 
01820     /* Do we only have 1 station in our order list? */
01821     if (n_st < 2 && problem_type == -1) problem_type = 0;
01822 
01823 #ifndef NDEBUG
01824     if (v->orders.list != NULL) v->orders.list->DebugCheckSanity();
01825 #endif
01826 
01827     /* We don't have a problem */
01828     if (problem_type < 0) return;
01829 
01830     message = STR_NEWS_VEHICLE_HAS_TOO_FEW_ORDERS + problem_type;
01831     //DEBUG(misc, 3, "Triggered News Item for vehicle %d", v->index);
01832 
01833     SetDParam(0, v->index);
01834     AddVehicleAdviceNewsItem(message, v->index);
01835   }
01836 }
01837 
01843 void RemoveOrderFromAllVehicles(OrderType type, DestinationID destination)
01844 {
01845   Vehicle *v;
01846 
01847   /* Aircraft have StationIDs for depot orders and never use DepotIDs
01848    * This fact is handled specially below
01849    */
01850 
01851   /* Go through all vehicles */
01852   FOR_ALL_VEHICLES(v) {
01853     Order *order;
01854 
01855     order = &v->current_order;
01856     if ((v->type == VEH_AIRCRAFT && order->IsType(OT_GOTO_DEPOT) ? OT_GOTO_STATION : order->GetType()) == type &&
01857         v->current_order.GetDestination() == destination) {
01858       order->MakeDummy();
01859       SetWindowDirty(WC_VEHICLE_VIEW, v->index);
01860     }
01861 
01862     /* Clear the order from the order-list */
01863     int id = -1;
01864     FOR_VEHICLE_ORDERS(v, order) {
01865       id++;
01866 restart:
01867 
01868       OrderType ot = order->GetType();
01869       if (ot == OT_GOTO_DEPOT && (order->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0) continue;
01870       if (ot == OT_IMPLICIT || (v->type == VEH_AIRCRAFT && ot == OT_GOTO_DEPOT)) ot = OT_GOTO_STATION;
01871       if (ot == type && order->GetDestination() == destination) {
01872         /* We want to clear implicit orders, but we don't want to make them
01873          * dummy orders. They should just vanish. Also check the actual order
01874          * type as ot is currently OT_GOTO_STATION. */
01875         if (order->IsType(OT_IMPLICIT)) {
01876           order = order->next; // DeleteOrder() invalidates current order
01877           DeleteOrder(v, id);
01878           if (order != NULL) goto restart;
01879           break;
01880         }
01881 
01882         order->MakeDummy();
01883         for (const Vehicle *w = v->FirstShared(); w != NULL; w = w->NextShared()) {
01884           /* In GUI, simulate by removing the order and adding it back */
01885           InvalidateVehicleOrder(w, id | (INVALID_VEH_ORDER_ID << 8));
01886           InvalidateVehicleOrder(w, (INVALID_VEH_ORDER_ID << 8) | id);
01887         }
01888       }
01889     }
01890   }
01891 
01892   OrderBackup::RemoveOrder(type, destination);
01893 }
01894 
01899 bool Vehicle::HasDepotOrder() const
01900 {
01901   const Order *order;
01902 
01903   FOR_VEHICLE_ORDERS(this, order) {
01904     if (order->IsType(OT_GOTO_DEPOT)) return true;
01905   }
01906 
01907   return false;
01908 }
01909 
01919 void DeleteVehicleOrders(Vehicle *v, bool keep_orderlist, bool reset_order_indices)
01920 {
01921   DeleteOrderWarnings(v);
01922 
01923   if (v->IsOrderListShared()) {
01924     /* Remove ourself from the shared order list. */
01925     v->RemoveFromShared();
01926     v->orders.list = NULL;
01927   } else if (v->orders.list != NULL) {
01928     /* Remove the orders */
01929     v->orders.list->FreeChain(keep_orderlist);
01930     if (!keep_orderlist) v->orders.list = NULL;
01931   }
01932 
01933   if (reset_order_indices) {
01934     v->cur_implicit_order_index = v->cur_real_order_index = 0;
01935     if (v->current_order.IsType(OT_LOADING)) {
01936       CancelLoadingDueToDeletedOrder(v);
01937     }
01938   }
01939 }
01940 
01948 uint16 GetServiceIntervalClamped(uint interval, CompanyID company_id)
01949 {
01950   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);
01951 }
01952 
01961 static bool CheckForValidOrders(const Vehicle *v)
01962 {
01963   const Order *order;
01964 
01965   FOR_VEHICLE_ORDERS(v, order) {
01966     switch (order->GetType()) {
01967       case OT_GOTO_STATION:
01968       case OT_GOTO_DEPOT:
01969       case OT_GOTO_WAYPOINT:
01970         return true;
01971 
01972       default:
01973         break;
01974     }
01975   }
01976 
01977   return false;
01978 }
01979 
01983 static bool OrderConditionCompare(OrderConditionComparator occ, int variable, int value)
01984 {
01985   switch (occ) {
01986     case OCC_EQUALS:      return variable == value;
01987     case OCC_NOT_EQUALS:  return variable != value;
01988     case OCC_LESS_THAN:   return variable <  value;
01989     case OCC_LESS_EQUALS: return variable <= value;
01990     case OCC_MORE_THAN:   return variable >  value;
01991     case OCC_MORE_EQUALS: return variable >= value;
01992     case OCC_IS_TRUE:     return variable != 0;
01993     case OCC_IS_FALSE:    return variable == 0;
01994     default: NOT_REACHED();
01995   }
01996 }
01997 
02004 VehicleOrderID ProcessConditionalOrder(const Order *order, const Vehicle *v)
02005 {
02006   if (order->GetType() != OT_CONDITIONAL) return INVALID_VEH_ORDER_ID;
02007 
02008   bool skip_order = false;
02009   OrderConditionComparator occ = order->GetConditionComparator();
02010   uint16 value = order->GetConditionValue();
02011 
02012   switch (order->GetConditionVariable()) {
02013     case OCV_LOAD_PERCENTAGE:    skip_order = OrderConditionCompare(occ, CalcPercentVehicleFilled(v, NULL), value); break;
02014     case OCV_RELIABILITY:        skip_order = OrderConditionCompare(occ, ToPercent16(v->reliability),       value); break;
02015     case OCV_MAX_SPEED:          skip_order = OrderConditionCompare(occ, v->GetDisplayMaxSpeed() * 10 / 16, value); break;
02016     case OCV_AGE:                skip_order = OrderConditionCompare(occ, v->age / DAYS_IN_LEAP_YEAR,        value); break;
02017     case OCV_REQUIRES_SERVICE:   skip_order = OrderConditionCompare(occ, v->NeedsServicing(),               value); break;
02018     case OCV_UNCONDITIONALLY:    skip_order = true; break;
02019     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;
02020     default: NOT_REACHED();
02021   }
02022 
02023   return skip_order ? order->GetConditionSkipToOrder() : (VehicleOrderID)INVALID_VEH_ORDER_ID;
02024 }
02025 
02033 bool UpdateOrderDest(Vehicle *v, const Order *order, int conditional_depth, bool pbs_look_ahead)
02034 {
02035   if (conditional_depth > v->GetNumOrders()) return false;
02036 
02037   switch (order->GetType()) {
02038     case OT_GOTO_STATION:
02039       v->dest_tile = v->GetOrderStationLocation(order->GetDestination());
02040       return true;
02041 
02042     case OT_GOTO_DEPOT:
02043       if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !v->NeedsServicing()) {
02044         assert(!pbs_look_ahead);
02045         UpdateVehicleTimetable(v, true);
02046         v->IncrementRealOrderIndex();
02047         break;
02048       }
02049 
02050       if (v->current_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) {
02051         /* We need to search for the nearest depot (hangar). */
02052         TileIndex location;
02053         DestinationID destination;
02054         bool reverse;
02055 
02056         if (v->FindClosestDepot(&location, &destination, &reverse)) {
02057           /* PBS reservations cannot reverse */
02058           if (pbs_look_ahead && reverse) return false;
02059 
02060           v->dest_tile = location;
02061           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());
02062 
02063           /* If there is no depot in front, reverse automatically (trains only) */
02064           if (v->type == VEH_TRAIN && reverse) DoCommand(v->tile, v->index, 0, DC_EXEC, CMD_REVERSE_TRAIN_DIRECTION);
02065 
02066           if (v->type == VEH_AIRCRAFT) {
02067             Aircraft *a = Aircraft::From(v);
02068             if (a->state == FLYING && a->targetairport != destination) {
02069               /* The aircraft is now heading for a different hangar than the next in the orders */
02070               extern void AircraftNextAirportPos_and_Order(Aircraft *a);
02071               AircraftNextAirportPos_and_Order(a);
02072             }
02073           }
02074           return true;
02075         }
02076 
02077         /* If there is no depot, we cannot help PBS either. */
02078         if (pbs_look_ahead) return false;
02079 
02080         UpdateVehicleTimetable(v, true);
02081         v->IncrementRealOrderIndex();
02082       } else {
02083         if (v->type != VEH_AIRCRAFT) {
02084           v->dest_tile = Depot::Get(order->GetDestination())->xy;
02085         }
02086         return true;
02087       }
02088       break;
02089 
02090     case OT_GOTO_WAYPOINT:
02091       v->dest_tile = Waypoint::Get(order->GetDestination())->xy;
02092       return true;
02093 
02094     case OT_CONDITIONAL: {
02095       assert(!pbs_look_ahead);
02096       VehicleOrderID next_order = ProcessConditionalOrder(order, v);
02097       if (next_order != INVALID_VEH_ORDER_ID) {
02098         /* Jump to next_order. cur_implicit_order_index becomes exactly that order,
02099          * cur_real_order_index might come after next_order. */
02100         UpdateVehicleTimetable(v, false);
02101         v->cur_implicit_order_index = v->cur_real_order_index = next_order;
02102         v->UpdateRealOrderIndex();
02103         v->current_order_time += v->GetOrder(v->cur_real_order_index)->travel_time;
02104 
02105         /* Disable creation of implicit orders.
02106          * When inserting them we do not know that we would have to make the conditional orders point to them. */
02107         if (v->IsGroundVehicle()) {
02108           uint16 &gv_flags = v->GetGroundVehicleFlags();
02109           SetBit(gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
02110         }
02111       } else {
02112         UpdateVehicleTimetable(v, true);
02113         v->IncrementRealOrderIndex();
02114       }
02115       break;
02116     }
02117 
02118     default:
02119       v->dest_tile = 0;
02120       return false;
02121   }
02122 
02123   assert(v->cur_implicit_order_index < v->GetNumOrders());
02124   assert(v->cur_real_order_index < v->GetNumOrders());
02125 
02126   /* Get the current order */
02127   order = v->GetOrder(v->cur_real_order_index);
02128   if (order != NULL && order->IsType(OT_IMPLICIT)) {
02129     assert(v->GetNumManualOrders() == 0);
02130     order = NULL;
02131   }
02132 
02133   if (order == NULL) {
02134     v->current_order.Free();
02135     v->dest_tile = 0;
02136     return false;
02137   }
02138 
02139   v->current_order = *order;
02140   return UpdateOrderDest(v, order, conditional_depth + 1, pbs_look_ahead);
02141 }
02142 
02150 bool ProcessOrders(Vehicle *v)
02151 {
02152   switch (v->current_order.GetType()) {
02153     case OT_GOTO_DEPOT:
02154       /* Let a depot order in the orderlist interrupt. */
02155       if (!(v->current_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) return false;
02156       break;
02157 
02158     case OT_LOADING:
02159       return false;
02160 
02161     case OT_LEAVESTATION:
02162       if (v->type != VEH_AIRCRAFT) return false;
02163       break;
02164 
02165     default: break;
02166   }
02167 
02175   bool may_reverse = v->current_order.IsType(OT_NOTHING);
02176 
02177   /* Check if we've reached a 'via' destination. */
02178   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)) &&
02179       IsTileType(v->tile, MP_STATION) &&
02180       v->current_order.GetDestination() == GetStationIndex(v->tile)) {
02181     v->DeleteUnreachedImplicitOrders();
02182     /* We set the last visited station here because we do not want
02183      * the train to stop at this 'via' station if the next order
02184      * is a no-non-stop order; in that case not setting the last
02185      * visited station will cause the vehicle to still stop. */
02186     v->last_station_visited = v->current_order.GetDestination();
02187     UpdateVehicleTimetable(v, true);
02188     v->IncrementImplicitOrderIndex();
02189   }
02190 
02191   /* Get the current order */
02192   assert(v->cur_implicit_order_index == 0 || v->cur_implicit_order_index < v->GetNumOrders());
02193   v->UpdateRealOrderIndex();
02194 
02195   const Order *order = v->GetOrder(v->cur_real_order_index);
02196   if (order != NULL && order->IsType(OT_IMPLICIT)) {
02197     assert(v->GetNumManualOrders() == 0);
02198     order = NULL;
02199   }
02200 
02201   /* If no order, do nothing. */
02202   if (order == NULL || (v->type == VEH_AIRCRAFT && !CheckForValidOrders(v))) {
02203     if (v->type == VEH_AIRCRAFT) {
02204       /* Aircraft do something vastly different here, so handle separately */
02205       extern void HandleMissingAircraftOrders(Aircraft *v);
02206       HandleMissingAircraftOrders(Aircraft::From(v));
02207       return false;
02208     }
02209 
02210     v->current_order.Free();
02211     v->dest_tile = 0;
02212     return false;
02213   }
02214 
02215   /* If it is unchanged, keep it. */
02216   if (order->Equals(v->current_order) && (v->type == VEH_AIRCRAFT || v->dest_tile != 0) &&
02217       (v->type != VEH_SHIP || !order->IsType(OT_GOTO_STATION) || Station::Get(order->GetDestination())->dock_tile != INVALID_TILE)) {
02218     return false;
02219   }
02220 
02221   /* Otherwise set it, and determine the destination tile. */
02222   v->current_order = *order;
02223 
02224   InvalidateVehicleOrder(v, VIWD_MODIFY_ORDERS);
02225   switch (v->type) {
02226     default:
02227       NOT_REACHED();
02228 
02229     case VEH_ROAD:
02230     case VEH_TRAIN:
02231       break;
02232 
02233     case VEH_AIRCRAFT:
02234     case VEH_SHIP:
02235       SetWindowClassesDirty(GetWindowClassForVehicleType(v->type));
02236       break;
02237   }
02238 
02239   return UpdateOrderDest(v, order) && may_reverse;
02240 }
02241 
02249 bool Order::ShouldStopAtStation(const Vehicle *v, StationID station) const
02250 {
02251   bool is_dest_station = this->IsType(OT_GOTO_STATION) && this->dest == station;
02252 
02253   return (!this->IsType(OT_GOTO_DEPOT) || (this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS) != 0) &&
02254       v->last_station_visited != station && // Do stop only when we've not just been there
02255       /* Finally do stop when there is no non-stop flag set for this type of station. */
02256       !(this->GetNonStopType() & (is_dest_station ? ONSF_NO_STOP_AT_DESTINATION_STATION : ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS));
02257 }
02258 
02259 bool Order::CanLoadOrUnload() const
02260 {
02261   return (this->IsType(OT_GOTO_STATION) || this->IsType(OT_IMPLICIT)) &&
02262       (this->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) == 0 &&
02263       ((this->GetLoadType() & OLFB_NO_LOAD) == 0 ||
02264       (this->GetUnloadType() & OUFB_NO_UNLOAD) == 0);
02265 }
02266 
02273 bool Order::CanLeaveWithCargo(bool has_cargo) const
02274 {
02275   return (this->GetLoadType() & OLFB_NO_LOAD) == 0 || (has_cargo &&
02276       (this->GetUnloadType() & (OUFB_UNLOAD | OUFB_TRANSFER)) == 0);
02277 }