# order_cmd.cpp

Go to the documentation of this file.

    00001 /* $Id: order_cmd.cpp 24995 2013-02-14 17:06:49Z rubidium $ */
    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 "aircraft.h"
    00024 #include "roadveh.h"
    00025 #include "station_base.h"
    00026 #include "waypoint_base.h"
    00027 #include "company_base.h"
    00028 #include "order_backup.h"
    00029
    00030 #include "table/strings.h"
    00031
    00032 /* DestinationID must be at least as large as every these below, because it can
    00033  * be any of them
    00034  */
    00035 assert_compile(sizeof(DestinationID) >= sizeof(DepotID));
    00036 assert_compile(sizeof(DestinationID) >= sizeof(StationID));
    00037
    00038 OrderPool _order_pool("Order");
    00039 INSTANTIATE_POOL_METHODS(Order)
    00040 OrderListPool _orderlist_pool("OrderList");
    00041 INSTANTIATE_POOL_METHODS(OrderList)
    00042
    00044 Order::~Order()
    00045 {
    00046   if (CleaningPool()) return;
    00047
    00048   /* We can visit oil rigs and buoys that are not our own. They will be shown in
    00049    * the list of stations. So, we need to invalidate that window if needed. */
    00050   if (this->IsType(OT_GOTO_STATION) || this->IsType(OT_GOTO_WAYPOINT)) {
    00051     BaseStation *bs = BaseStation::GetIfValid(this->GetDestination());
    00052     if (bs != NULL && bs->owner == OWNER_NONE) InvalidateWindowClassesData(WC_STATION_LIST, 0);
    00053   }
    00054 }
    00055
    00060 void Order::Free()
    00061 {
    00062   this->type  = OT_NOTHING;
    00063   this->flags = 0;
    00064   this->dest  = 0;
    00065   this->next  = NULL;
    00066 }
    00067
    00072 void Order::MakeGoToStation(StationID destination)
    00073 {
    00074   this->type = OT_GOTO_STATION;
    00075   this->flags = 0;
    00076   this->dest = destination;
    00077 }
    00078
    00088 void Order::MakeGoToDepot(DepotID destination, OrderDepotTypeFlags order, OrderNonStopFlags non_stop_type, OrderDepotActionFlags action, CargoID cargo, byte subtype)
    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, subtype);
    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
    00164 void Order::SetRefit(CargoID cargo, byte subtype)
    00165 {
    00166   this->refit_cargo = cargo;
    00167   this->refit_subtype = subtype;
    00168 }
    00169
    00175 bool Order::Equals(const Order &other) const
    00176 {
    00177   /* In case of go to nearest depot orders we need "only" compare the flags
    00178    * with the other and not the nearest depot order bit or the actual
    00179    * destination because those get clear/filled in during the order
    00180    * evaluation. If we do not do this the order will continuously be seen as
    00181    * a different order and it will try to find a "nearest depot" every tick. */
    00182   if ((this->IsType(OT_GOTO_DEPOT) && this->type == other.type) &&
    00183       ((this->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0 ||
    00184        (other.GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0)) {
    00185     return this->GetDepotOrderType() == other.GetDepotOrderType() &&
    00186         (this->GetDepotActionType() & ~ODATFB_NEAREST_DEPOT) == (other.GetDepotActionType() & ~ODATFB_NEAREST_DEPOT);
    00187   }
    00188
    00189   return this->type == other.type && this->flags == other.flags && this->dest == other.dest;
    00190 }
    00191
    00198 uint32 Order::Pack() const
    00199 {
    00200   return this->dest << 16 | this->flags << 8 | this->type;
    00201 }
    00202
    00208 uint16 Order::MapOldOrder() const
    00209 {
    00210   uint16 order = this->GetType();
    00211   switch (this->type) {
    00212     case OT_GOTO_STATION:
    00213       if (this->GetUnloadType() & OUFB_UNLOAD) SetBit(order, 5);
    00214       if (this->GetLoadType() & OLFB_FULL_LOAD) SetBit(order, 6);
    00215       if (this->GetNonStopType() & ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS) SetBit(order, 7);
    00216       order |= GB(this->GetDestination(), 0, 8) << 8;
    00217       break;
    00218     case OT_GOTO_DEPOT:
    00219       if (!(this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) SetBit(order, 6);
    00220       SetBit(order, 7);
    00221       order |= GB(this->GetDestination(), 0, 8) << 8;
    00222       break;
    00223     case OT_LOADING:
    00224       if (this->GetLoadType() & OLFB_FULL_LOAD) SetBit(order, 6);
    00225       break;
    00226   }
    00227   return order;
    00228 }
    00229
    00234 Order::Order(uint32 packed)
    00235 {
    00236   this->type    = (OrderType)GB(packed,  0,  8);
    00237   this->flags   = GB(packed,  8,  8);
    00238   this->dest    = GB(packed, 16, 16);
    00239   this->next    = NULL;
    00240   this->refit_cargo   = CT_NO_REFIT;
    00241   this->refit_subtype = 0;
    00242   this->wait_time     = 0;
    00243   this->travel_time   = 0;
    00244   this->max_speed     = UINT16_MAX;
    00245 }
    00246
    00252 void InvalidateVehicleOrder(const Vehicle *v, int data)
    00253 {
    00254   SetWindowDirty(WC_VEHICLE_VIEW, v->index);
    00255
    00256   if (data != 0) {
    00257     /* Calls SetDirty() too */
    00258     InvalidateWindowData(WC_VEHICLE_ORDERS,    v->index, data);
    00259     InvalidateWindowData(WC_VEHICLE_TIMETABLE, v->index, data);
    00260     return;
    00261   }
    00262
    00263   SetWindowDirty(WC_VEHICLE_ORDERS,    v->index);
    00264   SetWindowDirty(WC_VEHICLE_TIMETABLE, v->index);
    00265 }
    00266
    00274 void Order::AssignOrder(const Order &other)
    00275 {
    00276   this->type  = other.type;
    00277   this->flags = other.flags;
    00278   this->dest  = other.dest;
    00279
    00280   this->refit_cargo   = other.refit_cargo;
    00281   this->refit_subtype = other.refit_subtype;
    00282
    00283   this->wait_time   = other.wait_time;
    00284   this->travel_time = other.travel_time;
    00285   this->max_speed   = other.max_speed;
    00286 }
    00287
    00293 void OrderList::Initialize(Order *chain, Vehicle *v)
    00294 {
    00295   this->first = chain;
    00296   this->first_shared = v;
    00297
    00298   this->num_orders = 0;
    00299   this->num_manual_orders = 0;
    00300   this->num_vehicles = 1;
    00301   this->timetable_duration = 0;
    00302
    00303   for (Order *o = this->first; o != NULL; o = o->next) {
    00304     ++this->num_orders;
    00305     if (!o->IsType(OT_IMPLICIT)) ++this->num_manual_orders;
    00306     this->timetable_duration += o->wait_time + o->travel_time;
    00307   }
    00308
    00309   for (Vehicle *u = this->first_shared->PreviousShared(); u != NULL; u = u->PreviousShared()) {
    00310     ++this->num_vehicles;
    00311     this->first_shared = u;
    00312   }
    00313
    00314   for (const Vehicle *u = v->NextShared(); u != NULL; u = u->NextShared()) ++this->num_vehicles;
    00315 }
    00316
    00322 void OrderList::FreeChain(bool keep_orderlist)
    00323 {
    00324   Order *next;
    00325   for (Order *o = this->first; o != NULL; o = next) {
    00326     next = o->next;
    00327     delete o;
    00328   }
    00329
    00330   if (keep_orderlist) {
    00331     this->first = NULL;
    00332     this->num_orders = 0;
    00333     this->num_manual_orders = 0;
    00334     this->timetable_duration = 0;
    00335   } else {
    00336     delete this;
    00337   }
    00338 }
    00339
    00345 Order *OrderList::GetOrderAt(int index) const
    00346 {
    00347   if (index < 0) return NULL;
    00348
    00349   Order *order = this->first;
    00350
    00351   while (order != NULL && index-- > 0) {
    00352     order = order->next;
    00353   }
    00354   return order;
    00355 }
    00356
    00362 void OrderList::InsertOrderAt(Order *new_order, int index)
    00363 {
    00364   if (this->first == NULL) {
    00365     this->first = new_order;
    00366   } else {
    00367     if (index == 0) {
    00368       /* Insert as first or only order */
    00369       new_order->next = this->first;
    00370       this->first = new_order;
    00371     } else if (index >= this->num_orders) {
    00372       /* index is after the last order, add it to the end */
    00373       this->GetLastOrder()->next = new_order;
    00374     } else {
    00375       /* Put the new order in between */
    00376       Order *order = this->GetOrderAt(index - 1);
    00377       new_order->next = order->next;
    00378       order->next = new_order;
    00379     }
    00380   }
    00381   ++this->num_orders;
    00382   if (!new_order->IsType(OT_IMPLICIT)) ++this->num_manual_orders;
    00383   this->timetable_duration += new_order->wait_time + new_order->travel_time;
    00384
    00385   /* We can visit oil rigs and buoys that are not our own. They will be shown in
    00386    * the list of stations. So, we need to invalidate that window if needed. */
    00387   if (new_order->IsType(OT_GOTO_STATION) || new_order->IsType(OT_GOTO_WAYPOINT)) {
    00388     BaseStation *bs = BaseStation::Get(new_order->GetDestination());
    00389     if (bs->owner == OWNER_NONE) InvalidateWindowClassesData(WC_STATION_LIST, 0);
    00390   }
    00391
    00392 }
    00393
    00394
    00399 void OrderList::DeleteOrderAt(int index)
    00400 {
    00401   if (index >= this->num_orders) return;
    00402
    00403   Order *to_remove;
    00404
    00405   if (index == 0) {
    00406     to_remove = this->first;
    00407     this->first = to_remove->next;
    00408   } else {
    00409     Order *prev = GetOrderAt(index - 1);
    00410     to_remove = prev->next;
    00411     prev->next = to_remove->next;
    00412   }
    00413   --this->num_orders;
    00414   if (!to_remove->IsType(OT_IMPLICIT)) --this->num_manual_orders;
    00415   this->timetable_duration -= (to_remove->wait_time + to_remove->travel_time);
    00416   delete to_remove;
    00417 }
    00418
    00424 void OrderList::MoveOrder(int from, int to)
    00425 {
    00426   if (from >= this->num_orders || to >= this->num_orders || from == to) return;
    00427
    00428   Order *moving_one;
    00429
    00430   /* Take the moving order out of the pointer-chain */
    00431   if (from == 0) {
    00432     moving_one = this->first;
    00433     this->first = moving_one->next;
    00434   } else {
    00435     Order *one_before = GetOrderAt(from - 1);
    00436     moving_one = one_before->next;
    00437     one_before->next = moving_one->next;
    00438   }
    00439
    00440   /* Insert the moving_order again in the pointer-chain */
    00441   if (to == 0) {
    00442     moving_one->next = this->first;
    00443     this->first = moving_one;
    00444   } else {
    00445     Order *one_before = GetOrderAt(to - 1);
    00446     moving_one->next = one_before->next;
    00447     one_before->next = moving_one;
    00448   }
    00449 }
    00450
    00456 void OrderList::RemoveVehicle(Vehicle *v)
    00457 {
    00458   --this->num_vehicles;
    00459   if (v == this->first_shared) this->first_shared = v->NextShared();
    00460 }
    00461
    00466 bool OrderList::IsVehicleInSharedOrdersList(const Vehicle *v) const
    00467 {
    00468   for (const Vehicle *v_shared = this->first_shared; v_shared != NULL; v_shared = v_shared->NextShared()) {
    00469     if (v_shared == v) return true;
    00470   }
    00471
    00472   return false;
    00473 }
    00474
    00480 int OrderList::GetPositionInSharedOrderList(const Vehicle *v) const
    00481 {
    00482   int count = 0;
    00483   for (const Vehicle *v_shared = v->PreviousShared(); v_shared != NULL; v_shared = v_shared->PreviousShared()) count++;
    00484   return count;
    00485 }
    00486
    00491 bool OrderList::IsCompleteTimetable() const
    00492 {
    00493   for (Order *o = this->first; o != NULL; o = o->next) {
    00494     /* Implicit orders are, by definition, not timetabled. */
    00495     if (o->IsType(OT_IMPLICIT)) continue;
    00496     if (!o->IsCompletelyTimetabled()) return false;
    00497   }
    00498   return true;
    00499 }
    00500
    00504 void OrderList::DebugCheckSanity() const
    00505 {
    00506   VehicleOrderID check_num_orders = 0;
    00507   VehicleOrderID check_num_manual_orders = 0;
    00508   uint check_num_vehicles = 0;
    00509   Ticks check_timetable_duration = 0;
    00510
    00511   DEBUG(misc, 6, "Checking OrderList %hu for sanity...", this->index);
    00512
    00513   for (const Order *o = this->first; o != NULL; o = o->next) {
    00514     ++check_num_orders;
    00515     if (!o->IsType(OT_IMPLICIT)) ++check_num_manual_orders;
    00516     check_timetable_duration += o->wait_time + o->travel_time;
    00517   }
    00518   assert(this->num_orders == check_num_orders);
    00519   assert(this->num_manual_orders == check_num_manual_orders);
    00520   assert(this->timetable_duration == check_timetable_duration);
    00521
    00522   for (const Vehicle *v = this->first_shared; v != NULL; v = v->NextShared()) {
    00523     ++check_num_vehicles;
    00524     assert(v->orders.list == this);
    00525   }
    00526   assert(this->num_vehicles == check_num_vehicles);
    00527   DEBUG(misc, 6, "... detected %u orders (%u manual), %u vehicles, %i ticks",
    00528       (uint)this->num_orders, (uint)this->num_manual_orders,
    00529       this->num_vehicles, this->timetable_duration);
    00530 }
    00531
    00539 static inline bool OrderGoesToStation(const Vehicle *v, const Order *o)
    00540 {
    00541   return o->IsType(OT_GOTO_STATION) ||
    00542       (v->type == VEH_AIRCRAFT && o->IsType(OT_GOTO_DEPOT) && !(o->GetDepotActionType() & ODATFB_NEAREST_DEPOT));
    00543 }
    00544
    00551 static void DeleteOrderWarnings(const Vehicle *v)
    00552 {
    00553   DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_TOO_FEW_ORDERS);
    00554   DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_VOID_ORDER);
    00555   DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_DUPLICATE_ENTRY);
    00556   DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_INVALID_ENTRY);
    00557 }
    00558
    00565 TileIndex Order::GetLocation(const Vehicle *v, bool airport) const
    00566 {
    00567   switch (this->GetType()) {
    00568     case OT_GOTO_WAYPOINT:
    00569     case OT_GOTO_STATION:
    00570     case OT_IMPLICIT:
    00571       if (airport && v->type == VEH_AIRCRAFT) return Station::Get(this->GetDestination())->airport.tile;
    00572       return BaseStation::Get(this->GetDestination())->xy;
    00573
    00574     case OT_GOTO_DEPOT:
    00575       if ((this->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0) return INVALID_TILE;
    00576       return (v->type == VEH_AIRCRAFT) ? Station::Get(this->GetDestination())->xy : Depot::Get(this->GetDestination())->xy;
    00577
    00578     default:
    00579       return INVALID_TILE;
    00580   }
    00581 }
    00582
    00592 uint GetOrderDistance(const Order *prev, const Order *cur, const Vehicle *v, int conditional_depth)
    00593 {
    00594   if (cur->IsType(OT_CONDITIONAL)) {
    00595     if (conditional_depth > v->GetNumOrders()) return 0;
    00596
    00597     conditional_depth++;
    00598
    00599     int dist1 = GetOrderDistance(prev, v->GetOrder(cur->GetConditionSkipToOrder()), v, conditional_depth);
    00600     int dist2 = GetOrderDistance(prev, cur->next == NULL ? v->orders.list->GetFirstOrder() : cur->next, v, conditional_depth);
    00601     return max(dist1, dist2);
    00602   }
    00603
    00604   TileIndex prev_tile = prev->GetLocation(v, true);
    00605   TileIndex cur_tile = cur->GetLocation(v, true);
    00606   if (prev_tile == INVALID_TILE || cur_tile == INVALID_TILE) return 0;
    00607   return v->type == VEH_AIRCRAFT ? DistanceSquare(prev_tile, cur_tile) : DistanceManhattan(prev_tile, cur_tile);
    00608 }
    00609
    00623 CommandCost CmdInsertOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00624 {
    00625   VehicleID veh          = GB(p1,  0, 20);
    00626   VehicleOrderID sel_ord = GB(p1, 20, 8);
    00627   Order new_order(p2);
    00628
    00629   Vehicle *v = Vehicle::GetIfValid(veh);
    00630   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
    00631
    00632   CommandCost ret = CheckOwnership(v->owner);
    00633   if (ret.Failed()) return ret;
    00634
    00635   /* Check if the inserted order is to the correct destination (owner, type),
    00636    * and has the correct flags if any */
    00637   switch (new_order.GetType()) {
    00638     case OT_GOTO_STATION: {
    00639       const Station *st = Station::GetIfValid(new_order.GetDestination());
    00640       if (st == NULL) return CMD_ERROR;
    00641
    00642       if (st->owner != OWNER_NONE) {
    00643         CommandCost ret = CheckOwnership(st->owner);
    00644         if (ret.Failed()) return ret;
    00645       }
    00646
    00647       if (!CanVehicleUseStation(v, st)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
    00648       for (Vehicle *u = v->FirstShared(); u != NULL; u = u->NextShared()) {
    00649         if (!CanVehicleUseStation(u, st)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER_SHARED);
    00650       }
    00651
    00652       /* Non stop only allowed for ground vehicles. */
    00653       if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && !v->IsGroundVehicle()) return CMD_ERROR;
    00654
    00655       /* Filter invalid load/unload types. */
    00656       switch (new_order.GetLoadType()) {
    00657         case OLF_LOAD_IF_POSSIBLE: case OLFB_FULL_LOAD: case OLF_FULL_LOAD_ANY: case OLFB_NO_LOAD: break;
    00658         default: return CMD_ERROR;
    00659       }
    00660       switch (new_order.GetUnloadType()) {
    00661         case OUF_UNLOAD_IF_POSSIBLE: case OUFB_UNLOAD: case OUFB_TRANSFER: case OUFB_NO_UNLOAD: break;
    00662         default: return CMD_ERROR;
    00663       }
    00664
    00665       /* Filter invalid stop locations */
    00666       switch (new_order.GetStopLocation()) {
    00667         case OSL_PLATFORM_NEAR_END:
    00668         case OSL_PLATFORM_MIDDLE:
    00669           if (v->type != VEH_TRAIN) return CMD_ERROR;
    00670           /* FALL THROUGH */
    00671         case OSL_PLATFORM_FAR_END:
    00672           break;
    00673
    00674         default:
    00675           return CMD_ERROR;
    00676       }
    00677
    00678       break;
    00679     }
    00680
    00681     case OT_GOTO_DEPOT: {
    00682       if ((new_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) == 0) {
    00683         if (v->type == VEH_AIRCRAFT) {
    00684           const Station *st = Station::GetIfValid(new_order.GetDestination());
    00685
    00686           if (st == NULL) return CMD_ERROR;
    00687
    00688           CommandCost ret = CheckOwnership(st->owner);
    00689           if (ret.Failed()) return ret;
    00690
    00691           if (!CanVehicleUseStation(v, st) || !st->airport.HasHangar()) {
    00692             return CMD_ERROR;
    00693           }
    00694         } else {
    00695           const Depot *dp = Depot::GetIfValid(new_order.GetDestination());
    00696
    00697           if (dp == NULL) return CMD_ERROR;
    00698
    00699           CommandCost ret = CheckOwnership(GetTileOwner(dp->xy));
    00700           if (ret.Failed()) return ret;
    00701
    00702           switch (v->type) {
    00703             case VEH_TRAIN:
    00704               if (!IsRailDepotTile(dp->xy)) return CMD_ERROR;
    00705               break;
    00706
    00707             case VEH_ROAD:
    00708               if (!IsRoadDepotTile(dp->xy)) return CMD_ERROR;
    00709               break;
    00710
    00711             case VEH_SHIP:
    00712               if (!IsShipDepotTile(dp->xy)) return CMD_ERROR;
    00713               break;
    00714
    00715             default: return CMD_ERROR;
    00716           }
    00717         }
    00718       }
    00719
    00720       if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && !v->IsGroundVehicle()) return CMD_ERROR;
    00721       if (new_order.GetDepotOrderType() & ~(ODTFB_PART_OF_ORDERS | ((new_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS) != 0 ? ODTFB_SERVICE : 0))) return CMD_ERROR;
    00722       if (new_order.GetDepotActionType() & ~(ODATFB_HALT | ODATFB_NEAREST_DEPOT)) return CMD_ERROR;
    00723       if ((new_order.GetDepotOrderType() & ODTFB_SERVICE) && (new_order.GetDepotActionType() & ODATFB_HALT)) return CMD_ERROR;
    00724       break;
    00725     }
    00726
    00727     case OT_GOTO_WAYPOINT: {
    00728       const Waypoint *wp = Waypoint::GetIfValid(new_order.GetDestination());
    00729       if (wp == NULL) return CMD_ERROR;
    00730
    00731       switch (v->type) {
    00732         default: return CMD_ERROR;
    00733
    00734         case VEH_TRAIN: {
    00735           if (!(wp->facilities & FACIL_TRAIN)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
    00736
    00737           CommandCost ret = CheckOwnership(wp->owner);
    00738           if (ret.Failed()) return ret;
    00739           break;
    00740         }
    00741
    00742         case VEH_SHIP:
    00743           if (!(wp->facilities & FACIL_DOCK)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
    00744           if (wp->owner != OWNER_NONE) {
    00745             CommandCost ret = CheckOwnership(wp->owner);
    00746             if (ret.Failed()) return ret;
    00747           }
    00748           break;
    00749       }
    00750
    00751       /* Order flags can be any of the following for waypoints:
    00752        * [non-stop]
    00753        * non-stop orders (if any) are only valid for trains */
    00754       if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && v->type != VEH_TRAIN) return CMD_ERROR;
    00755       break;
    00756     }
    00757
    00758     case OT_CONDITIONAL: {
    00759       VehicleOrderID skip_to = new_order.GetConditionSkipToOrder();
    00760       if (skip_to != 0 && skip_to >= v->GetNumOrders()) return CMD_ERROR; // Always allow jumping to the first (even when there is no order).
    00761       if (new_order.GetConditionVariable() >= OCV_END) return CMD_ERROR;
    00762
    00763       OrderConditionComparator occ = new_order.GetConditionComparator();
    00764       if (occ >= OCC_END) return CMD_ERROR;
    00765       switch (new_order.GetConditionVariable()) {
    00766         case OCV_REQUIRES_SERVICE:
    00767           if (occ != OCC_IS_TRUE && occ != OCC_IS_FALSE) return CMD_ERROR;
    00768           break;
    00769
    00770         case OCV_UNCONDITIONALLY:
    00771           if (occ != OCC_EQUALS) return CMD_ERROR;
    00772           if (new_order.GetConditionValue() != 0) return CMD_ERROR;
    00773           break;
    00774
    00775         case OCV_LOAD_PERCENTAGE:
    00776         case OCV_RELIABILITY:
    00777           if (new_order.GetConditionValue() > 100) return CMD_ERROR;
    00778           /* FALL THROUGH */
    00779         default:
    00780           if (occ == OCC_IS_TRUE || occ == OCC_IS_FALSE) return CMD_ERROR;
    00781           break;
    00782       }
    00783       break;
    00784     }
    00785
    00786     default: return CMD_ERROR;
    00787   }
    00788
    00789   if (sel_ord > v->GetNumOrders()) return CMD_ERROR;
    00790
    00791   if (v->GetNumOrders() >= MAX_VEH_ORDER_ID) return_cmd_error(STR_ERROR_TOO_MANY_ORDERS);
    00792   if (!Order::CanAllocateItem()) return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
    00793   if (v->orders.list == NULL && !OrderList::CanAllocateItem()) return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
    00794
    00795   if (v->type == VEH_SHIP && _settings_game.pf.pathfinder_for_ships != VPF_NPF) {
    00796     /* Make sure the new destination is not too far away from the previous */
    00797     const Order *prev = NULL;
    00798     uint n = 0;
    00799
    00800     /* Find the last goto station or depot order before the insert location.
    00801      * If the order is to be inserted at the beginning of the order list this
    00802      * finds the last order in the list. */
    00803     const Order *o;
    00804     FOR_VEHICLE_ORDERS(v, o) {
    00805       switch (o->GetType()) {
    00806         case OT_GOTO_STATION:
    00807         case OT_GOTO_DEPOT:
    00808         case OT_GOTO_WAYPOINT:
    00809           prev = o;
    00810           break;
    00811
    00812         default: break;
    00813       }
    00814       if (++n == sel_ord && prev != NULL) break;
    00815     }
    00816     if (prev != NULL) {
    00817       uint dist;
    00818       if (new_order.IsType(OT_CONDITIONAL)) {
    00819         /* The order is not yet inserted, so we have to do the first iteration here. */
    00820         dist = GetOrderDistance(prev, v->GetOrder(new_order.GetConditionSkipToOrder()), v);
    00821       } else {
    00822         dist = GetOrderDistance(prev, &new_order, v);
    00823       }
    00824
    00825       if (dist >= 130) {
    00826         return_cmd_error(STR_ERROR_TOO_FAR_FROM_PREVIOUS_DESTINATION);
    00827       }
    00828     }
    00829   }
    00830
    00831   if (flags & DC_EXEC) {
    00832     Order *new_o = new Order();
    00833     new_o->AssignOrder(new_order);
    00834     InsertOrder(v, new_o, sel_ord);
    00835   }
    00836
    00837   return CommandCost();
    00838 }
    00839
    00846 void InsertOrder(Vehicle *v, Order *new_o, VehicleOrderID sel_ord)
    00847 {
    00848   /* Create new order and link in list */
    00849   if (v->orders.list == NULL) {
    00850     v->orders.list = new OrderList(new_o, v);
    00851   } else {
    00852     v->orders.list->InsertOrderAt(new_o, sel_ord);
    00853   }
    00854
    00855   Vehicle *u = v->FirstShared();
    00856   DeleteOrderWarnings(u);
    00857   for (; u != NULL; u = u->NextShared()) {
    00858     assert(v->orders.list == u->orders.list);
    00859
    00860     /* If there is added an order before the current one, we need
    00861      * to update the selected order. We do not change implicit/real order indices though.
    00862      * If the new order is between the current implicit order and real order, the implicit order will
    00863      * later skip the inserted order. */
    00864     if (sel_ord <= u->cur_real_order_index) {
    00865       uint cur = u->cur_real_order_index + 1;
    00866       /* Check if we don't go out of bound */
    00867       if (cur < u->GetNumOrders()) {
    00868         u->cur_real_order_index = cur;
    00869       }
    00870     }
    00871     if (sel_ord == u->cur_implicit_order_index && u->IsGroundVehicle()) {
    00872       /* We are inserting an order just before the current implicit order.
    00873        * We do not know whether we will reach current implicit or the newly inserted order first.
    00874        * So, disable creation of implicit orders until we are on track again. */
    00875       uint16 &gv_flags = u->GetGroundVehicleFlags();
    00876       SetBit(gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
    00877     }
    00878     if (sel_ord <= u->cur_implicit_order_index) {
    00879       uint cur = u->cur_implicit_order_index + 1;
    00880       /* Check if we don't go out of bound */
    00881       if (cur < u->GetNumOrders()) {
    00882         u->cur_implicit_order_index = cur;
    00883       }
    00884     }
    00885     /* Update any possible open window of the vehicle */
    00886     InvalidateVehicleOrder(u, INVALID_VEH_ORDER_ID | (sel_ord << 8));
    00887   }
    00888
    00889   /* As we insert an order, the order to skip to will be 'wrong'. */
    00890   VehicleOrderID cur_order_id = 0;
    00891   Order *order;
    00892   FOR_VEHICLE_ORDERS(v, order) {
    00893     if (order->IsType(OT_CONDITIONAL)) {
    00894       VehicleOrderID order_id = order->GetConditionSkipToOrder();
    00895       if (order_id >= sel_ord) {
    00896         order->SetConditionSkipToOrder(order_id + 1);
    00897       }
    00898       if (order_id == cur_order_id) {
    00899         order->SetConditionSkipToOrder((order_id + 1) % v->GetNumOrders());
    00900       }
    00901     }
    00902     cur_order_id++;
    00903   }
    00904
    00905   /* Make sure to rebuild the whole list */
    00906   InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
    00907 }
    00908
    00914 static CommandCost DecloneOrder(Vehicle *dst, DoCommandFlag flags)
    00915 {
    00916   if (flags & DC_EXEC) {
    00917     DeleteVehicleOrders(dst);
    00918     InvalidateVehicleOrder(dst, VIWD_REMOVE_ALL_ORDERS);
    00919     InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
    00920   }
    00921   return CommandCost();
    00922 }
    00923
    00933 CommandCost CmdDeleteOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00934 {
    00935   VehicleID veh_id = GB(p1, 0, 20);
    00936   VehicleOrderID sel_ord = GB(p2, 0, 8);
    00937
    00938   Vehicle *v = Vehicle::GetIfValid(veh_id);
    00939
    00940   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
    00941
    00942   CommandCost ret = CheckOwnership(v->owner);
    00943   if (ret.Failed()) return ret;
    00944
    00945   /* If we did not select an order, we maybe want to de-clone the orders */
    00946   if (sel_ord >= v->GetNumOrders()) return DecloneOrder(v, flags);
    00947
    00948   if (v->GetOrder(sel_ord) == NULL) return CMD_ERROR;
    00949
    00950   if (flags & DC_EXEC) DeleteOrder(v, sel_ord);
    00951   return CommandCost();
    00952 }
    00953
    00958 static void CancelLoadingDueToDeletedOrder(Vehicle *v)
    00959 {
    00960   assert(v->current_order.IsType(OT_LOADING));
    00961   /* NON-stop flag is misused to see if a train is in a station that is
    00962    * on his order list or not */
    00963   v->current_order.SetNonStopType(ONSF_STOP_EVERYWHERE);
    00964   /* When full loading, "cancel" that order so the vehicle doesn't
    00965    * stay indefinitely at this station anymore. */
    00966   if (v->current_order.GetLoadType() & OLFB_FULL_LOAD) v->current_order.SetLoadType(OLF_LOAD_IF_POSSIBLE);
    00967 }
    00968
    00974 void DeleteOrder(Vehicle *v, VehicleOrderID sel_ord)
    00975 {
    00976   v->orders.list->DeleteOrderAt(sel_ord);
    00977
    00978   Vehicle *u = v->FirstShared();
    00979   DeleteOrderWarnings(u);
    00980   for (; u != NULL; u = u->NextShared()) {
    00981     assert(v->orders.list == u->orders.list);
    00982
    00983     if (sel_ord == u->cur_real_order_index && u->current_order.IsType(OT_LOADING)) {
    00984       CancelLoadingDueToDeletedOrder(u);
    00985     }
    00986
    00987     if (sel_ord < u->cur_real_order_index) {
    00988       u->cur_real_order_index--;
    00989     } else if (sel_ord == u->cur_real_order_index) {
    00990       u->UpdateRealOrderIndex();
    00991     }
    00992
    00993     if (sel_ord < u->cur_implicit_order_index) {
    00994       u->cur_implicit_order_index--;
    00995     } else if (sel_ord == u->cur_implicit_order_index) {
    00996       /* Make sure the index is valid */
    00997       if (u->cur_implicit_order_index >= u->GetNumOrders()) u->cur_implicit_order_index = 0;
    00998
    00999       /* Skip non-implicit orders for the implicit-order-index (e.g. if the current implicit order was deleted */
    01000       while (u->cur_implicit_order_index != u->cur_real_order_index && !u->GetOrder(u->cur_implicit_order_index)->IsType(OT_IMPLICIT)) {
    01001         u->cur_implicit_order_index++;
    01002         if (u->cur_implicit_order_index >= u->GetNumOrders()) u->cur_implicit_order_index = 0;
    01003       }
    01004     }
    01005
    01006     /* Update any possible open window of the vehicle */
    01007     InvalidateVehicleOrder(u, sel_ord | (INVALID_VEH_ORDER_ID << 8));
    01008   }
    01009
    01010   /* As we delete an order, the order to skip to will be 'wrong'. */
    01011   VehicleOrderID cur_order_id = 0;
    01012   Order *order = NULL;
    01013   FOR_VEHICLE_ORDERS(v, order) {
    01014     if (order->IsType(OT_CONDITIONAL)) {
    01015       VehicleOrderID order_id = order->GetConditionSkipToOrder();
    01016       if (order_id >= sel_ord) {
    01017         order_id = max(order_id - 1, 0);
    01018       }
    01019       if (order_id == cur_order_id) {
    01020         order_id = (order_id + 1) % v->GetNumOrders();
    01021       }
    01022       order->SetConditionSkipToOrder(order_id);
    01023     }
    01024     cur_order_id++;
    01025   }
    01026
    01027   InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
    01028 }
    01029
    01039 CommandCost CmdSkipToOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    01040 {
    01041   VehicleID veh_id = GB(p1, 0, 20);
    01042   VehicleOrderID sel_ord = GB(p2, 0, 8);
    01043
    01044   Vehicle *v = Vehicle::GetIfValid(veh_id);
    01045
    01046   if (v == NULL || !v->IsPrimaryVehicle() || sel_ord == v->cur_implicit_order_index || sel_ord >= v->GetNumOrders() || v->GetNumOrders() < 2) return CMD_ERROR;
    01047
    01048   CommandCost ret = CheckOwnership(v->owner);
    01049   if (ret.Failed()) return ret;
    01050
    01051   if (flags & DC_EXEC) {
    01052     v->cur_implicit_order_index = v->cur_real_order_index = sel_ord;
    01053     v->UpdateRealOrderIndex();
    01054
    01055     if (v->current_order.IsType(OT_LOADING)) v->LeaveStation();
    01056
    01057     InvalidateVehicleOrder(v, VIWD_MODIFY_ORDERS);
    01058   }
    01059
    01060   /* We have an aircraft/ship, they have a mini-schedule, so update them all */
    01061   if (v->type == VEH_AIRCRAFT) SetWindowClassesDirty(WC_AIRCRAFT_LIST);
    01062   if (v->type == VEH_SHIP) SetWindowClassesDirty(WC_SHIPS_LIST);
    01063
    01064   return CommandCost();
    01065 }
    01066
    01080 CommandCost CmdMoveOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    01081 {
    01082   VehicleID veh = GB(p1, 0, 20);
    01083   VehicleOrderID moving_order = GB(p2,  0, 16);
    01084   VehicleOrderID target_order = GB(p2, 16, 16);
    01085
    01086   Vehicle *v = Vehicle::GetIfValid(veh);
    01087   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
    01088
    01089   CommandCost ret = CheckOwnership(v->owner);
    01090   if (ret.Failed()) return ret;
    01091
    01092   /* Don't make senseless movements */
    01093   if (moving_order >= v->GetNumOrders() || target_order >= v->GetNumOrders() ||
    01094       moving_order == target_order || v->GetNumOrders() <= 1) return CMD_ERROR;
    01095
    01096   Order *moving_one = v->GetOrder(moving_order);
    01097   /* Don't move an empty order */
    01098   if (moving_one == NULL) return CMD_ERROR;
    01099
    01100   if (flags & DC_EXEC) {
    01101     v->orders.list->MoveOrder(moving_order, target_order);
    01102
    01103     /* Update shared list */
    01104     Vehicle *u = v->FirstShared();
    01105
    01106     DeleteOrderWarnings(u);
    01107
    01108     for (; u != NULL; u = u->NextShared()) {
    01109       /* Update the current order.
    01110        * There are multiple ways to move orders, which result in cur_implicit_order_index
    01111        * and cur_real_order_index to not longer make any sense. E.g. moving another
    01112        * real order between them.
    01113        *
    01114        * Basically one could choose to preserve either of them, but not both.
    01115        * While both ways are suitable in this or that case from a human point of view, neither
    01116        * of them makes really sense.
    01117        * However, from an AI point of view, preserving cur_real_order_index is the most
    01118        * predictable and transparent behaviour.
    01119        *
    01120        * With that decision it basically does not matter what we do to cur_implicit_order_index.
    01121        * If we change orders between the implicit- and real-index, the implicit orders are mostly likely
    01122        * completely out-dated anyway. So, keep it simple and just keep cur_implicit_order_index as well.
    01123        * The worst which can happen is that a lot of implicit orders are removed when reaching current_order.
    01124        */
    01125       if (u->cur_real_order_index == moving_order) {
    01126         u->cur_real_order_index = target_order;
    01127       } else if (u->cur_real_order_index > moving_order && u->cur_real_order_index <= target_order) {
    01128         u->cur_real_order_index--;
    01129       } else if (u->cur_real_order_index < moving_order && u->cur_real_order_index >= target_order) {
    01130         u->cur_real_order_index++;
    01131       }
    01132
    01133       if (u->cur_implicit_order_index == moving_order) {
    01134         u->cur_implicit_order_index = target_order;
    01135       } else if (u->cur_implicit_order_index > moving_order && u->cur_implicit_order_index <= target_order) {
    01136         u->cur_implicit_order_index--;
    01137       } else if (u->cur_implicit_order_index < moving_order && u->cur_implicit_order_index >= target_order) {
    01138         u->cur_implicit_order_index++;
    01139       }
    01140
    01141       assert(v->orders.list == u->orders.list);
    01142       /* Update any possible open window of the vehicle */
    01143       InvalidateVehicleOrder(u, moving_order | (target_order << 8));
    01144     }
    01145
    01146     /* As we move an order, the order to skip to will be 'wrong'. */
    01147     Order *order;
    01148     FOR_VEHICLE_ORDERS(v, order) {
    01149       if (order->IsType(OT_CONDITIONAL)) {
    01150         VehicleOrderID order_id = order->GetConditionSkipToOrder();
    01151         if (order_id == moving_order) {
    01152           order_id = target_order;
    01153         } else if (order_id > moving_order && order_id <= target_order) {
    01154           order_id--;
    01155         } else if (order_id < moving_order && order_id >= target_order) {
    01156           order_id++;
    01157         }
    01158         order->SetConditionSkipToOrder(order_id);
    01159       }
    01160     }
    01161
    01162     /* Make sure to rebuild the whole list */
    01163     InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
    01164   }
    01165
    01166   return CommandCost();
    01167 }
    01168
    01184 CommandCost CmdModifyOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    01185 {
    01186   VehicleOrderID sel_ord = GB(p1, 20,  8);
    01187   VehicleID veh          = GB(p1,  0, 20);
    01188   ModifyOrderFlags mof   = Extract<ModifyOrderFlags, 0, 4>(p2);
    01189   uint16 data            = GB(p2,  4, 11);
    01190
    01191   if (mof >= MOF_END) return CMD_ERROR;
    01192
    01193   Vehicle *v = Vehicle::GetIfValid(veh);
    01194   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
    01195
    01196   CommandCost ret = CheckOwnership(v->owner);
    01197   if (ret.Failed()) return ret;
    01198
    01199   /* Is it a valid order? */
    01200   if (sel_ord >= v->GetNumOrders()) return CMD_ERROR;
    01201
    01202   Order *order = v->GetOrder(sel_ord);
    01203   switch (order->GetType()) {
    01204     case OT_GOTO_STATION:
    01205       if (mof == MOF_COND_VARIABLE || mof == MOF_COND_COMPARATOR || mof == MOF_DEPOT_ACTION || mof == MOF_COND_VALUE) return CMD_ERROR;
    01206       break;
    01207
    01208     case OT_GOTO_DEPOT:
    01209       if (mof != MOF_NON_STOP && mof != MOF_DEPOT_ACTION) return CMD_ERROR;
    01210       break;
    01211
    01212     case OT_GOTO_WAYPOINT:
    01213       if (mof != MOF_NON_STOP) return CMD_ERROR;
    01214       break;
    01215
    01216     case OT_CONDITIONAL:
    01217       if (mof != MOF_COND_VARIABLE && mof != MOF_COND_COMPARATOR && mof != MOF_COND_VALUE && mof != MOF_COND_DESTINATION) return CMD_ERROR;
    01218       break;
    01219
    01220     default:
    01221       return CMD_ERROR;
    01222   }
    01223
    01224   switch (mof) {
    01225     default: NOT_REACHED();
    01226
    01227     case MOF_NON_STOP:
    01228       if (!v->IsGroundVehicle()) return CMD_ERROR;
    01229       if (data >= ONSF_END) return CMD_ERROR;
    01230       if (data == order->GetNonStopType()) return CMD_ERROR;
    01231       break;
    01232
    01233     case MOF_STOP_LOCATION:
    01234       if (v->type != VEH_TRAIN) return CMD_ERROR;
    01235       if (data >= OSL_END) return CMD_ERROR;
    01236       break;
    01237
    01238     case MOF_UNLOAD:
    01239       if ((data & ~(OUFB_UNLOAD | OUFB_TRANSFER | OUFB_NO_UNLOAD)) != 0) return CMD_ERROR;
    01240       /* Unload and no-unload are mutual exclusive and so are transfer and no unload. */
    01241       if (data != 0 && ((data & (OUFB_UNLOAD | OUFB_TRANSFER)) != 0) == ((data & OUFB_NO_UNLOAD) != 0)) return CMD_ERROR;
    01242       if (data == order->GetUnloadType()) return CMD_ERROR;
    01243       break;
    01244
    01245     case MOF_LOAD:
    01246       if (data > OLFB_NO_LOAD || data == 1) return CMD_ERROR;
    01247       if (data == order->GetLoadType()) return CMD_ERROR;
    01248       break;
    01249
    01250     case MOF_DEPOT_ACTION:
    01251       if (data >= DA_END) return CMD_ERROR;
    01252       break;
    01253
    01254     case MOF_COND_VARIABLE:
    01255       if (data >= OCV_END) return CMD_ERROR;
    01256       break;
    01257
    01258     case MOF_COND_COMPARATOR:
    01259       if (data >= OCC_END) return CMD_ERROR;
    01260       switch (order->GetConditionVariable()) {
    01261         case OCV_UNCONDITIONALLY: return CMD_ERROR;
    01262
    01263         case OCV_REQUIRES_SERVICE:
    01264           if (data != OCC_IS_TRUE && data != OCC_IS_FALSE) return CMD_ERROR;
    01265           break;
    01266
    01267         default:
    01268           if (data == OCC_IS_TRUE || data == OCC_IS_FALSE) return CMD_ERROR;
    01269           break;
    01270       }
    01271       break;
    01272
    01273     case MOF_COND_VALUE:
    01274       switch (order->GetConditionVariable()) {
    01275         case OCV_UNCONDITIONALLY: return CMD_ERROR;
    01276
    01277         case OCV_LOAD_PERCENTAGE:
    01278         case OCV_RELIABILITY:
    01279           if (data > 100) return CMD_ERROR;
    01280           break;
    01281
    01282         default:
    01283           if (data > 2047) return CMD_ERROR;
    01284           break;
    01285       }
    01286       break;
    01287
    01288     case MOF_COND_DESTINATION:
    01289       if (data >= v->GetNumOrders()) return CMD_ERROR;
    01290       break;
    01291   }
    01292
    01293   if (flags & DC_EXEC) {
    01294     switch (mof) {
    01295       case MOF_NON_STOP:
    01296         order->SetNonStopType((OrderNonStopFlags)data);
    01297         if (data & ONSF_NO_STOP_AT_DESTINATION_STATION) order->SetRefit(CT_NO_REFIT);
    01298         break;
    01299
    01300       case MOF_STOP_LOCATION:
    01301         order->SetStopLocation((OrderStopLocation)data);
    01302         break;
    01303
    01304       case MOF_UNLOAD:
    01305         order->SetUnloadType((OrderUnloadFlags)data);
    01306         break;
    01307
    01308       case MOF_LOAD:
    01309         order->SetLoadType((OrderLoadFlags)data);
    01310         if (data & OLFB_NO_LOAD) order->SetRefit(CT_NO_REFIT);
    01311         break;
    01312
    01313       case MOF_DEPOT_ACTION: {
    01314         switch (data) {
    01315           case DA_ALWAYS_GO:
    01316             order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
    01317             order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
    01318             break;
    01319
    01320           case DA_SERVICE:
    01321             order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() | ODTFB_SERVICE));
    01322             order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
    01323             order->SetRefit(CT_NO_REFIT);
    01324             break;
    01325
    01326           case DA_STOP:
    01327             order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
    01328             order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() | ODATFB_HALT));
    01329             order->SetRefit(CT_NO_REFIT);
    01330             break;
    01331
    01332           default:
    01333             NOT_REACHED();
    01334         }
    01335         break;
    01336       }
    01337
    01338       case MOF_COND_VARIABLE: {
    01339         order->SetConditionVariable((OrderConditionVariable)data);
    01340
    01341         OrderConditionComparator occ = order->GetConditionComparator();
    01342         switch (order->GetConditionVariable()) {
    01343           case OCV_UNCONDITIONALLY:
    01344             order->SetConditionComparator(OCC_EQUALS);
    01345             order->SetConditionValue(0);
    01346             break;
    01347
    01348           case OCV_REQUIRES_SERVICE:
    01349             if (occ != OCC_IS_TRUE && occ != OCC_IS_FALSE) order->SetConditionComparator(OCC_IS_TRUE);
    01350             break;
    01351
    01352           case OCV_LOAD_PERCENTAGE:
    01353           case OCV_RELIABILITY:
    01354             if (order->GetConditionValue() > 100) order->SetConditionValue(100);
    01355             /* FALL THROUGH */
    01356           default:
    01357             if (occ == OCC_IS_TRUE || occ == OCC_IS_FALSE) order->SetConditionComparator(OCC_EQUALS);
    01358             break;
    01359         }
    01360         break;
    01361       }
    01362
    01363       case MOF_COND_COMPARATOR:
    01364         order->SetConditionComparator((OrderConditionComparator)data);
    01365         break;
    01366
    01367       case MOF_COND_VALUE:
    01368         order->SetConditionValue(data);
    01369         break;
    01370
    01371       case MOF_COND_DESTINATION:
    01372         order->SetConditionSkipToOrder(data);
    01373         break;
    01374
    01375       default: NOT_REACHED();
    01376     }
    01377
    01378     /* Update the windows and full load flags, also for vehicles that share the same order list */
    01379     Vehicle *u = v->FirstShared();
    01380     DeleteOrderWarnings(u);
    01381     for (; u != NULL; u = u->NextShared()) {
    01382       /* Toggle u->current_order "Full load" flag if it changed.
    01383        * However, as the same flag is used for depot orders, check
    01384        * whether we are not going to a depot as there are three
    01385        * cases where the full load flag can be active and only
    01386        * one case where the flag is used for depot orders. In the
    01387        * other cases for the OrderTypeByte the flags are not used,
    01388        * so do not care and those orders should not be active
    01389        * when this function is called.
    01390        */
    01391       if (sel_ord == u->cur_real_order_index &&
    01392           (u->current_order.IsType(OT_GOTO_STATION) || u->current_order.IsType(OT_LOADING)) &&
    01393           u->current_order.GetLoadType() != order->GetLoadType()) {
    01394         u->current_order.SetLoadType(order->GetLoadType());
    01395       }
    01396       InvalidateVehicleOrder(u, VIWD_MODIFY_ORDERS);
    01397     }
    01398   }
    01399
    01400   return CommandCost();
    01401 }
    01402
    01410 static bool CheckAircraftOrderDistance(const Aircraft *v_new, const Vehicle *v_order, const Order *first)
    01411 {
    01412   if (first == NULL || v_new->acache.cached_max_range == 0) return true;
    01413
    01414   /* Iterate over all orders to check the distance between all
    01415    * 'goto' orders and their respective next order (of any type). */
    01416   for (const Order *o = first; o != NULL; o = o->next) {
    01417     switch (o->GetType()) {
    01418       case OT_GOTO_STATION:
    01419       case OT_GOTO_DEPOT:
    01420       case OT_GOTO_WAYPOINT:
    01421         /* If we don't have a next order, we've reached the end and must check the first order instead. */
    01422         if (GetOrderDistance(o, o->next != NULL ? o->next : first, v_order) > v_new->acache.cached_max_range_sqr) return false;
    01423         break;
    01424
    01425       default: break;
    01426     }
    01427   }
    01428
    01429   return true;
    01430 }
    01431
    01443 CommandCost CmdCloneOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    01444 {
    01445   VehicleID veh_src = GB(p2, 0, 20);
    01446   VehicleID veh_dst = GB(p1, 0, 20);
    01447
    01448   Vehicle *dst = Vehicle::GetIfValid(veh_dst);
    01449   if (dst == NULL || !dst->IsPrimaryVehicle()) return CMD_ERROR;
    01450
    01451   CommandCost ret = CheckOwnership(dst->owner);
    01452   if (ret.Failed()) return ret;
    01453
    01454   switch (GB(p1, 30, 2)) {
    01455     case CO_SHARE: {
    01456       Vehicle *src = Vehicle::GetIfValid(veh_src);
    01457
    01458       /* Sanity checks */
    01459       if (src == NULL || !src->IsPrimaryVehicle() || dst->type != src->type || dst == src) return CMD_ERROR;
    01460
    01461       CommandCost ret = CheckOwnership(src->owner);
    01462       if (ret.Failed()) return ret;
    01463
    01464       /* Trucks can't share orders with busses (and visa versa) */
    01465       if (src->type == VEH_ROAD && RoadVehicle::From(src)->IsBus() != RoadVehicle::From(dst)->IsBus()) {
    01466         return CMD_ERROR;
    01467       }
    01468
    01469       /* Is the vehicle already in the shared list? */
    01470       if (src->FirstShared() == dst->FirstShared()) return CMD_ERROR;
    01471
    01472       const Order *order;
    01473
    01474       FOR_VEHICLE_ORDERS(src, order) {
    01475         if (!OrderGoesToStation(dst, order)) continue;
    01476
    01477         /* Allow copying unreachable destinations if they were already unreachable for the source.
    01478          * This is basically to allow cloning / autorenewing / autoreplacing vehicles, while the stations
    01479          * are temporarily invalid due to reconstruction. */
    01480         const Station *st = Station::Get(order->GetDestination());
    01481         if (CanVehicleUseStation(src, st) && !CanVehicleUseStation(dst, st)) {
    01482           return_cmd_error(STR_ERROR_CAN_T_COPY_SHARE_ORDER);
    01483         }
    01484       }
    01485
    01486       /* Check for aircraft range limits. */
    01487       if (dst->type == VEH_AIRCRAFT && !CheckAircraftOrderDistance(Aircraft::From(dst), src, src->GetFirstOrder())) {
    01488         return_cmd_error(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE);
    01489       }
    01490
    01491       if (src->orders.list == NULL && !OrderList::CanAllocateItem()) {
    01492         return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
    01493       }
    01494
    01495       if (flags & DC_EXEC) {
    01496         /* If the destination vehicle had a OrderList, destroy it.
    01497          * We only reset the order indices, if the new orders are obviously different.
    01498          * (We mainly do this to keep the order indices valid and in range.) */
    01499         DeleteVehicleOrders(dst, false, dst->GetNumOrders() != src->GetNumOrders());
    01500
    01501         dst->orders.list = src->orders.list;
    01502
    01503         /* Link this vehicle in the shared-list */
    01504         dst->AddToShared(src);
    01505
    01506         InvalidateVehicleOrder(dst, VIWD_REMOVE_ALL_ORDERS);
    01507         InvalidateVehicleOrder(src, VIWD_MODIFY_ORDERS);
    01508
    01509         InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
    01510       }
    01511       break;
    01512     }
    01513
    01514     case CO_COPY: {
    01515       Vehicle *src = Vehicle::GetIfValid(veh_src);
    01516
    01517       /* Sanity checks */
    01518       if (src == NULL || !src->IsPrimaryVehicle() || dst->type != src->type || dst == src) return CMD_ERROR;
    01519
    01520       CommandCost ret = CheckOwnership(src->owner);
    01521       if (ret.Failed()) return ret;
    01522
    01523       /* Trucks can't copy all the orders from busses (and visa versa),
    01524        * and neither can helicopters and aircraft. */
    01525       const Order *order;
    01526       FOR_VEHICLE_ORDERS(src, order) {
    01527         if (OrderGoesToStation(dst, order) &&
    01528             !CanVehicleUseStation(dst, Station::Get(order->GetDestination()))) {
    01529           return_cmd_error(STR_ERROR_CAN_T_COPY_SHARE_ORDER);
    01530         }
    01531       }
    01532
    01533       /* Check for aircraft range limits. */
    01534       if (dst->type == VEH_AIRCRAFT && !CheckAircraftOrderDistance(Aircraft::From(dst), src, src->GetFirstOrder())) {
    01535         return_cmd_error(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE);
    01536       }
    01537
    01538       /* make sure there are orders available */
    01539       if (!Order::CanAllocateItem(src->GetNumOrders()) || !OrderList::CanAllocateItem()) {
    01540         return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
    01541       }
    01542
    01543       if (flags & DC_EXEC) {
    01544         const Order *order;
    01545         Order *first = NULL;
    01546         Order **order_dst;
    01547
    01548         /* If the destination vehicle had an order list, destroy the chain but keep the OrderList.
    01549          * We only reset the order indices, if the new orders are obviously different.
    01550          * (We mainly do this to keep the order indices valid and in range.) */
    01551         DeleteVehicleOrders(dst, true, dst->GetNumOrders() != src->GetNumOrders());
    01552
    01553         order_dst = &first;
    01554         FOR_VEHICLE_ORDERS(src, order) {
    01555           *order_dst = new Order();
    01556           (*order_dst)->AssignOrder(*order);
    01557           order_dst = &(*order_dst)->next;
    01558         }
    01559         if (dst->orders.list == NULL) {
    01560           dst->orders.list = new OrderList(first, dst);
    01561         } else {
    01562           assert(dst->orders.list->GetFirstOrder() == NULL);
    01563           assert(!dst->orders.list->IsShared());
    01564           delete dst->orders.list;
    01565           assert(OrderList::CanAllocateItem());
    01566           dst->orders.list = new OrderList(first, dst);
    01567         }
    01568
    01569         InvalidateVehicleOrder(dst, VIWD_REMOVE_ALL_ORDERS);
    01570
    01571         InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
    01572       }
    01573       break;
    01574     }
    01575
    01576     case CO_UNSHARE: return DecloneOrder(dst, flags);
    01577     default: return CMD_ERROR;
    01578   }
    01579
    01580   return CommandCost();
    01581 }
    01582
    01595 CommandCost CmdOrderRefit(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    01596 {
    01597   VehicleID veh = GB(p1, 0, 20);
    01598   VehicleOrderID order_number  = GB(p2, 16, 8);
    01599   CargoID cargo = GB(p2, 0, 8);
    01600   byte subtype  = GB(p2, 8, 8);
    01601
    01602   if (cargo >= NUM_CARGO && cargo != CT_NO_REFIT && cargo != CT_AUTO_REFIT) return CMD_ERROR;
    01603
    01604   const Vehicle *v = Vehicle::GetIfValid(veh);
    01605   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
    01606
    01607   CommandCost ret = CheckOwnership(v->owner);
    01608   if (ret.Failed()) return ret;
    01609
    01610   Order *order = v->GetOrder(order_number);
    01611   if (order == NULL) return CMD_ERROR;
    01612
    01613   /* Automatic refit cargo is only supported for goto station orders. */
    01614   if (cargo == CT_AUTO_REFIT && !order->IsType(OT_GOTO_STATION)) return CMD_ERROR;
    01615
    01616   if (order->GetLoadType() & OLFB_NO_LOAD) return CMD_ERROR;
    01617
    01618   if (flags & DC_EXEC) {
    01619     order->SetRefit(cargo, subtype);
    01620
    01621     /* Make the depot order an 'always go' order. */
    01622     if (cargo != CT_NO_REFIT && order->IsType(OT_GOTO_DEPOT)) {
    01623       order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
    01624       order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
    01625     }
    01626
    01627     for (Vehicle *u = v->FirstShared(); u != NULL; u = u->NextShared()) {
    01628       /* Update any possible open window of the vehicle */
    01629       InvalidateVehicleOrder(u, VIWD_MODIFY_ORDERS);
    01630
    01631       /* If the vehicle already got the current depot set as current order, then update current order as well */
    01632       if (u->cur_real_order_index == order_number && (u->current_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) {
    01633         u->current_order.SetRefit(cargo, subtype);
    01634       }
    01635     }
    01636   }
    01637
    01638   return CommandCost();
    01639 }
    01640
    01641
    01647 void CheckOrders(const Vehicle *v)
    01648 {
    01649   /* Does the user wants us to check things? */
    01650   if (_settings_client.gui.order_review_system == 0) return;
    01651
    01652   /* Do nothing for crashed vehicles */
    01653   if (v->vehstatus & VS_CRASHED) return;
    01654
    01655   /* Do nothing for stopped vehicles if setting is '1' */
    01656   if (_settings_client.gui.order_review_system == 1 && (v->vehstatus & VS_STOPPED)) return;
    01657
    01658   /* do nothing we we're not the first vehicle in a share-chain */
    01659   if (v->FirstShared() != v) return;
    01660
    01661   /* Only check every 20 days, so that we don't flood the message log */
    01662   if (v->owner == _local_company && v->day_counter % 20 == 0) {
    01663     int n_st, problem_type = -1;
    01664     const Order *order;
    01665     int message = 0;
    01666
    01667     /* Check the order list */
    01668     n_st = 0;
    01669
    01670     FOR_VEHICLE_ORDERS(v, order) {
    01671       /* Dummy order? */
    01672       if (order->IsType(OT_DUMMY)) {
    01673         problem_type = 1;
    01674         break;
    01675       }
    01676       /* Does station have a load-bay for this vehicle? */
    01677       if (order->IsType(OT_GOTO_STATION)) {
    01678         const Station *st = Station::Get(order->GetDestination());
    01679
    01680         n_st++;
    01681         if (!CanVehicleUseStation(v, st)) problem_type = 3;
    01682       }
    01683     }
    01684
    01685     /* Check if the last and the first order are the same */
    01686     if (v->GetNumOrders() > 1) {
    01687       const Order *last = v->GetLastOrder();
    01688
    01689       if (v->orders.list->GetFirstOrder()->Equals(*last)) {
    01690         problem_type = 2;
    01691       }
    01692     }
    01693
    01694     /* Do we only have 1 station in our order list? */
    01695     if (n_st < 2 && problem_type == -1) problem_type = 0;
    01696
    01697 #ifndef NDEBUG
    01698     if (v->orders.list != NULL) v->orders.list->DebugCheckSanity();
    01699 #endif
    01700
    01701     /* We don't have a problem */
    01702     if (problem_type < 0) return;
    01703
    01704     message = STR_NEWS_VEHICLE_HAS_TOO_FEW_ORDERS + problem_type;
    01705     //DEBUG(misc, 3, "Triggered News Item for vehicle %d", v->index);
    01706
    01707     SetDParam(0, v->index);
    01708     AddVehicleAdviceNewsItem(message, v->index);
    01709   }
    01710 }
    01711
    01717 void RemoveOrderFromAllVehicles(OrderType type, DestinationID destination)
    01718 {
    01719   Vehicle *v;
    01720
    01721   /* Aircraft have StationIDs for depot orders and never use DepotIDs
    01722    * This fact is handled specially below
    01723    */
    01724
    01725   /* Go through all vehicles */
    01726   FOR_ALL_VEHICLES(v) {
    01727     Order *order;
    01728
    01729     order = &v->current_order;
    01730     if ((v->type == VEH_AIRCRAFT && order->IsType(OT_GOTO_DEPOT) ? OT_GOTO_STATION : order->GetType()) == type &&
    01731         v->current_order.GetDestination() == destination) {
    01732       order->MakeDummy();
    01733       SetWindowDirty(WC_VEHICLE_VIEW, v->index);
    01734     }
    01735
    01736     /* Clear the order from the order-list */
    01737     int id = -1;
    01738     FOR_VEHICLE_ORDERS(v, order) {
    01739       id++;
    01740 restart:
    01741
    01742       OrderType ot = order->GetType();
    01743       if (ot == OT_GOTO_DEPOT && (order->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0) continue;
    01744       if (ot == OT_IMPLICIT || (v->type == VEH_AIRCRAFT && ot == OT_GOTO_DEPOT)) ot = OT_GOTO_STATION;
    01745       if (ot == type && order->GetDestination() == destination) {
    01746         /* We want to clear implicit orders, but we don't want to make them
    01747          * dummy orders. They should just vanish. Also check the actual order
    01748          * type as ot is currently OT_GOTO_STATION. */
    01749         if (order->IsType(OT_IMPLICIT)) {
    01750           order = order->next; // DeleteOrder() invalidates current order
    01751           DeleteOrder(v, id);
    01752           if (order != NULL) goto restart;
    01753           break;
    01754         }
    01755
    01756         order->MakeDummy();
    01757         for (const Vehicle *w = v->FirstShared(); w != NULL; w = w->NextShared()) {
    01758           /* In GUI, simulate by removing the order and adding it back */
    01759           InvalidateVehicleOrder(w, id | (INVALID_VEH_ORDER_ID << 8));
    01760           InvalidateVehicleOrder(w, (INVALID_VEH_ORDER_ID << 8) | id);
    01761         }
    01762       }
    01763     }
    01764   }
    01765
    01766   OrderBackup::RemoveOrder(type, destination);
    01767 }
    01768
    01773 bool Vehicle::HasDepotOrder() const
    01774 {
    01775   const Order *order;
    01776
    01777   FOR_VEHICLE_ORDERS(this, order) {
    01778     if (order->IsType(OT_GOTO_DEPOT)) return true;
    01779   }
    01780
    01781   return false;
    01782 }
    01783
    01793 void DeleteVehicleOrders(Vehicle *v, bool keep_orderlist, bool reset_order_indices)
    01794 {
    01795   DeleteOrderWarnings(v);
    01796
    01797   if (v->IsOrderListShared()) {
    01798     /* Remove ourself from the shared order list. */
    01799     v->RemoveFromShared();
    01800     v->orders.list = NULL;
    01801   } else if (v->orders.list != NULL) {
    01802     /* Remove the orders */
    01803     v->orders.list->FreeChain(keep_orderlist);
    01804     if (!keep_orderlist) v->orders.list = NULL;
    01805   }
    01806
    01807   if (reset_order_indices) {
    01808     v->cur_implicit_order_index = v->cur_real_order_index = 0;
    01809     if (v->current_order.IsType(OT_LOADING)) {
    01810       CancelLoadingDueToDeletedOrder(v);
    01811     }
    01812   }
    01813 }
    01814
    01822 uint16 GetServiceIntervalClamped(uint interval, bool ispercent)
    01823 {
    01824   return ispercent ? Clamp(interval, MIN_SERVINT_PERCENT, MAX_SERVINT_PERCENT) : Clamp(interval, MIN_SERVINT_DAYS, MAX_SERVINT_DAYS);
    01825 }
    01826
    01835 static bool CheckForValidOrders(const Vehicle *v)
    01836 {
    01837   const Order *order;
    01838
    01839   FOR_VEHICLE_ORDERS(v, order) {
    01840     switch (order->GetType()) {
    01841       case OT_GOTO_STATION:
    01842       case OT_GOTO_DEPOT:
    01843       case OT_GOTO_WAYPOINT:
    01844         return true;
    01845
    01846       default:
    01847         break;
    01848     }
    01849   }
    01850
    01851   return false;
    01852 }
    01853
    01857 static bool OrderConditionCompare(OrderConditionComparator occ, int variable, int value)
    01858 {
    01859   switch (occ) {
    01860     case OCC_EQUALS:      return variable == value;
    01861     case OCC_NOT_EQUALS:  return variable != value;
    01862     case OCC_LESS_THAN:   return variable <  value;
    01863     case OCC_LESS_EQUALS: return variable <= value;
    01864     case OCC_MORE_THAN:   return variable >  value;
    01865     case OCC_MORE_EQUALS: return variable >= value;
    01866     case OCC_IS_TRUE:     return variable != 0;
    01867     case OCC_IS_FALSE:    return variable == 0;
    01868     default: NOT_REACHED();
    01869   }
    01870 }
    01871
    01878 VehicleOrderID ProcessConditionalOrder(const Order *order, const Vehicle *v)
    01879 {
    01880   if (order->GetType() != OT_CONDITIONAL) return INVALID_VEH_ORDER_ID;
    01881
    01882   bool skip_order = false;
    01883   OrderConditionComparator occ = order->GetConditionComparator();
    01884   uint16 value = order->GetConditionValue();
    01885
    01886   switch (order->GetConditionVariable()) {
    01887     case OCV_LOAD_PERCENTAGE:    skip_order = OrderConditionCompare(occ, CalcPercentVehicleFilled(v, NULL), value); break;
    01888     case OCV_RELIABILITY:        skip_order = OrderConditionCompare(occ, ToPercent16(v->reliability),       value); break;
    01889     case OCV_MAX_SPEED:          skip_order = OrderConditionCompare(occ, v->GetDisplayMaxSpeed() * 10 / 16, value); break;
    01890     case OCV_AGE:                skip_order = OrderConditionCompare(occ, v->age / DAYS_IN_LEAP_YEAR,        value); break;
    01891     case OCV_REQUIRES_SERVICE:   skip_order = OrderConditionCompare(occ, v->NeedsServicing(),               value); break;
    01892     case OCV_UNCONDITIONALLY:    skip_order = true; break;
    01893     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;
    01894     default: NOT_REACHED();
    01895   }
    01896
    01897   return skip_order ? order->GetConditionSkipToOrder() : (VehicleOrderID)INVALID_VEH_ORDER_ID;
    01898 }
    01899
    01907 bool UpdateOrderDest(Vehicle *v, const Order *order, int conditional_depth, bool pbs_look_ahead)
    01908 {
    01909   if (conditional_depth > v->GetNumOrders()) return false;
    01910
    01911   switch (order->GetType()) {
    01912     case OT_GOTO_STATION:
    01913       v->dest_tile = v->GetOrderStationLocation(order->GetDestination());
    01914       return true;
    01915
    01916     case OT_GOTO_DEPOT:
    01917       if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !v->NeedsServicing()) {
    01918         assert(!pbs_look_ahead);
    01919         UpdateVehicleTimetable(v, true);
    01920         v->IncrementRealOrderIndex();
    01921         break;
    01922       }
    01923
    01924       if (v->current_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) {
    01925         /* We need to search for the nearest depot (hangar). */
    01926         TileIndex location;
    01927         DestinationID destination;
    01928         bool reverse;
    01929
    01930         if (v->FindClosestDepot(&location, &destination, &reverse)) {
    01931           /* PBS reservations cannot reverse */
    01932           if (pbs_look_ahead && reverse) return false;
    01933
    01934           v->dest_tile = location;
    01935           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());
    01936
    01937           /* If there is no depot in front, reverse automatically (trains only) */
    01938           if (v->type == VEH_TRAIN && reverse) DoCommand(v->tile, v->index, 0, DC_EXEC, CMD_REVERSE_TRAIN_DIRECTION);
    01939
    01940           if (v->type == VEH_AIRCRAFT) {
    01941             Aircraft *a = Aircraft::From(v);
    01942             if (a->state == FLYING && a->targetairport != destination) {
    01943               /* The aircraft is now heading for a different hangar than the next in the orders */
    01944               extern void AircraftNextAirportPos_and_Order(Aircraft *a);
    01945               AircraftNextAirportPos_and_Order(a);
    01946             }
    01947           }
    01948           return true;
    01949         }
    01950
    01951         /* If there is no depot, we cannot help PBS either. */
    01952         if (pbs_look_ahead) return false;
    01953
    01954         UpdateVehicleTimetable(v, true);
    01955         v->IncrementRealOrderIndex();
    01956       } else {
    01957         if (v->type != VEH_AIRCRAFT) {
    01958           v->dest_tile = Depot::Get(order->GetDestination())->xy;
    01959         }
    01960         return true;
    01961       }
    01962       break;
    01963
    01964     case OT_GOTO_WAYPOINT:
    01965       v->dest_tile = Waypoint::Get(order->GetDestination())->xy;
    01966       return true;
    01967
    01968     case OT_CONDITIONAL: {
    01969       assert(!pbs_look_ahead);
    01970       VehicleOrderID next_order = ProcessConditionalOrder(order, v);
    01971       if (next_order != INVALID_VEH_ORDER_ID) {
    01972         /* Jump to next_order. cur_implicit_order_index becomes exactly that order,
    01973          * cur_real_order_index might come after next_order. */
    01974         UpdateVehicleTimetable(v, false);
    01975         v->cur_implicit_order_index = v->cur_real_order_index = next_order;
    01976         v->UpdateRealOrderIndex();
    01977         v->current_order_time += v->GetOrder(v->cur_real_order_index)->travel_time;
    01978
    01979         /* Disable creation of implicit orders.
    01980          * When inserting them we do not know that we would have to make the conditional orders point to them. */
    01981         if (v->IsGroundVehicle()) {
    01982           uint16 &gv_flags = v->GetGroundVehicleFlags();
    01983           SetBit(gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
    01984         }
    01985       } else {
    01986         UpdateVehicleTimetable(v, true);
    01987         v->IncrementRealOrderIndex();
    01988       }
    01989       break;
    01990     }
    01991
    01992     default:
    01993       v->dest_tile = 0;
    01994       return false;
    01995   }
    01996
    01997   assert(v->cur_implicit_order_index < v->GetNumOrders());
    01998   assert(v->cur_real_order_index < v->GetNumOrders());
    01999
    02000   /* Get the current order */
    02001   order = v->GetOrder(v->cur_real_order_index);
    02002   if (order != NULL && order->IsType(OT_IMPLICIT)) {
    02003     assert(v->GetNumManualOrders() == 0);
    02004     order = NULL;
    02005   }
    02006
    02007   if (order == NULL) {
    02008     v->current_order.Free();
    02009     v->dest_tile = 0;
    02010     return false;
    02011   }
    02012
    02013   v->current_order = *order;
    02014   return UpdateOrderDest(v, order, conditional_depth + 1, pbs_look_ahead);
    02015 }
    02016
    02024 bool ProcessOrders(Vehicle *v)
    02025 {
    02026   switch (v->current_order.GetType()) {
    02027     case OT_GOTO_DEPOT:
    02028       /* Let a depot order in the orderlist interrupt. */
    02029       if (!(v->current_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) return false;
    02030       break;
    02031
    02032     case OT_LOADING:
    02033       return false;
    02034
    02035     case OT_LEAVESTATION:
    02036       if (v->type != VEH_AIRCRAFT) return false;
    02037       break;
    02038
    02039     default: break;
    02040   }
    02041
    02049   bool may_reverse = v->current_order.IsType(OT_NOTHING);
    02050
    02051   /* Check if we've reached a 'via' destination. */
    02052   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)) &&
    02053       IsTileType(v->tile, MP_STATION) &&
    02054       v->current_order.GetDestination() == GetStationIndex(v->tile)) {
    02055     v->DeleteUnreachedImplicitOrders();
    02056     /* We set the last visited station here because we do not want
    02057      * the train to stop at this 'via' station if the next order
    02058      * is a no-non-stop order; in that case not setting the last
    02059      * visited station will cause the vehicle to still stop. */
    02060     v->last_station_visited = v->current_order.GetDestination();
    02061     UpdateVehicleTimetable(v, true);
    02062     v->IncrementImplicitOrderIndex();
    02063   }
    02064
    02065   /* Get the current order */
    02066   assert(v->cur_implicit_order_index == 0 || v->cur_implicit_order_index < v->GetNumOrders());
    02067   v->UpdateRealOrderIndex();
    02068
    02069   const Order *order = v->GetOrder(v->cur_real_order_index);
    02070   if (order != NULL && order->IsType(OT_IMPLICIT)) {
    02071     assert(v->GetNumManualOrders() == 0);
    02072     order = NULL;
    02073   }
    02074
    02075   /* If no order, do nothing. */
    02076   if (order == NULL || (v->type == VEH_AIRCRAFT && !CheckForValidOrders(v))) {
    02077     if (v->type == VEH_AIRCRAFT) {
    02078       /* Aircraft do something vastly different here, so handle separately */
    02079       extern void HandleMissingAircraftOrders(Aircraft *v);
    02080       HandleMissingAircraftOrders(Aircraft::From(v));
    02081       return false;
    02082     }
    02083
    02084     v->current_order.Free();
    02085     v->dest_tile = 0;
    02086     return false;
    02087   }
    02088
    02089   /* If it is unchanged, keep it. */
    02090   if (order->Equals(v->current_order) && (v->type == VEH_AIRCRAFT || v->dest_tile != 0) &&
    02091       (v->type != VEH_SHIP || !order->IsType(OT_GOTO_STATION) || Station::Get(order->GetDestination())->dock_tile != INVALID_TILE)) {
    02092     return false;
    02093   }
    02094
    02095   /* Otherwise set it, and determine the destination tile. */
    02096   v->current_order = *order;
    02097
    02098   InvalidateVehicleOrder(v, VIWD_MODIFY_ORDERS);
    02099   switch (v->type) {
    02100     default:
    02101       NOT_REACHED();
    02102
    02103     case VEH_ROAD:
    02104     case VEH_TRAIN:
    02105       break;
    02106
    02107     case VEH_AIRCRAFT:
    02108     case VEH_SHIP:
    02109       SetWindowClassesDirty(GetWindowClassForVehicleType(v->type));
    02110       break;
    02111   }
    02112
    02113   return UpdateOrderDest(v, order) && may_reverse;
    02114 }
    02115
    02123 bool Order::ShouldStopAtStation(const Vehicle *v, StationID station) const
    02124 {
    02125   bool is_dest_station = this->IsType(OT_GOTO_STATION) && this->dest == station;
    02126
    02127   return (!this->IsType(OT_GOTO_DEPOT) || (this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS) != 0) &&
    02128       v->last_station_visited != station && // Do stop only when we've not just been there
    02129       /* Finally do stop when there is no non-stop flag set for this type of station. */
    02130       !(this->GetNonStopType() & (is_dest_station ? ONSF_NO_STOP_AT_DESTINATION_STATION : ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS));
    02131 }