Inline GfxMainBlitterViewport
[openttd/fttd.git] / src / order_cmd.cpp
blob2a2c705f582ab232e4f54c6e228bdfb6a8f145c1
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
8 */
10 /** @file order_cmd.cpp Handling of orders. */
12 #include "stdafx.h"
13 #include "debug.h"
14 #include "cmd_helper.h"
15 #include "command_func.h"
16 #include "company_func.h"
17 #include "news_func.h"
18 #include "strings_func.h"
19 #include "timetable.h"
20 #include "vehicle_func.h"
21 #include "depot_base.h"
22 #include "core/pool_func.hpp"
23 #include "core/random_func.hpp"
24 #include "aircraft.h"
25 #include "roadveh.h"
26 #include "station_base.h"
27 #include "waypoint_base.h"
28 #include "company_base.h"
29 #include "order_backup.h"
30 #include "cheat_type.h"
32 #include "table/strings.h"
34 /* DestinationID must be at least as large as every these below, because it can
35 * be any of them
37 assert_compile(sizeof(DestinationID) >= sizeof(DepotID));
38 assert_compile(sizeof(DestinationID) >= sizeof(StationID));
40 template<> Order::Pool Order::PoolItem::pool ("Order");
41 INSTANTIATE_POOL_METHODS(Order)
42 template<> OrderList::Pool OrderList::PoolItem::pool ("OrderList");
43 INSTANTIATE_POOL_METHODS(OrderList)
45 /** Clean everything up. */
46 Order::~Order()
48 if (CleaningPool()) return;
50 /* We can visit oil rigs and buoys that are not our own. They will be shown in
51 * the list of stations. So, we need to invalidate that window if needed. */
52 if (this->IsType(OT_GOTO_STATION) || this->IsType(OT_GOTO_WAYPOINT)) {
53 BaseStation *bs = BaseStation::GetIfValid(this->GetDestination());
54 if (bs != NULL && bs->owner == OWNER_NONE) InvalidateWindowClassesData(WC_STATION_LIST, 0);
58 /**
59 * Clear the order
61 void BaseOrder::Clear()
63 this->type = OT_NOTHING;
64 this->flags = 0;
65 this->dest = 0;
68 /**
69 * Makes this order a Go To Station order.
70 * @param destination the station to go to.
72 void BaseOrder::MakeGoToStation(StationID destination)
74 this->type = OT_GOTO_STATION;
75 this->flags = 0;
76 this->dest = destination;
79 /**
80 * Makes this order a Go To Depot order.
81 * @param destination the depot to go to.
82 * @param order is this order a 'default' order, or an overridden vehicle order?
83 * @param non_stop_type how to get to the depot?
84 * @param action what to do in the depot?
86 void BaseOrder::MakeGoToDepot (DepotID destination, OrderDepotTypeFlags order, OrderNonStopFlags non_stop_type, OrderDepotActionFlags action)
88 this->type = OT_GOTO_DEPOT;
89 this->SetDepotOrderType(order);
90 this->SetDepotActionType(action);
91 this->SetNonStopType(non_stop_type);
92 this->dest = destination;
93 this->SetRefitMask();
96 /**
97 * Makes this order a Go To Depot order from a "go to nearest depot" order.
98 * @param destination the depot to go to.
100 inline void BaseOrder::SetGoToDepotDestination (DepotID destination)
102 this->SetDepotActionType ((OrderDepotActionFlags)(this->GetDepotActionType() & ~ODATFB_NEAREST_DEPOT));
103 this->dest = destination;
107 * Makes this order a Go To Waypoint order.
108 * @param destination the waypoint to go to.
110 void BaseOrder::MakeGoToWaypoint(StationID destination)
112 this->type = OT_GOTO_WAYPOINT;
113 this->flags = 0;
114 this->dest = destination;
118 * Makes this order a Loading order.
119 * @param ordered is this an ordered stop?
121 void BaseOrder::MakeLoading(bool ordered)
123 this->type = OT_LOADING;
124 if (!ordered) this->flags = 0;
128 * Makes this order a Leave Station order.
130 void BaseOrder::MakeLeaveStation()
132 this->type = OT_LEAVESTATION;
133 this->flags = 0;
137 * Makes this order a Dummy order.
139 void BaseOrder::MakeDummy()
141 this->type = OT_DUMMY;
142 this->flags = 0;
146 * Makes this order an conditional order.
147 * @param order the order to jump to.
149 void BaseOrder::MakeConditional(VehicleOrderID order)
151 this->type = OT_CONDITIONAL;
152 this->flags = order;
153 this->dest = 0;
157 * Makes this order an implicit order.
158 * @param destination the station to go to.
160 void BaseOrder::MakeImplicit(StationID destination)
162 this->type = OT_IMPLICIT;
163 this->dest = destination;
167 * Make this depot/station order also a refit order.
168 * @param cargo the cargo mask of allowed types to change to.
169 * @pre IsType(OT_GOTO_DEPOT) || IsType(OT_GOTO_STATION).
171 void BaseOrder::SetRefitMask (CargoMask mask)
173 this->refit_cargo_mask = mask;
177 * Does this order have the same type, flags and destination?
178 * @param other the second order to compare to.
179 * @return true if the type, flags and destination match.
181 bool BaseOrder::Equals (const BaseOrder &other) const
183 /* In case of go to nearest depot orders we need "only" compare the flags
184 * with the other and not the nearest depot order bit or the actual
185 * destination because those get clear/filled in during the order
186 * evaluation. If we do not do this the order will continuously be seen as
187 * a different order and it will try to find a "nearest depot" every tick. */
188 if ((this->IsType(OT_GOTO_DEPOT) && this->type == other.type) &&
189 ((this->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0 ||
190 (other.GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0)) {
191 return this->GetDepotOrderType() == other.GetDepotOrderType() &&
192 (this->GetDepotActionType() & ~ODATFB_NEAREST_DEPOT) == (other.GetDepotActionType() & ~ODATFB_NEAREST_DEPOT);
195 return this->type == other.type && this->flags == other.flags && this->dest == other.dest;
199 * Pack this order into a 32 bits integer, or actually only
200 * the type, flags and destination.
201 * @return the packed representation.
202 * @note unpacking is done in the constructor.
204 uint32 BaseOrder::Pack() const
206 return this->dest << 16 | this->flags << 8 | this->type;
210 * Pack this order into a 16 bits integer as close to the TTD
211 * representation as possible.
212 * @return the TTD-like packed representation.
214 uint16 BaseOrder::MapOldOrder() const
216 uint16 order = this->GetType();
217 switch (this->type) {
218 case OT_GOTO_STATION:
219 if (this->GetUnloadType() & OUFB_UNLOAD) SetBit(order, 5);
220 if (this->GetLoadType() & OLFB_FULL_LOAD) SetBit(order, 6);
221 if (this->GetNonStopType() & ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS) SetBit(order, 7);
222 order |= GB(this->GetDestination(), 0, 8) << 8;
223 break;
224 case OT_GOTO_DEPOT:
225 if (!(this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) SetBit(order, 6);
226 SetBit(order, 7);
227 order |= GB(this->GetDestination(), 0, 8) << 8;
228 break;
229 case OT_LOADING:
230 if (this->GetLoadType() & OLFB_FULL_LOAD) SetBit(order, 6);
231 break;
233 return order;
238 * Updates the widgets of a vehicle which contains the order-data
241 void InvalidateVehicleOrder(const Vehicle *v, int data)
243 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
245 if (data != 0) {
246 /* Calls SetDirty() too */
247 InvalidateWindowData(WC_VEHICLE_ORDERS, v->index, data);
248 InvalidateWindowData(WC_VEHICLE_TIMETABLE, v->index, data);
249 return;
252 SetWindowDirty(WC_VEHICLE_ORDERS, v->index);
253 SetWindowDirty(WC_VEHICLE_TIMETABLE, v->index);
258 * Assign data to an order (from another order)
259 * @param other the data to copy (except next pointer).
262 void BaseOrder::AssignOrder (const BaseOrder &other)
264 this->type = other.type;
265 this->flags = other.flags;
266 this->dest = other.dest;
268 this->refit_cargo_mask = other.refit_cargo_mask;
270 this->wait_time = other.wait_time;
271 this->travel_time = other.travel_time;
272 this->max_speed = other.max_speed;
276 * Recomputes everything.
277 * @param chain first order in the chain
278 * @param v one of vehicle that is using this orderlist
280 void OrderList::Initialize(Order *chain, Vehicle *v)
282 this->first = chain;
283 this->first_shared = v;
285 this->num_orders = 0;
286 this->num_manual_orders = 0;
287 this->num_vehicles = 1;
288 this->timetable_duration = 0;
289 this->total_duration = 0;
291 for (Order *o = this->first; o != NULL; o = o->next) {
292 ++this->num_orders;
293 if (!o->IsType(OT_IMPLICIT)) ++this->num_manual_orders;
294 this->timetable_duration += o->GetTimetabledWait() + o->GetTimetabledTravel();
295 this->total_duration += o->GetWaitTime() + o->GetTravelTime();
298 for (Vehicle *u = this->first_shared->PreviousShared(); u != NULL; u = u->PreviousShared()) {
299 ++this->num_vehicles;
300 this->first_shared = u;
303 for (const Vehicle *u = v->NextShared(); u != NULL; u = u->NextShared()) ++this->num_vehicles;
307 * Free a complete order chain.
308 * @param keep_orderlist If this is true only delete the orders, otherwise also delete the OrderList.
309 * @note do not use on "current_order" vehicle orders!
311 void OrderList::FreeChain(bool keep_orderlist)
313 Order *next;
314 for (Order *o = this->first; o != NULL; o = next) {
315 next = o->next;
316 delete o;
319 if (keep_orderlist) {
320 this->first = NULL;
321 this->num_orders = 0;
322 this->num_manual_orders = 0;
323 this->timetable_duration = 0;
324 } else {
325 delete this;
330 * Get a certain order of the order chain.
331 * @param index zero-based index of the order within the chain.
332 * @return the order at position index.
334 Order *OrderList::GetOrderAt(int index) const
336 if (index < 0) return NULL;
338 Order *order = this->first;
340 while (order != NULL && index-- > 0) {
341 order = order->next;
343 return order;
347 * Get the next order which will make the given vehicle stop at a station
348 * or refit at a depot or evaluate a non-trivial condition.
349 * @param next The order to start looking at.
350 * @param hops The number of orders we have already looked at.
351 * @return Either of
352 * \li a station order
353 * \li a refitting depot order
354 * \li a non-trivial conditional order
355 * \li NULL if the vehicle won't stop anymore.
357 const Order *OrderList::GetNextDecisionNode(const Order *next, uint hops) const
359 if (hops > this->GetNumOrders() || next == NULL) return NULL;
361 if (next->IsType(OT_CONDITIONAL)) {
362 if (next->GetConditionVariable() != OCV_UNCONDITIONALLY) return next;
364 /* We can evaluate trivial conditions right away. They're conceptually
365 * the same as regular order progression. */
366 return this->GetNextDecisionNode(
367 this->GetOrderAt(next->GetConditionSkipToOrder()),
368 hops + 1);
371 if (next->IsType(OT_GOTO_DEPOT)) {
372 if (next->GetDepotActionType() == ODATFB_HALT) return NULL;
373 if (next->IsRefit()) return next;
376 if (!next->CanLoadOrUnload()) {
377 return this->GetNextDecisionNode(this->GetNext(next), hops + 1);
380 return next;
384 * Recursively determine the next deterministic station to stop at.
385 * @param result Station id stack to append the next stations to.
386 * @param v The vehicle we're looking at.
387 * @param first Order to start searching at or NULL to start at cur_implicit_order_index + 1.
388 * @param hops Number of orders we have already looked at.
389 * @pre The vehicle is currently loading and v->last_station_visited is meaningful.
390 * @note This function may draw a random number. Don't use it from the GUI.
392 void OrderList::AppendNextStoppingStations (StationIDStack *result,
393 const Vehicle *v, const Order *first, uint hops) const
396 const Order *next = first;
397 if (first == NULL) {
398 next = this->GetOrderAt(v->cur_implicit_order_index);
399 if (next == NULL) {
400 next = this->GetFirstOrder();
401 if (next == NULL) {
402 result->push_back (INVALID_STATION);
403 return;
405 } else {
406 /* GetNext never returns NULL if there is a valid station in the list.
407 * As the given "next" is already valid and a station in the list, we
408 * don't have to check for NULL here. */
409 next = this->GetNext(next);
410 assert(next != NULL);
414 do {
415 next = this->GetNextDecisionNode(next, ++hops);
417 /* Resolve possibly nested conditionals by estimation. */
418 while (next != NULL && next->IsType(OT_CONDITIONAL)) {
419 /* We return both options of conditional orders. */
420 const Order *skip_to = this->GetNextDecisionNode(
421 this->GetOrderAt(next->GetConditionSkipToOrder()), hops);
422 const Order *advance = this->GetNextDecisionNode(
423 this->GetNext(next), hops);
424 if (advance == NULL || advance == first || skip_to == advance) {
425 next = (skip_to == first) ? NULL : skip_to;
426 } else if (skip_to == NULL || skip_to == first) {
427 next = (advance == first) ? NULL : advance;
428 } else {
429 this->AppendNextStoppingStations (result, v, skip_to, hops);
430 this->AppendNextStoppingStations (result, v, advance, hops);
431 return;
433 ++hops;
436 /* Don't return a next stop if the vehicle has to unload everything. */
437 if (next == NULL || ((next->IsType(OT_GOTO_STATION) || next->IsType(OT_IMPLICIT)) &&
438 next->GetDestination() == v->last_station_visited &&
439 (next->GetUnloadType() & (OUFB_TRANSFER | OUFB_UNLOAD)) != 0)) {
440 result->push_back (INVALID_STATION);
441 return;
443 } while (next->IsType(OT_GOTO_DEPOT) || next->GetDestination() == v->last_station_visited);
445 result->push_back (next->GetDestination());
449 * Insert a new order into the order chain.
450 * @param new_order is the order to insert into the chain.
451 * @param index is the position where the order is supposed to be inserted.
453 void OrderList::InsertOrderAt(Order *new_order, int index)
455 if (this->first == NULL) {
456 this->first = new_order;
457 } else {
458 if (index == 0) {
459 /* Insert as first or only order */
460 new_order->next = this->first;
461 this->first = new_order;
462 } else if (index >= this->num_orders) {
463 /* index is after the last order, add it to the end */
464 this->GetLastOrder()->next = new_order;
465 } else {
466 /* Put the new order in between */
467 Order *order = this->GetOrderAt(index - 1);
468 new_order->next = order->next;
469 order->next = new_order;
472 ++this->num_orders;
473 if (!new_order->IsType(OT_IMPLICIT)) ++this->num_manual_orders;
474 this->timetable_duration += new_order->GetTimetabledWait() + new_order->GetTimetabledTravel();
475 this->total_duration += new_order->GetWaitTime() + new_order->GetTravelTime();
477 /* We can visit oil rigs and buoys that are not our own. They will be shown in
478 * the list of stations. So, we need to invalidate that window if needed. */
479 if (new_order->IsType(OT_GOTO_STATION) || new_order->IsType(OT_GOTO_WAYPOINT)) {
480 BaseStation *bs = BaseStation::Get(new_order->GetDestination());
481 if (bs->owner == OWNER_NONE) InvalidateWindowClassesData(WC_STATION_LIST, 0);
488 * Remove an order from the order list and delete it.
489 * @param index is the position of the order which is to be deleted.
491 void OrderList::DeleteOrderAt(int index)
493 if (index >= this->num_orders) return;
495 Order *to_remove;
497 if (index == 0) {
498 to_remove = this->first;
499 this->first = to_remove->next;
500 } else {
501 Order *prev = GetOrderAt(index - 1);
502 to_remove = prev->next;
503 prev->next = to_remove->next;
505 --this->num_orders;
506 if (!to_remove->IsType(OT_IMPLICIT)) --this->num_manual_orders;
507 this->timetable_duration -= (to_remove->GetTimetabledWait() + to_remove->GetTimetabledTravel());
508 this->total_duration -= (to_remove->GetWaitTime() + to_remove->GetTravelTime());
509 delete to_remove;
513 * Move an order to another position within the order list.
514 * @param from is the zero-based position of the order to move.
515 * @param to is the zero-based position where the order is moved to.
517 void OrderList::MoveOrder(int from, int to)
519 if (from >= this->num_orders || to >= this->num_orders || from == to) return;
521 Order *moving_one;
523 /* Take the moving order out of the pointer-chain */
524 if (from == 0) {
525 moving_one = this->first;
526 this->first = moving_one->next;
527 } else {
528 Order *one_before = GetOrderAt(from - 1);
529 moving_one = one_before->next;
530 one_before->next = moving_one->next;
533 /* Insert the moving_order again in the pointer-chain */
534 if (to == 0) {
535 moving_one->next = this->first;
536 this->first = moving_one;
537 } else {
538 Order *one_before = GetOrderAt(to - 1);
539 moving_one->next = one_before->next;
540 one_before->next = moving_one;
545 * Removes the vehicle from the shared order list.
546 * @note This is supposed to be called when the vehicle is still in the chain
547 * @param v vehicle to remove from the list
549 void OrderList::RemoveVehicle(Vehicle *v)
551 --this->num_vehicles;
552 if (v == this->first_shared) this->first_shared = v->NextShared();
556 * Checks whether a vehicle is part of the shared vehicle chain.
557 * @param v is the vehicle to search in the shared vehicle chain.
559 bool OrderList::IsVehicleInSharedOrdersList(const Vehicle *v) const
561 for (const Vehicle *v_shared = this->first_shared; v_shared != NULL; v_shared = v_shared->NextShared()) {
562 if (v_shared == v) return true;
565 return false;
569 * Gets the position of the given vehicle within the shared order vehicle list.
570 * @param v is the vehicle of which to get the position
571 * @return position of v within the shared vehicle chain.
573 int OrderList::GetPositionInSharedOrderList(const Vehicle *v) const
575 int count = 0;
576 for (const Vehicle *v_shared = v->PreviousShared(); v_shared != NULL; v_shared = v_shared->PreviousShared()) count++;
577 return count;
581 * Checks whether all orders of the list have a filled timetable.
582 * @return whether all orders have a filled timetable.
584 bool OrderList::IsCompleteTimetable() const
586 for (Order *o = this->first; o != NULL; o = o->next) {
587 /* Implicit orders are, by definition, not timetabled. */
588 if (o->IsType(OT_IMPLICIT)) continue;
589 if (!o->IsCompletelyTimetabled()) return false;
591 return true;
595 * Checks for internal consistency of order list. Triggers assertion if something is wrong.
597 void OrderList::DebugCheckSanity() const
599 VehicleOrderID check_num_orders = 0;
600 VehicleOrderID check_num_manual_orders = 0;
601 uint check_num_vehicles = 0;
602 Ticks check_timetable_duration = 0;
603 Ticks check_total_duration = 0;
605 DEBUG(misc, 6, "Checking OrderList %hu for sanity...", this->index);
607 for (const Order *o = this->first; o != NULL; o = o->next) {
608 ++check_num_orders;
609 if (!o->IsType(OT_IMPLICIT)) ++check_num_manual_orders;
610 check_timetable_duration += o->GetTimetabledWait() + o->GetTimetabledTravel();
611 check_total_duration += o->GetWaitTime() + o->GetTravelTime();
613 assert(this->num_orders == check_num_orders);
614 assert(this->num_manual_orders == check_num_manual_orders);
615 assert(this->timetable_duration == check_timetable_duration);
616 assert(this->total_duration == check_total_duration);
618 for (const Vehicle *v = this->first_shared; v != NULL; v = v->NextShared()) {
619 ++check_num_vehicles;
620 assert(v->orders.list == this);
622 assert(this->num_vehicles == check_num_vehicles);
623 DEBUG(misc, 6, "... detected %u orders (%u manual), %u vehicles, %i timetabled, %i total",
624 (uint)this->num_orders, (uint)this->num_manual_orders,
625 this->num_vehicles, this->timetable_duration, this->total_duration);
629 * Checks whether the order goes to a station or not, i.e. whether the
630 * destination is a station
631 * @param v the vehicle to check for
632 * @param o the order to check
633 * @return true if the destination is a station
635 static inline bool OrderGoesToStation(const Vehicle *v, const Order *o)
637 return o->IsType(OT_GOTO_STATION) ||
638 (v->type == VEH_AIRCRAFT && o->IsType(OT_GOTO_DEPOT) && !(o->GetDepotActionType() & ODATFB_NEAREST_DEPOT));
642 * Delete all news items regarding defective orders about a vehicle
643 * This could kill still valid warnings (for example about void order when just
644 * another order gets added), but assume the company will notice the problems,
645 * when (s)he's changing the orders.
647 static void DeleteOrderWarnings(const Vehicle *v)
649 DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_TOO_FEW_ORDERS);
650 DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_VOID_ORDER);
651 DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_DUPLICATE_ENTRY);
652 DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_INVALID_ENTRY);
653 DeleteVehicleNews(v->index, STR_NEWS_PLANE_USES_TOO_SHORT_RUNWAY);
657 * Returns a tile somewhat representing the order destination (not suitable for pathfinding).
658 * @param v The vehicle to get the location for.
659 * @param airport Get the airport tile and not the station location for aircraft.
660 * @return destination of order, or INVALID_TILE if none.
662 TileIndex BaseOrder::GetLocation(const Vehicle *v, bool airport) const
664 switch (this->GetType()) {
665 case OT_GOTO_WAYPOINT:
666 case OT_GOTO_STATION:
667 case OT_IMPLICIT:
668 if (airport && v->type == VEH_AIRCRAFT) return Station::Get(this->GetDestination())->airport.tile;
669 return BaseStation::Get(this->GetDestination())->xy;
671 case OT_GOTO_DEPOT:
672 if ((this->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0) return INVALID_TILE;
673 return (v->type == VEH_AIRCRAFT) ? Station::Get(this->GetDestination())->xy : Depot::Get(this->GetDestination())->xy;
675 default:
676 return INVALID_TILE;
681 * Get the distance between two orders.
682 * @param prev Origin order.
683 * @param cur Destination order.
684 * @param v The vehicle to get the distance for.
685 * @return Maximum distance between the two orders.
687 static uint GetBaseOrderDistance (const BaseOrder *prev, const BaseOrder *cur, const Vehicle *v)
689 TileIndex prev_tile = prev->GetLocation (v, true);
690 TileIndex cur_tile = cur->GetLocation (v, true);
691 if (prev_tile == INVALID_TILE || cur_tile == INVALID_TILE) return 0;
692 return v->type == VEH_AIRCRAFT ? DistanceSquare (prev_tile, cur_tile) : DistanceManhattan (prev_tile, cur_tile);
696 * Get the distance between two orders of a vehicle. Conditional orders are resolved
697 * and the bigger distance of the two order branches is returned.
698 * @param prev Origin order.
699 * @param cur Destination order.
700 * @param v The vehicle to get the distance for.
701 * @param conditional_depth Internal param for resolving conditional orders.
702 * @return Maximum distance between the two orders.
704 uint GetOrderDistance(const Order *prev, const Order *cur, const Vehicle *v, int conditional_depth)
706 if (cur->IsType(OT_CONDITIONAL)) {
707 if (conditional_depth > v->GetNumOrders()) return 0;
709 conditional_depth++;
711 int dist1 = GetOrderDistance(prev, v->GetOrder(cur->GetConditionSkipToOrder()), v, conditional_depth);
712 int dist2 = GetOrderDistance(prev, cur->next == NULL ? v->orders.list->GetFirstOrder() : cur->next, v, conditional_depth);
713 return max(dist1, dist2);
716 return GetBaseOrderDistance (prev, cur, v);
720 * Add an order to the orderlist of a vehicle.
721 * @param tile unused
722 * @param flags operation to perform
723 * @param p1 various bitstuffed elements
724 * - p1 = (bit 0 - 19) - ID of the vehicle
725 * - p1 = (bit 24 - 31) - the selected order (if any). If the last order is given,
726 * the order will be inserted before that one
727 * the maximum vehicle order id is 254.
728 * @param p2 packed order to insert
729 * @param text unused
730 * @return the cost of this operation or an error
732 CommandCost CmdInsertOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
734 VehicleID veh = GB(p1, 0, 20);
735 VehicleOrderID sel_ord = GB(p1, 20, 8);
736 BaseOrder new_order (p2);
738 Vehicle *v = Vehicle::GetIfValid(veh);
739 if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
741 CommandCost ret = CheckOwnership(v->owner);
742 if (ret.Failed()) return ret;
744 /* Check if the inserted order is to the correct destination (owner, type),
745 * and has the correct flags if any */
746 switch (new_order.GetType()) {
747 case OT_GOTO_STATION: {
748 const Station *st = Station::GetIfValid(new_order.GetDestination());
749 if (st == NULL) return CMD_ERROR;
751 if (st->owner != OWNER_NONE) {
752 CommandCost ret = CheckOwnership(st->owner);
753 if (ret.Failed()) return ret;
756 if (!CanVehicleUseStation(v, st)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
757 for (Vehicle *u = v->FirstShared(); u != NULL; u = u->NextShared()) {
758 if (!CanVehicleUseStation(u, st)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER_SHARED);
761 /* Non stop only allowed for ground vehicles. */
762 if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && !v->IsGroundVehicle()) return CMD_ERROR;
764 /* Filter invalid load/unload types. */
765 switch (new_order.GetLoadType()) {
766 case OLF_LOAD_IF_POSSIBLE: case OLFB_FULL_LOAD: case OLF_FULL_LOAD_ANY: case OLFB_NO_LOAD: break;
767 default: return CMD_ERROR;
769 switch (new_order.GetUnloadType()) {
770 case OUF_UNLOAD_IF_POSSIBLE: case OUFB_UNLOAD: case OUFB_TRANSFER: case OUFB_NO_UNLOAD: break;
771 default: return CMD_ERROR;
774 /* Filter invalid stop locations */
775 switch (new_order.GetStopLocation()) {
776 case OSL_PLATFORM_NEAR_END:
777 case OSL_PLATFORM_MIDDLE:
778 if (v->type != VEH_TRAIN) return CMD_ERROR;
779 /* FALL THROUGH */
780 case OSL_PLATFORM_FAR_END:
781 break;
783 default:
784 return CMD_ERROR;
787 break;
790 case OT_GOTO_DEPOT: {
791 if ((new_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) == 0) {
792 if (v->type == VEH_AIRCRAFT) {
793 const Station *st = Station::GetIfValid(new_order.GetDestination());
795 if (st == NULL) return CMD_ERROR;
797 CommandCost ret = CheckOwnership(st->owner);
798 if (ret.Failed()) return ret;
800 if (!CanVehicleUseStation(v, st) || !st->airport.HasHangar()) {
801 return CMD_ERROR;
803 } else {
804 const Depot *dp = Depot::GetIfValid(new_order.GetDestination());
806 if (dp == NULL) return CMD_ERROR;
808 CommandCost ret = CheckOwnership(GetTileOwner(dp->xy));
809 if (ret.Failed()) return ret;
811 switch (v->type) {
812 case VEH_TRAIN:
813 if (!IsRailDepotTile(dp->xy)) return CMD_ERROR;
814 break;
816 case VEH_ROAD:
817 if (!IsRoadDepotTile(dp->xy)) return CMD_ERROR;
818 break;
820 case VEH_SHIP:
821 if (!IsShipDepotTile(dp->xy)) return CMD_ERROR;
822 break;
824 default: return CMD_ERROR;
829 if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && !v->IsGroundVehicle()) return CMD_ERROR;
830 if (new_order.GetDepotOrderType() & ~(ODTFB_PART_OF_ORDERS | ((new_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS) != 0 ? ODTFB_SERVICE : 0))) return CMD_ERROR;
831 if (new_order.GetDepotActionType() & ~(ODATFB_HALT | ODATFB_NEAREST_DEPOT)) return CMD_ERROR;
832 if ((new_order.GetDepotOrderType() & ODTFB_SERVICE) && (new_order.GetDepotActionType() & ODATFB_HALT)) return CMD_ERROR;
833 break;
836 case OT_GOTO_WAYPOINT: {
837 const Waypoint *wp = Waypoint::GetIfValid(new_order.GetDestination());
838 if (wp == NULL) return CMD_ERROR;
840 switch (v->type) {
841 default: return CMD_ERROR;
843 case VEH_TRAIN: {
844 if (!(wp->facilities & FACIL_TRAIN)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
846 CommandCost ret = CheckOwnership(wp->owner);
847 if (ret.Failed()) return ret;
848 break;
851 case VEH_SHIP:
852 if (!(wp->facilities & FACIL_DOCK)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
853 if (wp->owner != OWNER_NONE) {
854 CommandCost ret = CheckOwnership(wp->owner);
855 if (ret.Failed()) return ret;
857 break;
860 /* Order flags can be any of the following for waypoints:
861 * [non-stop]
862 * non-stop orders (if any) are only valid for trains */
863 if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && v->type != VEH_TRAIN) return CMD_ERROR;
864 break;
867 case OT_CONDITIONAL: {
868 VehicleOrderID skip_to = new_order.GetConditionSkipToOrder();
869 if (skip_to != 0 && skip_to >= v->GetNumOrders()) return CMD_ERROR; // Always allow jumping to the first (even when there is no order).
870 if (new_order.GetConditionVariable() >= OCV_END) return CMD_ERROR;
872 OrderConditionComparator occ = new_order.GetConditionComparator();
873 if (occ >= OCC_END) return CMD_ERROR;
874 switch (new_order.GetConditionVariable()) {
875 case OCV_REQUIRES_SERVICE:
876 if (occ != OCC_IS_TRUE && occ != OCC_IS_FALSE) return CMD_ERROR;
877 break;
879 case OCV_UNCONDITIONALLY:
880 if (occ != OCC_EQUALS) return CMD_ERROR;
881 if (new_order.GetConditionValue() != 0) return CMD_ERROR;
882 break;
884 case OCV_LOAD_PERCENTAGE:
885 case OCV_RELIABILITY:
886 if (new_order.GetConditionValue() > 100) return CMD_ERROR;
887 /* FALL THROUGH */
888 default:
889 if (occ == OCC_IS_TRUE || occ == OCC_IS_FALSE) return CMD_ERROR;
890 break;
892 break;
895 default: return CMD_ERROR;
898 if (sel_ord > v->GetNumOrders()) return CMD_ERROR;
900 if (v->GetNumOrders() >= MAX_VEH_ORDER_ID) return_cmd_error(STR_ERROR_TOO_MANY_ORDERS);
901 if (!Order::CanAllocateItem()) return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
902 if (v->orders.list == NULL && !OrderList::CanAllocateItem()) return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
904 if (v->type == VEH_SHIP) {
905 /* Make sure the new destination is not too far away from the previous */
906 const Order *prev = NULL;
907 uint n = 0;
909 /* Find the last goto station or depot order before the insert location.
910 * If the order is to be inserted at the beginning of the order list this
911 * finds the last order in the list. */
912 const Order *o;
913 FOR_VEHICLE_ORDERS(v, o) {
914 switch (o->GetType()) {
915 case OT_GOTO_STATION:
916 case OT_GOTO_DEPOT:
917 case OT_GOTO_WAYPOINT:
918 prev = o;
919 break;
921 default: break;
923 if (++n == sel_ord && prev != NULL) break;
925 if (prev != NULL) {
926 uint dist;
927 if (new_order.IsType(OT_CONDITIONAL)) {
928 /* The order is not yet inserted, so we have to do the first iteration here. */
929 dist = GetOrderDistance(prev, v->GetOrder(new_order.GetConditionSkipToOrder()), v);
930 } else {
931 dist = GetBaseOrderDistance (prev, &new_order, v);
934 if (dist >= 130) {
935 return_cmd_error(STR_ERROR_TOO_FAR_FROM_PREVIOUS_DESTINATION);
940 if (flags & DC_EXEC) {
941 InsertOrder (v, new Order (new_order), sel_ord);
944 return CommandCost();
948 * Insert a new order but skip the validation.
949 * @param v The vehicle to insert the order to.
950 * @param new_o The new order.
951 * @param sel_ord The position the order should be inserted at.
953 void InsertOrder(Vehicle *v, Order *new_o, VehicleOrderID sel_ord)
955 /* Create new order and link in list */
956 if (v->orders.list == NULL) {
957 v->orders.list = new OrderList(new_o, v);
958 } else {
959 v->orders.list->InsertOrderAt(new_o, sel_ord);
962 Vehicle *u = v->FirstShared();
963 DeleteOrderWarnings(u);
964 for (; u != NULL; u = u->NextShared()) {
965 assert(v->orders.list == u->orders.list);
967 /* If there is added an order before the current one, we need
968 * to update the selected order. We do not change implicit/real order indices though.
969 * If the new order is between the current implicit order and real order, the implicit order will
970 * later skip the inserted order. */
971 if (sel_ord <= u->cur_real_order_index) {
972 uint cur = u->cur_real_order_index + 1;
973 /* Check if we don't go out of bound */
974 if (cur < u->GetNumOrders()) {
975 u->cur_real_order_index = cur;
978 if (sel_ord == u->cur_implicit_order_index && u->IsGroundVehicle()) {
979 /* We are inserting an order just before the current implicit order.
980 * We do not know whether we will reach current implicit or the newly inserted order first.
981 * So, disable creation of implicit orders until we are on track again. */
982 SetBit(GroundVehicleBase::From(u)->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
984 if (sel_ord <= u->cur_implicit_order_index) {
985 uint cur = u->cur_implicit_order_index + 1;
986 /* Check if we don't go out of bound */
987 if (cur < u->GetNumOrders()) {
988 u->cur_implicit_order_index = cur;
991 /* Update any possible open window of the vehicle */
992 InvalidateVehicleOrder(u, INVALID_VEH_ORDER_ID | (sel_ord << 8));
995 /* As we insert an order, the order to skip to will be 'wrong'. */
996 VehicleOrderID cur_order_id = 0;
997 Order *order;
998 FOR_VEHICLE_ORDERS(v, order) {
999 if (order->IsType(OT_CONDITIONAL)) {
1000 VehicleOrderID order_id = order->GetConditionSkipToOrder();
1001 if (order_id >= sel_ord) {
1002 order->SetConditionSkipToOrder(order_id + 1);
1004 if (order_id == cur_order_id) {
1005 order->SetConditionSkipToOrder((order_id + 1) % v->GetNumOrders());
1008 cur_order_id++;
1011 /* Make sure to rebuild the whole list */
1012 InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
1016 * Declone an order-list
1017 * @param *dst delete the orders of this vehicle
1018 * @param flags execution flags
1020 static CommandCost DecloneOrder(Vehicle *dst, DoCommandFlag flags)
1022 if (flags & DC_EXEC) {
1023 DeleteVehicleOrders(dst);
1024 InvalidateVehicleOrder(dst, VIWD_REMOVE_ALL_ORDERS);
1025 InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
1027 return CommandCost();
1031 * Delete an order from the orderlist of a vehicle.
1032 * @param tile unused
1033 * @param flags operation to perform
1034 * @param p1 the ID of the vehicle
1035 * @param p2 the order to delete (max 255)
1036 * @param text unused
1037 * @return the cost of this operation or an error
1039 CommandCost CmdDeleteOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1041 VehicleID veh_id = GB(p1, 0, 20);
1042 VehicleOrderID sel_ord = GB(p2, 0, 8);
1044 Vehicle *v = Vehicle::GetIfValid(veh_id);
1046 if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
1048 CommandCost ret = CheckOwnership(v->owner);
1049 if (ret.Failed()) return ret;
1051 /* If we did not select an order, we maybe want to de-clone the orders */
1052 if (sel_ord >= v->GetNumOrders()) return DecloneOrder(v, flags);
1054 if (v->GetOrder(sel_ord) == NULL) return CMD_ERROR;
1056 if (flags & DC_EXEC) DeleteOrder(v, sel_ord);
1057 return CommandCost();
1061 * Cancel the current loading order of the vehicle as the order was deleted.
1062 * @param v the vehicle
1064 static void CancelLoadingDueToDeletedOrder(Vehicle *v)
1066 assert(v->current_order.IsType(OT_LOADING));
1067 /* NON-stop flag is misused to see if a train is in a station that is
1068 * on his order list or not */
1069 v->current_order.SetNonStopType(ONSF_STOP_EVERYWHERE);
1070 /* When full loading, "cancel" that order so the vehicle doesn't
1071 * stay indefinitely at this station anymore. */
1072 if (v->current_order.GetLoadType() & OLFB_FULL_LOAD) v->current_order.SetLoadType(OLF_LOAD_IF_POSSIBLE);
1076 * Delete an order but skip the parameter validation.
1077 * @param v The vehicle to delete the order from.
1078 * @param sel_ord The id of the order to be deleted.
1080 void DeleteOrder(Vehicle *v, VehicleOrderID sel_ord)
1082 v->orders.list->DeleteOrderAt(sel_ord);
1084 Vehicle *u = v->FirstShared();
1085 DeleteOrderWarnings(u);
1086 for (; u != NULL; u = u->NextShared()) {
1087 assert(v->orders.list == u->orders.list);
1089 if (sel_ord == u->cur_real_order_index && u->current_order.IsType(OT_LOADING)) {
1090 CancelLoadingDueToDeletedOrder(u);
1093 if (sel_ord < u->cur_real_order_index) {
1094 u->cur_real_order_index--;
1095 } else if (sel_ord == u->cur_real_order_index) {
1096 u->UpdateRealOrderIndex();
1099 if (sel_ord < u->cur_implicit_order_index) {
1100 u->cur_implicit_order_index--;
1101 } else if (sel_ord == u->cur_implicit_order_index) {
1102 /* Make sure the index is valid */
1103 if (u->cur_implicit_order_index >= u->GetNumOrders()) u->cur_implicit_order_index = 0;
1105 /* Skip non-implicit orders for the implicit-order-index (e.g. if the current implicit order was deleted */
1106 while (u->cur_implicit_order_index != u->cur_real_order_index && !u->GetOrder(u->cur_implicit_order_index)->IsType(OT_IMPLICIT)) {
1107 u->cur_implicit_order_index++;
1108 if (u->cur_implicit_order_index >= u->GetNumOrders()) u->cur_implicit_order_index = 0;
1112 /* Update any possible open window of the vehicle */
1113 InvalidateVehicleOrder(u, sel_ord | (INVALID_VEH_ORDER_ID << 8));
1116 /* As we delete an order, the order to skip to will be 'wrong'. */
1117 VehicleOrderID cur_order_id = 0;
1118 Order *order = NULL;
1119 FOR_VEHICLE_ORDERS(v, order) {
1120 if (order->IsType(OT_CONDITIONAL)) {
1121 VehicleOrderID order_id = order->GetConditionSkipToOrder();
1122 if (order_id >= sel_ord) {
1123 order_id = max(order_id - 1, 0);
1125 if (order_id == cur_order_id) {
1126 order_id = (order_id + 1) % v->GetNumOrders();
1128 order->SetConditionSkipToOrder(order_id);
1130 cur_order_id++;
1133 InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
1137 * Goto order of order-list.
1138 * @param tile unused
1139 * @param flags operation to perform
1140 * @param p1 The ID of the vehicle which order is skipped
1141 * @param p2 the selected order to which we want to skip
1142 * @param text unused
1143 * @return the cost of this operation or an error
1145 CommandCost CmdSkipToOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1147 VehicleID veh_id = GB(p1, 0, 20);
1148 VehicleOrderID sel_ord = GB(p2, 0, 8);
1150 Vehicle *v = Vehicle::GetIfValid(veh_id);
1152 if (v == NULL || !v->IsPrimaryVehicle() || sel_ord == v->cur_implicit_order_index || sel_ord >= v->GetNumOrders() || v->GetNumOrders() < 2) return CMD_ERROR;
1154 CommandCost ret = CheckOwnership(v->owner);
1155 if (ret.Failed()) return ret;
1157 if (flags & DC_EXEC) {
1158 if (v->current_order.IsType(OT_LOADING)) v->LeaveStation();
1160 v->cur_implicit_order_index = v->cur_real_order_index = sel_ord;
1161 v->UpdateRealOrderIndex();
1163 InvalidateVehicleOrder(v, VIWD_MODIFY_ORDERS);
1166 /* We have an aircraft/ship, they have a mini-schedule, so update them all */
1167 if (v->type == VEH_AIRCRAFT) SetWindowClassesDirty(WC_AIRCRAFT_LIST);
1168 if (v->type == VEH_SHIP) SetWindowClassesDirty(WC_SHIPS_LIST);
1170 return CommandCost();
1174 * Move an order inside the orderlist
1175 * @param tile unused
1176 * @param flags operation to perform
1177 * @param p1 the ID of the vehicle
1178 * @param p2 order to move and target
1179 * bit 0-15 : the order to move
1180 * bit 16-31 : the target order
1181 * @param text unused
1182 * @return the cost of this operation or an error
1183 * @note The target order will move one place down in the orderlist
1184 * if you move the order upwards else it'll move it one place down
1186 CommandCost CmdMoveOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1188 VehicleID veh = GB(p1, 0, 20);
1189 VehicleOrderID moving_order = GB(p2, 0, 16);
1190 VehicleOrderID target_order = GB(p2, 16, 16);
1192 Vehicle *v = Vehicle::GetIfValid(veh);
1193 if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
1195 CommandCost ret = CheckOwnership(v->owner);
1196 if (ret.Failed()) return ret;
1198 /* Don't make senseless movements */
1199 if (moving_order >= v->GetNumOrders() || target_order >= v->GetNumOrders() ||
1200 moving_order == target_order || v->GetNumOrders() <= 1) return CMD_ERROR;
1202 Order *moving_one = v->GetOrder(moving_order);
1203 /* Don't move an empty order */
1204 if (moving_one == NULL) return CMD_ERROR;
1206 if (flags & DC_EXEC) {
1207 v->orders.list->MoveOrder(moving_order, target_order);
1209 /* Update shared list */
1210 Vehicle *u = v->FirstShared();
1212 DeleteOrderWarnings(u);
1214 for (; u != NULL; u = u->NextShared()) {
1215 /* Update the current order.
1216 * There are multiple ways to move orders, which result in cur_implicit_order_index
1217 * and cur_real_order_index to not longer make any sense. E.g. moving another
1218 * real order between them.
1220 * Basically one could choose to preserve either of them, but not both.
1221 * While both ways are suitable in this or that case from a human point of view, neither
1222 * of them makes really sense.
1223 * However, from an AI point of view, preserving cur_real_order_index is the most
1224 * predictable and transparent behaviour.
1226 * With that decision it basically does not matter what we do to cur_implicit_order_index.
1227 * If we change orders between the implicit- and real-index, the implicit orders are mostly likely
1228 * completely out-dated anyway. So, keep it simple and just keep cur_implicit_order_index as well.
1229 * The worst which can happen is that a lot of implicit orders are removed when reaching current_order.
1231 if (u->cur_real_order_index == moving_order) {
1232 u->cur_real_order_index = target_order;
1233 } else if (u->cur_real_order_index > moving_order && u->cur_real_order_index <= target_order) {
1234 u->cur_real_order_index--;
1235 } else if (u->cur_real_order_index < moving_order && u->cur_real_order_index >= target_order) {
1236 u->cur_real_order_index++;
1239 if (u->cur_implicit_order_index == moving_order) {
1240 u->cur_implicit_order_index = target_order;
1241 } else if (u->cur_implicit_order_index > moving_order && u->cur_implicit_order_index <= target_order) {
1242 u->cur_implicit_order_index--;
1243 } else if (u->cur_implicit_order_index < moving_order && u->cur_implicit_order_index >= target_order) {
1244 u->cur_implicit_order_index++;
1247 assert(v->orders.list == u->orders.list);
1248 /* Update any possible open window of the vehicle */
1249 InvalidateVehicleOrder(u, moving_order | (target_order << 8));
1252 /* As we move an order, the order to skip to will be 'wrong'. */
1253 Order *order;
1254 FOR_VEHICLE_ORDERS(v, order) {
1255 if (order->IsType(OT_CONDITIONAL)) {
1256 VehicleOrderID order_id = order->GetConditionSkipToOrder();
1257 if (order_id == moving_order) {
1258 order_id = target_order;
1259 } else if (order_id > moving_order && order_id <= target_order) {
1260 order_id--;
1261 } else if (order_id < moving_order && order_id >= target_order) {
1262 order_id++;
1264 order->SetConditionSkipToOrder(order_id);
1268 /* Make sure to rebuild the whole list */
1269 InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
1272 return CommandCost();
1276 * Modify an order in the orderlist of a vehicle.
1277 * @param tile unused
1278 * @param flags operation to perform
1279 * @param p1 various bitstuffed elements
1280 * - p1 = (bit 0 - 19) - ID of the vehicle
1281 * - p1 = (bit 24 - 31) - the selected order (if any). If the last order is given,
1282 * the order will be inserted before that one
1283 * the maximum vehicle order id is 254.
1284 * @param p2 various bitstuffed elements
1285 * - p2 = (bit 0 - 3) - what data to modify (@see ModifyOrderFlags)
1286 * - p2 = (bit 4 - 15) - the data to modify
1287 * @param text unused
1288 * @return the cost of this operation or an error
1290 CommandCost CmdModifyOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1292 VehicleOrderID sel_ord = GB(p1, 20, 8);
1293 VehicleID veh = GB(p1, 0, 20);
1294 ModifyOrderFlags mof = Extract<ModifyOrderFlags, 0, 4>(p2);
1295 uint16 data = GB(p2, 4, 11);
1297 if (mof >= MOF_END) return CMD_ERROR;
1299 Vehicle *v = Vehicle::GetIfValid(veh);
1300 if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
1302 CommandCost ret = CheckOwnership(v->owner);
1303 if (ret.Failed()) return ret;
1305 /* Is it a valid order? */
1306 if (sel_ord >= v->GetNumOrders()) return CMD_ERROR;
1308 Order *order = v->GetOrder(sel_ord);
1309 switch (order->GetType()) {
1310 case OT_GOTO_STATION:
1311 if (mof != MOF_NON_STOP && mof != MOF_STOP_LOCATION && mof != MOF_UNLOAD && mof != MOF_LOAD) return CMD_ERROR;
1312 break;
1314 case OT_GOTO_DEPOT:
1315 if (mof != MOF_NON_STOP && mof != MOF_DEPOT_ACTION) return CMD_ERROR;
1316 break;
1318 case OT_GOTO_WAYPOINT:
1319 if (mof != MOF_NON_STOP) return CMD_ERROR;
1320 break;
1322 case OT_CONDITIONAL:
1323 if (mof != MOF_COND_VARIABLE && mof != MOF_COND_COMPARATOR && mof != MOF_COND_VALUE && mof != MOF_COND_DESTINATION) return CMD_ERROR;
1324 break;
1326 default:
1327 return CMD_ERROR;
1330 switch (mof) {
1331 default: NOT_REACHED();
1333 case MOF_NON_STOP:
1334 if (!v->IsGroundVehicle()) return CMD_ERROR;
1335 if (data >= ONSF_END) return CMD_ERROR;
1336 if (data == order->GetNonStopType()) return CMD_ERROR;
1337 break;
1339 case MOF_STOP_LOCATION:
1340 if (v->type != VEH_TRAIN) return CMD_ERROR;
1341 if (data >= OSL_END) return CMD_ERROR;
1342 break;
1344 case MOF_UNLOAD:
1345 if (order->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) return CMD_ERROR;
1346 if ((data & ~(OUFB_UNLOAD | OUFB_TRANSFER | OUFB_NO_UNLOAD)) != 0) return CMD_ERROR;
1347 /* Unload and no-unload are mutual exclusive and so are transfer and no unload. */
1348 if (data != 0 && ((data & (OUFB_UNLOAD | OUFB_TRANSFER)) != 0) == ((data & OUFB_NO_UNLOAD) != 0)) return CMD_ERROR;
1349 if (data == order->GetUnloadType()) return CMD_ERROR;
1350 break;
1352 case MOF_LOAD:
1353 if (order->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) return CMD_ERROR;
1354 if (data > OLFB_NO_LOAD || data == 1) return CMD_ERROR;
1355 if (data == order->GetLoadType()) return CMD_ERROR;
1356 break;
1358 case MOF_DEPOT_ACTION:
1359 if (data >= DA_END) return CMD_ERROR;
1360 break;
1362 case MOF_COND_VARIABLE:
1363 if (data >= OCV_END) return CMD_ERROR;
1364 break;
1366 case MOF_COND_COMPARATOR:
1367 if (data >= OCC_END) return CMD_ERROR;
1368 switch (order->GetConditionVariable()) {
1369 case OCV_UNCONDITIONALLY: return CMD_ERROR;
1371 case OCV_REQUIRES_SERVICE:
1372 if (data != OCC_IS_TRUE && data != OCC_IS_FALSE) return CMD_ERROR;
1373 break;
1375 default:
1376 if (data == OCC_IS_TRUE || data == OCC_IS_FALSE) return CMD_ERROR;
1377 break;
1379 break;
1381 case MOF_COND_VALUE:
1382 switch (order->GetConditionVariable()) {
1383 case OCV_UNCONDITIONALLY:
1384 case OCV_REQUIRES_SERVICE:
1385 return CMD_ERROR;
1387 case OCV_LOAD_PERCENTAGE:
1388 case OCV_RELIABILITY:
1389 if (data > 100) return CMD_ERROR;
1390 break;
1392 default:
1393 if (data > 2047) return CMD_ERROR;
1394 break;
1396 break;
1398 case MOF_COND_DESTINATION:
1399 if (data >= v->GetNumOrders()) return CMD_ERROR;
1400 break;
1403 if (flags & DC_EXEC) {
1404 switch (mof) {
1405 case MOF_NON_STOP:
1406 order->SetNonStopType((OrderNonStopFlags)data);
1407 if (data & ONSF_NO_STOP_AT_DESTINATION_STATION) {
1408 order->SetRefitMask();
1409 order->SetLoadType(OLF_LOAD_IF_POSSIBLE);
1410 order->SetUnloadType(OUF_UNLOAD_IF_POSSIBLE);
1412 break;
1414 case MOF_STOP_LOCATION:
1415 order->SetStopLocation((OrderStopLocation)data);
1416 break;
1418 case MOF_UNLOAD:
1419 order->SetUnloadType((OrderUnloadFlags)data);
1420 break;
1422 case MOF_LOAD:
1423 order->SetLoadType((OrderLoadFlags)data);
1424 if (data & OLFB_NO_LOAD) order->SetRefitMask();
1425 break;
1427 case MOF_DEPOT_ACTION: {
1428 switch (data) {
1429 case DA_ALWAYS_GO:
1430 order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
1431 order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
1432 break;
1434 case DA_SERVICE:
1435 order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() | ODTFB_SERVICE));
1436 order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
1437 order->SetRefitMask();
1438 break;
1440 case DA_STOP:
1441 order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
1442 order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() | ODATFB_HALT));
1443 order->SetRefitMask();
1444 break;
1446 default:
1447 NOT_REACHED();
1449 break;
1452 case MOF_COND_VARIABLE: {
1453 order->SetConditionVariable((OrderConditionVariable)data);
1455 OrderConditionComparator occ = order->GetConditionComparator();
1456 switch (order->GetConditionVariable()) {
1457 case OCV_UNCONDITIONALLY:
1458 order->SetConditionComparator(OCC_EQUALS);
1459 order->SetConditionValue(0);
1460 break;
1462 case OCV_REQUIRES_SERVICE:
1463 if (occ != OCC_IS_TRUE && occ != OCC_IS_FALSE) order->SetConditionComparator(OCC_IS_TRUE);
1464 order->SetConditionValue(0);
1465 break;
1467 case OCV_LOAD_PERCENTAGE:
1468 case OCV_RELIABILITY:
1469 if (order->GetConditionValue() > 100) order->SetConditionValue(100);
1470 /* FALL THROUGH */
1471 default:
1472 if (occ == OCC_IS_TRUE || occ == OCC_IS_FALSE) order->SetConditionComparator(OCC_EQUALS);
1473 break;
1475 break;
1478 case MOF_COND_COMPARATOR:
1479 order->SetConditionComparator((OrderConditionComparator)data);
1480 break;
1482 case MOF_COND_VALUE:
1483 order->SetConditionValue(data);
1484 break;
1486 case MOF_COND_DESTINATION:
1487 order->SetConditionSkipToOrder(data);
1488 break;
1490 default: NOT_REACHED();
1493 /* Update the windows and full load flags, also for vehicles that share the same order list */
1494 Vehicle *u = v->FirstShared();
1495 DeleteOrderWarnings(u);
1496 for (; u != NULL; u = u->NextShared()) {
1497 /* Toggle u->current_order "Full load" flag if it changed.
1498 * However, as the same flag is used for depot orders, check
1499 * whether we are not going to a depot as there are three
1500 * cases where the full load flag can be active and only
1501 * one case where the flag is used for depot orders. In the
1502 * other cases for the OrderTypeByte the flags are not used,
1503 * so do not care and those orders should not be active
1504 * when this function is called.
1506 if (sel_ord == u->cur_real_order_index &&
1507 (u->current_order.IsType(OT_GOTO_STATION) || u->current_order.IsType(OT_LOADING)) &&
1508 u->current_order.GetLoadType() != order->GetLoadType()) {
1509 u->current_order.SetLoadType(order->GetLoadType());
1511 InvalidateVehicleOrder(u, VIWD_MODIFY_ORDERS);
1515 return CommandCost();
1519 * Check if an aircraft has enough range for an order list.
1520 * @param v_new Aircraft to check.
1521 * @param v_order Vehicle currently holding the order list.
1522 * @param first First order in the source order list.
1523 * @return True if the aircraft has enough range for the orders, false otherwise.
1525 static bool CheckAircraftOrderDistance(const Aircraft *v_new, const Vehicle *v_order, const Order *first)
1527 if (first == NULL || v_new->acache.cached_max_range == 0) return true;
1529 /* Iterate over all orders to check the distance between all
1530 * 'goto' orders and their respective next order (of any type). */
1531 for (const Order *o = first; o != NULL; o = o->next) {
1532 switch (o->GetType()) {
1533 case OT_GOTO_STATION:
1534 case OT_GOTO_DEPOT:
1535 case OT_GOTO_WAYPOINT:
1536 /* If we don't have a next order, we've reached the end and must check the first order instead. */
1537 if (GetOrderDistance(o, o->next != NULL ? o->next : first, v_order) > v_new->acache.cached_max_range_sqr) return false;
1538 break;
1540 default: break;
1544 return true;
1548 * Clone/share/copy an order-list of another vehicle.
1549 * @param tile unused
1550 * @param flags operation to perform
1551 * @param p1 various bitstuffed elements
1552 * - p1 = (bit 0-19) - destination vehicle to clone orders to
1553 * - p1 = (bit 30-31) - action to perform
1554 * @param p2 source vehicle to clone orders from, if any (none for CO_UNSHARE_CLEAR)
1555 * @param text unused
1556 * @return the cost of this operation or an error
1558 CommandCost CmdCloneOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1560 VehicleID veh_src = GB(p2, 0, 20);
1561 VehicleID veh_dst = GB(p1, 0, 20);
1563 Vehicle *dst = Vehicle::GetIfValid(veh_dst);
1564 if (dst == NULL || !dst->IsPrimaryVehicle()) return CMD_ERROR;
1566 CommandCost ret = CheckOwnership(dst->owner);
1567 if (ret.Failed()) return ret;
1569 switch (GB(p1, 30, 2)) {
1570 case CO_SHARE: {
1571 Vehicle *src = Vehicle::GetIfValid(veh_src);
1573 /* Sanity checks */
1574 if (src == NULL || !src->IsPrimaryVehicle() || dst->type != src->type || dst == src) return CMD_ERROR;
1576 CommandCost ret = CheckOwnership(src->owner);
1577 if (ret.Failed()) return ret;
1579 /* Trucks can't share orders with busses (and visa versa) */
1580 if (src->type == VEH_ROAD && RoadVehicle::From(src)->IsBus() != RoadVehicle::From(dst)->IsBus()) {
1581 return CMD_ERROR;
1584 /* Is the vehicle already in the shared list? */
1585 if (src->FirstShared() == dst->FirstShared()) return CMD_ERROR;
1587 const Order *order;
1589 FOR_VEHICLE_ORDERS(src, order) {
1590 if (!OrderGoesToStation(dst, order)) continue;
1592 /* Allow copying unreachable destinations if they were already unreachable for the source.
1593 * This is basically to allow cloning / autorenewing / autoreplacing vehicles, while the stations
1594 * are temporarily invalid due to reconstruction. */
1595 const Station *st = Station::Get(order->GetDestination());
1596 if (CanVehicleUseStation(src, st) && !CanVehicleUseStation(dst, st)) {
1597 return_cmd_error(STR_ERROR_CAN_T_COPY_SHARE_ORDER);
1601 /* Check for aircraft range limits. */
1602 if (dst->type == VEH_AIRCRAFT && !CheckAircraftOrderDistance(Aircraft::From(dst), src, src->GetFirstOrder())) {
1603 return_cmd_error(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE);
1606 if (src->orders.list == NULL && !OrderList::CanAllocateItem()) {
1607 return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
1610 if (flags & DC_EXEC) {
1611 /* If the destination vehicle had a OrderList, destroy it.
1612 * We only reset the order indices, if the new orders are obviously different.
1613 * (We mainly do this to keep the order indices valid and in range.) */
1614 DeleteVehicleOrders(dst, false, dst->GetNumOrders() != src->GetNumOrders());
1616 dst->orders.list = src->orders.list;
1618 /* Link this vehicle in the shared-list */
1619 dst->AddToShared(src);
1621 InvalidateVehicleOrder(dst, VIWD_REMOVE_ALL_ORDERS);
1622 InvalidateVehicleOrder(src, VIWD_MODIFY_ORDERS);
1624 InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
1626 break;
1629 case CO_COPY:
1630 case CO_UNSHARE_COPY: {
1631 Vehicle *src = Vehicle::GetIfValid(veh_src);
1633 /* Sanity checks */
1634 if (src == NULL || !src->IsPrimaryVehicle() || dst->type != src->type || dst == src) return CMD_ERROR;
1636 CommandCost ret = CheckOwnership(src->owner);
1637 if (ret.Failed()) return ret;
1639 /* Trucks can't copy all the orders from busses (and visa versa),
1640 * and neither can helicopters and aircraft. */
1641 const Order *order;
1642 FOR_VEHICLE_ORDERS(src, order) {
1643 if (OrderGoesToStation(dst, order) &&
1644 !CanVehicleUseStation(dst, Station::Get(order->GetDestination()))) {
1645 return_cmd_error(STR_ERROR_CAN_T_COPY_SHARE_ORDER);
1649 /* Check for aircraft range limits. */
1650 if (dst->type == VEH_AIRCRAFT && !CheckAircraftOrderDistance(Aircraft::From(dst), src, src->GetFirstOrder())) {
1651 return_cmd_error(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE);
1654 /* make sure there are orders available */
1655 if (!Order::CanAllocateItem(src->GetNumOrders()) || !OrderList::CanAllocateItem()) {
1656 return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
1659 if (flags & DC_EXEC) {
1660 const Order *order;
1661 Order *first = NULL;
1662 Order **order_dst;
1664 /* If the destination vehicle had an order list, destroy the chain but keep the OrderList.
1665 * We only reset the order indices, if the new orders are obviously different.
1666 * (We mainly do this to keep the order indices valid and in range.) */
1667 DeleteVehicleOrders(dst, true, dst->GetNumOrders() != src->GetNumOrders());
1669 order_dst = &first;
1670 FOR_VEHICLE_ORDERS(src, order) {
1671 *order_dst = new Order();
1672 (*order_dst)->AssignOrder(*order);
1673 order_dst = &(*order_dst)->next;
1675 if (dst->orders.list == NULL) {
1676 dst->orders.list = new OrderList(first, dst);
1677 } else {
1678 assert(dst->orders.list->GetFirstOrder() == NULL);
1679 assert(!dst->orders.list->IsShared());
1680 delete dst->orders.list;
1681 assert(OrderList::CanAllocateItem());
1682 dst->orders.list = new OrderList(first, dst);
1685 InvalidateVehicleOrder(dst, VIWD_REMOVE_ALL_ORDERS);
1687 InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
1689 break;
1692 case CO_UNSHARE_CLEAR: return DecloneOrder(dst, flags);
1693 default: return CMD_ERROR;
1696 return CommandCost();
1700 * Add/remove refit orders from an order
1701 * @param tile Not used
1702 * @param flags operation to perform
1703 * @param p1 bitmask
1704 * - bit 0-19 VehicleIndex of the vehicle having the order
1705 * - bit 24-31 number of order to modify
1706 * @param p2 Cargo mask of allowed refits
1707 * @param text unused
1708 * @return the cost of this operation or an error
1710 CommandCost CmdOrderRefit(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1712 VehicleID veh = GB(p1, 0, 20);
1713 VehicleOrderID order_number = GB(p1, 24, 8);
1714 CargoMask mask = p2;
1716 const Vehicle *v = Vehicle::GetIfValid(veh);
1717 if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
1719 CommandCost ret = CheckOwnership(v->owner);
1720 if (ret.Failed()) return ret;
1722 Order *order = v->GetOrder(order_number);
1723 if (order == NULL) return CMD_ERROR;
1725 /* Automatic refit cargo is only supported for goto station orders. */
1726 if (!HasAtMostOneBit (mask) && !order->IsType(OT_GOTO_STATION)) return CMD_ERROR;
1728 if (order->GetLoadType() & OLFB_NO_LOAD) return CMD_ERROR;
1730 if (flags & DC_EXEC) {
1731 order->SetRefitMask (mask);
1733 /* Make the depot order an 'always go' order. */
1734 if (mask != 0 && order->IsType(OT_GOTO_DEPOT)) {
1735 order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
1736 order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
1739 for (Vehicle *u = v->FirstShared(); u != NULL; u = u->NextShared()) {
1740 /* Update any possible open window of the vehicle */
1741 InvalidateVehicleOrder(u, VIWD_MODIFY_ORDERS);
1743 /* If the vehicle already got the current depot set as current order, then update current order as well */
1744 if (u->cur_real_order_index == order_number && (u->current_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) {
1745 u->current_order.SetRefitMask (mask);
1750 return CommandCost();
1756 * Check the orders of a vehicle, to see if there are invalid orders and stuff
1759 void CheckOrders(const Vehicle *v)
1761 /* Does the user wants us to check things? */
1762 if (_settings_client.gui.order_review_system == 0) return;
1764 /* Do nothing for crashed vehicles */
1765 if (v->vehstatus & VS_CRASHED) return;
1767 /* Do nothing for stopped vehicles if setting is '1' */
1768 if (_settings_client.gui.order_review_system == 1 && (v->vehstatus & VS_STOPPED)) return;
1770 /* do nothing we we're not the first vehicle in a share-chain */
1771 if (v->FirstShared() != v) return;
1773 /* Only check every 20 days, so that we don't flood the message log */
1774 if (v->owner == _local_company && v->day_counter % 20 == 0) {
1775 const Order *order;
1776 StringID message = INVALID_STRING_ID;
1778 /* Check the order list */
1779 int n_st = 0;
1781 FOR_VEHICLE_ORDERS(v, order) {
1782 /* Dummy order? */
1783 if (order->IsType(OT_DUMMY)) {
1784 message = STR_NEWS_VEHICLE_HAS_VOID_ORDER;
1785 break;
1787 /* Does station have a load-bay for this vehicle? */
1788 if (order->IsType(OT_GOTO_STATION)) {
1789 const Station *st = Station::Get(order->GetDestination());
1791 n_st++;
1792 if (!CanVehicleUseStation(v, st)) {
1793 message = STR_NEWS_VEHICLE_HAS_INVALID_ENTRY;
1794 } else if (v->type == VEH_AIRCRAFT &&
1795 (AircraftVehInfo(v->engine_type)->subtype & AIR_FAST) &&
1796 (st->airport.GetFTA()->flags & AirportFTAClass::SHORT_STRIP) &&
1797 _settings_game.vehicle.plane_crashes != 0 &&
1798 !_cheats.no_jetcrash.value &&
1799 message == INVALID_STRING_ID) {
1800 message = STR_NEWS_PLANE_USES_TOO_SHORT_RUNWAY;
1805 /* Check if the last and the first order are the same */
1806 if (v->GetNumOrders() > 1) {
1807 const Order *last = v->GetLastOrder();
1809 if (v->orders.list->GetFirstOrder()->Equals(*last)) {
1810 message = STR_NEWS_VEHICLE_HAS_DUPLICATE_ENTRY;
1814 /* Do we only have 1 station in our order list? */
1815 if (n_st < 2 && message == INVALID_STRING_ID) message = STR_NEWS_VEHICLE_HAS_TOO_FEW_ORDERS;
1817 #ifndef NDEBUG
1818 if (v->orders.list != NULL) v->orders.list->DebugCheckSanity();
1819 #endif
1821 /* We don't have a problem */
1822 if (message == INVALID_STRING_ID) return;
1824 AddNewsItem<VehicleAdviceNewsItem> (message, v->index);
1829 * Removes an order from all vehicles. Triggers when, say, a station is removed.
1830 * @param type The type of the order (OT_GOTO_[STATION|DEPOT|WAYPOINT]).
1831 * @param destination The destination. Can be a StationID, DepotID or WaypointID.
1833 void RemoveOrderFromAllVehicles(OrderType type, DestinationID destination)
1835 Vehicle *v;
1837 /* Aircraft have StationIDs for depot orders and never use DepotIDs
1838 * This fact is handled specially below
1841 /* Go through all vehicles */
1842 FOR_ALL_VEHICLES(v) {
1843 if ((v->type == VEH_AIRCRAFT && v->current_order.IsType(OT_GOTO_DEPOT) ? OT_GOTO_STATION : v->current_order.GetType()) == type &&
1844 v->current_order.GetDestination() == destination) {
1845 v->current_order.MakeDummy();
1846 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
1849 /* Clear the order from the order-list */
1850 Order *order;
1851 int id = -1;
1852 FOR_VEHICLE_ORDERS(v, order) {
1853 id++;
1854 restart:
1856 OrderType ot = order->GetType();
1857 if (ot == OT_GOTO_DEPOT && (order->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0) continue;
1858 if (ot == OT_IMPLICIT || (v->type == VEH_AIRCRAFT && ot == OT_GOTO_DEPOT)) ot = OT_GOTO_STATION;
1859 if (ot == type && order->GetDestination() == destination) {
1860 /* We want to clear implicit orders, but we don't want to make them
1861 * dummy orders. They should just vanish. Also check the actual order
1862 * type as ot is currently OT_GOTO_STATION. */
1863 if (order->IsType(OT_IMPLICIT)) {
1864 order = order->next; // DeleteOrder() invalidates current order
1865 DeleteOrder(v, id);
1866 if (order != NULL) goto restart;
1867 break;
1870 /* Clear wait time */
1871 v->orders.list->UpdateTotalDuration(-order->GetWaitTime());
1872 if (order->IsWaitTimetabled()) {
1873 v->orders.list->UpdateTimetableDuration(-order->GetTimetabledWait());
1874 order->SetWaitTimetabled(false);
1876 order->SetWaitTime(0);
1878 /* Clear order, preserving travel time */
1879 bool travel_timetabled = order->IsTravelTimetabled();
1880 order->MakeDummy();
1881 order->SetTravelTimetabled(travel_timetabled);
1883 for (const Vehicle *w = v->FirstShared(); w != NULL; w = w->NextShared()) {
1884 /* In GUI, simulate by removing the order and adding it back */
1885 InvalidateVehicleOrder(w, id | (INVALID_VEH_ORDER_ID << 8));
1886 InvalidateVehicleOrder(w, (INVALID_VEH_ORDER_ID << 8) | id);
1892 OrderBackup::RemoveOrder(type, destination);
1896 * Checks if a vehicle has a depot in its order list.
1897 * @return True iff at least one order is a depot order.
1899 bool Vehicle::HasDepotOrder() const
1901 const Order *order;
1903 FOR_VEHICLE_ORDERS(this, order) {
1904 if (order->IsType(OT_GOTO_DEPOT)) return true;
1907 return false;
1911 * Delete all orders from a vehicle
1912 * @param v Vehicle whose orders to reset
1913 * @param keep_orderlist If true, do not free the order list, only empty it.
1914 * @param reset_order_indices If true, reset cur_implicit_order_index and cur_real_order_index
1915 * and cancel the current full load order (if the vehicle is loading).
1916 * If false, _you_ have to make sure the order indices are valid after
1917 * your messing with them!
1919 void DeleteVehicleOrders(Vehicle *v, bool keep_orderlist, bool reset_order_indices)
1921 DeleteOrderWarnings(v);
1923 if (v->IsOrderListShared()) {
1924 /* Remove ourself from the shared order list. */
1925 v->RemoveFromShared();
1926 v->orders.list = NULL;
1927 } else if (v->orders.list != NULL) {
1928 /* Remove the orders */
1929 v->orders.list->FreeChain(keep_orderlist);
1930 if (!keep_orderlist) v->orders.list = NULL;
1933 if (reset_order_indices) {
1934 v->cur_implicit_order_index = v->cur_real_order_index = 0;
1935 if (v->current_order.IsType(OT_LOADING)) {
1936 CancelLoadingDueToDeletedOrder(v);
1942 * Clamp the service interval to the correct min/max. The actual min/max values
1943 * depend on whether it's in percent or days.
1944 * @param interval proposed service interval
1945 * @param company_id the owner of the vehicle
1946 * @return Clamped service interval
1948 uint16 GetServiceIntervalClamped(uint interval, bool ispercent)
1950 return ispercent ? Clamp(interval, MIN_SERVINT_PERCENT, MAX_SERVINT_PERCENT) : Clamp(interval, MIN_SERVINT_DAYS, MAX_SERVINT_DAYS);
1955 * Check if a vehicle has any valid orders
1957 * @return false if there are no valid orders
1958 * @note Conditional orders are not considered valid destination orders
1961 static bool CheckForValidOrders(const Vehicle *v)
1963 const Order *order;
1965 FOR_VEHICLE_ORDERS(v, order) {
1966 switch (order->GetType()) {
1967 case OT_GOTO_STATION:
1968 case OT_GOTO_DEPOT:
1969 case OT_GOTO_WAYPOINT:
1970 return true;
1972 default:
1973 break;
1977 return false;
1981 * Compare the variable and value based on the given comparator.
1983 static bool OrderConditionCompare(OrderConditionComparator occ, int variable, int value)
1985 switch (occ) {
1986 case OCC_EQUALS: return variable == value;
1987 case OCC_NOT_EQUALS: return variable != value;
1988 case OCC_LESS_THAN: return variable < value;
1989 case OCC_LESS_EQUALS: return variable <= value;
1990 case OCC_MORE_THAN: return variable > value;
1991 case OCC_MORE_EQUALS: return variable >= value;
1992 case OCC_IS_TRUE: return variable != 0;
1993 case OCC_IS_FALSE: return variable == 0;
1994 default: NOT_REACHED();
1999 * Process a conditional order and determine the next order.
2000 * @param order the order the vehicle currently has
2001 * @param v the vehicle to update
2002 * @return index of next order to jump to, or INVALID_VEH_ORDER_ID to use the next order
2004 VehicleOrderID ProcessConditionalOrder(const Order *order, const Vehicle *v)
2006 if (order->GetType() != OT_CONDITIONAL) return INVALID_VEH_ORDER_ID;
2008 bool skip_order = false;
2009 OrderConditionComparator occ = order->GetConditionComparator();
2010 uint16 value = order->GetConditionValue();
2012 switch (order->GetConditionVariable()) {
2013 case OCV_LOAD_PERCENTAGE: skip_order = OrderConditionCompare(occ, CalcPercentVehicleFilled(v, NULL), value); break;
2014 case OCV_RELIABILITY: skip_order = OrderConditionCompare(occ, ToPercent16(v->reliability), value); break;
2015 case OCV_MAX_SPEED: skip_order = OrderConditionCompare(occ, v->GetDisplayMaxSpeed() * 10 / 16, value); break;
2016 case OCV_AGE: skip_order = OrderConditionCompare(occ, v->age / DAYS_IN_LEAP_YEAR, value); break;
2017 case OCV_REQUIRES_SERVICE: skip_order = OrderConditionCompare(occ, v->NeedsServicing(), value); break;
2018 case OCV_UNCONDITIONALLY: skip_order = true; break;
2019 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;
2020 default: NOT_REACHED();
2023 return skip_order ? order->GetConditionSkipToOrder() : (VehicleOrderID)INVALID_VEH_ORDER_ID;
2027 * Update the vehicle's destination tile from an order.
2028 * @param order the order the vehicle currently has
2029 * @param v the vehicle to update
2030 * @param conditional_depth the depth (amount of steps) to go with conditional orders. This to prevent infinite loops.
2031 * @param pbs_look_ahead Whether we are forecasting orders for pbs reservations in advance. If true, the order indices must not be modified.
2033 bool UpdateOrderDest(Vehicle *v, const Order *order, int conditional_depth, bool pbs_look_ahead)
2035 if (conditional_depth > v->GetNumOrders()) {
2036 v->current_order.Clear();
2037 v->dest_tile = 0;
2038 return false;
2041 switch (order->GetType()) {
2042 case OT_GOTO_STATION:
2043 v->dest_tile = v->GetOrderStationLocation(order->GetDestination());
2044 return true;
2046 case OT_GOTO_DEPOT:
2047 if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !v->NeedsServicing()) {
2048 assert(!pbs_look_ahead);
2049 UpdateVehicleTimetable(v, true);
2050 v->IncrementRealOrderIndex();
2051 break;
2054 if (v->current_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) {
2055 /* We need to search for the nearest depot (hangar). */
2056 TileIndex location;
2057 DestinationID destination;
2058 bool reverse;
2060 if (v->FindClosestDepot(&location, &destination, &reverse)) {
2061 /* PBS reservations cannot reverse */
2062 if (pbs_look_ahead && reverse) return false;
2064 v->dest_tile = location;
2065 v->current_order.SetGoToDepotDestination (destination);
2067 /* If there is no depot in front, reverse automatically (trains only) */
2068 if (v->type == VEH_TRAIN && reverse) DoCommand(v->tile, v->index, 0, DC_EXEC, CMD_REVERSE_TRAIN_DIRECTION);
2070 if (v->type == VEH_AIRCRAFT) {
2071 Aircraft *a = Aircraft::From(v);
2072 if (a->state == FLYING && a->targetairport != destination) {
2073 /* The aircraft is now heading for a different hangar than the next in the orders */
2074 extern void AircraftNextAirportPos_and_Order(Aircraft *a);
2075 AircraftNextAirportPos_and_Order(a);
2078 return true;
2081 /* If there is no depot, we cannot help PBS either. */
2082 if (pbs_look_ahead) return false;
2084 UpdateVehicleTimetable(v, true);
2085 v->IncrementRealOrderIndex();
2086 } else {
2087 if (v->type != VEH_AIRCRAFT) {
2088 v->dest_tile = Depot::Get(order->GetDestination())->xy;
2090 return true;
2092 break;
2094 case OT_GOTO_WAYPOINT:
2095 v->dest_tile = Waypoint::Get(order->GetDestination())->xy;
2096 return true;
2098 case OT_CONDITIONAL: {
2099 assert(!pbs_look_ahead);
2100 VehicleOrderID next_order = ProcessConditionalOrder(order, v);
2101 if (next_order != INVALID_VEH_ORDER_ID) {
2102 /* Jump to next_order. cur_implicit_order_index becomes exactly that order,
2103 * cur_real_order_index might come after next_order. */
2104 UpdateVehicleTimetable(v, false);
2105 v->cur_implicit_order_index = v->cur_real_order_index = next_order;
2106 v->UpdateRealOrderIndex();
2107 v->current_order_time += v->GetOrder(v->cur_real_order_index)->GetTimetabledTravel();
2109 /* Disable creation of implicit orders.
2110 * When inserting them we do not know that we would have to make the conditional orders point to them. */
2111 if (v->IsGroundVehicle()) {
2112 SetBit(GroundVehicleBase::From(v)->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
2114 } else {
2115 UpdateVehicleTimetable(v, true);
2116 v->IncrementRealOrderIndex();
2118 break;
2121 default:
2122 v->dest_tile = 0;
2123 return false;
2126 assert(v->cur_implicit_order_index < v->GetNumOrders());
2127 assert(v->cur_real_order_index < v->GetNumOrders());
2129 /* Get the current order */
2130 order = v->GetOrder(v->cur_real_order_index);
2131 if (order != NULL && order->IsType(OT_IMPLICIT)) {
2132 assert(v->GetNumManualOrders() == 0);
2133 order = NULL;
2136 if (order == NULL) {
2137 v->current_order.Clear();
2138 v->dest_tile = 0;
2139 return false;
2142 v->current_order = *order;
2143 return UpdateOrderDest(v, order, conditional_depth + 1, pbs_look_ahead);
2147 * Handle the orders of a vehicle and determine the next place
2148 * to go to if needed.
2149 * @param v the vehicle to do this for.
2150 * @return true *if* the vehicle is eligible for reversing
2151 * (basically only when leaving a station).
2153 bool ProcessOrders(Vehicle *v)
2155 switch (v->current_order.GetType()) {
2156 case OT_GOTO_DEPOT:
2157 /* Let a depot order in the orderlist interrupt. */
2158 if (!(v->current_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) return false;
2159 break;
2161 case OT_LOADING:
2162 return false;
2164 case OT_LEAVESTATION:
2165 if (v->type != VEH_AIRCRAFT) return false;
2166 break;
2168 default: break;
2172 * Reversing because of order change is allowed only just after leaving a
2173 * station (and the difficulty setting to allowed, of course)
2174 * this can be detected because only after OT_LEAVESTATION, current_order
2175 * will be reset to nothing. (That also happens if no order, but in that case
2176 * it won't hit the point in code where may_reverse is checked)
2178 bool may_reverse = v->current_order.IsType(OT_NOTHING);
2180 /* Check if we've reached a 'via' destination. */
2181 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)) &&
2182 IsStationTile(v->tile) &&
2183 v->current_order.GetDestination() == GetStationIndex(v->tile)) {
2184 v->DeleteUnreachedImplicitOrders();
2185 /* We set the last visited station here because we do not want
2186 * the train to stop at this 'via' station if the next order
2187 * is a no-non-stop order; in that case not setting the last
2188 * visited station will cause the vehicle to still stop. */
2189 v->last_station_visited = v->current_order.GetDestination();
2190 UpdateVehicleTimetable(v, true);
2191 v->IncrementImplicitOrderIndex();
2194 /* Get the current order */
2195 assert(v->cur_implicit_order_index == 0 || v->cur_implicit_order_index < v->GetNumOrders());
2196 v->UpdateRealOrderIndex();
2198 const Order *order = v->GetOrder(v->cur_real_order_index);
2199 if (order != NULL && order->IsType(OT_IMPLICIT)) {
2200 assert(v->GetNumManualOrders() == 0);
2201 order = NULL;
2204 /* If no order, do nothing. */
2205 if (order == NULL || (v->type == VEH_AIRCRAFT && !CheckForValidOrders(v))) {
2206 if (v->type == VEH_AIRCRAFT) {
2207 /* Aircraft do something vastly different here, so handle separately */
2208 extern void HandleMissingAircraftOrders(Aircraft *v);
2209 HandleMissingAircraftOrders(Aircraft::From(v));
2210 return false;
2213 v->current_order.Clear();
2214 v->dest_tile = 0;
2215 return false;
2218 /* If it is unchanged, keep it. */
2219 if (order->Equals(v->current_order) && (v->type == VEH_AIRCRAFT || v->dest_tile != 0) &&
2220 (v->type != VEH_SHIP || !order->IsType(OT_GOTO_STATION) || Station::Get(order->GetDestination())->docks != NULL)) {
2221 return false;
2224 /* Otherwise set it, and determine the destination tile. */
2225 v->current_order = *order;
2227 InvalidateVehicleOrder(v, VIWD_MODIFY_ORDERS);
2228 switch (v->type) {
2229 default:
2230 NOT_REACHED();
2232 case VEH_ROAD:
2233 case VEH_TRAIN:
2234 break;
2236 case VEH_AIRCRAFT:
2237 case VEH_SHIP:
2238 SetWindowClassesDirty(GetWindowClassForVehicleType(v->type));
2239 break;
2242 return UpdateOrderDest(v, order) && may_reverse;
2246 * Check whether the given vehicle should stop at the given station
2247 * based on this order and the non-stop settings.
2248 * @param v the vehicle that might be stopping.
2249 * @param station the station to stop at.
2250 * @return true if the vehicle should stop.
2252 bool BaseOrder::ShouldStopAtStation(const Vehicle *v, StationID station) const
2254 bool is_dest_station = this->IsType(OT_GOTO_STATION) && this->dest == station;
2256 return (!this->IsType(OT_GOTO_DEPOT) || (this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS) != 0) &&
2257 v->last_station_visited != station && // Do stop only when we've not just been there
2258 /* Finally do stop when there is no non-stop flag set for this type of station. */
2259 !(this->GetNonStopType() & (is_dest_station ? ONSF_NO_STOP_AT_DESTINATION_STATION : ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS));
2262 bool BaseOrder::CanLoadOrUnload() const
2264 return (this->IsType(OT_GOTO_STATION) || this->IsType(OT_IMPLICIT)) &&
2265 (this->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) == 0 &&
2266 ((this->GetLoadType() & OLFB_NO_LOAD) == 0 ||
2267 (this->GetUnloadType() & OUFB_NO_UNLOAD) == 0);
2271 * A vehicle can leave the current station with cargo if:
2272 * 1. it can load cargo here OR
2273 * 2a. it could leave the last station with cargo AND
2274 * 2b. it doesn't have to unload all cargo here.
2276 bool BaseOrder::CanLeaveWithCargo(bool has_cargo) const
2278 return (this->GetLoadType() & OLFB_NO_LOAD) == 0 || (has_cargo &&
2279 (this->GetUnloadType() & (OUFB_UNLOAD | OUFB_TRANSFER)) == 0);