2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * 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 /** @file order_cmd.cpp Handling of orders. */
12 #include "command_func.h"
13 #include "company_func.h"
14 #include "news_func.h"
15 #include "strings_func.h"
16 #include "timetable.h"
17 #include "vehicle_func.h"
18 #include "depot_base.h"
19 #include "core/pool_func.hpp"
20 #include "core/random_func.hpp"
23 #include "station_base.h"
24 #include "waypoint_base.h"
25 #include "company_base.h"
26 #include "order_backup.h"
27 #include "cheat_type.h"
28 #include "order_cmd.h"
29 #include "train_cmd.h"
31 #include "table/strings.h"
33 #include "safeguards.h"
35 /* DestinationID must be at least as large as every these below, because it can
38 static_assert(sizeof(DestinationID
) >= sizeof(DepotID
));
39 static_assert(sizeof(DestinationID
) >= sizeof(StationID
));
41 OrderPool
_order_pool("Order");
42 INSTANTIATE_POOL_METHODS(Order
)
43 OrderListPool
_orderlist_pool("OrderList");
44 INSTANTIATE_POOL_METHODS(OrderList
)
46 /** Clean everything up. */
49 if (CleaningPool()) return;
51 /* We can visit oil rigs and buoys that are not our own. They will be shown in
52 * the list of stations. So, we need to invalidate that window if needed. */
53 if (this->IsType(OT_GOTO_STATION
) || this->IsType(OT_GOTO_WAYPOINT
)) {
54 BaseStation
*bs
= BaseStation::GetIfValid(this->GetDestination());
55 if (bs
!= nullptr && bs
->owner
== OWNER_NONE
) InvalidateWindowClassesData(WC_STATION_LIST
, 0);
61 * @note ONLY use on "current_order" vehicle orders!
65 this->type
= OT_NOTHING
;
72 * Makes this order a Go To Station order.
73 * @param destination the station to go to.
75 void Order::MakeGoToStation(StationID destination
)
77 this->type
= OT_GOTO_STATION
;
79 this->dest
= destination
;
83 * Makes this order a Go To Depot order.
84 * @param destination the depot to go to.
85 * @param order is this order a 'default' order, or an overridden vehicle order?
86 * @param non_stop_type how to get to the depot?
87 * @param action what to do in the depot?
88 * @param cargo the cargo type to change to.
90 void Order::MakeGoToDepot(DepotID destination
, OrderDepotTypeFlags order
, OrderNonStopFlags non_stop_type
, OrderDepotActionFlags action
, CargoID cargo
)
92 this->type
= OT_GOTO_DEPOT
;
93 this->SetDepotOrderType(order
);
94 this->SetDepotActionType(action
);
95 this->SetNonStopType(non_stop_type
);
96 this->dest
= destination
;
97 this->SetRefit(cargo
);
101 * Makes this order a Go To Waypoint order.
102 * @param destination the waypoint to go to.
104 void Order::MakeGoToWaypoint(StationID destination
)
106 this->type
= OT_GOTO_WAYPOINT
;
108 this->dest
= destination
;
112 * Makes this order a Loading order.
113 * @param ordered is this an ordered stop?
115 void Order::MakeLoading(bool ordered
)
117 this->type
= OT_LOADING
;
118 if (!ordered
) this->flags
= 0;
122 * Makes this order a Leave Station order.
124 void Order::MakeLeaveStation()
126 this->type
= OT_LEAVESTATION
;
131 * Makes this order a Dummy order.
133 void Order::MakeDummy()
135 this->type
= OT_DUMMY
;
140 * Makes this order an conditional order.
141 * @param order the order to jump to.
143 void Order::MakeConditional(VehicleOrderID order
)
145 this->type
= OT_CONDITIONAL
;
151 * Makes this order an implicit order.
152 * @param destination the station to go to.
154 void Order::MakeImplicit(StationID destination
)
156 this->type
= OT_IMPLICIT
;
157 this->dest
= destination
;
161 * Make this depot/station order also a refit order.
162 * @param cargo the cargo type to change to.
163 * @pre IsType(OT_GOTO_DEPOT) || IsType(OT_GOTO_STATION).
165 void Order::SetRefit(CargoID cargo
)
167 this->refit_cargo
= cargo
;
171 * Does this order have the same type, flags and destination?
172 * @param other the second order to compare to.
173 * @return true if the type, flags and destination match.
175 bool Order::Equals(const Order
&other
) const
177 /* In case of go to nearest depot orders we need "only" compare the flags
178 * with the other and not the nearest depot order bit or the actual
179 * destination because those get clear/filled in during the order
180 * evaluation. If we do not do this the order will continuously be seen as
181 * a different order and it will try to find a "nearest depot" every tick. */
182 if ((this->IsType(OT_GOTO_DEPOT
) && this->type
== other
.type
) &&
183 ((this->GetDepotActionType() & ODATFB_NEAREST_DEPOT
) != 0 ||
184 (other
.GetDepotActionType() & ODATFB_NEAREST_DEPOT
) != 0)) {
185 return this->GetDepotOrderType() == other
.GetDepotOrderType() &&
186 (this->GetDepotActionType() & ~ODATFB_NEAREST_DEPOT
) == (other
.GetDepotActionType() & ~ODATFB_NEAREST_DEPOT
);
189 return this->type
== other
.type
&& this->flags
== other
.flags
&& this->dest
== other
.dest
;
193 * Pack this order into a 32 bits integer, or actually only
194 * the type, flags and destination.
195 * @return the packed representation.
196 * @note unpacking is done in the constructor.
198 uint32
Order::Pack() const
200 return this->dest
<< 16 | this->flags
<< 8 | this->type
;
204 * Pack this order into a 16 bits integer as close to the TTD
205 * representation as possible.
206 * @return the TTD-like packed representation.
208 uint16
Order::MapOldOrder() const
210 uint16 order
= this->GetType();
211 switch (this->type
) {
212 case OT_GOTO_STATION
:
213 if (this->GetUnloadType() & OUFB_UNLOAD
) SetBit(order
, 5);
214 if (this->GetLoadType() & OLFB_FULL_LOAD
) SetBit(order
, 6);
215 if (this->GetNonStopType() & ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS
) SetBit(order
, 7);
216 order
|= GB(this->GetDestination(), 0, 8) << 8;
219 if (!(this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS
)) SetBit(order
, 6);
221 order
|= GB(this->GetDestination(), 0, 8) << 8;
224 if (this->GetLoadType() & OLFB_FULL_LOAD
) SetBit(order
, 6);
231 * Create an order based on a packed representation of that order.
232 * @param packed the packed representation.
234 Order::Order(uint32 packed
)
236 this->type
= (OrderType
)GB(packed
, 0, 8);
237 this->flags
= GB(packed
, 8, 8);
238 this->dest
= GB(packed
, 16, 16);
239 this->next
= nullptr;
240 this->refit_cargo
= CT_NO_REFIT
;
242 this->travel_time
= 0;
243 this->max_speed
= UINT16_MAX
;
248 * Updates the widgets of a vehicle which contains the order-data
251 void InvalidateVehicleOrder(const Vehicle
*v
, int data
)
253 SetWindowDirty(WC_VEHICLE_VIEW
, v
->index
);
256 /* Calls SetDirty() too */
257 InvalidateWindowData(WC_VEHICLE_ORDERS
, v
->index
, data
);
258 InvalidateWindowData(WC_VEHICLE_TIMETABLE
, v
->index
, data
);
262 SetWindowDirty(WC_VEHICLE_ORDERS
, v
->index
);
263 SetWindowDirty(WC_VEHICLE_TIMETABLE
, v
->index
);
268 * Assign data to an order (from another order)
269 * This function makes sure that the index is maintained correctly
270 * @param other the data to copy (except next pointer).
273 void Order::AssignOrder(const Order
&other
)
275 this->type
= other
.type
;
276 this->flags
= other
.flags
;
277 this->dest
= other
.dest
;
279 this->refit_cargo
= other
.refit_cargo
;
281 this->wait_time
= other
.wait_time
;
282 this->travel_time
= other
.travel_time
;
283 this->max_speed
= other
.max_speed
;
287 * Recomputes everything.
288 * @param chain first order in the chain
289 * @param v one of vehicle that is using this orderlist
291 void OrderList::Initialize(Order
*chain
, Vehicle
*v
)
294 this->first_shared
= v
;
296 this->num_orders
= 0;
297 this->num_manual_orders
= 0;
298 this->num_vehicles
= 1;
299 this->timetable_duration
= 0;
301 for (Order
*o
= this->first
; o
!= nullptr; o
= o
->next
) {
303 if (!o
->IsType(OT_IMPLICIT
)) ++this->num_manual_orders
;
304 this->total_duration
+= o
->GetWaitTime() + o
->GetTravelTime();
307 this->RecalculateTimetableDuration();
309 for (Vehicle
*u
= this->first_shared
->PreviousShared(); u
!= nullptr; u
= u
->PreviousShared()) {
310 ++this->num_vehicles
;
311 this->first_shared
= u
;
314 for (const Vehicle
*u
= v
->NextShared(); u
!= nullptr; u
= u
->NextShared()) ++this->num_vehicles
;
318 * Recomputes Timetable duration.
319 * Split out into a separate function so it can be used by afterload.
321 void OrderList::RecalculateTimetableDuration()
323 this->timetable_duration
= 0;
324 for (Order
*o
= this->first
; o
!= nullptr; o
= o
->next
) {
325 this->timetable_duration
+= o
->GetTimetabledWait() + o
->GetTimetabledTravel();
330 * Free a complete order chain.
331 * @param keep_orderlist If this is true only delete the orders, otherwise also delete the OrderList.
332 * @note do not use on "current_order" vehicle orders!
334 void OrderList::FreeChain(bool keep_orderlist
)
337 for (Order
*o
= this->first
; o
!= nullptr; o
= next
) {
342 if (keep_orderlist
) {
343 this->first
= nullptr;
344 this->num_orders
= 0;
345 this->num_manual_orders
= 0;
346 this->timetable_duration
= 0;
353 * Get a certain order of the order chain.
354 * @param index zero-based index of the order within the chain.
355 * @return the order at position index.
357 Order
*OrderList::GetOrderAt(int index
) const
359 if (index
< 0) return nullptr;
361 Order
*order
= this->first
;
363 while (order
!= nullptr && index
-- > 0) {
370 * Get the next order which will make the given vehicle stop at a station
371 * or refit at a depot or evaluate a non-trivial condition.
372 * @param next The order to start looking at.
373 * @param hops The number of orders we have already looked at.
375 * \li a station order
376 * \li a refitting depot order
377 * \li a non-trivial conditional order
378 * \li nullptr if the vehicle won't stop anymore.
380 const Order
*OrderList::GetNextDecisionNode(const Order
*next
, uint hops
) const
382 if (hops
> this->GetNumOrders() || next
== nullptr) return nullptr;
384 if (next
->IsType(OT_CONDITIONAL
)) {
385 if (next
->GetConditionVariable() != OCV_UNCONDITIONALLY
) return next
;
387 /* We can evaluate trivial conditions right away. They're conceptually
388 * the same as regular order progression. */
389 return this->GetNextDecisionNode(
390 this->GetOrderAt(next
->GetConditionSkipToOrder()),
394 if (next
->IsType(OT_GOTO_DEPOT
)) {
395 if (next
->GetDepotActionType() == ODATFB_HALT
) return nullptr;
396 if (next
->IsRefit()) return next
;
399 if (!next
->CanLoadOrUnload()) {
400 return this->GetNextDecisionNode(this->GetNext(next
), hops
+ 1);
407 * Recursively determine the next deterministic station to stop at.
408 * @param v The vehicle we're looking at.
409 * @param first Order to start searching at or nullptr to start at cur_implicit_order_index + 1.
410 * @param hops Number of orders we have already looked at.
411 * @return Next stopping station or INVALID_STATION.
412 * @pre The vehicle is currently loading and v->last_station_visited is meaningful.
413 * @note This function may draw a random number. Don't use it from the GUI.
415 StationIDStack
OrderList::GetNextStoppingStation(const Vehicle
*v
, const Order
*first
, uint hops
) const
418 const Order
*next
= first
;
419 if (first
== nullptr) {
420 next
= this->GetOrderAt(v
->cur_implicit_order_index
);
421 if (next
== nullptr) {
422 next
= this->GetFirstOrder();
423 if (next
== nullptr) return INVALID_STATION
;
425 /* GetNext never returns nullptr if there is a valid station in the list.
426 * As the given "next" is already valid and a station in the list, we
427 * don't have to check for nullptr here. */
428 next
= this->GetNext(next
);
429 assert(next
!= nullptr);
434 next
= this->GetNextDecisionNode(next
, ++hops
);
436 /* Resolve possibly nested conditionals by estimation. */
437 while (next
!= nullptr && next
->IsType(OT_CONDITIONAL
)) {
438 /* We return both options of conditional orders. */
439 const Order
*skip_to
= this->GetNextDecisionNode(
440 this->GetOrderAt(next
->GetConditionSkipToOrder()), hops
);
441 const Order
*advance
= this->GetNextDecisionNode(
442 this->GetNext(next
), hops
);
443 if (advance
== nullptr || advance
== first
|| skip_to
== advance
) {
444 next
= (skip_to
== first
) ? nullptr : skip_to
;
445 } else if (skip_to
== nullptr || skip_to
== first
) {
446 next
= (advance
== first
) ? nullptr : advance
;
448 StationIDStack st1
= this->GetNextStoppingStation(v
, skip_to
, hops
);
449 StationIDStack st2
= this->GetNextStoppingStation(v
, advance
, hops
);
450 while (!st2
.IsEmpty()) st1
.Push(st2
.Pop());
456 /* Don't return a next stop if the vehicle has to unload everything. */
457 if (next
== nullptr || ((next
->IsType(OT_GOTO_STATION
) || next
->IsType(OT_IMPLICIT
)) &&
458 next
->GetDestination() == v
->last_station_visited
&&
459 (next
->GetUnloadType() & (OUFB_TRANSFER
| OUFB_UNLOAD
)) != 0)) {
460 return INVALID_STATION
;
462 } while (next
->IsType(OT_GOTO_DEPOT
) || next
->GetDestination() == v
->last_station_visited
);
464 return next
->GetDestination();
468 * Insert a new order into the order chain.
469 * @param new_order is the order to insert into the chain.
470 * @param index is the position where the order is supposed to be inserted.
472 void OrderList::InsertOrderAt(Order
*new_order
, int index
)
474 if (this->first
== nullptr) {
475 this->first
= new_order
;
478 /* Insert as first or only order */
479 new_order
->next
= this->first
;
480 this->first
= new_order
;
481 } else if (index
>= this->num_orders
) {
482 /* index is after the last order, add it to the end */
483 this->GetLastOrder()->next
= new_order
;
485 /* Put the new order in between */
486 Order
*order
= this->GetOrderAt(index
- 1);
487 new_order
->next
= order
->next
;
488 order
->next
= new_order
;
492 if (!new_order
->IsType(OT_IMPLICIT
)) ++this->num_manual_orders
;
493 this->timetable_duration
+= new_order
->GetTimetabledWait() + new_order
->GetTimetabledTravel();
494 this->total_duration
+= new_order
->GetWaitTime() + new_order
->GetTravelTime();
496 /* We can visit oil rigs and buoys that are not our own. They will be shown in
497 * the list of stations. So, we need to invalidate that window if needed. */
498 if (new_order
->IsType(OT_GOTO_STATION
) || new_order
->IsType(OT_GOTO_WAYPOINT
)) {
499 BaseStation
*bs
= BaseStation::Get(new_order
->GetDestination());
500 if (bs
->owner
== OWNER_NONE
) InvalidateWindowClassesData(WC_STATION_LIST
, 0);
507 * Remove an order from the order list and delete it.
508 * @param index is the position of the order which is to be deleted.
510 void OrderList::DeleteOrderAt(int index
)
512 if (index
>= this->num_orders
) return;
517 to_remove
= this->first
;
518 this->first
= to_remove
->next
;
520 Order
*prev
= GetOrderAt(index
- 1);
521 to_remove
= prev
->next
;
522 prev
->next
= to_remove
->next
;
525 if (!to_remove
->IsType(OT_IMPLICIT
)) --this->num_manual_orders
;
526 this->timetable_duration
-= (to_remove
->GetTimetabledWait() + to_remove
->GetTimetabledTravel());
527 this->total_duration
-= (to_remove
->GetWaitTime() + to_remove
->GetTravelTime());
532 * Move an order to another position within the order list.
533 * @param from is the zero-based position of the order to move.
534 * @param to is the zero-based position where the order is moved to.
536 void OrderList::MoveOrder(int from
, int to
)
538 if (from
>= this->num_orders
|| to
>= this->num_orders
|| from
== to
) return;
542 /* Take the moving order out of the pointer-chain */
544 moving_one
= this->first
;
545 this->first
= moving_one
->next
;
547 Order
*one_before
= GetOrderAt(from
- 1);
548 moving_one
= one_before
->next
;
549 one_before
->next
= moving_one
->next
;
552 /* Insert the moving_order again in the pointer-chain */
554 moving_one
->next
= this->first
;
555 this->first
= moving_one
;
557 Order
*one_before
= GetOrderAt(to
- 1);
558 moving_one
->next
= one_before
->next
;
559 one_before
->next
= moving_one
;
564 * Removes the vehicle from the shared order list.
565 * @note This is supposed to be called when the vehicle is still in the chain
566 * @param v vehicle to remove from the list
568 void OrderList::RemoveVehicle(Vehicle
*v
)
570 --this->num_vehicles
;
571 if (v
== this->first_shared
) this->first_shared
= v
->NextShared();
575 * Checks whether a vehicle is part of the shared vehicle chain.
576 * @param v is the vehicle to search in the shared vehicle chain.
578 bool OrderList::IsVehicleInSharedOrdersList(const Vehicle
*v
) const
580 for (const Vehicle
*v_shared
= this->first_shared
; v_shared
!= nullptr; v_shared
= v_shared
->NextShared()) {
581 if (v_shared
== v
) return true;
588 * Gets the position of the given vehicle within the shared order vehicle list.
589 * @param v is the vehicle of which to get the position
590 * @return position of v within the shared vehicle chain.
592 int OrderList::GetPositionInSharedOrderList(const Vehicle
*v
) const
595 for (const Vehicle
*v_shared
= v
->PreviousShared(); v_shared
!= nullptr; v_shared
= v_shared
->PreviousShared()) count
++;
600 * Checks whether all orders of the list have a filled timetable.
601 * @return whether all orders have a filled timetable.
603 bool OrderList::IsCompleteTimetable() const
605 for (Order
*o
= this->first
; o
!= nullptr; o
= o
->next
) {
606 /* Implicit orders are, by definition, not timetabled. */
607 if (o
->IsType(OT_IMPLICIT
)) continue;
608 if (!o
->IsCompletelyTimetabled()) return false;
615 * Checks for internal consistency of order list. Triggers assertion if something is wrong.
617 void OrderList::DebugCheckSanity() const
619 VehicleOrderID check_num_orders
= 0;
620 VehicleOrderID check_num_manual_orders
= 0;
621 uint check_num_vehicles
= 0;
622 Ticks check_timetable_duration
= 0;
623 Ticks check_total_duration
= 0;
625 Debug(misc
, 6, "Checking OrderList {} for sanity...", this->index
);
627 for (const Order
*o
= this->first
; o
!= nullptr; o
= o
->next
) {
629 if (!o
->IsType(OT_IMPLICIT
)) ++check_num_manual_orders
;
630 check_timetable_duration
+= o
->GetTimetabledWait() + o
->GetTimetabledTravel();
631 check_total_duration
+= o
->GetWaitTime() + o
->GetTravelTime();
633 assert(this->num_orders
== check_num_orders
);
634 assert(this->num_manual_orders
== check_num_manual_orders
);
635 assert(this->timetable_duration
== check_timetable_duration
);
636 assert(this->total_duration
== check_total_duration
);
638 for (const Vehicle
*v
= this->first_shared
; v
!= nullptr; v
= v
->NextShared()) {
639 ++check_num_vehicles
;
640 assert(v
->orders
== this);
642 assert(this->num_vehicles
== check_num_vehicles
);
643 Debug(misc
, 6, "... detected {} orders ({} manual), {} vehicles, {} timetabled, {} total",
644 (uint
)this->num_orders
, (uint
)this->num_manual_orders
,
645 this->num_vehicles
, this->timetable_duration
, this->total_duration
);
650 * Checks whether the order goes to a station or not, i.e. whether the
651 * destination is a station
652 * @param v the vehicle to check for
653 * @param o the order to check
654 * @return true if the destination is a station
656 static inline bool OrderGoesToStation(const Vehicle
*v
, const Order
*o
)
658 return o
->IsType(OT_GOTO_STATION
) ||
659 (v
->type
== VEH_AIRCRAFT
&& o
->IsType(OT_GOTO_DEPOT
) && !(o
->GetDepotActionType() & ODATFB_NEAREST_DEPOT
));
663 * Delete all news items regarding defective orders about a vehicle
664 * This could kill still valid warnings (for example about void order when just
665 * another order gets added), but assume the company will notice the problems,
666 * when they're changing the orders.
668 static void DeleteOrderWarnings(const Vehicle
*v
)
670 DeleteVehicleNews(v
->index
, STR_NEWS_VEHICLE_HAS_TOO_FEW_ORDERS
);
671 DeleteVehicleNews(v
->index
, STR_NEWS_VEHICLE_HAS_VOID_ORDER
);
672 DeleteVehicleNews(v
->index
, STR_NEWS_VEHICLE_HAS_DUPLICATE_ENTRY
);
673 DeleteVehicleNews(v
->index
, STR_NEWS_VEHICLE_HAS_INVALID_ENTRY
);
674 DeleteVehicleNews(v
->index
, STR_NEWS_PLANE_USES_TOO_SHORT_RUNWAY
);
678 * Returns a tile somewhat representing the order destination (not suitable for pathfinding).
679 * @param v The vehicle to get the location for.
680 * @param airport Get the airport tile and not the station location for aircraft.
681 * @return destination of order, or INVALID_TILE if none.
683 TileIndex
Order::GetLocation(const Vehicle
*v
, bool airport
) const
685 switch (this->GetType()) {
686 case OT_GOTO_WAYPOINT
:
687 case OT_GOTO_STATION
:
689 if (airport
&& v
->type
== VEH_AIRCRAFT
) return Station::Get(this->GetDestination())->airport
.tile
;
690 return BaseStation::Get(this->GetDestination())->xy
;
693 if ((this->GetDepotActionType() & ODATFB_NEAREST_DEPOT
) != 0) return INVALID_TILE
;
694 return (v
->type
== VEH_AIRCRAFT
) ? Station::Get(this->GetDestination())->xy
: Depot::Get(this->GetDestination())->xy
;
702 * Get the distance between two orders of a vehicle. Conditional orders are resolved
703 * and the bigger distance of the two order branches is returned.
704 * @param prev Origin order.
705 * @param cur Destination order.
706 * @param v The vehicle to get the distance for.
707 * @param conditional_depth Internal param for resolving conditional orders.
708 * @return Maximum distance between the two orders.
710 uint
GetOrderDistance(const Order
*prev
, const Order
*cur
, const Vehicle
*v
, int conditional_depth
)
712 if (cur
->IsType(OT_CONDITIONAL
)) {
713 if (conditional_depth
> v
->GetNumOrders()) return 0;
717 int dist1
= GetOrderDistance(prev
, v
->GetOrder(cur
->GetConditionSkipToOrder()), v
, conditional_depth
);
718 int dist2
= GetOrderDistance(prev
, cur
->next
== nullptr ? v
->orders
->GetFirstOrder() : cur
->next
, v
, conditional_depth
);
719 return std::max(dist1
, dist2
);
722 TileIndex prev_tile
= prev
->GetLocation(v
, true);
723 TileIndex cur_tile
= cur
->GetLocation(v
, true);
724 if (prev_tile
== INVALID_TILE
|| cur_tile
== INVALID_TILE
) return 0;
725 return v
->type
== VEH_AIRCRAFT
? DistanceSquare(prev_tile
, cur_tile
) : DistanceManhattan(prev_tile
, cur_tile
);
729 * Add an order to the orderlist of a vehicle.
730 * @param flags operation to perform
731 * @param veh ID of the vehicle
732 * @param sel_ord the selected order (if any). If the last order is given,
733 * the order will be inserted before that one
734 * the maximum vehicle order id is 254.
735 * @param new_order order to insert
736 * @return the cost of this operation or an error
738 CommandCost
CmdInsertOrder(DoCommandFlag flags
, VehicleID veh
, VehicleOrderID sel_ord
, const Order
&new_order
)
740 Vehicle
*v
= Vehicle::GetIfValid(veh
);
741 if (v
== nullptr || !v
->IsPrimaryVehicle()) return CMD_ERROR
;
743 CommandCost ret
= CheckOwnership(v
->owner
);
744 if (ret
.Failed()) return ret
;
746 /* Validate properties we don't want to have different from default as they are set by other commands. */
747 if (new_order
.GetRefitCargo() != CT_NO_REFIT
|| new_order
.GetWaitTime() != 0 || new_order
.GetTravelTime() != 0 || new_order
.GetMaxSpeed() != UINT16_MAX
) return CMD_ERROR
;
749 /* Check if the inserted order is to the correct destination (owner, type),
750 * and has the correct flags if any */
751 switch (new_order
.GetType()) {
752 case OT_GOTO_STATION
: {
753 const Station
*st
= Station::GetIfValid(new_order
.GetDestination());
754 if (st
== nullptr) return CMD_ERROR
;
756 if (st
->owner
!= OWNER_NONE
) {
757 CommandCost ret
= CheckOwnership(st
->owner
);
758 if (ret
.Failed()) return ret
;
761 if (!CanVehicleUseStation(v
, st
)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER
);
762 for (Vehicle
*u
= v
->FirstShared(); u
!= nullptr; u
= u
->NextShared()) {
763 if (!CanVehicleUseStation(u
, st
)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER_SHARED
);
766 /* Non stop only allowed for ground vehicles. */
767 if (new_order
.GetNonStopType() != ONSF_STOP_EVERYWHERE
&& !v
->IsGroundVehicle()) return CMD_ERROR
;
769 /* Filter invalid load/unload types. */
770 switch (new_order
.GetLoadType()) {
771 case OLF_LOAD_IF_POSSIBLE
: case OLFB_FULL_LOAD
: case OLF_FULL_LOAD_ANY
: case OLFB_NO_LOAD
: break;
772 default: return CMD_ERROR
;
774 switch (new_order
.GetUnloadType()) {
775 case OUF_UNLOAD_IF_POSSIBLE
: case OUFB_UNLOAD
: case OUFB_TRANSFER
: case OUFB_NO_UNLOAD
: break;
776 default: return CMD_ERROR
;
779 /* Filter invalid stop locations */
780 switch (new_order
.GetStopLocation()) {
781 case OSL_PLATFORM_NEAR_END
:
782 case OSL_PLATFORM_MIDDLE
:
783 if (v
->type
!= VEH_TRAIN
) return CMD_ERROR
;
786 case OSL_PLATFORM_FAR_END
:
796 case OT_GOTO_DEPOT
: {
797 if ((new_order
.GetDepotActionType() & ODATFB_NEAREST_DEPOT
) == 0) {
798 if (v
->type
== VEH_AIRCRAFT
) {
799 const Station
*st
= Station::GetIfValid(new_order
.GetDestination());
801 if (st
== nullptr) return CMD_ERROR
;
803 CommandCost ret
= CheckOwnership(st
->owner
);
804 if (ret
.Failed()) return ret
;
806 if (!CanVehicleUseStation(v
, st
) || !st
->airport
.HasHangar()) {
810 const Depot
*dp
= Depot::GetIfValid(new_order
.GetDestination());
812 if (dp
== nullptr) return CMD_ERROR
;
814 CommandCost ret
= CheckOwnership(GetTileOwner(dp
->xy
));
815 if (ret
.Failed()) return ret
;
819 if (!IsRailDepotTile(dp
->xy
)) return CMD_ERROR
;
823 if (!IsRoadDepotTile(dp
->xy
)) return CMD_ERROR
;
827 if (!IsShipDepotTile(dp
->xy
)) return CMD_ERROR
;
830 default: return CMD_ERROR
;
835 if (new_order
.GetNonStopType() != ONSF_STOP_EVERYWHERE
&& !v
->IsGroundVehicle()) return CMD_ERROR
;
836 if (new_order
.GetDepotOrderType() & ~(ODTFB_PART_OF_ORDERS
| ((new_order
.GetDepotOrderType() & ODTFB_PART_OF_ORDERS
) != 0 ? ODTFB_SERVICE
: 0))) return CMD_ERROR
;
837 if (new_order
.GetDepotActionType() & ~(ODATFB_HALT
| ODATFB_NEAREST_DEPOT
)) return CMD_ERROR
;
838 if ((new_order
.GetDepotOrderType() & ODTFB_SERVICE
) && (new_order
.GetDepotActionType() & ODATFB_HALT
)) return CMD_ERROR
;
842 case OT_GOTO_WAYPOINT
: {
843 const Waypoint
*wp
= Waypoint::GetIfValid(new_order
.GetDestination());
844 if (wp
== nullptr) return CMD_ERROR
;
847 default: return CMD_ERROR
;
850 if (!(wp
->facilities
& FACIL_TRAIN
)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER
);
852 CommandCost ret
= CheckOwnership(wp
->owner
);
853 if (ret
.Failed()) return ret
;
858 if (!(wp
->facilities
& FACIL_DOCK
)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER
);
859 if (wp
->owner
!= OWNER_NONE
) {
860 CommandCost ret
= CheckOwnership(wp
->owner
);
861 if (ret
.Failed()) return ret
;
866 /* Order flags can be any of the following for waypoints:
868 * non-stop orders (if any) are only valid for trains */
869 if (new_order
.GetNonStopType() != ONSF_STOP_EVERYWHERE
&& v
->type
!= VEH_TRAIN
) return CMD_ERROR
;
873 case OT_CONDITIONAL
: {
874 VehicleOrderID skip_to
= new_order
.GetConditionSkipToOrder();
875 if (skip_to
!= 0 && skip_to
>= v
->GetNumOrders()) return CMD_ERROR
; // Always allow jumping to the first (even when there is no order).
876 if (new_order
.GetConditionVariable() >= OCV_END
) return CMD_ERROR
;
878 OrderConditionComparator occ
= new_order
.GetConditionComparator();
879 if (occ
>= OCC_END
) return CMD_ERROR
;
880 switch (new_order
.GetConditionVariable()) {
881 case OCV_REQUIRES_SERVICE
:
882 if (occ
!= OCC_IS_TRUE
&& occ
!= OCC_IS_FALSE
) return CMD_ERROR
;
885 case OCV_UNCONDITIONALLY
:
886 if (occ
!= OCC_EQUALS
) return CMD_ERROR
;
887 if (new_order
.GetConditionValue() != 0) return CMD_ERROR
;
890 case OCV_LOAD_PERCENTAGE
:
891 case OCV_RELIABILITY
:
892 if (new_order
.GetConditionValue() > 100) return CMD_ERROR
;
896 if (occ
== OCC_IS_TRUE
|| occ
== OCC_IS_FALSE
) return CMD_ERROR
;
902 default: return CMD_ERROR
;
905 if (sel_ord
> v
->GetNumOrders()) return CMD_ERROR
;
907 if (v
->GetNumOrders() >= MAX_VEH_ORDER_ID
) return_cmd_error(STR_ERROR_TOO_MANY_ORDERS
);
908 if (!Order::CanAllocateItem()) return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS
);
909 if (v
->orders
== nullptr && !OrderList::CanAllocateItem()) return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS
);
911 if (flags
& DC_EXEC
) {
912 Order
*new_o
= new Order();
913 new_o
->AssignOrder(new_order
);
914 InsertOrder(v
, new_o
, sel_ord
);
917 return CommandCost();
921 * Insert a new order but skip the validation.
922 * @param v The vehicle to insert the order to.
923 * @param new_o The new order.
924 * @param sel_ord The position the order should be inserted at.
926 void InsertOrder(Vehicle
*v
, Order
*new_o
, VehicleOrderID sel_ord
)
928 /* Create new order and link in list */
929 if (v
->orders
== nullptr) {
930 v
->orders
= new OrderList(new_o
, v
);
932 v
->orders
->InsertOrderAt(new_o
, sel_ord
);
935 Vehicle
*u
= v
->FirstShared();
936 DeleteOrderWarnings(u
);
937 for (; u
!= nullptr; u
= u
->NextShared()) {
938 assert(v
->orders
== u
->orders
);
940 /* If there is added an order before the current one, we need
941 * to update the selected order. We do not change implicit/real order indices though.
942 * If the new order is between the current implicit order and real order, the implicit order will
943 * later skip the inserted order. */
944 if (sel_ord
<= u
->cur_real_order_index
) {
945 uint cur
= u
->cur_real_order_index
+ 1;
946 /* Check if we don't go out of bound */
947 if (cur
< u
->GetNumOrders()) {
948 u
->cur_real_order_index
= cur
;
951 if (sel_ord
== u
->cur_implicit_order_index
&& u
->IsGroundVehicle()) {
952 /* We are inserting an order just before the current implicit order.
953 * We do not know whether we will reach current implicit or the newly inserted order first.
954 * So, disable creation of implicit orders until we are on track again. */
955 uint16
&gv_flags
= u
->GetGroundVehicleFlags();
956 SetBit(gv_flags
, GVF_SUPPRESS_IMPLICIT_ORDERS
);
958 if (sel_ord
<= u
->cur_implicit_order_index
) {
959 uint cur
= u
->cur_implicit_order_index
+ 1;
960 /* Check if we don't go out of bound */
961 if (cur
< u
->GetNumOrders()) {
962 u
->cur_implicit_order_index
= cur
;
965 /* Update any possible open window of the vehicle */
966 InvalidateVehicleOrder(u
, INVALID_VEH_ORDER_ID
| (sel_ord
<< 8));
969 /* As we insert an order, the order to skip to will be 'wrong'. */
970 VehicleOrderID cur_order_id
= 0;
971 for (Order
*order
: v
->Orders()) {
972 if (order
->IsType(OT_CONDITIONAL
)) {
973 VehicleOrderID order_id
= order
->GetConditionSkipToOrder();
974 if (order_id
>= sel_ord
) {
975 order
->SetConditionSkipToOrder(order_id
+ 1);
977 if (order_id
== cur_order_id
) {
978 order
->SetConditionSkipToOrder((order_id
+ 1) % v
->GetNumOrders());
984 /* Make sure to rebuild the whole list */
985 InvalidateWindowClassesData(GetWindowClassForVehicleType(v
->type
), 0);
989 * Declone an order-list
990 * @param *dst delete the orders of this vehicle
991 * @param flags execution flags
993 static CommandCost
DecloneOrder(Vehicle
*dst
, DoCommandFlag flags
)
995 if (flags
& DC_EXEC
) {
996 DeleteVehicleOrders(dst
);
997 InvalidateVehicleOrder(dst
, VIWD_REMOVE_ALL_ORDERS
);
998 InvalidateWindowClassesData(GetWindowClassForVehicleType(dst
->type
), 0);
1000 return CommandCost();
1004 * Delete an order from the orderlist of a vehicle.
1005 * @param flags operation to perform
1006 * @param veh_id the ID of the vehicle
1007 * @param sel_ord the order to delete (max 255)
1008 * @return the cost of this operation or an error
1010 CommandCost
CmdDeleteOrder(DoCommandFlag flags
, VehicleID veh_id
, VehicleOrderID sel_ord
)
1012 Vehicle
*v
= Vehicle::GetIfValid(veh_id
);
1014 if (v
== nullptr || !v
->IsPrimaryVehicle()) return CMD_ERROR
;
1016 CommandCost ret
= CheckOwnership(v
->owner
);
1017 if (ret
.Failed()) return ret
;
1019 /* If we did not select an order, we maybe want to de-clone the orders */
1020 if (sel_ord
>= v
->GetNumOrders()) return DecloneOrder(v
, flags
);
1022 if (v
->GetOrder(sel_ord
) == nullptr) return CMD_ERROR
;
1024 if (flags
& DC_EXEC
) DeleteOrder(v
, sel_ord
);
1025 return CommandCost();
1029 * Cancel the current loading order of the vehicle as the order was deleted.
1030 * @param v the vehicle
1032 static void CancelLoadingDueToDeletedOrder(Vehicle
*v
)
1034 assert(v
->current_order
.IsType(OT_LOADING
));
1035 /* NON-stop flag is misused to see if a train is in a station that is
1036 * on its order list or not */
1037 v
->current_order
.SetNonStopType(ONSF_STOP_EVERYWHERE
);
1038 /* When full loading, "cancel" that order so the vehicle doesn't
1039 * stay indefinitely at this station anymore. */
1040 if (v
->current_order
.GetLoadType() & OLFB_FULL_LOAD
) v
->current_order
.SetLoadType(OLF_LOAD_IF_POSSIBLE
);
1044 * Delete an order but skip the parameter validation.
1045 * @param v The vehicle to delete the order from.
1046 * @param sel_ord The id of the order to be deleted.
1048 void DeleteOrder(Vehicle
*v
, VehicleOrderID sel_ord
)
1050 v
->orders
->DeleteOrderAt(sel_ord
);
1052 Vehicle
*u
= v
->FirstShared();
1053 DeleteOrderWarnings(u
);
1054 for (; u
!= nullptr; u
= u
->NextShared()) {
1055 assert(v
->orders
== u
->orders
);
1057 if (sel_ord
== u
->cur_real_order_index
&& u
->current_order
.IsType(OT_LOADING
)) {
1058 CancelLoadingDueToDeletedOrder(u
);
1061 if (sel_ord
< u
->cur_real_order_index
) {
1062 u
->cur_real_order_index
--;
1063 } else if (sel_ord
== u
->cur_real_order_index
) {
1064 u
->UpdateRealOrderIndex();
1067 if (sel_ord
< u
->cur_implicit_order_index
) {
1068 u
->cur_implicit_order_index
--;
1069 } else if (sel_ord
== u
->cur_implicit_order_index
) {
1070 /* Make sure the index is valid */
1071 if (u
->cur_implicit_order_index
>= u
->GetNumOrders()) u
->cur_implicit_order_index
= 0;
1073 /* Skip non-implicit orders for the implicit-order-index (e.g. if the current implicit order was deleted */
1074 while (u
->cur_implicit_order_index
!= u
->cur_real_order_index
&& !u
->GetOrder(u
->cur_implicit_order_index
)->IsType(OT_IMPLICIT
)) {
1075 u
->cur_implicit_order_index
++;
1076 if (u
->cur_implicit_order_index
>= u
->GetNumOrders()) u
->cur_implicit_order_index
= 0;
1080 /* Update any possible open window of the vehicle */
1081 InvalidateVehicleOrder(u
, sel_ord
| (INVALID_VEH_ORDER_ID
<< 8));
1084 /* As we delete an order, the order to skip to will be 'wrong'. */
1085 VehicleOrderID cur_order_id
= 0;
1086 for (Order
*order
: v
->Orders()) {
1087 if (order
->IsType(OT_CONDITIONAL
)) {
1088 VehicleOrderID order_id
= order
->GetConditionSkipToOrder();
1089 if (order_id
>= sel_ord
) {
1090 order_id
= std::max(order_id
- 1, 0);
1092 if (order_id
== cur_order_id
) {
1093 order_id
= (order_id
+ 1) % v
->GetNumOrders();
1095 order
->SetConditionSkipToOrder(order_id
);
1100 InvalidateWindowClassesData(GetWindowClassForVehicleType(v
->type
), 0);
1104 * Goto order of order-list.
1105 * @param flags operation to perform
1106 * @param veh_id The ID of the vehicle which order is skipped
1107 * @param sel_ord the selected order to which we want to skip
1108 * @return the cost of this operation or an error
1110 CommandCost
CmdSkipToOrder(DoCommandFlag flags
, VehicleID veh_id
, VehicleOrderID sel_ord
)
1112 Vehicle
*v
= Vehicle::GetIfValid(veh_id
);
1114 if (v
== nullptr || !v
->IsPrimaryVehicle() || sel_ord
== v
->cur_implicit_order_index
|| sel_ord
>= v
->GetNumOrders() || v
->GetNumOrders() < 2) return CMD_ERROR
;
1116 CommandCost ret
= CheckOwnership(v
->owner
);
1117 if (ret
.Failed()) return ret
;
1119 if (flags
& DC_EXEC
) {
1120 if (v
->current_order
.IsType(OT_LOADING
)) v
->LeaveStation();
1122 v
->cur_implicit_order_index
= v
->cur_real_order_index
= sel_ord
;
1123 v
->UpdateRealOrderIndex();
1125 InvalidateVehicleOrder(v
, VIWD_MODIFY_ORDERS
);
1127 /* We have an aircraft/ship, they have a mini-schedule, so update them all */
1128 if (v
->type
== VEH_AIRCRAFT
) SetWindowClassesDirty(WC_AIRCRAFT_LIST
);
1129 if (v
->type
== VEH_SHIP
) SetWindowClassesDirty(WC_SHIPS_LIST
);
1132 return CommandCost();
1136 * Move an order inside the orderlist
1137 * @param flags operation to perform
1138 * @param veh the ID of the vehicle
1139 * @param moving_order the order to move
1140 * @param target_order the target order
1141 * @return the cost of this operation or an error
1142 * @note The target order will move one place down in the orderlist
1143 * if you move the order upwards else it'll move it one place down
1145 CommandCost
CmdMoveOrder(DoCommandFlag flags
, VehicleID veh
, VehicleOrderID moving_order
, VehicleOrderID target_order
)
1147 Vehicle
*v
= Vehicle::GetIfValid(veh
);
1148 if (v
== nullptr || !v
->IsPrimaryVehicle()) return CMD_ERROR
;
1150 CommandCost ret
= CheckOwnership(v
->owner
);
1151 if (ret
.Failed()) return ret
;
1153 /* Don't make senseless movements */
1154 if (moving_order
>= v
->GetNumOrders() || target_order
>= v
->GetNumOrders() ||
1155 moving_order
== target_order
|| v
->GetNumOrders() <= 1) return CMD_ERROR
;
1157 Order
*moving_one
= v
->GetOrder(moving_order
);
1158 /* Don't move an empty order */
1159 if (moving_one
== nullptr) return CMD_ERROR
;
1161 if (flags
& DC_EXEC
) {
1162 v
->orders
->MoveOrder(moving_order
, target_order
);
1164 /* Update shared list */
1165 Vehicle
*u
= v
->FirstShared();
1167 DeleteOrderWarnings(u
);
1169 for (; u
!= nullptr; u
= u
->NextShared()) {
1170 /* Update the current order.
1171 * There are multiple ways to move orders, which result in cur_implicit_order_index
1172 * and cur_real_order_index to not longer make any sense. E.g. moving another
1173 * real order between them.
1175 * Basically one could choose to preserve either of them, but not both.
1176 * While both ways are suitable in this or that case from a human point of view, neither
1177 * of them makes really sense.
1178 * However, from an AI point of view, preserving cur_real_order_index is the most
1179 * predictable and transparent behaviour.
1181 * With that decision it basically does not matter what we do to cur_implicit_order_index.
1182 * If we change orders between the implicit- and real-index, the implicit orders are mostly likely
1183 * completely out-dated anyway. So, keep it simple and just keep cur_implicit_order_index as well.
1184 * The worst which can happen is that a lot of implicit orders are removed when reaching current_order.
1186 if (u
->cur_real_order_index
== moving_order
) {
1187 u
->cur_real_order_index
= target_order
;
1188 } else if (u
->cur_real_order_index
> moving_order
&& u
->cur_real_order_index
<= target_order
) {
1189 u
->cur_real_order_index
--;
1190 } else if (u
->cur_real_order_index
< moving_order
&& u
->cur_real_order_index
>= target_order
) {
1191 u
->cur_real_order_index
++;
1194 if (u
->cur_implicit_order_index
== moving_order
) {
1195 u
->cur_implicit_order_index
= target_order
;
1196 } else if (u
->cur_implicit_order_index
> moving_order
&& u
->cur_implicit_order_index
<= target_order
) {
1197 u
->cur_implicit_order_index
--;
1198 } else if (u
->cur_implicit_order_index
< moving_order
&& u
->cur_implicit_order_index
>= target_order
) {
1199 u
->cur_implicit_order_index
++;
1202 assert(v
->orders
== u
->orders
);
1203 /* Update any possible open window of the vehicle */
1204 InvalidateVehicleOrder(u
, moving_order
| (target_order
<< 8));
1207 /* As we move an order, the order to skip to will be 'wrong'. */
1208 for (Order
*order
: v
->Orders()) {
1209 if (order
->IsType(OT_CONDITIONAL
)) {
1210 VehicleOrderID order_id
= order
->GetConditionSkipToOrder();
1211 if (order_id
== moving_order
) {
1212 order_id
= target_order
;
1213 } else if (order_id
> moving_order
&& order_id
<= target_order
) {
1215 } else if (order_id
< moving_order
&& order_id
>= target_order
) {
1218 order
->SetConditionSkipToOrder(order_id
);
1222 /* Make sure to rebuild the whole list */
1223 InvalidateWindowClassesData(GetWindowClassForVehicleType(v
->type
), 0);
1226 return CommandCost();
1230 * Modify an order in the orderlist of a vehicle.
1231 * @param flags operation to perform
1232 * @param veh ID of the vehicle
1233 * @param sel_ord the selected order (if any). If the last order is given,
1234 * the order will be inserted before that one
1235 * the maximum vehicle order id is 254.
1236 * @param mof what data to modify (@see ModifyOrderFlags)
1237 * @param data the data to modify
1238 * @return the cost of this operation or an error
1240 CommandCost
CmdModifyOrder(DoCommandFlag flags
, VehicleID veh
, VehicleOrderID sel_ord
, ModifyOrderFlags mof
, uint16 data
)
1242 if (mof
>= MOF_END
) return CMD_ERROR
;
1244 Vehicle
*v
= Vehicle::GetIfValid(veh
);
1245 if (v
== nullptr || !v
->IsPrimaryVehicle()) return CMD_ERROR
;
1247 CommandCost ret
= CheckOwnership(v
->owner
);
1248 if (ret
.Failed()) return ret
;
1250 /* Is it a valid order? */
1251 if (sel_ord
>= v
->GetNumOrders()) return CMD_ERROR
;
1253 Order
*order
= v
->GetOrder(sel_ord
);
1254 switch (order
->GetType()) {
1255 case OT_GOTO_STATION
:
1256 if (mof
!= MOF_NON_STOP
&& mof
!= MOF_STOP_LOCATION
&& mof
!= MOF_UNLOAD
&& mof
!= MOF_LOAD
) return CMD_ERROR
;
1260 if (mof
!= MOF_NON_STOP
&& mof
!= MOF_DEPOT_ACTION
) return CMD_ERROR
;
1263 case OT_GOTO_WAYPOINT
:
1264 if (mof
!= MOF_NON_STOP
) return CMD_ERROR
;
1267 case OT_CONDITIONAL
:
1268 if (mof
!= MOF_COND_VARIABLE
&& mof
!= MOF_COND_COMPARATOR
&& mof
!= MOF_COND_VALUE
&& mof
!= MOF_COND_DESTINATION
) return CMD_ERROR
;
1276 default: NOT_REACHED();
1279 if (!v
->IsGroundVehicle()) return CMD_ERROR
;
1280 if (data
>= ONSF_END
) return CMD_ERROR
;
1281 if (data
== order
->GetNonStopType()) return CMD_ERROR
;
1284 case MOF_STOP_LOCATION
:
1285 if (v
->type
!= VEH_TRAIN
) return CMD_ERROR
;
1286 if (data
>= OSL_END
) return CMD_ERROR
;
1290 if (order
->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION
) return CMD_ERROR
;
1291 if ((data
& ~(OUFB_UNLOAD
| OUFB_TRANSFER
| OUFB_NO_UNLOAD
)) != 0) return CMD_ERROR
;
1292 /* Unload and no-unload are mutual exclusive and so are transfer and no unload. */
1293 if (data
!= 0 && ((data
& (OUFB_UNLOAD
| OUFB_TRANSFER
)) != 0) == ((data
& OUFB_NO_UNLOAD
) != 0)) return CMD_ERROR
;
1294 if (data
== order
->GetUnloadType()) return CMD_ERROR
;
1298 if (order
->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION
) return CMD_ERROR
;
1299 if (data
> OLFB_NO_LOAD
|| data
== 1) return CMD_ERROR
;
1300 if (data
== order
->GetLoadType()) return CMD_ERROR
;
1303 case MOF_DEPOT_ACTION
:
1304 if (data
>= DA_END
) return CMD_ERROR
;
1307 case MOF_COND_VARIABLE
:
1308 if (data
>= OCV_END
) return CMD_ERROR
;
1311 case MOF_COND_COMPARATOR
:
1312 if (data
>= OCC_END
) return CMD_ERROR
;
1313 switch (order
->GetConditionVariable()) {
1314 case OCV_UNCONDITIONALLY
: return CMD_ERROR
;
1316 case OCV_REQUIRES_SERVICE
:
1317 if (data
!= OCC_IS_TRUE
&& data
!= OCC_IS_FALSE
) return CMD_ERROR
;
1321 if (data
== OCC_IS_TRUE
|| data
== OCC_IS_FALSE
) return CMD_ERROR
;
1326 case MOF_COND_VALUE
:
1327 switch (order
->GetConditionVariable()) {
1328 case OCV_UNCONDITIONALLY
:
1329 case OCV_REQUIRES_SERVICE
:
1332 case OCV_LOAD_PERCENTAGE
:
1333 case OCV_RELIABILITY
:
1334 if (data
> 100) return CMD_ERROR
;
1338 if (data
> 2047) return CMD_ERROR
;
1343 case MOF_COND_DESTINATION
:
1344 if (data
>= v
->GetNumOrders()) return CMD_ERROR
;
1348 if (flags
& DC_EXEC
) {
1351 order
->SetNonStopType((OrderNonStopFlags
)data
);
1352 if (data
& ONSF_NO_STOP_AT_DESTINATION_STATION
) {
1353 order
->SetRefit(CT_NO_REFIT
);
1354 order
->SetLoadType(OLF_LOAD_IF_POSSIBLE
);
1355 order
->SetUnloadType(OUF_UNLOAD_IF_POSSIBLE
);
1359 case MOF_STOP_LOCATION
:
1360 order
->SetStopLocation((OrderStopLocation
)data
);
1364 order
->SetUnloadType((OrderUnloadFlags
)data
);
1368 order
->SetLoadType((OrderLoadFlags
)data
);
1369 if (data
& OLFB_NO_LOAD
) order
->SetRefit(CT_NO_REFIT
);
1372 case MOF_DEPOT_ACTION
: {
1375 order
->SetDepotOrderType((OrderDepotTypeFlags
)(order
->GetDepotOrderType() & ~ODTFB_SERVICE
));
1376 order
->SetDepotActionType((OrderDepotActionFlags
)(order
->GetDepotActionType() & ~ODATFB_HALT
));
1380 order
->SetDepotOrderType((OrderDepotTypeFlags
)(order
->GetDepotOrderType() | ODTFB_SERVICE
));
1381 order
->SetDepotActionType((OrderDepotActionFlags
)(order
->GetDepotActionType() & ~ODATFB_HALT
));
1382 order
->SetRefit(CT_NO_REFIT
);
1386 order
->SetDepotOrderType((OrderDepotTypeFlags
)(order
->GetDepotOrderType() & ~ODTFB_SERVICE
));
1387 order
->SetDepotActionType((OrderDepotActionFlags
)(order
->GetDepotActionType() | ODATFB_HALT
));
1388 order
->SetRefit(CT_NO_REFIT
);
1397 case MOF_COND_VARIABLE
: {
1398 order
->SetConditionVariable((OrderConditionVariable
)data
);
1400 OrderConditionComparator occ
= order
->GetConditionComparator();
1401 switch (order
->GetConditionVariable()) {
1402 case OCV_UNCONDITIONALLY
:
1403 order
->SetConditionComparator(OCC_EQUALS
);
1404 order
->SetConditionValue(0);
1407 case OCV_REQUIRES_SERVICE
:
1408 if (occ
!= OCC_IS_TRUE
&& occ
!= OCC_IS_FALSE
) order
->SetConditionComparator(OCC_IS_TRUE
);
1409 order
->SetConditionValue(0);
1412 case OCV_LOAD_PERCENTAGE
:
1413 case OCV_RELIABILITY
:
1414 if (order
->GetConditionValue() > 100) order
->SetConditionValue(100);
1418 if (occ
== OCC_IS_TRUE
|| occ
== OCC_IS_FALSE
) order
->SetConditionComparator(OCC_EQUALS
);
1424 case MOF_COND_COMPARATOR
:
1425 order
->SetConditionComparator((OrderConditionComparator
)data
);
1428 case MOF_COND_VALUE
:
1429 order
->SetConditionValue(data
);
1432 case MOF_COND_DESTINATION
:
1433 order
->SetConditionSkipToOrder(data
);
1436 default: NOT_REACHED();
1439 /* Update the windows and full load flags, also for vehicles that share the same order list */
1440 Vehicle
*u
= v
->FirstShared();
1441 DeleteOrderWarnings(u
);
1442 for (; u
!= nullptr; u
= u
->NextShared()) {
1443 /* Toggle u->current_order "Full load" flag if it changed.
1444 * However, as the same flag is used for depot orders, check
1445 * whether we are not going to a depot as there are three
1446 * cases where the full load flag can be active and only
1447 * one case where the flag is used for depot orders. In the
1448 * other cases for the OrderType the flags are not used,
1449 * so do not care and those orders should not be active
1450 * when this function is called.
1452 if (sel_ord
== u
->cur_real_order_index
&&
1453 (u
->current_order
.IsType(OT_GOTO_STATION
) || u
->current_order
.IsType(OT_LOADING
)) &&
1454 u
->current_order
.GetLoadType() != order
->GetLoadType()) {
1455 u
->current_order
.SetLoadType(order
->GetLoadType());
1457 InvalidateVehicleOrder(u
, VIWD_MODIFY_ORDERS
);
1461 return CommandCost();
1465 * Check if an aircraft has enough range for an order list.
1466 * @param v_new Aircraft to check.
1467 * @param v_order Vehicle currently holding the order list.
1468 * @param first First order in the source order list.
1469 * @return True if the aircraft has enough range for the orders, false otherwise.
1471 static bool CheckAircraftOrderDistance(const Aircraft
*v_new
, const Vehicle
*v_order
, const Order
*first
)
1473 if (first
== nullptr || v_new
->acache
.cached_max_range
== 0) return true;
1475 /* Iterate over all orders to check the distance between all
1476 * 'goto' orders and their respective next order (of any type). */
1477 for (const Order
*o
= first
; o
!= nullptr; o
= o
->next
) {
1478 switch (o
->GetType()) {
1479 case OT_GOTO_STATION
:
1481 case OT_GOTO_WAYPOINT
:
1482 /* If we don't have a next order, we've reached the end and must check the first order instead. */
1483 if (GetOrderDistance(o
, o
->next
!= nullptr ? o
->next
: first
, v_order
) > v_new
->acache
.cached_max_range_sqr
) return false;
1494 * Clone/share/copy an order-list of another vehicle.
1495 * @param flags operation to perform
1496 * @param action action to perform
1497 * @param veh_dst destination vehicle to clone orders to
1498 * @param veh_src source vehicle to clone orders from, if any (none for CO_UNSHARE)
1499 * @return the cost of this operation or an error
1501 CommandCost
CmdCloneOrder(DoCommandFlag flags
, CloneOptions action
, VehicleID veh_dst
, VehicleID veh_src
)
1503 Vehicle
*dst
= Vehicle::GetIfValid(veh_dst
);
1504 if (dst
== nullptr || !dst
->IsPrimaryVehicle()) return CMD_ERROR
;
1506 CommandCost ret
= CheckOwnership(dst
->owner
);
1507 if (ret
.Failed()) return ret
;
1511 Vehicle
*src
= Vehicle::GetIfValid(veh_src
);
1514 if (src
== nullptr || !src
->IsPrimaryVehicle() || dst
->type
!= src
->type
|| dst
== src
) return CMD_ERROR
;
1516 CommandCost ret
= CheckOwnership(src
->owner
);
1517 if (ret
.Failed()) return ret
;
1519 /* Trucks can't share orders with busses (and visa versa) */
1520 if (src
->type
== VEH_ROAD
&& RoadVehicle::From(src
)->IsBus() != RoadVehicle::From(dst
)->IsBus()) {
1524 /* Is the vehicle already in the shared list? */
1525 if (src
->FirstShared() == dst
->FirstShared()) return CMD_ERROR
;
1527 for (const Order
*order
: src
->Orders()) {
1528 if (!OrderGoesToStation(dst
, order
)) continue;
1530 /* Allow copying unreachable destinations if they were already unreachable for the source.
1531 * This is basically to allow cloning / autorenewing / autoreplacing vehicles, while the stations
1532 * are temporarily invalid due to reconstruction. */
1533 const Station
*st
= Station::Get(order
->GetDestination());
1534 if (CanVehicleUseStation(src
, st
) && !CanVehicleUseStation(dst
, st
)) {
1535 return_cmd_error(STR_ERROR_CAN_T_COPY_SHARE_ORDER
);
1539 /* Check for aircraft range limits. */
1540 if (dst
->type
== VEH_AIRCRAFT
&& !CheckAircraftOrderDistance(Aircraft::From(dst
), src
, src
->GetFirstOrder())) {
1541 return_cmd_error(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE
);
1544 if (src
->orders
== nullptr && !OrderList::CanAllocateItem()) {
1545 return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS
);
1548 if (flags
& DC_EXEC
) {
1549 /* If the destination vehicle had a OrderList, destroy it.
1550 * We only reset the order indices, if the new orders are obviously different.
1551 * (We mainly do this to keep the order indices valid and in range.) */
1552 DeleteVehicleOrders(dst
, false, dst
->GetNumOrders() != src
->GetNumOrders());
1554 dst
->orders
= src
->orders
;
1556 /* Link this vehicle in the shared-list */
1557 dst
->AddToShared(src
);
1559 InvalidateVehicleOrder(dst
, VIWD_REMOVE_ALL_ORDERS
);
1560 InvalidateVehicleOrder(src
, VIWD_MODIFY_ORDERS
);
1562 InvalidateWindowClassesData(GetWindowClassForVehicleType(dst
->type
), 0);
1568 Vehicle
*src
= Vehicle::GetIfValid(veh_src
);
1571 if (src
== nullptr || !src
->IsPrimaryVehicle() || dst
->type
!= src
->type
|| dst
== src
) return CMD_ERROR
;
1573 CommandCost ret
= CheckOwnership(src
->owner
);
1574 if (ret
.Failed()) return ret
;
1576 /* Trucks can't copy all the orders from busses (and visa versa),
1577 * and neither can helicopters and aircraft. */
1578 for (const Order
*order
: src
->Orders()) {
1579 if (OrderGoesToStation(dst
, order
) &&
1580 !CanVehicleUseStation(dst
, Station::Get(order
->GetDestination()))) {
1581 return_cmd_error(STR_ERROR_CAN_T_COPY_SHARE_ORDER
);
1585 /* Check for aircraft range limits. */
1586 if (dst
->type
== VEH_AIRCRAFT
&& !CheckAircraftOrderDistance(Aircraft::From(dst
), src
, src
->GetFirstOrder())) {
1587 return_cmd_error(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE
);
1590 /* make sure there are orders available */
1591 if (!Order::CanAllocateItem(src
->GetNumOrders()) || !OrderList::CanAllocateItem()) {
1592 return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS
);
1595 if (flags
& DC_EXEC
) {
1596 Order
*first
= nullptr;
1599 /* If the destination vehicle had an order list, destroy the chain but keep the OrderList.
1600 * We only reset the order indices, if the new orders are obviously different.
1601 * (We mainly do this to keep the order indices valid and in range.) */
1602 DeleteVehicleOrders(dst
, true, dst
->GetNumOrders() != src
->GetNumOrders());
1605 for (const Order
*order
: src
->Orders()) {
1606 *order_dst
= new Order();
1607 (*order_dst
)->AssignOrder(*order
);
1608 order_dst
= &(*order_dst
)->next
;
1610 if (dst
->orders
== nullptr) {
1611 dst
->orders
= new OrderList(first
, dst
);
1613 assert(dst
->orders
->GetFirstOrder() == nullptr);
1614 assert(!dst
->orders
->IsShared());
1616 assert(OrderList::CanAllocateItem());
1617 dst
->orders
= new OrderList(first
, dst
);
1620 InvalidateVehicleOrder(dst
, VIWD_REMOVE_ALL_ORDERS
);
1622 InvalidateWindowClassesData(GetWindowClassForVehicleType(dst
->type
), 0);
1627 case CO_UNSHARE
: return DecloneOrder(dst
, flags
);
1628 default: return CMD_ERROR
;
1631 return CommandCost();
1635 * Add/remove refit orders from an order
1636 * @param flags operation to perform
1637 * @param veh VehicleIndex of the vehicle having the order
1638 * @param order_number number of order to modify
1639 * @param cargo CargoID
1640 * @return the cost of this operation or an error
1642 CommandCost
CmdOrderRefit(DoCommandFlag flags
, VehicleID veh
, VehicleOrderID order_number
, CargoID cargo
)
1644 if (cargo
>= NUM_CARGO
&& cargo
!= CT_NO_REFIT
&& cargo
!= CT_AUTO_REFIT
) return CMD_ERROR
;
1646 const Vehicle
*v
= Vehicle::GetIfValid(veh
);
1647 if (v
== nullptr || !v
->IsPrimaryVehicle()) return CMD_ERROR
;
1649 CommandCost ret
= CheckOwnership(v
->owner
);
1650 if (ret
.Failed()) return ret
;
1652 Order
*order
= v
->GetOrder(order_number
);
1653 if (order
== nullptr) return CMD_ERROR
;
1655 /* Automatic refit cargo is only supported for goto station orders. */
1656 if (cargo
== CT_AUTO_REFIT
&& !order
->IsType(OT_GOTO_STATION
)) return CMD_ERROR
;
1658 if (order
->GetLoadType() & OLFB_NO_LOAD
) return CMD_ERROR
;
1660 if (flags
& DC_EXEC
) {
1661 order
->SetRefit(cargo
);
1663 /* Make the depot order an 'always go' order. */
1664 if (cargo
!= CT_NO_REFIT
&& order
->IsType(OT_GOTO_DEPOT
)) {
1665 order
->SetDepotOrderType((OrderDepotTypeFlags
)(order
->GetDepotOrderType() & ~ODTFB_SERVICE
));
1666 order
->SetDepotActionType((OrderDepotActionFlags
)(order
->GetDepotActionType() & ~ODATFB_HALT
));
1669 for (Vehicle
*u
= v
->FirstShared(); u
!= nullptr; u
= u
->NextShared()) {
1670 /* Update any possible open window of the vehicle */
1671 InvalidateVehicleOrder(u
, VIWD_MODIFY_ORDERS
);
1673 /* If the vehicle already got the current depot set as current order, then update current order as well */
1674 if (u
->cur_real_order_index
== order_number
&& (u
->current_order
.GetDepotOrderType() & ODTFB_PART_OF_ORDERS
)) {
1675 u
->current_order
.SetRefit(cargo
);
1680 return CommandCost();
1686 * Check the orders of a vehicle, to see if there are invalid orders and stuff
1689 void CheckOrders(const Vehicle
*v
)
1691 /* Does the user wants us to check things? */
1692 if (_settings_client
.gui
.order_review_system
== 0) return;
1694 /* Do nothing for crashed vehicles */
1695 if (v
->vehstatus
& VS_CRASHED
) return;
1697 /* Do nothing for stopped vehicles if setting is '1' */
1698 if (_settings_client
.gui
.order_review_system
== 1 && (v
->vehstatus
& VS_STOPPED
)) return;
1700 /* do nothing we we're not the first vehicle in a share-chain */
1701 if (v
->FirstShared() != v
) return;
1703 /* Only check every 20 days, so that we don't flood the message log */
1704 if (v
->owner
== _local_company
&& v
->day_counter
% 20 == 0) {
1705 StringID message
= INVALID_STRING_ID
;
1707 /* Check the order list */
1710 for (const Order
*order
: v
->Orders()) {
1712 if (order
->IsType(OT_DUMMY
)) {
1713 message
= STR_NEWS_VEHICLE_HAS_VOID_ORDER
;
1716 /* Does station have a load-bay for this vehicle? */
1717 if (order
->IsType(OT_GOTO_STATION
)) {
1718 const Station
*st
= Station::Get(order
->GetDestination());
1721 if (!CanVehicleUseStation(v
, st
)) {
1722 message
= STR_NEWS_VEHICLE_HAS_INVALID_ENTRY
;
1723 } else if (v
->type
== VEH_AIRCRAFT
&&
1724 (AircraftVehInfo(v
->engine_type
)->subtype
& AIR_FAST
) &&
1725 (st
->airport
.GetFTA()->flags
& AirportFTAClass::SHORT_STRIP
) &&
1726 !_cheats
.no_jetcrash
.value
&&
1727 message
== INVALID_STRING_ID
) {
1728 message
= STR_NEWS_PLANE_USES_TOO_SHORT_RUNWAY
;
1733 /* Check if the last and the first order are the same */
1734 if (v
->GetNumOrders() > 1) {
1735 const Order
*last
= v
->GetLastOrder();
1737 if (v
->orders
->GetFirstOrder()->Equals(*last
)) {
1738 message
= STR_NEWS_VEHICLE_HAS_DUPLICATE_ENTRY
;
1742 /* Do we only have 1 station in our order list? */
1743 if (n_st
< 2 && message
== INVALID_STRING_ID
) message
= STR_NEWS_VEHICLE_HAS_TOO_FEW_ORDERS
;
1746 if (v
->orders
!= nullptr) v
->orders
->DebugCheckSanity();
1749 /* We don't have a problem */
1750 if (message
== INVALID_STRING_ID
) return;
1752 SetDParam(0, v
->index
);
1753 AddVehicleAdviceNewsItem(message
, v
->index
);
1758 * Removes an order from all vehicles. Triggers when, say, a station is removed.
1759 * @param type The type of the order (OT_GOTO_[STATION|DEPOT|WAYPOINT]).
1760 * @param destination The destination. Can be a StationID, DepotID or WaypointID.
1761 * @param hangar Only used for airports in the destination.
1762 * When false, remove airport and hangar orders.
1763 * When true, remove either airport or hangar order.
1765 void RemoveOrderFromAllVehicles(OrderType type
, DestinationID destination
, bool hangar
)
1767 /* Aircraft have StationIDs for depot orders and never use DepotIDs
1768 * This fact is handled specially below
1771 /* Go through all vehicles */
1772 for (Vehicle
*v
: Vehicle::Iterate()) {
1775 order
= &v
->current_order
;
1776 if ((v
->type
== VEH_AIRCRAFT
&& order
->IsType(OT_GOTO_DEPOT
) && !hangar
? OT_GOTO_STATION
: order
->GetType()) == type
&&
1777 (!hangar
|| v
->type
== VEH_AIRCRAFT
) && v
->current_order
.GetDestination() == destination
) {
1779 SetWindowDirty(WC_VEHICLE_VIEW
, v
->index
);
1782 /* Clear the order from the order-list */
1784 for (Order
*order
: v
->Orders()) {
1788 OrderType ot
= order
->GetType();
1789 if (ot
== OT_GOTO_DEPOT
&& (order
->GetDepotActionType() & ODATFB_NEAREST_DEPOT
) != 0) continue;
1790 if (ot
== OT_GOTO_DEPOT
&& hangar
&& v
->type
!= VEH_AIRCRAFT
) continue; // Not an aircraft? Can't have a hangar order.
1791 if (ot
== OT_IMPLICIT
|| (v
->type
== VEH_AIRCRAFT
&& ot
== OT_GOTO_DEPOT
&& !hangar
)) ot
= OT_GOTO_STATION
;
1792 if (ot
== type
&& order
->GetDestination() == destination
) {
1793 /* We want to clear implicit orders, but we don't want to make them
1794 * dummy orders. They should just vanish. Also check the actual order
1795 * type as ot is currently OT_GOTO_STATION. */
1796 if (order
->IsType(OT_IMPLICIT
)) {
1797 order
= order
->next
; // DeleteOrder() invalidates current order
1799 if (order
!= nullptr) goto restart
;
1803 /* Clear wait time */
1804 v
->orders
->UpdateTotalDuration(-order
->GetWaitTime());
1805 if (order
->IsWaitTimetabled()) {
1806 v
->orders
->UpdateTimetableDuration(-order
->GetTimetabledWait());
1807 order
->SetWaitTimetabled(false);
1809 order
->SetWaitTime(0);
1811 /* Clear order, preserving travel time */
1812 bool travel_timetabled
= order
->IsTravelTimetabled();
1814 order
->SetTravelTimetabled(travel_timetabled
);
1816 for (const Vehicle
*w
= v
->FirstShared(); w
!= nullptr; w
= w
->NextShared()) {
1817 /* In GUI, simulate by removing the order and adding it back */
1818 InvalidateVehicleOrder(w
, id
| (INVALID_VEH_ORDER_ID
<< 8));
1819 InvalidateVehicleOrder(w
, (INVALID_VEH_ORDER_ID
<< 8) | id
);
1825 OrderBackup::RemoveOrder(type
, destination
, hangar
);
1829 * Checks if a vehicle has a depot in its order list.
1830 * @return True iff at least one order is a depot order.
1832 bool Vehicle::HasDepotOrder() const
1834 for (const Order
*order
: this->Orders()) {
1835 if (order
->IsType(OT_GOTO_DEPOT
)) return true;
1842 * Delete all orders from a vehicle
1843 * @param v Vehicle whose orders to reset
1844 * @param keep_orderlist If true, do not free the order list, only empty it.
1845 * @param reset_order_indices If true, reset cur_implicit_order_index and cur_real_order_index
1846 * and cancel the current full load order (if the vehicle is loading).
1847 * If false, _you_ have to make sure the order indices are valid after
1848 * your messing with them!
1850 void DeleteVehicleOrders(Vehicle
*v
, bool keep_orderlist
, bool reset_order_indices
)
1852 DeleteOrderWarnings(v
);
1854 if (v
->IsOrderListShared()) {
1855 /* Remove ourself from the shared order list. */
1856 v
->RemoveFromShared();
1857 v
->orders
= nullptr;
1858 } else if (v
->orders
!= nullptr) {
1859 /* Remove the orders */
1860 v
->orders
->FreeChain(keep_orderlist
);
1861 if (!keep_orderlist
) v
->orders
= nullptr;
1864 if (reset_order_indices
) {
1865 v
->cur_implicit_order_index
= v
->cur_real_order_index
= 0;
1866 if (v
->current_order
.IsType(OT_LOADING
)) {
1867 CancelLoadingDueToDeletedOrder(v
);
1873 * Clamp the service interval to the correct min/max. The actual min/max values
1874 * depend on whether it's in percent or days.
1875 * @param interval proposed service interval
1876 * @return Clamped service interval
1878 uint16
GetServiceIntervalClamped(uint interval
, bool ispercent
)
1880 return ispercent
? Clamp(interval
, MIN_SERVINT_PERCENT
, MAX_SERVINT_PERCENT
) : Clamp(interval
, MIN_SERVINT_DAYS
, MAX_SERVINT_DAYS
);
1885 * Check if a vehicle has any valid orders
1887 * @return false if there are no valid orders
1888 * @note Conditional orders are not considered valid destination orders
1891 static bool CheckForValidOrders(const Vehicle
*v
)
1893 for (const Order
*order
: v
->Orders()) {
1894 switch (order
->GetType()) {
1895 case OT_GOTO_STATION
:
1897 case OT_GOTO_WAYPOINT
:
1909 * Compare the variable and value based on the given comparator.
1911 static bool OrderConditionCompare(OrderConditionComparator occ
, int variable
, int value
)
1914 case OCC_EQUALS
: return variable
== value
;
1915 case OCC_NOT_EQUALS
: return variable
!= value
;
1916 case OCC_LESS_THAN
: return variable
< value
;
1917 case OCC_LESS_EQUALS
: return variable
<= value
;
1918 case OCC_MORE_THAN
: return variable
> value
;
1919 case OCC_MORE_EQUALS
: return variable
>= value
;
1920 case OCC_IS_TRUE
: return variable
!= 0;
1921 case OCC_IS_FALSE
: return variable
== 0;
1922 default: NOT_REACHED();
1927 * Process a conditional order and determine the next order.
1928 * @param order the order the vehicle currently has
1929 * @param v the vehicle to update
1930 * @return index of next order to jump to, or INVALID_VEH_ORDER_ID to use the next order
1932 VehicleOrderID
ProcessConditionalOrder(const Order
*order
, const Vehicle
*v
)
1934 if (order
->GetType() != OT_CONDITIONAL
) return INVALID_VEH_ORDER_ID
;
1936 bool skip_order
= false;
1937 OrderConditionComparator occ
= order
->GetConditionComparator();
1938 uint16 value
= order
->GetConditionValue();
1940 switch (order
->GetConditionVariable()) {
1941 case OCV_LOAD_PERCENTAGE
: skip_order
= OrderConditionCompare(occ
, CalcPercentVehicleFilled(v
, nullptr), value
); break;
1942 case OCV_RELIABILITY
: skip_order
= OrderConditionCompare(occ
, ToPercent16(v
->reliability
), value
); break;
1943 case OCV_MAX_RELIABILITY
: skip_order
= OrderConditionCompare(occ
, ToPercent16(v
->GetEngine()->reliability
), value
); break;
1944 case OCV_MAX_SPEED
: skip_order
= OrderConditionCompare(occ
, v
->GetDisplayMaxSpeed() * 10 / 16, value
); break;
1945 case OCV_AGE
: skip_order
= OrderConditionCompare(occ
, v
->age
/ DAYS_IN_LEAP_YEAR
, value
); break;
1946 case OCV_REQUIRES_SERVICE
: skip_order
= OrderConditionCompare(occ
, v
->NeedsServicing(), value
); break;
1947 case OCV_UNCONDITIONALLY
: skip_order
= true; break;
1948 case OCV_REMAINING_LIFETIME
: skip_order
= OrderConditionCompare(occ
, std::max(v
->max_age
- v
->age
+ DAYS_IN_LEAP_YEAR
- 1, 0) / DAYS_IN_LEAP_YEAR
, value
); break;
1949 default: NOT_REACHED();
1952 return skip_order
? order
->GetConditionSkipToOrder() : (VehicleOrderID
)INVALID_VEH_ORDER_ID
;
1956 * Update the vehicle's destination tile from an order.
1957 * @param order the order the vehicle currently has
1958 * @param v the vehicle to update
1959 * @param conditional_depth the depth (amount of steps) to go with conditional orders. This to prevent infinite loops.
1960 * @param pbs_look_ahead Whether we are forecasting orders for pbs reservations in advance. If true, the order indices must not be modified.
1962 bool UpdateOrderDest(Vehicle
*v
, const Order
*order
, int conditional_depth
, bool pbs_look_ahead
)
1964 if (conditional_depth
> v
->GetNumOrders()) {
1965 v
->current_order
.Free();
1970 switch (order
->GetType()) {
1971 case OT_GOTO_STATION
:
1972 v
->SetDestTile(v
->GetOrderStationLocation(order
->GetDestination()));
1976 if ((order
->GetDepotOrderType() & ODTFB_SERVICE
) && !v
->NeedsServicing()) {
1977 assert(!pbs_look_ahead
);
1978 UpdateVehicleTimetable(v
, true);
1979 v
->IncrementRealOrderIndex();
1983 if (v
->current_order
.GetDepotActionType() & ODATFB_NEAREST_DEPOT
) {
1984 /* We need to search for the nearest depot (hangar). */
1986 DestinationID destination
;
1989 if (v
->FindClosestDepot(&location
, &destination
, &reverse
)) {
1990 /* PBS reservations cannot reverse */
1991 if (pbs_look_ahead
&& reverse
) return false;
1993 v
->SetDestTile(location
);
1994 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());
1996 /* If there is no depot in front, reverse automatically (trains only) */
1997 if (v
->type
== VEH_TRAIN
&& reverse
) Command
<CMD_REVERSE_TRAIN_DIRECTION
>::Do(DC_EXEC
, v
->index
, false);
1999 if (v
->type
== VEH_AIRCRAFT
) {
2000 Aircraft
*a
= Aircraft::From(v
);
2001 if (a
->state
== FLYING
&& a
->targetairport
!= destination
) {
2002 /* The aircraft is now heading for a different hangar than the next in the orders */
2003 extern void AircraftNextAirportPos_and_Order(Aircraft
*a
);
2004 AircraftNextAirportPos_and_Order(a
);
2010 /* If there is no depot, we cannot help PBS either. */
2011 if (pbs_look_ahead
) return false;
2013 UpdateVehicleTimetable(v
, true);
2014 v
->IncrementRealOrderIndex();
2016 if (v
->type
!= VEH_AIRCRAFT
) {
2017 v
->SetDestTile(Depot::Get(order
->GetDestination())->xy
);
2019 Aircraft
*a
= Aircraft::From(v
);
2020 DestinationID destination
= a
->current_order
.GetDestination();
2021 if (a
->targetairport
!= destination
) {
2022 /* The aircraft is now heading for a different hangar than the next in the orders */
2023 a
->SetDestTile(a
->GetOrderStationLocation(destination
));
2030 case OT_GOTO_WAYPOINT
:
2031 v
->SetDestTile(Waypoint::Get(order
->GetDestination())->xy
);
2034 case OT_CONDITIONAL
: {
2035 assert(!pbs_look_ahead
);
2036 VehicleOrderID next_order
= ProcessConditionalOrder(order
, v
);
2037 if (next_order
!= INVALID_VEH_ORDER_ID
) {
2038 /* Jump to next_order. cur_implicit_order_index becomes exactly that order,
2039 * cur_real_order_index might come after next_order. */
2040 UpdateVehicleTimetable(v
, false);
2041 v
->cur_implicit_order_index
= v
->cur_real_order_index
= next_order
;
2042 v
->UpdateRealOrderIndex();
2043 v
->current_order_time
+= v
->GetOrder(v
->cur_real_order_index
)->GetTimetabledTravel();
2045 /* Disable creation of implicit orders.
2046 * When inserting them we do not know that we would have to make the conditional orders point to them. */
2047 if (v
->IsGroundVehicle()) {
2048 uint16
&gv_flags
= v
->GetGroundVehicleFlags();
2049 SetBit(gv_flags
, GVF_SUPPRESS_IMPLICIT_ORDERS
);
2052 UpdateVehicleTimetable(v
, true);
2053 v
->IncrementRealOrderIndex();
2063 assert(v
->cur_implicit_order_index
< v
->GetNumOrders());
2064 assert(v
->cur_real_order_index
< v
->GetNumOrders());
2066 /* Get the current order */
2067 order
= v
->GetOrder(v
->cur_real_order_index
);
2068 if (order
!= nullptr && order
->IsType(OT_IMPLICIT
)) {
2069 assert(v
->GetNumManualOrders() == 0);
2073 if (order
== nullptr) {
2074 v
->current_order
.Free();
2079 v
->current_order
= *order
;
2080 return UpdateOrderDest(v
, order
, conditional_depth
+ 1, pbs_look_ahead
);
2084 * Handle the orders of a vehicle and determine the next place
2085 * to go to if needed.
2086 * @param v the vehicle to do this for.
2087 * @return true *if* the vehicle is eligible for reversing
2088 * (basically only when leaving a station).
2090 bool ProcessOrders(Vehicle
*v
)
2092 switch (v
->current_order
.GetType()) {
2094 /* Let a depot order in the orderlist interrupt. */
2095 if (!(v
->current_order
.GetDepotOrderType() & ODTFB_PART_OF_ORDERS
)) return false;
2101 case OT_LEAVESTATION
:
2102 if (v
->type
!= VEH_AIRCRAFT
) return false;
2109 * Reversing because of order change is allowed only just after leaving a
2110 * station (and the difficulty setting to allowed, of course)
2111 * this can be detected because only after OT_LEAVESTATION, current_order
2112 * will be reset to nothing. (That also happens if no order, but in that case
2113 * it won't hit the point in code where may_reverse is checked)
2115 bool may_reverse
= v
->current_order
.IsType(OT_NOTHING
);
2117 /* Check if we've reached a 'via' destination. */
2118 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
)) &&
2119 IsTileType(v
->tile
, MP_STATION
) &&
2120 v
->current_order
.GetDestination() == GetStationIndex(v
->tile
)) {
2121 v
->DeleteUnreachedImplicitOrders();
2122 /* We set the last visited station here because we do not want
2123 * the train to stop at this 'via' station if the next order
2124 * is a no-non-stop order; in that case not setting the last
2125 * visited station will cause the vehicle to still stop. */
2126 v
->last_station_visited
= v
->current_order
.GetDestination();
2127 UpdateVehicleTimetable(v
, true);
2128 v
->IncrementImplicitOrderIndex();
2131 /* Get the current order */
2132 assert(v
->cur_implicit_order_index
== 0 || v
->cur_implicit_order_index
< v
->GetNumOrders());
2133 v
->UpdateRealOrderIndex();
2135 const Order
*order
= v
->GetOrder(v
->cur_real_order_index
);
2136 if (order
!= nullptr && order
->IsType(OT_IMPLICIT
)) {
2137 assert(v
->GetNumManualOrders() == 0);
2141 /* If no order, do nothing. */
2142 if (order
== nullptr || (v
->type
== VEH_AIRCRAFT
&& !CheckForValidOrders(v
))) {
2143 if (v
->type
== VEH_AIRCRAFT
) {
2144 /* Aircraft do something vastly different here, so handle separately */
2145 extern void HandleMissingAircraftOrders(Aircraft
*v
);
2146 HandleMissingAircraftOrders(Aircraft::From(v
));
2150 v
->current_order
.Free();
2155 /* If it is unchanged, keep it. */
2156 if (order
->Equals(v
->current_order
) && (v
->type
== VEH_AIRCRAFT
|| v
->dest_tile
!= 0) &&
2157 (v
->type
!= VEH_SHIP
|| !order
->IsType(OT_GOTO_STATION
) || Station::Get(order
->GetDestination())->ship_station
.tile
!= INVALID_TILE
)) {
2161 /* Otherwise set it, and determine the destination tile. */
2162 v
->current_order
= *order
;
2164 InvalidateVehicleOrder(v
, VIWD_MODIFY_ORDERS
);
2175 SetWindowClassesDirty(GetWindowClassForVehicleType(v
->type
));
2179 return UpdateOrderDest(v
, order
) && may_reverse
;
2183 * Check whether the given vehicle should stop at the given station
2184 * based on this order and the non-stop settings.
2185 * @param v the vehicle that might be stopping.
2186 * @param station the station to stop at.
2187 * @return true if the vehicle should stop.
2189 bool Order::ShouldStopAtStation(const Vehicle
*v
, StationID station
) const
2191 bool is_dest_station
= this->IsType(OT_GOTO_STATION
) && this->dest
== station
;
2193 return (!this->IsType(OT_GOTO_DEPOT
) || (this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS
) != 0) &&
2194 v
->last_station_visited
!= station
&& // Do stop only when we've not just been there
2195 /* Finally do stop when there is no non-stop flag set for this type of station. */
2196 !(this->GetNonStopType() & (is_dest_station
? ONSF_NO_STOP_AT_DESTINATION_STATION
: ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS
));
2199 bool Order::CanLoadOrUnload() const
2201 return (this->IsType(OT_GOTO_STATION
) || this->IsType(OT_IMPLICIT
)) &&
2202 (this->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION
) == 0 &&
2203 ((this->GetLoadType() & OLFB_NO_LOAD
) == 0 ||
2204 (this->GetUnloadType() & OUFB_NO_UNLOAD
) == 0);
2208 * A vehicle can leave the current station with cargo if:
2209 * 1. it can load cargo here OR
2210 * 2a. it could leave the last station with cargo AND
2211 * 2b. it doesn't have to unload all cargo here.
2213 bool Order::CanLeaveWithCargo(bool has_cargo
) const
2215 return (this->GetLoadType() & OLFB_NO_LOAD
) == 0 || (has_cargo
&&
2216 (this->GetUnloadType() & (OUFB_UNLOAD
| OUFB_TRANSFER
)) == 0);