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 "cmd_helper.h"
13 #include "command_func.h"
14 #include "company_func.h"
15 #include "news_func.h"
16 #include "strings_func.h"
17 #include "timetable.h"
18 #include "vehicle_func.h"
19 #include "depot_base.h"
20 #include "core/pool_func.hpp"
21 #include "core/random_func.hpp"
24 #include "station_base.h"
25 #include "waypoint_base.h"
26 #include "company_base.h"
27 #include "order_backup.h"
28 #include "cheat_type.h"
29 #include "order_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
.list
== 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
.list
->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
732 * @param p1 various bitstuffed elements
733 * - p1 = (bit 0 - 19) - ID of the vehicle
734 * - p1 = (bit 24 - 31) - the selected order (if any). If the last order is given,
735 * the order will be inserted before that one
736 * the maximum vehicle order id is 254.
737 * @param p2 packed order to insert
739 * @return the cost of this operation or an error
741 CommandCost
CmdInsertOrder(DoCommandFlag flags
, TileIndex tile
, uint32 p1
, uint32 p2
, const std::string
&text
)
743 VehicleID veh
= GB(p1
, 0, 20);
744 VehicleOrderID sel_ord
= GB(p1
, 20, 8);
747 Vehicle
*v
= Vehicle::GetIfValid(veh
);
748 if (v
== nullptr || !v
->IsPrimaryVehicle()) return CMD_ERROR
;
750 CommandCost ret
= CheckOwnership(v
->owner
);
751 if (ret
.Failed()) return ret
;
753 /* Check if the inserted order is to the correct destination (owner, type),
754 * and has the correct flags if any */
755 switch (new_order
.GetType()) {
756 case OT_GOTO_STATION
: {
757 const Station
*st
= Station::GetIfValid(new_order
.GetDestination());
758 if (st
== nullptr) return CMD_ERROR
;
760 if (st
->owner
!= OWNER_NONE
) {
761 CommandCost ret
= CheckOwnership(st
->owner
);
762 if (ret
.Failed()) return ret
;
765 if (!CanVehicleUseStation(v
, st
)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER
);
766 for (Vehicle
*u
= v
->FirstShared(); u
!= nullptr; u
= u
->NextShared()) {
767 if (!CanVehicleUseStation(u
, st
)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER_SHARED
);
770 /* Non stop only allowed for ground vehicles. */
771 if (new_order
.GetNonStopType() != ONSF_STOP_EVERYWHERE
&& !v
->IsGroundVehicle()) return CMD_ERROR
;
773 /* Filter invalid load/unload types. */
774 switch (new_order
.GetLoadType()) {
775 case OLF_LOAD_IF_POSSIBLE
: case OLFB_FULL_LOAD
: case OLF_FULL_LOAD_ANY
: case OLFB_NO_LOAD
: break;
776 default: return CMD_ERROR
;
778 switch (new_order
.GetUnloadType()) {
779 case OUF_UNLOAD_IF_POSSIBLE
: case OUFB_UNLOAD
: case OUFB_TRANSFER
: case OUFB_NO_UNLOAD
: break;
780 default: return CMD_ERROR
;
783 /* Filter invalid stop locations */
784 switch (new_order
.GetStopLocation()) {
785 case OSL_PLATFORM_NEAR_END
:
786 case OSL_PLATFORM_MIDDLE
:
787 if (v
->type
!= VEH_TRAIN
) return CMD_ERROR
;
790 case OSL_PLATFORM_FAR_END
:
800 case OT_GOTO_DEPOT
: {
801 if ((new_order
.GetDepotActionType() & ODATFB_NEAREST_DEPOT
) == 0) {
802 if (v
->type
== VEH_AIRCRAFT
) {
803 const Station
*st
= Station::GetIfValid(new_order
.GetDestination());
805 if (st
== nullptr) return CMD_ERROR
;
807 CommandCost ret
= CheckOwnership(st
->owner
);
808 if (ret
.Failed()) return ret
;
810 if (!CanVehicleUseStation(v
, st
) || !st
->airport
.HasHangar()) {
814 const Depot
*dp
= Depot::GetIfValid(new_order
.GetDestination());
816 if (dp
== nullptr) return CMD_ERROR
;
818 CommandCost ret
= CheckOwnership(GetTileOwner(dp
->xy
));
819 if (ret
.Failed()) return ret
;
823 if (!IsRailDepotTile(dp
->xy
)) return CMD_ERROR
;
827 if (!IsRoadDepotTile(dp
->xy
)) return CMD_ERROR
;
831 if (!IsShipDepotTile(dp
->xy
)) return CMD_ERROR
;
834 default: return CMD_ERROR
;
839 if (new_order
.GetNonStopType() != ONSF_STOP_EVERYWHERE
&& !v
->IsGroundVehicle()) return CMD_ERROR
;
840 if (new_order
.GetDepotOrderType() & ~(ODTFB_PART_OF_ORDERS
| ((new_order
.GetDepotOrderType() & ODTFB_PART_OF_ORDERS
) != 0 ? ODTFB_SERVICE
: 0))) return CMD_ERROR
;
841 if (new_order
.GetDepotActionType() & ~(ODATFB_HALT
| ODATFB_NEAREST_DEPOT
)) return CMD_ERROR
;
842 if ((new_order
.GetDepotOrderType() & ODTFB_SERVICE
) && (new_order
.GetDepotActionType() & ODATFB_HALT
)) return CMD_ERROR
;
846 case OT_GOTO_WAYPOINT
: {
847 const Waypoint
*wp
= Waypoint::GetIfValid(new_order
.GetDestination());
848 if (wp
== nullptr) return CMD_ERROR
;
851 default: return CMD_ERROR
;
854 if (!(wp
->facilities
& FACIL_TRAIN
)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER
);
856 CommandCost ret
= CheckOwnership(wp
->owner
);
857 if (ret
.Failed()) return ret
;
862 if (!(wp
->facilities
& FACIL_DOCK
)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER
);
863 if (wp
->owner
!= OWNER_NONE
) {
864 CommandCost ret
= CheckOwnership(wp
->owner
);
865 if (ret
.Failed()) return ret
;
870 /* Order flags can be any of the following for waypoints:
872 * non-stop orders (if any) are only valid for trains */
873 if (new_order
.GetNonStopType() != ONSF_STOP_EVERYWHERE
&& v
->type
!= VEH_TRAIN
) return CMD_ERROR
;
877 case OT_CONDITIONAL
: {
878 VehicleOrderID skip_to
= new_order
.GetConditionSkipToOrder();
879 if (skip_to
!= 0 && skip_to
>= v
->GetNumOrders()) return CMD_ERROR
; // Always allow jumping to the first (even when there is no order).
880 if (new_order
.GetConditionVariable() >= OCV_END
) return CMD_ERROR
;
882 OrderConditionComparator occ
= new_order
.GetConditionComparator();
883 if (occ
>= OCC_END
) return CMD_ERROR
;
884 switch (new_order
.GetConditionVariable()) {
885 case OCV_REQUIRES_SERVICE
:
886 if (occ
!= OCC_IS_TRUE
&& occ
!= OCC_IS_FALSE
) return CMD_ERROR
;
889 case OCV_UNCONDITIONALLY
:
890 if (occ
!= OCC_EQUALS
) return CMD_ERROR
;
891 if (new_order
.GetConditionValue() != 0) return CMD_ERROR
;
894 case OCV_LOAD_PERCENTAGE
:
895 case OCV_RELIABILITY
:
896 if (new_order
.GetConditionValue() > 100) return CMD_ERROR
;
900 if (occ
== OCC_IS_TRUE
|| occ
== OCC_IS_FALSE
) return CMD_ERROR
;
906 default: return CMD_ERROR
;
909 if (sel_ord
> v
->GetNumOrders()) return CMD_ERROR
;
911 if (v
->GetNumOrders() >= MAX_VEH_ORDER_ID
) return_cmd_error(STR_ERROR_TOO_MANY_ORDERS
);
912 if (!Order::CanAllocateItem()) return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS
);
913 if (v
->orders
.list
== nullptr && !OrderList::CanAllocateItem()) return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS
);
915 if (flags
& DC_EXEC
) {
916 Order
*new_o
= new Order();
917 new_o
->AssignOrder(new_order
);
918 InsertOrder(v
, new_o
, sel_ord
);
921 return CommandCost();
925 * Insert a new order but skip the validation.
926 * @param v The vehicle to insert the order to.
927 * @param new_o The new order.
928 * @param sel_ord The position the order should be inserted at.
930 void InsertOrder(Vehicle
*v
, Order
*new_o
, VehicleOrderID sel_ord
)
932 /* Create new order and link in list */
933 if (v
->orders
.list
== nullptr) {
934 v
->orders
.list
= new OrderList(new_o
, v
);
936 v
->orders
.list
->InsertOrderAt(new_o
, sel_ord
);
939 Vehicle
*u
= v
->FirstShared();
940 DeleteOrderWarnings(u
);
941 for (; u
!= nullptr; u
= u
->NextShared()) {
942 assert(v
->orders
.list
== u
->orders
.list
);
944 /* If there is added an order before the current one, we need
945 * to update the selected order. We do not change implicit/real order indices though.
946 * If the new order is between the current implicit order and real order, the implicit order will
947 * later skip the inserted order. */
948 if (sel_ord
<= u
->cur_real_order_index
) {
949 uint cur
= u
->cur_real_order_index
+ 1;
950 /* Check if we don't go out of bound */
951 if (cur
< u
->GetNumOrders()) {
952 u
->cur_real_order_index
= cur
;
955 if (sel_ord
== u
->cur_implicit_order_index
&& u
->IsGroundVehicle()) {
956 /* We are inserting an order just before the current implicit order.
957 * We do not know whether we will reach current implicit or the newly inserted order first.
958 * So, disable creation of implicit orders until we are on track again. */
959 uint16
&gv_flags
= u
->GetGroundVehicleFlags();
960 SetBit(gv_flags
, GVF_SUPPRESS_IMPLICIT_ORDERS
);
962 if (sel_ord
<= u
->cur_implicit_order_index
) {
963 uint cur
= u
->cur_implicit_order_index
+ 1;
964 /* Check if we don't go out of bound */
965 if (cur
< u
->GetNumOrders()) {
966 u
->cur_implicit_order_index
= cur
;
969 /* Update any possible open window of the vehicle */
970 InvalidateVehicleOrder(u
, INVALID_VEH_ORDER_ID
| (sel_ord
<< 8));
973 /* As we insert an order, the order to skip to will be 'wrong'. */
974 VehicleOrderID cur_order_id
= 0;
975 for (Order
*order
: v
->Orders()) {
976 if (order
->IsType(OT_CONDITIONAL
)) {
977 VehicleOrderID order_id
= order
->GetConditionSkipToOrder();
978 if (order_id
>= sel_ord
) {
979 order
->SetConditionSkipToOrder(order_id
+ 1);
981 if (order_id
== cur_order_id
) {
982 order
->SetConditionSkipToOrder((order_id
+ 1) % v
->GetNumOrders());
988 /* Make sure to rebuild the whole list */
989 InvalidateWindowClassesData(GetWindowClassForVehicleType(v
->type
), 0);
993 * Declone an order-list
994 * @param *dst delete the orders of this vehicle
995 * @param flags execution flags
997 static CommandCost
DecloneOrder(Vehicle
*dst
, DoCommandFlag flags
)
999 if (flags
& DC_EXEC
) {
1000 DeleteVehicleOrders(dst
);
1001 InvalidateVehicleOrder(dst
, VIWD_REMOVE_ALL_ORDERS
);
1002 InvalidateWindowClassesData(GetWindowClassForVehicleType(dst
->type
), 0);
1004 return CommandCost();
1008 * Delete an order from the orderlist of a vehicle.
1009 * @param flags operation to perform
1010 * @param tile unused
1011 * @param p1 the ID of the vehicle
1012 * @param p2 the order to delete (max 255)
1013 * @param text unused
1014 * @return the cost of this operation or an error
1016 CommandCost
CmdDeleteOrder(DoCommandFlag flags
, TileIndex tile
, uint32 p1
, uint32 p2
, const std::string
&text
)
1018 VehicleID veh_id
= GB(p1
, 0, 20);
1019 VehicleOrderID sel_ord
= GB(p2
, 0, 8);
1021 Vehicle
*v
= Vehicle::GetIfValid(veh_id
);
1023 if (v
== nullptr || !v
->IsPrimaryVehicle()) return CMD_ERROR
;
1025 CommandCost ret
= CheckOwnership(v
->owner
);
1026 if (ret
.Failed()) return ret
;
1028 /* If we did not select an order, we maybe want to de-clone the orders */
1029 if (sel_ord
>= v
->GetNumOrders()) return DecloneOrder(v
, flags
);
1031 if (v
->GetOrder(sel_ord
) == nullptr) return CMD_ERROR
;
1033 if (flags
& DC_EXEC
) DeleteOrder(v
, sel_ord
);
1034 return CommandCost();
1038 * Cancel the current loading order of the vehicle as the order was deleted.
1039 * @param v the vehicle
1041 static void CancelLoadingDueToDeletedOrder(Vehicle
*v
)
1043 assert(v
->current_order
.IsType(OT_LOADING
));
1044 /* NON-stop flag is misused to see if a train is in a station that is
1045 * on its order list or not */
1046 v
->current_order
.SetNonStopType(ONSF_STOP_EVERYWHERE
);
1047 /* When full loading, "cancel" that order so the vehicle doesn't
1048 * stay indefinitely at this station anymore. */
1049 if (v
->current_order
.GetLoadType() & OLFB_FULL_LOAD
) v
->current_order
.SetLoadType(OLF_LOAD_IF_POSSIBLE
);
1053 * Delete an order but skip the parameter validation.
1054 * @param v The vehicle to delete the order from.
1055 * @param sel_ord The id of the order to be deleted.
1057 void DeleteOrder(Vehicle
*v
, VehicleOrderID sel_ord
)
1059 v
->orders
.list
->DeleteOrderAt(sel_ord
);
1061 Vehicle
*u
= v
->FirstShared();
1062 DeleteOrderWarnings(u
);
1063 for (; u
!= nullptr; u
= u
->NextShared()) {
1064 assert(v
->orders
.list
== u
->orders
.list
);
1066 if (sel_ord
== u
->cur_real_order_index
&& u
->current_order
.IsType(OT_LOADING
)) {
1067 CancelLoadingDueToDeletedOrder(u
);
1070 if (sel_ord
< u
->cur_real_order_index
) {
1071 u
->cur_real_order_index
--;
1072 } else if (sel_ord
== u
->cur_real_order_index
) {
1073 u
->UpdateRealOrderIndex();
1076 if (sel_ord
< u
->cur_implicit_order_index
) {
1077 u
->cur_implicit_order_index
--;
1078 } else if (sel_ord
== u
->cur_implicit_order_index
) {
1079 /* Make sure the index is valid */
1080 if (u
->cur_implicit_order_index
>= u
->GetNumOrders()) u
->cur_implicit_order_index
= 0;
1082 /* Skip non-implicit orders for the implicit-order-index (e.g. if the current implicit order was deleted */
1083 while (u
->cur_implicit_order_index
!= u
->cur_real_order_index
&& !u
->GetOrder(u
->cur_implicit_order_index
)->IsType(OT_IMPLICIT
)) {
1084 u
->cur_implicit_order_index
++;
1085 if (u
->cur_implicit_order_index
>= u
->GetNumOrders()) u
->cur_implicit_order_index
= 0;
1089 /* Update any possible open window of the vehicle */
1090 InvalidateVehicleOrder(u
, sel_ord
| (INVALID_VEH_ORDER_ID
<< 8));
1093 /* As we delete an order, the order to skip to will be 'wrong'. */
1094 VehicleOrderID cur_order_id
= 0;
1095 for (Order
*order
: v
->Orders()) {
1096 if (order
->IsType(OT_CONDITIONAL
)) {
1097 VehicleOrderID order_id
= order
->GetConditionSkipToOrder();
1098 if (order_id
>= sel_ord
) {
1099 order_id
= std::max(order_id
- 1, 0);
1101 if (order_id
== cur_order_id
) {
1102 order_id
= (order_id
+ 1) % v
->GetNumOrders();
1104 order
->SetConditionSkipToOrder(order_id
);
1109 InvalidateWindowClassesData(GetWindowClassForVehicleType(v
->type
), 0);
1113 * Goto order of order-list.
1114 * @param flags operation to perform
1115 * @param tile unused
1116 * @param p1 The ID of the vehicle which order is skipped
1117 * @param p2 the selected order to which we want to skip
1118 * @param text unused
1119 * @return the cost of this operation or an error
1121 CommandCost
CmdSkipToOrder(DoCommandFlag flags
, TileIndex tile
, uint32 p1
, uint32 p2
, const std::string
&text
)
1123 VehicleID veh_id
= GB(p1
, 0, 20);
1124 VehicleOrderID sel_ord
= GB(p2
, 0, 8);
1126 Vehicle
*v
= Vehicle::GetIfValid(veh_id
);
1128 if (v
== nullptr || !v
->IsPrimaryVehicle() || sel_ord
== v
->cur_implicit_order_index
|| sel_ord
>= v
->GetNumOrders() || v
->GetNumOrders() < 2) return CMD_ERROR
;
1130 CommandCost ret
= CheckOwnership(v
->owner
);
1131 if (ret
.Failed()) return ret
;
1133 if (flags
& DC_EXEC
) {
1134 if (v
->current_order
.IsType(OT_LOADING
)) v
->LeaveStation();
1136 v
->cur_implicit_order_index
= v
->cur_real_order_index
= sel_ord
;
1137 v
->UpdateRealOrderIndex();
1139 InvalidateVehicleOrder(v
, VIWD_MODIFY_ORDERS
);
1141 /* We have an aircraft/ship, they have a mini-schedule, so update them all */
1142 if (v
->type
== VEH_AIRCRAFT
) SetWindowClassesDirty(WC_AIRCRAFT_LIST
);
1143 if (v
->type
== VEH_SHIP
) SetWindowClassesDirty(WC_SHIPS_LIST
);
1146 return CommandCost();
1150 * Move an order inside the orderlist
1151 * @param flags operation to perform
1152 * @param tile unused
1153 * @param p1 the ID of the vehicle
1154 * @param p2 order to move and target
1155 * bit 0-15 : the order to move
1156 * bit 16-31 : the target order
1157 * @param text unused
1158 * @return the cost of this operation or an error
1159 * @note The target order will move one place down in the orderlist
1160 * if you move the order upwards else it'll move it one place down
1162 CommandCost
CmdMoveOrder(DoCommandFlag flags
, TileIndex tile
, uint32 p1
, uint32 p2
, const std::string
&text
)
1164 VehicleID veh
= GB(p1
, 0, 20);
1165 VehicleOrderID moving_order
= GB(p2
, 0, 16);
1166 VehicleOrderID target_order
= GB(p2
, 16, 16);
1168 Vehicle
*v
= Vehicle::GetIfValid(veh
);
1169 if (v
== nullptr || !v
->IsPrimaryVehicle()) return CMD_ERROR
;
1171 CommandCost ret
= CheckOwnership(v
->owner
);
1172 if (ret
.Failed()) return ret
;
1174 /* Don't make senseless movements */
1175 if (moving_order
>= v
->GetNumOrders() || target_order
>= v
->GetNumOrders() ||
1176 moving_order
== target_order
|| v
->GetNumOrders() <= 1) return CMD_ERROR
;
1178 Order
*moving_one
= v
->GetOrder(moving_order
);
1179 /* Don't move an empty order */
1180 if (moving_one
== nullptr) return CMD_ERROR
;
1182 if (flags
& DC_EXEC
) {
1183 v
->orders
.list
->MoveOrder(moving_order
, target_order
);
1185 /* Update shared list */
1186 Vehicle
*u
= v
->FirstShared();
1188 DeleteOrderWarnings(u
);
1190 for (; u
!= nullptr; u
= u
->NextShared()) {
1191 /* Update the current order.
1192 * There are multiple ways to move orders, which result in cur_implicit_order_index
1193 * and cur_real_order_index to not longer make any sense. E.g. moving another
1194 * real order between them.
1196 * Basically one could choose to preserve either of them, but not both.
1197 * While both ways are suitable in this or that case from a human point of view, neither
1198 * of them makes really sense.
1199 * However, from an AI point of view, preserving cur_real_order_index is the most
1200 * predictable and transparent behaviour.
1202 * With that decision it basically does not matter what we do to cur_implicit_order_index.
1203 * If we change orders between the implicit- and real-index, the implicit orders are mostly likely
1204 * completely out-dated anyway. So, keep it simple and just keep cur_implicit_order_index as well.
1205 * The worst which can happen is that a lot of implicit orders are removed when reaching current_order.
1207 if (u
->cur_real_order_index
== moving_order
) {
1208 u
->cur_real_order_index
= target_order
;
1209 } else if (u
->cur_real_order_index
> moving_order
&& u
->cur_real_order_index
<= target_order
) {
1210 u
->cur_real_order_index
--;
1211 } else if (u
->cur_real_order_index
< moving_order
&& u
->cur_real_order_index
>= target_order
) {
1212 u
->cur_real_order_index
++;
1215 if (u
->cur_implicit_order_index
== moving_order
) {
1216 u
->cur_implicit_order_index
= target_order
;
1217 } else if (u
->cur_implicit_order_index
> moving_order
&& u
->cur_implicit_order_index
<= target_order
) {
1218 u
->cur_implicit_order_index
--;
1219 } else if (u
->cur_implicit_order_index
< moving_order
&& u
->cur_implicit_order_index
>= target_order
) {
1220 u
->cur_implicit_order_index
++;
1223 assert(v
->orders
.list
== u
->orders
.list
);
1224 /* Update any possible open window of the vehicle */
1225 InvalidateVehicleOrder(u
, moving_order
| (target_order
<< 8));
1228 /* As we move an order, the order to skip to will be 'wrong'. */
1229 for (Order
*order
: v
->Orders()) {
1230 if (order
->IsType(OT_CONDITIONAL
)) {
1231 VehicleOrderID order_id
= order
->GetConditionSkipToOrder();
1232 if (order_id
== moving_order
) {
1233 order_id
= target_order
;
1234 } else if (order_id
> moving_order
&& order_id
<= target_order
) {
1236 } else if (order_id
< moving_order
&& order_id
>= target_order
) {
1239 order
->SetConditionSkipToOrder(order_id
);
1243 /* Make sure to rebuild the whole list */
1244 InvalidateWindowClassesData(GetWindowClassForVehicleType(v
->type
), 0);
1247 return CommandCost();
1251 * Modify an order in the orderlist of a vehicle.
1252 * @param flags operation to perform
1253 * @param tile unused
1254 * @param p1 various bitstuffed elements
1255 * - p1 = (bit 0 - 19) - ID of the vehicle
1256 * - p1 = (bit 24 - 31) - the selected order (if any). If the last order is given,
1257 * the order will be inserted before that one
1258 * the maximum vehicle order id is 254.
1259 * @param p2 various bitstuffed elements
1260 * - p2 = (bit 0 - 3) - what data to modify (@see ModifyOrderFlags)
1261 * - p2 = (bit 4 - 15) - the data to modify
1262 * @param text unused
1263 * @return the cost of this operation or an error
1265 CommandCost
CmdModifyOrder(DoCommandFlag flags
, TileIndex tile
, uint32 p1
, uint32 p2
, const std::string
&text
)
1267 VehicleOrderID sel_ord
= GB(p1
, 20, 8);
1268 VehicleID veh
= GB(p1
, 0, 20);
1269 ModifyOrderFlags mof
= Extract
<ModifyOrderFlags
, 0, 4>(p2
);
1270 uint16 data
= GB(p2
, 4, 11);
1272 if (mof
>= MOF_END
) return CMD_ERROR
;
1274 Vehicle
*v
= Vehicle::GetIfValid(veh
);
1275 if (v
== nullptr || !v
->IsPrimaryVehicle()) return CMD_ERROR
;
1277 CommandCost ret
= CheckOwnership(v
->owner
);
1278 if (ret
.Failed()) return ret
;
1280 /* Is it a valid order? */
1281 if (sel_ord
>= v
->GetNumOrders()) return CMD_ERROR
;
1283 Order
*order
= v
->GetOrder(sel_ord
);
1284 switch (order
->GetType()) {
1285 case OT_GOTO_STATION
:
1286 if (mof
!= MOF_NON_STOP
&& mof
!= MOF_STOP_LOCATION
&& mof
!= MOF_UNLOAD
&& mof
!= MOF_LOAD
) return CMD_ERROR
;
1290 if (mof
!= MOF_NON_STOP
&& mof
!= MOF_DEPOT_ACTION
) return CMD_ERROR
;
1293 case OT_GOTO_WAYPOINT
:
1294 if (mof
!= MOF_NON_STOP
) return CMD_ERROR
;
1297 case OT_CONDITIONAL
:
1298 if (mof
!= MOF_COND_VARIABLE
&& mof
!= MOF_COND_COMPARATOR
&& mof
!= MOF_COND_VALUE
&& mof
!= MOF_COND_DESTINATION
) return CMD_ERROR
;
1306 default: NOT_REACHED();
1309 if (!v
->IsGroundVehicle()) return CMD_ERROR
;
1310 if (data
>= ONSF_END
) return CMD_ERROR
;
1311 if (data
== order
->GetNonStopType()) return CMD_ERROR
;
1314 case MOF_STOP_LOCATION
:
1315 if (v
->type
!= VEH_TRAIN
) return CMD_ERROR
;
1316 if (data
>= OSL_END
) return CMD_ERROR
;
1320 if (order
->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION
) return CMD_ERROR
;
1321 if ((data
& ~(OUFB_UNLOAD
| OUFB_TRANSFER
| OUFB_NO_UNLOAD
)) != 0) return CMD_ERROR
;
1322 /* Unload and no-unload are mutual exclusive and so are transfer and no unload. */
1323 if (data
!= 0 && ((data
& (OUFB_UNLOAD
| OUFB_TRANSFER
)) != 0) == ((data
& OUFB_NO_UNLOAD
) != 0)) return CMD_ERROR
;
1324 if (data
== order
->GetUnloadType()) return CMD_ERROR
;
1328 if (order
->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION
) return CMD_ERROR
;
1329 if (data
> OLFB_NO_LOAD
|| data
== 1) return CMD_ERROR
;
1330 if (data
== order
->GetLoadType()) return CMD_ERROR
;
1333 case MOF_DEPOT_ACTION
:
1334 if (data
>= DA_END
) return CMD_ERROR
;
1337 case MOF_COND_VARIABLE
:
1338 if (data
>= OCV_END
) return CMD_ERROR
;
1341 case MOF_COND_COMPARATOR
:
1342 if (data
>= OCC_END
) return CMD_ERROR
;
1343 switch (order
->GetConditionVariable()) {
1344 case OCV_UNCONDITIONALLY
: return CMD_ERROR
;
1346 case OCV_REQUIRES_SERVICE
:
1347 if (data
!= OCC_IS_TRUE
&& data
!= OCC_IS_FALSE
) return CMD_ERROR
;
1351 if (data
== OCC_IS_TRUE
|| data
== OCC_IS_FALSE
) return CMD_ERROR
;
1356 case MOF_COND_VALUE
:
1357 switch (order
->GetConditionVariable()) {
1358 case OCV_UNCONDITIONALLY
:
1359 case OCV_REQUIRES_SERVICE
:
1362 case OCV_LOAD_PERCENTAGE
:
1363 case OCV_RELIABILITY
:
1364 if (data
> 100) return CMD_ERROR
;
1368 if (data
> 2047) return CMD_ERROR
;
1373 case MOF_COND_DESTINATION
:
1374 if (data
>= v
->GetNumOrders()) return CMD_ERROR
;
1378 if (flags
& DC_EXEC
) {
1381 order
->SetNonStopType((OrderNonStopFlags
)data
);
1382 if (data
& ONSF_NO_STOP_AT_DESTINATION_STATION
) {
1383 order
->SetRefit(CT_NO_REFIT
);
1384 order
->SetLoadType(OLF_LOAD_IF_POSSIBLE
);
1385 order
->SetUnloadType(OUF_UNLOAD_IF_POSSIBLE
);
1389 case MOF_STOP_LOCATION
:
1390 order
->SetStopLocation((OrderStopLocation
)data
);
1394 order
->SetUnloadType((OrderUnloadFlags
)data
);
1398 order
->SetLoadType((OrderLoadFlags
)data
);
1399 if (data
& OLFB_NO_LOAD
) order
->SetRefit(CT_NO_REFIT
);
1402 case MOF_DEPOT_ACTION
: {
1405 order
->SetDepotOrderType((OrderDepotTypeFlags
)(order
->GetDepotOrderType() & ~ODTFB_SERVICE
));
1406 order
->SetDepotActionType((OrderDepotActionFlags
)(order
->GetDepotActionType() & ~ODATFB_HALT
));
1410 order
->SetDepotOrderType((OrderDepotTypeFlags
)(order
->GetDepotOrderType() | ODTFB_SERVICE
));
1411 order
->SetDepotActionType((OrderDepotActionFlags
)(order
->GetDepotActionType() & ~ODATFB_HALT
));
1412 order
->SetRefit(CT_NO_REFIT
);
1416 order
->SetDepotOrderType((OrderDepotTypeFlags
)(order
->GetDepotOrderType() & ~ODTFB_SERVICE
));
1417 order
->SetDepotActionType((OrderDepotActionFlags
)(order
->GetDepotActionType() | ODATFB_HALT
));
1418 order
->SetRefit(CT_NO_REFIT
);
1427 case MOF_COND_VARIABLE
: {
1428 order
->SetConditionVariable((OrderConditionVariable
)data
);
1430 OrderConditionComparator occ
= order
->GetConditionComparator();
1431 switch (order
->GetConditionVariable()) {
1432 case OCV_UNCONDITIONALLY
:
1433 order
->SetConditionComparator(OCC_EQUALS
);
1434 order
->SetConditionValue(0);
1437 case OCV_REQUIRES_SERVICE
:
1438 if (occ
!= OCC_IS_TRUE
&& occ
!= OCC_IS_FALSE
) order
->SetConditionComparator(OCC_IS_TRUE
);
1439 order
->SetConditionValue(0);
1442 case OCV_LOAD_PERCENTAGE
:
1443 case OCV_RELIABILITY
:
1444 if (order
->GetConditionValue() > 100) order
->SetConditionValue(100);
1448 if (occ
== OCC_IS_TRUE
|| occ
== OCC_IS_FALSE
) order
->SetConditionComparator(OCC_EQUALS
);
1454 case MOF_COND_COMPARATOR
:
1455 order
->SetConditionComparator((OrderConditionComparator
)data
);
1458 case MOF_COND_VALUE
:
1459 order
->SetConditionValue(data
);
1462 case MOF_COND_DESTINATION
:
1463 order
->SetConditionSkipToOrder(data
);
1466 default: NOT_REACHED();
1469 /* Update the windows and full load flags, also for vehicles that share the same order list */
1470 Vehicle
*u
= v
->FirstShared();
1471 DeleteOrderWarnings(u
);
1472 for (; u
!= nullptr; u
= u
->NextShared()) {
1473 /* Toggle u->current_order "Full load" flag if it changed.
1474 * However, as the same flag is used for depot orders, check
1475 * whether we are not going to a depot as there are three
1476 * cases where the full load flag can be active and only
1477 * one case where the flag is used for depot orders. In the
1478 * other cases for the OrderType the flags are not used,
1479 * so do not care and those orders should not be active
1480 * when this function is called.
1482 if (sel_ord
== u
->cur_real_order_index
&&
1483 (u
->current_order
.IsType(OT_GOTO_STATION
) || u
->current_order
.IsType(OT_LOADING
)) &&
1484 u
->current_order
.GetLoadType() != order
->GetLoadType()) {
1485 u
->current_order
.SetLoadType(order
->GetLoadType());
1487 InvalidateVehicleOrder(u
, VIWD_MODIFY_ORDERS
);
1491 return CommandCost();
1495 * Check if an aircraft has enough range for an order list.
1496 * @param v_new Aircraft to check.
1497 * @param v_order Vehicle currently holding the order list.
1498 * @param first First order in the source order list.
1499 * @return True if the aircraft has enough range for the orders, false otherwise.
1501 static bool CheckAircraftOrderDistance(const Aircraft
*v_new
, const Vehicle
*v_order
, const Order
*first
)
1503 if (first
== nullptr || v_new
->acache
.cached_max_range
== 0) return true;
1505 /* Iterate over all orders to check the distance between all
1506 * 'goto' orders and their respective next order (of any type). */
1507 for (const Order
*o
= first
; o
!= nullptr; o
= o
->next
) {
1508 switch (o
->GetType()) {
1509 case OT_GOTO_STATION
:
1511 case OT_GOTO_WAYPOINT
:
1512 /* If we don't have a next order, we've reached the end and must check the first order instead. */
1513 if (GetOrderDistance(o
, o
->next
!= nullptr ? o
->next
: first
, v_order
) > v_new
->acache
.cached_max_range_sqr
) return false;
1524 * Clone/share/copy an order-list of another vehicle.
1525 * @param flags operation to perform
1526 * @param tile unused
1527 * @param p1 various bitstuffed elements
1528 * - p1 = (bit 0-19) - destination vehicle to clone orders to
1529 * - p1 = (bit 30-31) - action to perform
1530 * @param p2 source vehicle to clone orders from, if any (none for CO_UNSHARE)
1531 * @param text unused
1532 * @return the cost of this operation or an error
1534 CommandCost
CmdCloneOrder(DoCommandFlag flags
, TileIndex tile
, uint32 p1
, uint32 p2
, const std::string
&text
)
1536 VehicleID veh_src
= GB(p2
, 0, 20);
1537 VehicleID veh_dst
= GB(p1
, 0, 20);
1539 Vehicle
*dst
= Vehicle::GetIfValid(veh_dst
);
1540 if (dst
== nullptr || !dst
->IsPrimaryVehicle()) return CMD_ERROR
;
1542 CommandCost ret
= CheckOwnership(dst
->owner
);
1543 if (ret
.Failed()) return ret
;
1545 switch (GB(p1
, 30, 2)) {
1547 Vehicle
*src
= Vehicle::GetIfValid(veh_src
);
1550 if (src
== nullptr || !src
->IsPrimaryVehicle() || dst
->type
!= src
->type
|| dst
== src
) return CMD_ERROR
;
1552 CommandCost ret
= CheckOwnership(src
->owner
);
1553 if (ret
.Failed()) return ret
;
1555 /* Trucks can't share orders with busses (and visa versa) */
1556 if (src
->type
== VEH_ROAD
&& RoadVehicle::From(src
)->IsBus() != RoadVehicle::From(dst
)->IsBus()) {
1560 /* Is the vehicle already in the shared list? */
1561 if (src
->FirstShared() == dst
->FirstShared()) return CMD_ERROR
;
1563 for (const Order
*order
: src
->Orders()) {
1564 if (!OrderGoesToStation(dst
, order
)) continue;
1566 /* Allow copying unreachable destinations if they were already unreachable for the source.
1567 * This is basically to allow cloning / autorenewing / autoreplacing vehicles, while the stations
1568 * are temporarily invalid due to reconstruction. */
1569 const Station
*st
= Station::Get(order
->GetDestination());
1570 if (CanVehicleUseStation(src
, st
) && !CanVehicleUseStation(dst
, st
)) {
1571 return_cmd_error(STR_ERROR_CAN_T_COPY_SHARE_ORDER
);
1575 /* Check for aircraft range limits. */
1576 if (dst
->type
== VEH_AIRCRAFT
&& !CheckAircraftOrderDistance(Aircraft::From(dst
), src
, src
->GetFirstOrder())) {
1577 return_cmd_error(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE
);
1580 if (src
->orders
.list
== nullptr && !OrderList::CanAllocateItem()) {
1581 return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS
);
1584 if (flags
& DC_EXEC
) {
1585 /* If the destination vehicle had a OrderList, destroy it.
1586 * We only reset the order indices, if the new orders are obviously different.
1587 * (We mainly do this to keep the order indices valid and in range.) */
1588 DeleteVehicleOrders(dst
, false, dst
->GetNumOrders() != src
->GetNumOrders());
1590 dst
->orders
.list
= src
->orders
.list
;
1592 /* Link this vehicle in the shared-list */
1593 dst
->AddToShared(src
);
1595 InvalidateVehicleOrder(dst
, VIWD_REMOVE_ALL_ORDERS
);
1596 InvalidateVehicleOrder(src
, VIWD_MODIFY_ORDERS
);
1598 InvalidateWindowClassesData(GetWindowClassForVehicleType(dst
->type
), 0);
1604 Vehicle
*src
= Vehicle::GetIfValid(veh_src
);
1607 if (src
== nullptr || !src
->IsPrimaryVehicle() || dst
->type
!= src
->type
|| dst
== src
) return CMD_ERROR
;
1609 CommandCost ret
= CheckOwnership(src
->owner
);
1610 if (ret
.Failed()) return ret
;
1612 /* Trucks can't copy all the orders from busses (and visa versa),
1613 * and neither can helicopters and aircraft. */
1614 for (const Order
*order
: src
->Orders()) {
1615 if (OrderGoesToStation(dst
, order
) &&
1616 !CanVehicleUseStation(dst
, Station::Get(order
->GetDestination()))) {
1617 return_cmd_error(STR_ERROR_CAN_T_COPY_SHARE_ORDER
);
1621 /* Check for aircraft range limits. */
1622 if (dst
->type
== VEH_AIRCRAFT
&& !CheckAircraftOrderDistance(Aircraft::From(dst
), src
, src
->GetFirstOrder())) {
1623 return_cmd_error(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE
);
1626 /* make sure there are orders available */
1627 if (!Order::CanAllocateItem(src
->GetNumOrders()) || !OrderList::CanAllocateItem()) {
1628 return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS
);
1631 if (flags
& DC_EXEC
) {
1632 Order
*first
= nullptr;
1635 /* If the destination vehicle had an order list, destroy the chain but keep the OrderList.
1636 * We only reset the order indices, if the new orders are obviously different.
1637 * (We mainly do this to keep the order indices valid and in range.) */
1638 DeleteVehicleOrders(dst
, true, dst
->GetNumOrders() != src
->GetNumOrders());
1641 for (const Order
*order
: src
->Orders()) {
1642 *order_dst
= new Order();
1643 (*order_dst
)->AssignOrder(*order
);
1644 order_dst
= &(*order_dst
)->next
;
1646 if (dst
->orders
.list
== nullptr) {
1647 dst
->orders
.list
= new OrderList(first
, dst
);
1649 assert(dst
->orders
.list
->GetFirstOrder() == nullptr);
1650 assert(!dst
->orders
.list
->IsShared());
1651 delete dst
->orders
.list
;
1652 assert(OrderList::CanAllocateItem());
1653 dst
->orders
.list
= new OrderList(first
, dst
);
1656 InvalidateVehicleOrder(dst
, VIWD_REMOVE_ALL_ORDERS
);
1658 InvalidateWindowClassesData(GetWindowClassForVehicleType(dst
->type
), 0);
1663 case CO_UNSHARE
: return DecloneOrder(dst
, flags
);
1664 default: return CMD_ERROR
;
1667 return CommandCost();
1671 * Add/remove refit orders from an order
1672 * @param flags operation to perform
1673 * @param tile Not used
1674 * @param p1 VehicleIndex of the vehicle having the order
1677 * - bit 16-23 number of order to modify
1678 * @param text unused
1679 * @return the cost of this operation or an error
1681 CommandCost
CmdOrderRefit(DoCommandFlag flags
, TileIndex tile
, uint32 p1
, uint32 p2
, const std::string
&text
)
1683 VehicleID veh
= GB(p1
, 0, 20);
1684 VehicleOrderID order_number
= GB(p2
, 16, 8);
1685 CargoID cargo
= GB(p2
, 0, 8);
1687 if (cargo
>= NUM_CARGO
&& cargo
!= CT_NO_REFIT
&& cargo
!= CT_AUTO_REFIT
) return CMD_ERROR
;
1689 const Vehicle
*v
= Vehicle::GetIfValid(veh
);
1690 if (v
== nullptr || !v
->IsPrimaryVehicle()) return CMD_ERROR
;
1692 CommandCost ret
= CheckOwnership(v
->owner
);
1693 if (ret
.Failed()) return ret
;
1695 Order
*order
= v
->GetOrder(order_number
);
1696 if (order
== nullptr) return CMD_ERROR
;
1698 /* Automatic refit cargo is only supported for goto station orders. */
1699 if (cargo
== CT_AUTO_REFIT
&& !order
->IsType(OT_GOTO_STATION
)) return CMD_ERROR
;
1701 if (order
->GetLoadType() & OLFB_NO_LOAD
) return CMD_ERROR
;
1703 if (flags
& DC_EXEC
) {
1704 order
->SetRefit(cargo
);
1706 /* Make the depot order an 'always go' order. */
1707 if (cargo
!= CT_NO_REFIT
&& order
->IsType(OT_GOTO_DEPOT
)) {
1708 order
->SetDepotOrderType((OrderDepotTypeFlags
)(order
->GetDepotOrderType() & ~ODTFB_SERVICE
));
1709 order
->SetDepotActionType((OrderDepotActionFlags
)(order
->GetDepotActionType() & ~ODATFB_HALT
));
1712 for (Vehicle
*u
= v
->FirstShared(); u
!= nullptr; u
= u
->NextShared()) {
1713 /* Update any possible open window of the vehicle */
1714 InvalidateVehicleOrder(u
, VIWD_MODIFY_ORDERS
);
1716 /* If the vehicle already got the current depot set as current order, then update current order as well */
1717 if (u
->cur_real_order_index
== order_number
&& (u
->current_order
.GetDepotOrderType() & ODTFB_PART_OF_ORDERS
)) {
1718 u
->current_order
.SetRefit(cargo
);
1723 return CommandCost();
1729 * Check the orders of a vehicle, to see if there are invalid orders and stuff
1732 void CheckOrders(const Vehicle
*v
)
1734 /* Does the user wants us to check things? */
1735 if (_settings_client
.gui
.order_review_system
== 0) return;
1737 /* Do nothing for crashed vehicles */
1738 if (v
->vehstatus
& VS_CRASHED
) return;
1740 /* Do nothing for stopped vehicles if setting is '1' */
1741 if (_settings_client
.gui
.order_review_system
== 1 && (v
->vehstatus
& VS_STOPPED
)) return;
1743 /* do nothing we we're not the first vehicle in a share-chain */
1744 if (v
->FirstShared() != v
) return;
1746 /* Only check every 20 days, so that we don't flood the message log */
1747 if (v
->owner
== _local_company
&& v
->day_counter
% 20 == 0) {
1748 StringID message
= INVALID_STRING_ID
;
1750 /* Check the order list */
1753 for (const Order
*order
: v
->Orders()) {
1755 if (order
->IsType(OT_DUMMY
)) {
1756 message
= STR_NEWS_VEHICLE_HAS_VOID_ORDER
;
1759 /* Does station have a load-bay for this vehicle? */
1760 if (order
->IsType(OT_GOTO_STATION
)) {
1761 const Station
*st
= Station::Get(order
->GetDestination());
1764 if (!CanVehicleUseStation(v
, st
)) {
1765 message
= STR_NEWS_VEHICLE_HAS_INVALID_ENTRY
;
1766 } else if (v
->type
== VEH_AIRCRAFT
&&
1767 (AircraftVehInfo(v
->engine_type
)->subtype
& AIR_FAST
) &&
1768 (st
->airport
.GetFTA()->flags
& AirportFTAClass::SHORT_STRIP
) &&
1769 !_cheats
.no_jetcrash
.value
&&
1770 message
== INVALID_STRING_ID
) {
1771 message
= STR_NEWS_PLANE_USES_TOO_SHORT_RUNWAY
;
1776 /* Check if the last and the first order are the same */
1777 if (v
->GetNumOrders() > 1) {
1778 const Order
*last
= v
->GetLastOrder();
1780 if (v
->orders
.list
->GetFirstOrder()->Equals(*last
)) {
1781 message
= STR_NEWS_VEHICLE_HAS_DUPLICATE_ENTRY
;
1785 /* Do we only have 1 station in our order list? */
1786 if (n_st
< 2 && message
== INVALID_STRING_ID
) message
= STR_NEWS_VEHICLE_HAS_TOO_FEW_ORDERS
;
1789 if (v
->orders
.list
!= nullptr) v
->orders
.list
->DebugCheckSanity();
1792 /* We don't have a problem */
1793 if (message
== INVALID_STRING_ID
) return;
1795 SetDParam(0, v
->index
);
1796 AddVehicleAdviceNewsItem(message
, v
->index
);
1801 * Removes an order from all vehicles. Triggers when, say, a station is removed.
1802 * @param type The type of the order (OT_GOTO_[STATION|DEPOT|WAYPOINT]).
1803 * @param destination The destination. Can be a StationID, DepotID or WaypointID.
1804 * @param hangar Only used for airports in the destination.
1805 * When false, remove airport and hangar orders.
1806 * When true, remove either airport or hangar order.
1808 void RemoveOrderFromAllVehicles(OrderType type
, DestinationID destination
, bool hangar
)
1810 /* Aircraft have StationIDs for depot orders and never use DepotIDs
1811 * This fact is handled specially below
1814 /* Go through all vehicles */
1815 for (Vehicle
*v
: Vehicle::Iterate()) {
1818 order
= &v
->current_order
;
1819 if ((v
->type
== VEH_AIRCRAFT
&& order
->IsType(OT_GOTO_DEPOT
) && !hangar
? OT_GOTO_STATION
: order
->GetType()) == type
&&
1820 (!hangar
|| v
->type
== VEH_AIRCRAFT
) && v
->current_order
.GetDestination() == destination
) {
1822 SetWindowDirty(WC_VEHICLE_VIEW
, v
->index
);
1825 /* Clear the order from the order-list */
1827 for (Order
*order
: v
->Orders()) {
1831 OrderType ot
= order
->GetType();
1832 if (ot
== OT_GOTO_DEPOT
&& (order
->GetDepotActionType() & ODATFB_NEAREST_DEPOT
) != 0) continue;
1833 if (ot
== OT_GOTO_DEPOT
&& hangar
&& v
->type
!= VEH_AIRCRAFT
) continue; // Not an aircraft? Can't have a hangar order.
1834 if (ot
== OT_IMPLICIT
|| (v
->type
== VEH_AIRCRAFT
&& ot
== OT_GOTO_DEPOT
&& !hangar
)) ot
= OT_GOTO_STATION
;
1835 if (ot
== type
&& order
->GetDestination() == destination
) {
1836 /* We want to clear implicit orders, but we don't want to make them
1837 * dummy orders. They should just vanish. Also check the actual order
1838 * type as ot is currently OT_GOTO_STATION. */
1839 if (order
->IsType(OT_IMPLICIT
)) {
1840 order
= order
->next
; // DeleteOrder() invalidates current order
1842 if (order
!= nullptr) goto restart
;
1846 /* Clear wait time */
1847 v
->orders
.list
->UpdateTotalDuration(-order
->GetWaitTime());
1848 if (order
->IsWaitTimetabled()) {
1849 v
->orders
.list
->UpdateTimetableDuration(-order
->GetTimetabledWait());
1850 order
->SetWaitTimetabled(false);
1852 order
->SetWaitTime(0);
1854 /* Clear order, preserving travel time */
1855 bool travel_timetabled
= order
->IsTravelTimetabled();
1857 order
->SetTravelTimetabled(travel_timetabled
);
1859 for (const Vehicle
*w
= v
->FirstShared(); w
!= nullptr; w
= w
->NextShared()) {
1860 /* In GUI, simulate by removing the order and adding it back */
1861 InvalidateVehicleOrder(w
, id
| (INVALID_VEH_ORDER_ID
<< 8));
1862 InvalidateVehicleOrder(w
, (INVALID_VEH_ORDER_ID
<< 8) | id
);
1868 OrderBackup::RemoveOrder(type
, destination
, hangar
);
1872 * Checks if a vehicle has a depot in its order list.
1873 * @return True iff at least one order is a depot order.
1875 bool Vehicle::HasDepotOrder() const
1877 for (const Order
*order
: this->Orders()) {
1878 if (order
->IsType(OT_GOTO_DEPOT
)) return true;
1885 * Delete all orders from a vehicle
1886 * @param v Vehicle whose orders to reset
1887 * @param keep_orderlist If true, do not free the order list, only empty it.
1888 * @param reset_order_indices If true, reset cur_implicit_order_index and cur_real_order_index
1889 * and cancel the current full load order (if the vehicle is loading).
1890 * If false, _you_ have to make sure the order indices are valid after
1891 * your messing with them!
1893 void DeleteVehicleOrders(Vehicle
*v
, bool keep_orderlist
, bool reset_order_indices
)
1895 DeleteOrderWarnings(v
);
1897 if (v
->IsOrderListShared()) {
1898 /* Remove ourself from the shared order list. */
1899 v
->RemoveFromShared();
1900 v
->orders
.list
= nullptr;
1901 } else if (v
->orders
.list
!= nullptr) {
1902 /* Remove the orders */
1903 v
->orders
.list
->FreeChain(keep_orderlist
);
1904 if (!keep_orderlist
) v
->orders
.list
= nullptr;
1907 if (reset_order_indices
) {
1908 v
->cur_implicit_order_index
= v
->cur_real_order_index
= 0;
1909 if (v
->current_order
.IsType(OT_LOADING
)) {
1910 CancelLoadingDueToDeletedOrder(v
);
1916 * Clamp the service interval to the correct min/max. The actual min/max values
1917 * depend on whether it's in percent or days.
1918 * @param interval proposed service interval
1919 * @return Clamped service interval
1921 uint16
GetServiceIntervalClamped(uint interval
, bool ispercent
)
1923 return ispercent
? Clamp(interval
, MIN_SERVINT_PERCENT
, MAX_SERVINT_PERCENT
) : Clamp(interval
, MIN_SERVINT_DAYS
, MAX_SERVINT_DAYS
);
1928 * Check if a vehicle has any valid orders
1930 * @return false if there are no valid orders
1931 * @note Conditional orders are not considered valid destination orders
1934 static bool CheckForValidOrders(const Vehicle
*v
)
1936 for (const Order
*order
: v
->Orders()) {
1937 switch (order
->GetType()) {
1938 case OT_GOTO_STATION
:
1940 case OT_GOTO_WAYPOINT
:
1952 * Compare the variable and value based on the given comparator.
1954 static bool OrderConditionCompare(OrderConditionComparator occ
, int variable
, int value
)
1957 case OCC_EQUALS
: return variable
== value
;
1958 case OCC_NOT_EQUALS
: return variable
!= value
;
1959 case OCC_LESS_THAN
: return variable
< value
;
1960 case OCC_LESS_EQUALS
: return variable
<= value
;
1961 case OCC_MORE_THAN
: return variable
> value
;
1962 case OCC_MORE_EQUALS
: return variable
>= value
;
1963 case OCC_IS_TRUE
: return variable
!= 0;
1964 case OCC_IS_FALSE
: return variable
== 0;
1965 default: NOT_REACHED();
1970 * Process a conditional order and determine the next order.
1971 * @param order the order the vehicle currently has
1972 * @param v the vehicle to update
1973 * @return index of next order to jump to, or INVALID_VEH_ORDER_ID to use the next order
1975 VehicleOrderID
ProcessConditionalOrder(const Order
*order
, const Vehicle
*v
)
1977 if (order
->GetType() != OT_CONDITIONAL
) return INVALID_VEH_ORDER_ID
;
1979 bool skip_order
= false;
1980 OrderConditionComparator occ
= order
->GetConditionComparator();
1981 uint16 value
= order
->GetConditionValue();
1983 switch (order
->GetConditionVariable()) {
1984 case OCV_LOAD_PERCENTAGE
: skip_order
= OrderConditionCompare(occ
, CalcPercentVehicleFilled(v
, nullptr), value
); break;
1985 case OCV_RELIABILITY
: skip_order
= OrderConditionCompare(occ
, ToPercent16(v
->reliability
), value
); break;
1986 case OCV_MAX_RELIABILITY
: skip_order
= OrderConditionCompare(occ
, ToPercent16(v
->GetEngine()->reliability
), value
); break;
1987 case OCV_MAX_SPEED
: skip_order
= OrderConditionCompare(occ
, v
->GetDisplayMaxSpeed() * 10 / 16, value
); break;
1988 case OCV_AGE
: skip_order
= OrderConditionCompare(occ
, v
->age
/ DAYS_IN_LEAP_YEAR
, value
); break;
1989 case OCV_REQUIRES_SERVICE
: skip_order
= OrderConditionCompare(occ
, v
->NeedsServicing(), value
); break;
1990 case OCV_UNCONDITIONALLY
: skip_order
= true; break;
1991 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;
1992 default: NOT_REACHED();
1995 return skip_order
? order
->GetConditionSkipToOrder() : (VehicleOrderID
)INVALID_VEH_ORDER_ID
;
1999 * Update the vehicle's destination tile from an order.
2000 * @param order the order the vehicle currently has
2001 * @param v the vehicle to update
2002 * @param conditional_depth the depth (amount of steps) to go with conditional orders. This to prevent infinite loops.
2003 * @param pbs_look_ahead Whether we are forecasting orders for pbs reservations in advance. If true, the order indices must not be modified.
2005 bool UpdateOrderDest(Vehicle
*v
, const Order
*order
, int conditional_depth
, bool pbs_look_ahead
)
2007 if (conditional_depth
> v
->GetNumOrders()) {
2008 v
->current_order
.Free();
2013 switch (order
->GetType()) {
2014 case OT_GOTO_STATION
:
2015 v
->SetDestTile(v
->GetOrderStationLocation(order
->GetDestination()));
2019 if ((order
->GetDepotOrderType() & ODTFB_SERVICE
) && !v
->NeedsServicing()) {
2020 assert(!pbs_look_ahead
);
2021 UpdateVehicleTimetable(v
, true);
2022 v
->IncrementRealOrderIndex();
2026 if (v
->current_order
.GetDepotActionType() & ODATFB_NEAREST_DEPOT
) {
2027 /* We need to search for the nearest depot (hangar). */
2029 DestinationID destination
;
2032 if (v
->FindClosestDepot(&location
, &destination
, &reverse
)) {
2033 /* PBS reservations cannot reverse */
2034 if (pbs_look_ahead
&& reverse
) return false;
2036 v
->SetDestTile(location
);
2037 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());
2039 /* If there is no depot in front, reverse automatically (trains only) */
2040 if (v
->type
== VEH_TRAIN
&& reverse
) DoCommand(DC_EXEC
, CMD_REVERSE_TRAIN_DIRECTION
, v
->tile
, v
->index
, 0);
2042 if (v
->type
== VEH_AIRCRAFT
) {
2043 Aircraft
*a
= Aircraft::From(v
);
2044 if (a
->state
== FLYING
&& a
->targetairport
!= destination
) {
2045 /* The aircraft is now heading for a different hangar than the next in the orders */
2046 extern void AircraftNextAirportPos_and_Order(Aircraft
*a
);
2047 AircraftNextAirportPos_and_Order(a
);
2053 /* If there is no depot, we cannot help PBS either. */
2054 if (pbs_look_ahead
) return false;
2056 UpdateVehicleTimetable(v
, true);
2057 v
->IncrementRealOrderIndex();
2059 if (v
->type
!= VEH_AIRCRAFT
) {
2060 v
->SetDestTile(Depot::Get(order
->GetDestination())->xy
);
2062 Aircraft
*a
= Aircraft::From(v
);
2063 DestinationID destination
= a
->current_order
.GetDestination();
2064 if (a
->targetairport
!= destination
) {
2065 /* The aircraft is now heading for a different hangar than the next in the orders */
2066 a
->SetDestTile(a
->GetOrderStationLocation(destination
));
2073 case OT_GOTO_WAYPOINT
:
2074 v
->SetDestTile(Waypoint::Get(order
->GetDestination())->xy
);
2077 case OT_CONDITIONAL
: {
2078 assert(!pbs_look_ahead
);
2079 VehicleOrderID next_order
= ProcessConditionalOrder(order
, v
);
2080 if (next_order
!= INVALID_VEH_ORDER_ID
) {
2081 /* Jump to next_order. cur_implicit_order_index becomes exactly that order,
2082 * cur_real_order_index might come after next_order. */
2083 UpdateVehicleTimetable(v
, false);
2084 v
->cur_implicit_order_index
= v
->cur_real_order_index
= next_order
;
2085 v
->UpdateRealOrderIndex();
2086 v
->current_order_time
+= v
->GetOrder(v
->cur_real_order_index
)->GetTimetabledTravel();
2088 /* Disable creation of implicit orders.
2089 * When inserting them we do not know that we would have to make the conditional orders point to them. */
2090 if (v
->IsGroundVehicle()) {
2091 uint16
&gv_flags
= v
->GetGroundVehicleFlags();
2092 SetBit(gv_flags
, GVF_SUPPRESS_IMPLICIT_ORDERS
);
2095 UpdateVehicleTimetable(v
, true);
2096 v
->IncrementRealOrderIndex();
2106 assert(v
->cur_implicit_order_index
< v
->GetNumOrders());
2107 assert(v
->cur_real_order_index
< v
->GetNumOrders());
2109 /* Get the current order */
2110 order
= v
->GetOrder(v
->cur_real_order_index
);
2111 if (order
!= nullptr && order
->IsType(OT_IMPLICIT
)) {
2112 assert(v
->GetNumManualOrders() == 0);
2116 if (order
== nullptr) {
2117 v
->current_order
.Free();
2122 v
->current_order
= *order
;
2123 return UpdateOrderDest(v
, order
, conditional_depth
+ 1, pbs_look_ahead
);
2127 * Handle the orders of a vehicle and determine the next place
2128 * to go to if needed.
2129 * @param v the vehicle to do this for.
2130 * @return true *if* the vehicle is eligible for reversing
2131 * (basically only when leaving a station).
2133 bool ProcessOrders(Vehicle
*v
)
2135 switch (v
->current_order
.GetType()) {
2137 /* Let a depot order in the orderlist interrupt. */
2138 if (!(v
->current_order
.GetDepotOrderType() & ODTFB_PART_OF_ORDERS
)) return false;
2144 case OT_LEAVESTATION
:
2145 if (v
->type
!= VEH_AIRCRAFT
) return false;
2152 * Reversing because of order change is allowed only just after leaving a
2153 * station (and the difficulty setting to allowed, of course)
2154 * this can be detected because only after OT_LEAVESTATION, current_order
2155 * will be reset to nothing. (That also happens if no order, but in that case
2156 * it won't hit the point in code where may_reverse is checked)
2158 bool may_reverse
= v
->current_order
.IsType(OT_NOTHING
);
2160 /* Check if we've reached a 'via' destination. */
2161 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
)) &&
2162 IsTileType(v
->tile
, MP_STATION
) &&
2163 v
->current_order
.GetDestination() == GetStationIndex(v
->tile
)) {
2164 v
->DeleteUnreachedImplicitOrders();
2165 /* We set the last visited station here because we do not want
2166 * the train to stop at this 'via' station if the next order
2167 * is a no-non-stop order; in that case not setting the last
2168 * visited station will cause the vehicle to still stop. */
2169 v
->last_station_visited
= v
->current_order
.GetDestination();
2170 UpdateVehicleTimetable(v
, true);
2171 v
->IncrementImplicitOrderIndex();
2174 /* Get the current order */
2175 assert(v
->cur_implicit_order_index
== 0 || v
->cur_implicit_order_index
< v
->GetNumOrders());
2176 v
->UpdateRealOrderIndex();
2178 const Order
*order
= v
->GetOrder(v
->cur_real_order_index
);
2179 if (order
!= nullptr && order
->IsType(OT_IMPLICIT
)) {
2180 assert(v
->GetNumManualOrders() == 0);
2184 /* If no order, do nothing. */
2185 if (order
== nullptr || (v
->type
== VEH_AIRCRAFT
&& !CheckForValidOrders(v
))) {
2186 if (v
->type
== VEH_AIRCRAFT
) {
2187 /* Aircraft do something vastly different here, so handle separately */
2188 extern void HandleMissingAircraftOrders(Aircraft
*v
);
2189 HandleMissingAircraftOrders(Aircraft::From(v
));
2193 v
->current_order
.Free();
2198 /* If it is unchanged, keep it. */
2199 if (order
->Equals(v
->current_order
) && (v
->type
== VEH_AIRCRAFT
|| v
->dest_tile
!= 0) &&
2200 (v
->type
!= VEH_SHIP
|| !order
->IsType(OT_GOTO_STATION
) || Station::Get(order
->GetDestination())->ship_station
.tile
!= INVALID_TILE
)) {
2204 /* Otherwise set it, and determine the destination tile. */
2205 v
->current_order
= *order
;
2207 InvalidateVehicleOrder(v
, VIWD_MODIFY_ORDERS
);
2218 SetWindowClassesDirty(GetWindowClassForVehicleType(v
->type
));
2222 return UpdateOrderDest(v
, order
) && may_reverse
;
2226 * Check whether the given vehicle should stop at the given station
2227 * based on this order and the non-stop settings.
2228 * @param v the vehicle that might be stopping.
2229 * @param station the station to stop at.
2230 * @return true if the vehicle should stop.
2232 bool Order::ShouldStopAtStation(const Vehicle
*v
, StationID station
) const
2234 bool is_dest_station
= this->IsType(OT_GOTO_STATION
) && this->dest
== station
;
2236 return (!this->IsType(OT_GOTO_DEPOT
) || (this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS
) != 0) &&
2237 v
->last_station_visited
!= station
&& // Do stop only when we've not just been there
2238 /* Finally do stop when there is no non-stop flag set for this type of station. */
2239 !(this->GetNonStopType() & (is_dest_station
? ONSF_NO_STOP_AT_DESTINATION_STATION
: ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS
));
2242 bool Order::CanLoadOrUnload() const
2244 return (this->IsType(OT_GOTO_STATION
) || this->IsType(OT_IMPLICIT
)) &&
2245 (this->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION
) == 0 &&
2246 ((this->GetLoadType() & OLFB_NO_LOAD
) == 0 ||
2247 (this->GetUnloadType() & OUFB_NO_UNLOAD
) == 0);
2251 * A vehicle can leave the current station with cargo if:
2252 * 1. it can load cargo here OR
2253 * 2a. it could leave the last station with cargo AND
2254 * 2b. it doesn't have to unload all cargo here.
2256 bool Order::CanLeaveWithCargo(bool has_cargo
) const
2258 return (this->GetLoadType() & OLFB_NO_LOAD
) == 0 || (has_cargo
&&
2259 (this->GetUnloadType() & (OUFB_UNLOAD
| OUFB_TRANSFER
)) == 0);