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"
30 #include "table/strings.h"
32 #include "safeguards.h"
34 /* DestinationID must be at least as large as every these below, because it can
37 static_assert(sizeof(DestinationID
) >= sizeof(DepotID
));
38 static_assert(sizeof(DestinationID
) >= sizeof(StationID
));
40 OrderPool
_order_pool("Order");
41 INSTANTIATE_POOL_METHODS(Order
)
42 OrderListPool
_orderlist_pool("OrderList");
43 INSTANTIATE_POOL_METHODS(OrderList
)
45 /** Clean everything up. */
48 if (CleaningPool()) return;
50 /* We can visit oil rigs and buoys that are not our own. They will be shown in
51 * the list of stations. So, we need to invalidate that window if needed. */
52 if (this->IsType(OT_GOTO_STATION
) || this->IsType(OT_GOTO_WAYPOINT
)) {
53 BaseStation
*bs
= BaseStation::GetIfValid(this->GetDestination());
54 if (bs
!= nullptr && bs
->owner
== OWNER_NONE
) InvalidateWindowClassesData(WC_STATION_LIST
, 0);
60 * @note ONLY use on "current_order" vehicle orders!
64 this->type
= OT_NOTHING
;
71 * Makes this order a Go To Station order.
72 * @param destination the station to go to.
74 void Order::MakeGoToStation(StationID destination
)
76 this->type
= OT_GOTO_STATION
;
78 this->dest
= destination
;
82 * Makes this order a Go To Depot order.
83 * @param destination the depot to go to.
84 * @param order is this order a 'default' order, or an overridden vehicle order?
85 * @param non_stop_type how to get to the depot?
86 * @param action what to do in the depot?
87 * @param cargo the cargo type to change to.
89 void Order::MakeGoToDepot(DepotID destination
, OrderDepotTypeFlags order
, OrderNonStopFlags non_stop_type
, OrderDepotActionFlags action
, CargoID cargo
)
91 this->type
= OT_GOTO_DEPOT
;
92 this->SetDepotOrderType(order
);
93 this->SetDepotActionType(action
);
94 this->SetNonStopType(non_stop_type
);
95 this->dest
= destination
;
96 this->SetRefit(cargo
);
100 * Makes this order a Go To Waypoint order.
101 * @param destination the waypoint to go to.
103 void Order::MakeGoToWaypoint(StationID destination
)
105 this->type
= OT_GOTO_WAYPOINT
;
107 this->dest
= destination
;
111 * Makes this order a Loading order.
112 * @param ordered is this an ordered stop?
114 void Order::MakeLoading(bool ordered
)
116 this->type
= OT_LOADING
;
117 if (!ordered
) this->flags
= 0;
121 * Makes this order a Leave Station order.
123 void Order::MakeLeaveStation()
125 this->type
= OT_LEAVESTATION
;
130 * Makes this order a Dummy order.
132 void Order::MakeDummy()
134 this->type
= OT_DUMMY
;
139 * Makes this order an conditional order.
140 * @param order the order to jump to.
142 void Order::MakeConditional(VehicleOrderID order
)
144 this->type
= OT_CONDITIONAL
;
150 * Makes this order an implicit order.
151 * @param destination the station to go to.
153 void Order::MakeImplicit(StationID destination
)
155 this->type
= OT_IMPLICIT
;
156 this->dest
= destination
;
160 * Make this depot/station order also a refit order.
161 * @param cargo the cargo type to change to.
162 * @pre IsType(OT_GOTO_DEPOT) || IsType(OT_GOTO_STATION).
164 void Order::SetRefit(CargoID cargo
)
166 this->refit_cargo
= cargo
;
170 * Does this order have the same type, flags and destination?
171 * @param other the second order to compare to.
172 * @return true if the type, flags and destination match.
174 bool Order::Equals(const Order
&other
) const
176 /* In case of go to nearest depot orders we need "only" compare the flags
177 * with the other and not the nearest depot order bit or the actual
178 * destination because those get clear/filled in during the order
179 * evaluation. If we do not do this the order will continuously be seen as
180 * a different order and it will try to find a "nearest depot" every tick. */
181 if ((this->IsType(OT_GOTO_DEPOT
) && this->type
== other
.type
) &&
182 ((this->GetDepotActionType() & ODATFB_NEAREST_DEPOT
) != 0 ||
183 (other
.GetDepotActionType() & ODATFB_NEAREST_DEPOT
) != 0)) {
184 return this->GetDepotOrderType() == other
.GetDepotOrderType() &&
185 (this->GetDepotActionType() & ~ODATFB_NEAREST_DEPOT
) == (other
.GetDepotActionType() & ~ODATFB_NEAREST_DEPOT
);
188 return this->type
== other
.type
&& this->flags
== other
.flags
&& this->dest
== other
.dest
;
192 * Pack this order into a 32 bits integer, or actually only
193 * the type, flags and destination.
194 * @return the packed representation.
195 * @note unpacking is done in the constructor.
197 uint32
Order::Pack() const
199 return this->dest
<< 16 | this->flags
<< 8 | this->type
;
203 * Pack this order into a 16 bits integer as close to the TTD
204 * representation as possible.
205 * @return the TTD-like packed representation.
207 uint16
Order::MapOldOrder() const
209 uint16 order
= this->GetType();
210 switch (this->type
) {
211 case OT_GOTO_STATION
:
212 if (this->GetUnloadType() & OUFB_UNLOAD
) SetBit(order
, 5);
213 if (this->GetLoadType() & OLFB_FULL_LOAD
) SetBit(order
, 6);
214 if (this->GetNonStopType() & ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS
) SetBit(order
, 7);
215 order
|= GB(this->GetDestination(), 0, 8) << 8;
218 if (!(this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS
)) SetBit(order
, 6);
220 order
|= GB(this->GetDestination(), 0, 8) << 8;
223 if (this->GetLoadType() & OLFB_FULL_LOAD
) SetBit(order
, 6);
230 * Create an order based on a packed representation of that order.
231 * @param packed the packed representation.
233 Order::Order(uint32 packed
)
235 this->type
= (OrderType
)GB(packed
, 0, 8);
236 this->flags
= GB(packed
, 8, 8);
237 this->dest
= GB(packed
, 16, 16);
238 this->next
= nullptr;
239 this->refit_cargo
= CT_NO_REFIT
;
241 this->travel_time
= 0;
242 this->max_speed
= UINT16_MAX
;
247 * Updates the widgets of a vehicle which contains the order-data
250 void InvalidateVehicleOrder(const Vehicle
*v
, int data
)
252 SetWindowDirty(WC_VEHICLE_VIEW
, v
->index
);
255 /* Calls SetDirty() too */
256 InvalidateWindowData(WC_VEHICLE_ORDERS
, v
->index
, data
);
257 InvalidateWindowData(WC_VEHICLE_TIMETABLE
, v
->index
, data
);
261 SetWindowDirty(WC_VEHICLE_ORDERS
, v
->index
);
262 SetWindowDirty(WC_VEHICLE_TIMETABLE
, v
->index
);
267 * Assign data to an order (from another order)
268 * This function makes sure that the index is maintained correctly
269 * @param other the data to copy (except next pointer).
272 void Order::AssignOrder(const Order
&other
)
274 this->type
= other
.type
;
275 this->flags
= other
.flags
;
276 this->dest
= other
.dest
;
278 this->refit_cargo
= other
.refit_cargo
;
280 this->wait_time
= other
.wait_time
;
281 this->travel_time
= other
.travel_time
;
282 this->max_speed
= other
.max_speed
;
286 * Recomputes everything.
287 * @param chain first order in the chain
288 * @param v one of vehicle that is using this orderlist
290 void OrderList::Initialize(Order
*chain
, Vehicle
*v
)
293 this->first_shared
= v
;
295 this->num_orders
= 0;
296 this->num_manual_orders
= 0;
297 this->num_vehicles
= 1;
298 this->timetable_duration
= 0;
300 for (Order
*o
= this->first
; o
!= nullptr; o
= o
->next
) {
302 if (!o
->IsType(OT_IMPLICIT
)) ++this->num_manual_orders
;
303 this->total_duration
+= o
->GetWaitTime() + o
->GetTravelTime();
306 this->RecalculateTimetableDuration();
308 for (Vehicle
*u
= this->first_shared
->PreviousShared(); u
!= nullptr; u
= u
->PreviousShared()) {
309 ++this->num_vehicles
;
310 this->first_shared
= u
;
313 for (const Vehicle
*u
= v
->NextShared(); u
!= nullptr; u
= u
->NextShared()) ++this->num_vehicles
;
317 * Recomputes Timetable duration.
318 * Split out into a separate function so it can be used by afterload.
320 void OrderList::RecalculateTimetableDuration()
322 this->timetable_duration
= 0;
323 for (Order
*o
= this->first
; o
!= nullptr; o
= o
->next
) {
324 this->timetable_duration
+= o
->GetTimetabledWait() + o
->GetTimetabledTravel();
329 * Free a complete order chain.
330 * @param keep_orderlist If this is true only delete the orders, otherwise also delete the OrderList.
331 * @note do not use on "current_order" vehicle orders!
333 void OrderList::FreeChain(bool keep_orderlist
)
336 for (Order
*o
= this->first
; o
!= nullptr; o
= next
) {
341 if (keep_orderlist
) {
342 this->first
= nullptr;
343 this->num_orders
= 0;
344 this->num_manual_orders
= 0;
345 this->timetable_duration
= 0;
352 * Get a certain order of the order chain.
353 * @param index zero-based index of the order within the chain.
354 * @return the order at position index.
356 Order
*OrderList::GetOrderAt(int index
) const
358 if (index
< 0) return nullptr;
360 Order
*order
= this->first
;
362 while (order
!= nullptr && index
-- > 0) {
369 * Get the next order which will make the given vehicle stop at a station
370 * or refit at a depot or evaluate a non-trivial condition.
371 * @param next The order to start looking at.
372 * @param hops The number of orders we have already looked at.
374 * \li a station order
375 * \li a refitting depot order
376 * \li a non-trivial conditional order
377 * \li nullptr if the vehicle won't stop anymore.
379 const Order
*OrderList::GetNextDecisionNode(const Order
*next
, uint hops
) const
381 if (hops
> this->GetNumOrders() || next
== nullptr) return nullptr;
383 if (next
->IsType(OT_CONDITIONAL
)) {
384 if (next
->GetConditionVariable() != OCV_UNCONDITIONALLY
) return next
;
386 /* We can evaluate trivial conditions right away. They're conceptually
387 * the same as regular order progression. */
388 return this->GetNextDecisionNode(
389 this->GetOrderAt(next
->GetConditionSkipToOrder()),
393 if (next
->IsType(OT_GOTO_DEPOT
)) {
394 if (next
->GetDepotActionType() == ODATFB_HALT
) return nullptr;
395 if (next
->IsRefit()) return next
;
398 if (!next
->CanLoadOrUnload()) {
399 return this->GetNextDecisionNode(this->GetNext(next
), hops
+ 1);
406 * Recursively determine the next deterministic station to stop at.
407 * @param v The vehicle we're looking at.
408 * @param first Order to start searching at or nullptr to start at cur_implicit_order_index + 1.
409 * @param hops Number of orders we have already looked at.
410 * @return Next stopping station or INVALID_STATION.
411 * @pre The vehicle is currently loading and v->last_station_visited is meaningful.
412 * @note This function may draw a random number. Don't use it from the GUI.
414 StationIDStack
OrderList::GetNextStoppingStation(const Vehicle
*v
, const Order
*first
, uint hops
) const
417 const Order
*next
= first
;
418 if (first
== nullptr) {
419 next
= this->GetOrderAt(v
->cur_implicit_order_index
);
420 if (next
== nullptr) {
421 next
= this->GetFirstOrder();
422 if (next
== nullptr) return INVALID_STATION
;
424 /* GetNext never returns nullptr if there is a valid station in the list.
425 * As the given "next" is already valid and a station in the list, we
426 * don't have to check for nullptr here. */
427 next
= this->GetNext(next
);
428 assert(next
!= nullptr);
433 next
= this->GetNextDecisionNode(next
, ++hops
);
435 /* Resolve possibly nested conditionals by estimation. */
436 while (next
!= nullptr && next
->IsType(OT_CONDITIONAL
)) {
437 /* We return both options of conditional orders. */
438 const Order
*skip_to
= this->GetNextDecisionNode(
439 this->GetOrderAt(next
->GetConditionSkipToOrder()), hops
);
440 const Order
*advance
= this->GetNextDecisionNode(
441 this->GetNext(next
), hops
);
442 if (advance
== nullptr || advance
== first
|| skip_to
== advance
) {
443 next
= (skip_to
== first
) ? nullptr : skip_to
;
444 } else if (skip_to
== nullptr || skip_to
== first
) {
445 next
= (advance
== first
) ? nullptr : advance
;
447 StationIDStack st1
= this->GetNextStoppingStation(v
, skip_to
, hops
);
448 StationIDStack st2
= this->GetNextStoppingStation(v
, advance
, hops
);
449 while (!st2
.IsEmpty()) st1
.Push(st2
.Pop());
455 /* Don't return a next stop if the vehicle has to unload everything. */
456 if (next
== nullptr || ((next
->IsType(OT_GOTO_STATION
) || next
->IsType(OT_IMPLICIT
)) &&
457 next
->GetDestination() == v
->last_station_visited
&&
458 (next
->GetUnloadType() & (OUFB_TRANSFER
| OUFB_UNLOAD
)) != 0)) {
459 return INVALID_STATION
;
461 } while (next
->IsType(OT_GOTO_DEPOT
) || next
->GetDestination() == v
->last_station_visited
);
463 return next
->GetDestination();
467 * Insert a new order into the order chain.
468 * @param new_order is the order to insert into the chain.
469 * @param index is the position where the order is supposed to be inserted.
471 void OrderList::InsertOrderAt(Order
*new_order
, int index
)
473 if (this->first
== nullptr) {
474 this->first
= new_order
;
477 /* Insert as first or only order */
478 new_order
->next
= this->first
;
479 this->first
= new_order
;
480 } else if (index
>= this->num_orders
) {
481 /* index is after the last order, add it to the end */
482 this->GetLastOrder()->next
= new_order
;
484 /* Put the new order in between */
485 Order
*order
= this->GetOrderAt(index
- 1);
486 new_order
->next
= order
->next
;
487 order
->next
= new_order
;
491 if (!new_order
->IsType(OT_IMPLICIT
)) ++this->num_manual_orders
;
492 this->timetable_duration
+= new_order
->GetTimetabledWait() + new_order
->GetTimetabledTravel();
493 this->total_duration
+= new_order
->GetWaitTime() + new_order
->GetTravelTime();
495 /* We can visit oil rigs and buoys that are not our own. They will be shown in
496 * the list of stations. So, we need to invalidate that window if needed. */
497 if (new_order
->IsType(OT_GOTO_STATION
) || new_order
->IsType(OT_GOTO_WAYPOINT
)) {
498 BaseStation
*bs
= BaseStation::Get(new_order
->GetDestination());
499 if (bs
->owner
== OWNER_NONE
) InvalidateWindowClassesData(WC_STATION_LIST
, 0);
506 * Remove an order from the order list and delete it.
507 * @param index is the position of the order which is to be deleted.
509 void OrderList::DeleteOrderAt(int index
)
511 if (index
>= this->num_orders
) return;
516 to_remove
= this->first
;
517 this->first
= to_remove
->next
;
519 Order
*prev
= GetOrderAt(index
- 1);
520 to_remove
= prev
->next
;
521 prev
->next
= to_remove
->next
;
524 if (!to_remove
->IsType(OT_IMPLICIT
)) --this->num_manual_orders
;
525 this->timetable_duration
-= (to_remove
->GetTimetabledWait() + to_remove
->GetTimetabledTravel());
526 this->total_duration
-= (to_remove
->GetWaitTime() + to_remove
->GetTravelTime());
531 * Move an order to another position within the order list.
532 * @param from is the zero-based position of the order to move.
533 * @param to is the zero-based position where the order is moved to.
535 void OrderList::MoveOrder(int from
, int to
)
537 if (from
>= this->num_orders
|| to
>= this->num_orders
|| from
== to
) return;
541 /* Take the moving order out of the pointer-chain */
543 moving_one
= this->first
;
544 this->first
= moving_one
->next
;
546 Order
*one_before
= GetOrderAt(from
- 1);
547 moving_one
= one_before
->next
;
548 one_before
->next
= moving_one
->next
;
551 /* Insert the moving_order again in the pointer-chain */
553 moving_one
->next
= this->first
;
554 this->first
= moving_one
;
556 Order
*one_before
= GetOrderAt(to
- 1);
557 moving_one
->next
= one_before
->next
;
558 one_before
->next
= moving_one
;
563 * Removes the vehicle from the shared order list.
564 * @note This is supposed to be called when the vehicle is still in the chain
565 * @param v vehicle to remove from the list
567 void OrderList::RemoveVehicle(Vehicle
*v
)
569 --this->num_vehicles
;
570 if (v
== this->first_shared
) this->first_shared
= v
->NextShared();
574 * Checks whether a vehicle is part of the shared vehicle chain.
575 * @param v is the vehicle to search in the shared vehicle chain.
577 bool OrderList::IsVehicleInSharedOrdersList(const Vehicle
*v
) const
579 for (const Vehicle
*v_shared
= this->first_shared
; v_shared
!= nullptr; v_shared
= v_shared
->NextShared()) {
580 if (v_shared
== v
) return true;
587 * Gets the position of the given vehicle within the shared order vehicle list.
588 * @param v is the vehicle of which to get the position
589 * @return position of v within the shared vehicle chain.
591 int OrderList::GetPositionInSharedOrderList(const Vehicle
*v
) const
594 for (const Vehicle
*v_shared
= v
->PreviousShared(); v_shared
!= nullptr; v_shared
= v_shared
->PreviousShared()) count
++;
599 * Checks whether all orders of the list have a filled timetable.
600 * @return whether all orders have a filled timetable.
602 bool OrderList::IsCompleteTimetable() const
604 for (Order
*o
= this->first
; o
!= nullptr; o
= o
->next
) {
605 /* Implicit orders are, by definition, not timetabled. */
606 if (o
->IsType(OT_IMPLICIT
)) continue;
607 if (!o
->IsCompletelyTimetabled()) return false;
613 * Checks for internal consistency of order list. Triggers assertion if something is wrong.
615 void OrderList::DebugCheckSanity() const
617 VehicleOrderID check_num_orders
= 0;
618 VehicleOrderID check_num_manual_orders
= 0;
619 uint check_num_vehicles
= 0;
620 Ticks check_timetable_duration
= 0;
621 Ticks check_total_duration
= 0;
623 Debug(misc
, 6, "Checking OrderList {} for sanity...", this->index
);
625 for (const Order
*o
= this->first
; o
!= nullptr; o
= o
->next
) {
627 if (!o
->IsType(OT_IMPLICIT
)) ++check_num_manual_orders
;
628 check_timetable_duration
+= o
->GetTimetabledWait() + o
->GetTimetabledTravel();
629 check_total_duration
+= o
->GetWaitTime() + o
->GetTravelTime();
631 assert(this->num_orders
== check_num_orders
);
632 assert(this->num_manual_orders
== check_num_manual_orders
);
633 assert(this->timetable_duration
== check_timetable_duration
);
634 assert(this->total_duration
== check_total_duration
);
636 for (const Vehicle
*v
= this->first_shared
; v
!= nullptr; v
= v
->NextShared()) {
637 ++check_num_vehicles
;
638 assert(v
->orders
.list
== this);
640 assert(this->num_vehicles
== check_num_vehicles
);
641 Debug(misc
, 6, "... detected {} orders ({} manual), {} vehicles, {} timetabled, {} total",
642 (uint
)this->num_orders
, (uint
)this->num_manual_orders
,
643 this->num_vehicles
, this->timetable_duration
, this->total_duration
);
647 * Checks whether the order goes to a station or not, i.e. whether the
648 * destination is a station
649 * @param v the vehicle to check for
650 * @param o the order to check
651 * @return true if the destination is a station
653 static inline bool OrderGoesToStation(const Vehicle
*v
, const Order
*o
)
655 return o
->IsType(OT_GOTO_STATION
) ||
656 (v
->type
== VEH_AIRCRAFT
&& o
->IsType(OT_GOTO_DEPOT
) && !(o
->GetDepotActionType() & ODATFB_NEAREST_DEPOT
));
660 * Delete all news items regarding defective orders about a vehicle
661 * This could kill still valid warnings (for example about void order when just
662 * another order gets added), but assume the company will notice the problems,
663 * when they're changing the orders.
665 static void DeleteOrderWarnings(const Vehicle
*v
)
667 DeleteVehicleNews(v
->index
, STR_NEWS_VEHICLE_HAS_TOO_FEW_ORDERS
);
668 DeleteVehicleNews(v
->index
, STR_NEWS_VEHICLE_HAS_VOID_ORDER
);
669 DeleteVehicleNews(v
->index
, STR_NEWS_VEHICLE_HAS_DUPLICATE_ENTRY
);
670 DeleteVehicleNews(v
->index
, STR_NEWS_VEHICLE_HAS_INVALID_ENTRY
);
671 DeleteVehicleNews(v
->index
, STR_NEWS_PLANE_USES_TOO_SHORT_RUNWAY
);
675 * Returns a tile somewhat representing the order destination (not suitable for pathfinding).
676 * @param v The vehicle to get the location for.
677 * @param airport Get the airport tile and not the station location for aircraft.
678 * @return destination of order, or INVALID_TILE if none.
680 TileIndex
Order::GetLocation(const Vehicle
*v
, bool airport
) const
682 switch (this->GetType()) {
683 case OT_GOTO_WAYPOINT
:
684 case OT_GOTO_STATION
:
686 if (airport
&& v
->type
== VEH_AIRCRAFT
) return Station::Get(this->GetDestination())->airport
.tile
;
687 return BaseStation::Get(this->GetDestination())->xy
;
690 if ((this->GetDepotActionType() & ODATFB_NEAREST_DEPOT
) != 0) return INVALID_TILE
;
691 return (v
->type
== VEH_AIRCRAFT
) ? Station::Get(this->GetDestination())->xy
: Depot::Get(this->GetDestination())->xy
;
699 * Get the distance between two orders of a vehicle. Conditional orders are resolved
700 * and the bigger distance of the two order branches is returned.
701 * @param prev Origin order.
702 * @param cur Destination order.
703 * @param v The vehicle to get the distance for.
704 * @param conditional_depth Internal param for resolving conditional orders.
705 * @return Maximum distance between the two orders.
707 uint
GetOrderDistance(const Order
*prev
, const Order
*cur
, const Vehicle
*v
, int conditional_depth
)
709 if (cur
->IsType(OT_CONDITIONAL
)) {
710 if (conditional_depth
> v
->GetNumOrders()) return 0;
714 int dist1
= GetOrderDistance(prev
, v
->GetOrder(cur
->GetConditionSkipToOrder()), v
, conditional_depth
);
715 int dist2
= GetOrderDistance(prev
, cur
->next
== nullptr ? v
->orders
.list
->GetFirstOrder() : cur
->next
, v
, conditional_depth
);
716 return std::max(dist1
, dist2
);
719 TileIndex prev_tile
= prev
->GetLocation(v
, true);
720 TileIndex cur_tile
= cur
->GetLocation(v
, true);
721 if (prev_tile
== INVALID_TILE
|| cur_tile
== INVALID_TILE
) return 0;
722 return v
->type
== VEH_AIRCRAFT
? DistanceSquare(prev_tile
, cur_tile
) : DistanceManhattan(prev_tile
, cur_tile
);
726 * Add an order to the orderlist of a vehicle.
728 * @param flags operation to perform
729 * @param p1 various bitstuffed elements
730 * - p1 = (bit 0 - 19) - ID of the vehicle
731 * - p1 = (bit 24 - 31) - the selected order (if any). If the last order is given,
732 * the order will be inserted before that one
733 * the maximum vehicle order id is 254.
734 * @param p2 packed order to insert
736 * @return the cost of this operation or an error
738 CommandCost
CmdInsertOrder(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const std::string
&text
)
740 VehicleID veh
= GB(p1
, 0, 20);
741 VehicleOrderID sel_ord
= GB(p1
, 20, 8);
744 Vehicle
*v
= Vehicle::GetIfValid(veh
);
745 if (v
== nullptr || !v
->IsPrimaryVehicle()) return CMD_ERROR
;
747 CommandCost ret
= CheckOwnership(v
->owner
);
748 if (ret
.Failed()) return ret
;
750 /* Check if the inserted order is to the correct destination (owner, type),
751 * and has the correct flags if any */
752 switch (new_order
.GetType()) {
753 case OT_GOTO_STATION
: {
754 const Station
*st
= Station::GetIfValid(new_order
.GetDestination());
755 if (st
== nullptr) return CMD_ERROR
;
757 if (st
->owner
!= OWNER_NONE
) {
758 CommandCost ret
= CheckOwnership(st
->owner
);
759 if (ret
.Failed()) return ret
;
762 if (!CanVehicleUseStation(v
, st
)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER
);
763 for (Vehicle
*u
= v
->FirstShared(); u
!= nullptr; u
= u
->NextShared()) {
764 if (!CanVehicleUseStation(u
, st
)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER_SHARED
);
767 /* Non stop only allowed for ground vehicles. */
768 if (new_order
.GetNonStopType() != ONSF_STOP_EVERYWHERE
&& !v
->IsGroundVehicle()) return CMD_ERROR
;
770 /* Filter invalid load/unload types. */
771 switch (new_order
.GetLoadType()) {
772 case OLF_LOAD_IF_POSSIBLE
: case OLFB_FULL_LOAD
: case OLF_FULL_LOAD_ANY
: case OLFB_NO_LOAD
: break;
773 default: return CMD_ERROR
;
775 switch (new_order
.GetUnloadType()) {
776 case OUF_UNLOAD_IF_POSSIBLE
: case OUFB_UNLOAD
: case OUFB_TRANSFER
: case OUFB_NO_UNLOAD
: break;
777 default: return CMD_ERROR
;
780 /* Filter invalid stop locations */
781 switch (new_order
.GetStopLocation()) {
782 case OSL_PLATFORM_NEAR_END
:
783 case OSL_PLATFORM_MIDDLE
:
784 if (v
->type
!= VEH_TRAIN
) return CMD_ERROR
;
787 case OSL_PLATFORM_FAR_END
:
797 case OT_GOTO_DEPOT
: {
798 if ((new_order
.GetDepotActionType() & ODATFB_NEAREST_DEPOT
) == 0) {
799 if (v
->type
== VEH_AIRCRAFT
) {
800 const Station
*st
= Station::GetIfValid(new_order
.GetDestination());
802 if (st
== nullptr) return CMD_ERROR
;
804 CommandCost ret
= CheckOwnership(st
->owner
);
805 if (ret
.Failed()) return ret
;
807 if (!CanVehicleUseStation(v
, st
) || !st
->airport
.HasHangar()) {
811 const Depot
*dp
= Depot::GetIfValid(new_order
.GetDestination());
813 if (dp
== nullptr) return CMD_ERROR
;
815 CommandCost ret
= CheckOwnership(GetTileOwner(dp
->xy
));
816 if (ret
.Failed()) return ret
;
820 if (!IsRailDepotTile(dp
->xy
)) return CMD_ERROR
;
824 if (!IsRoadDepotTile(dp
->xy
)) return CMD_ERROR
;
828 if (!IsShipDepotTile(dp
->xy
)) return CMD_ERROR
;
831 default: return CMD_ERROR
;
836 if (new_order
.GetNonStopType() != ONSF_STOP_EVERYWHERE
&& !v
->IsGroundVehicle()) return CMD_ERROR
;
837 if (new_order
.GetDepotOrderType() & ~(ODTFB_PART_OF_ORDERS
| ((new_order
.GetDepotOrderType() & ODTFB_PART_OF_ORDERS
) != 0 ? ODTFB_SERVICE
: 0))) return CMD_ERROR
;
838 if (new_order
.GetDepotActionType() & ~(ODATFB_HALT
| ODATFB_NEAREST_DEPOT
)) return CMD_ERROR
;
839 if ((new_order
.GetDepotOrderType() & ODTFB_SERVICE
) && (new_order
.GetDepotActionType() & ODATFB_HALT
)) return CMD_ERROR
;
843 case OT_GOTO_WAYPOINT
: {
844 const Waypoint
*wp
= Waypoint::GetIfValid(new_order
.GetDestination());
845 if (wp
== nullptr) return CMD_ERROR
;
848 default: return CMD_ERROR
;
851 if (!(wp
->facilities
& FACIL_TRAIN
)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER
);
853 CommandCost ret
= CheckOwnership(wp
->owner
);
854 if (ret
.Failed()) return ret
;
859 if (!(wp
->facilities
& FACIL_DOCK
)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER
);
860 if (wp
->owner
!= OWNER_NONE
) {
861 CommandCost ret
= CheckOwnership(wp
->owner
);
862 if (ret
.Failed()) return ret
;
867 /* Order flags can be any of the following for waypoints:
869 * non-stop orders (if any) are only valid for trains */
870 if (new_order
.GetNonStopType() != ONSF_STOP_EVERYWHERE
&& v
->type
!= VEH_TRAIN
) return CMD_ERROR
;
874 case OT_CONDITIONAL
: {
875 VehicleOrderID skip_to
= new_order
.GetConditionSkipToOrder();
876 if (skip_to
!= 0 && skip_to
>= v
->GetNumOrders()) return CMD_ERROR
; // Always allow jumping to the first (even when there is no order).
877 if (new_order
.GetConditionVariable() >= OCV_END
) return CMD_ERROR
;
879 OrderConditionComparator occ
= new_order
.GetConditionComparator();
880 if (occ
>= OCC_END
) return CMD_ERROR
;
881 switch (new_order
.GetConditionVariable()) {
882 case OCV_REQUIRES_SERVICE
:
883 if (occ
!= OCC_IS_TRUE
&& occ
!= OCC_IS_FALSE
) return CMD_ERROR
;
886 case OCV_UNCONDITIONALLY
:
887 if (occ
!= OCC_EQUALS
) return CMD_ERROR
;
888 if (new_order
.GetConditionValue() != 0) return CMD_ERROR
;
891 case OCV_LOAD_PERCENTAGE
:
892 case OCV_RELIABILITY
:
893 if (new_order
.GetConditionValue() > 100) return CMD_ERROR
;
897 if (occ
== OCC_IS_TRUE
|| occ
== OCC_IS_FALSE
) return CMD_ERROR
;
903 default: return CMD_ERROR
;
906 if (sel_ord
> v
->GetNumOrders()) return CMD_ERROR
;
908 if (v
->GetNumOrders() >= MAX_VEH_ORDER_ID
) return_cmd_error(STR_ERROR_TOO_MANY_ORDERS
);
909 if (!Order::CanAllocateItem()) return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS
);
910 if (v
->orders
.list
== nullptr && !OrderList::CanAllocateItem()) return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS
);
912 if (flags
& DC_EXEC
) {
913 Order
*new_o
= new Order();
914 new_o
->AssignOrder(new_order
);
915 InsertOrder(v
, new_o
, sel_ord
);
918 return CommandCost();
922 * Insert a new order but skip the validation.
923 * @param v The vehicle to insert the order to.
924 * @param new_o The new order.
925 * @param sel_ord The position the order should be inserted at.
927 void InsertOrder(Vehicle
*v
, Order
*new_o
, VehicleOrderID sel_ord
)
929 /* Create new order and link in list */
930 if (v
->orders
.list
== nullptr) {
931 v
->orders
.list
= new OrderList(new_o
, v
);
933 v
->orders
.list
->InsertOrderAt(new_o
, sel_ord
);
936 Vehicle
*u
= v
->FirstShared();
937 DeleteOrderWarnings(u
);
938 for (; u
!= nullptr; u
= u
->NextShared()) {
939 assert(v
->orders
.list
== u
->orders
.list
);
941 /* If there is added an order before the current one, we need
942 * to update the selected order. We do not change implicit/real order indices though.
943 * If the new order is between the current implicit order and real order, the implicit order will
944 * later skip the inserted order. */
945 if (sel_ord
<= u
->cur_real_order_index
) {
946 uint cur
= u
->cur_real_order_index
+ 1;
947 /* Check if we don't go out of bound */
948 if (cur
< u
->GetNumOrders()) {
949 u
->cur_real_order_index
= cur
;
952 if (sel_ord
== u
->cur_implicit_order_index
&& u
->IsGroundVehicle()) {
953 /* We are inserting an order just before the current implicit order.
954 * We do not know whether we will reach current implicit or the newly inserted order first.
955 * So, disable creation of implicit orders until we are on track again. */
956 uint16
&gv_flags
= u
->GetGroundVehicleFlags();
957 SetBit(gv_flags
, GVF_SUPPRESS_IMPLICIT_ORDERS
);
959 if (sel_ord
<= u
->cur_implicit_order_index
) {
960 uint cur
= u
->cur_implicit_order_index
+ 1;
961 /* Check if we don't go out of bound */
962 if (cur
< u
->GetNumOrders()) {
963 u
->cur_implicit_order_index
= cur
;
966 /* Update any possible open window of the vehicle */
967 InvalidateVehicleOrder(u
, INVALID_VEH_ORDER_ID
| (sel_ord
<< 8));
970 /* As we insert an order, the order to skip to will be 'wrong'. */
971 VehicleOrderID cur_order_id
= 0;
972 for (Order
*order
: v
->Orders()) {
973 if (order
->IsType(OT_CONDITIONAL
)) {
974 VehicleOrderID order_id
= order
->GetConditionSkipToOrder();
975 if (order_id
>= sel_ord
) {
976 order
->SetConditionSkipToOrder(order_id
+ 1);
978 if (order_id
== cur_order_id
) {
979 order
->SetConditionSkipToOrder((order_id
+ 1) % v
->GetNumOrders());
985 /* Make sure to rebuild the whole list */
986 InvalidateWindowClassesData(GetWindowClassForVehicleType(v
->type
), 0);
990 * Declone an order-list
991 * @param *dst delete the orders of this vehicle
992 * @param flags execution flags
994 static CommandCost
DecloneOrder(Vehicle
*dst
, DoCommandFlag flags
)
996 if (flags
& DC_EXEC
) {
997 DeleteVehicleOrders(dst
);
998 InvalidateVehicleOrder(dst
, VIWD_REMOVE_ALL_ORDERS
);
999 InvalidateWindowClassesData(GetWindowClassForVehicleType(dst
->type
), 0);
1001 return CommandCost();
1005 * Delete an order from the orderlist of a vehicle.
1006 * @param tile unused
1007 * @param flags operation to perform
1008 * @param p1 the ID of the vehicle
1009 * @param p2 the order to delete (max 255)
1010 * @param text unused
1011 * @return the cost of this operation or an error
1013 CommandCost
CmdDeleteOrder(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const std::string
&text
)
1015 VehicleID veh_id
= GB(p1
, 0, 20);
1016 VehicleOrderID sel_ord
= GB(p2
, 0, 8);
1018 Vehicle
*v
= Vehicle::GetIfValid(veh_id
);
1020 if (v
== nullptr || !v
->IsPrimaryVehicle()) return CMD_ERROR
;
1022 CommandCost ret
= CheckOwnership(v
->owner
);
1023 if (ret
.Failed()) return ret
;
1025 /* If we did not select an order, we maybe want to de-clone the orders */
1026 if (sel_ord
>= v
->GetNumOrders()) return DecloneOrder(v
, flags
);
1028 if (v
->GetOrder(sel_ord
) == nullptr) return CMD_ERROR
;
1030 if (flags
& DC_EXEC
) DeleteOrder(v
, sel_ord
);
1031 return CommandCost();
1035 * Cancel the current loading order of the vehicle as the order was deleted.
1036 * @param v the vehicle
1038 static void CancelLoadingDueToDeletedOrder(Vehicle
*v
)
1040 assert(v
->current_order
.IsType(OT_LOADING
));
1041 /* NON-stop flag is misused to see if a train is in a station that is
1042 * on its order list or not */
1043 v
->current_order
.SetNonStopType(ONSF_STOP_EVERYWHERE
);
1044 /* When full loading, "cancel" that order so the vehicle doesn't
1045 * stay indefinitely at this station anymore. */
1046 if (v
->current_order
.GetLoadType() & OLFB_FULL_LOAD
) v
->current_order
.SetLoadType(OLF_LOAD_IF_POSSIBLE
);
1050 * Delete an order but skip the parameter validation.
1051 * @param v The vehicle to delete the order from.
1052 * @param sel_ord The id of the order to be deleted.
1054 void DeleteOrder(Vehicle
*v
, VehicleOrderID sel_ord
)
1056 v
->orders
.list
->DeleteOrderAt(sel_ord
);
1058 Vehicle
*u
= v
->FirstShared();
1059 DeleteOrderWarnings(u
);
1060 for (; u
!= nullptr; u
= u
->NextShared()) {
1061 assert(v
->orders
.list
== u
->orders
.list
);
1063 if (sel_ord
== u
->cur_real_order_index
&& u
->current_order
.IsType(OT_LOADING
)) {
1064 CancelLoadingDueToDeletedOrder(u
);
1067 if (sel_ord
< u
->cur_real_order_index
) {
1068 u
->cur_real_order_index
--;
1069 } else if (sel_ord
== u
->cur_real_order_index
) {
1070 u
->UpdateRealOrderIndex();
1073 if (sel_ord
< u
->cur_implicit_order_index
) {
1074 u
->cur_implicit_order_index
--;
1075 } else if (sel_ord
== u
->cur_implicit_order_index
) {
1076 /* Make sure the index is valid */
1077 if (u
->cur_implicit_order_index
>= u
->GetNumOrders()) u
->cur_implicit_order_index
= 0;
1079 /* Skip non-implicit orders for the implicit-order-index (e.g. if the current implicit order was deleted */
1080 while (u
->cur_implicit_order_index
!= u
->cur_real_order_index
&& !u
->GetOrder(u
->cur_implicit_order_index
)->IsType(OT_IMPLICIT
)) {
1081 u
->cur_implicit_order_index
++;
1082 if (u
->cur_implicit_order_index
>= u
->GetNumOrders()) u
->cur_implicit_order_index
= 0;
1086 /* Update any possible open window of the vehicle */
1087 InvalidateVehicleOrder(u
, sel_ord
| (INVALID_VEH_ORDER_ID
<< 8));
1090 /* As we delete an order, the order to skip to will be 'wrong'. */
1091 VehicleOrderID cur_order_id
= 0;
1092 for (Order
*order
: v
->Orders()) {
1093 if (order
->IsType(OT_CONDITIONAL
)) {
1094 VehicleOrderID order_id
= order
->GetConditionSkipToOrder();
1095 if (order_id
>= sel_ord
) {
1096 order_id
= std::max(order_id
- 1, 0);
1098 if (order_id
== cur_order_id
) {
1099 order_id
= (order_id
+ 1) % v
->GetNumOrders();
1101 order
->SetConditionSkipToOrder(order_id
);
1106 InvalidateWindowClassesData(GetWindowClassForVehicleType(v
->type
), 0);
1110 * Goto order of order-list.
1111 * @param tile unused
1112 * @param flags operation to perform
1113 * @param p1 The ID of the vehicle which order is skipped
1114 * @param p2 the selected order to which we want to skip
1115 * @param text unused
1116 * @return the cost of this operation or an error
1118 CommandCost
CmdSkipToOrder(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const std::string
&text
)
1120 VehicleID veh_id
= GB(p1
, 0, 20);
1121 VehicleOrderID sel_ord
= GB(p2
, 0, 8);
1123 Vehicle
*v
= Vehicle::GetIfValid(veh_id
);
1125 if (v
== nullptr || !v
->IsPrimaryVehicle() || sel_ord
== v
->cur_implicit_order_index
|| sel_ord
>= v
->GetNumOrders() || v
->GetNumOrders() < 2) return CMD_ERROR
;
1127 CommandCost ret
= CheckOwnership(v
->owner
);
1128 if (ret
.Failed()) return ret
;
1130 if (flags
& DC_EXEC
) {
1131 if (v
->current_order
.IsType(OT_LOADING
)) v
->LeaveStation();
1133 v
->cur_implicit_order_index
= v
->cur_real_order_index
= sel_ord
;
1134 v
->UpdateRealOrderIndex();
1136 InvalidateVehicleOrder(v
, VIWD_MODIFY_ORDERS
);
1139 /* We have an aircraft/ship, they have a mini-schedule, so update them all */
1140 if (v
->type
== VEH_AIRCRAFT
) SetWindowClassesDirty(WC_AIRCRAFT_LIST
);
1141 if (v
->type
== VEH_SHIP
) SetWindowClassesDirty(WC_SHIPS_LIST
);
1143 return CommandCost();
1147 * Move an order inside the orderlist
1148 * @param tile unused
1149 * @param flags operation to perform
1150 * @param p1 the ID of the vehicle
1151 * @param p2 order to move and target
1152 * bit 0-15 : the order to move
1153 * bit 16-31 : the target order
1154 * @param text unused
1155 * @return the cost of this operation or an error
1156 * @note The target order will move one place down in the orderlist
1157 * if you move the order upwards else it'll move it one place down
1159 CommandCost
CmdMoveOrder(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const std::string
&text
)
1161 VehicleID veh
= GB(p1
, 0, 20);
1162 VehicleOrderID moving_order
= GB(p2
, 0, 16);
1163 VehicleOrderID target_order
= GB(p2
, 16, 16);
1165 Vehicle
*v
= Vehicle::GetIfValid(veh
);
1166 if (v
== nullptr || !v
->IsPrimaryVehicle()) return CMD_ERROR
;
1168 CommandCost ret
= CheckOwnership(v
->owner
);
1169 if (ret
.Failed()) return ret
;
1171 /* Don't make senseless movements */
1172 if (moving_order
>= v
->GetNumOrders() || target_order
>= v
->GetNumOrders() ||
1173 moving_order
== target_order
|| v
->GetNumOrders() <= 1) return CMD_ERROR
;
1175 Order
*moving_one
= v
->GetOrder(moving_order
);
1176 /* Don't move an empty order */
1177 if (moving_one
== nullptr) return CMD_ERROR
;
1179 if (flags
& DC_EXEC
) {
1180 v
->orders
.list
->MoveOrder(moving_order
, target_order
);
1182 /* Update shared list */
1183 Vehicle
*u
= v
->FirstShared();
1185 DeleteOrderWarnings(u
);
1187 for (; u
!= nullptr; u
= u
->NextShared()) {
1188 /* Update the current order.
1189 * There are multiple ways to move orders, which result in cur_implicit_order_index
1190 * and cur_real_order_index to not longer make any sense. E.g. moving another
1191 * real order between them.
1193 * Basically one could choose to preserve either of them, but not both.
1194 * While both ways are suitable in this or that case from a human point of view, neither
1195 * of them makes really sense.
1196 * However, from an AI point of view, preserving cur_real_order_index is the most
1197 * predictable and transparent behaviour.
1199 * With that decision it basically does not matter what we do to cur_implicit_order_index.
1200 * If we change orders between the implicit- and real-index, the implicit orders are mostly likely
1201 * completely out-dated anyway. So, keep it simple and just keep cur_implicit_order_index as well.
1202 * The worst which can happen is that a lot of implicit orders are removed when reaching current_order.
1204 if (u
->cur_real_order_index
== moving_order
) {
1205 u
->cur_real_order_index
= target_order
;
1206 } else if (u
->cur_real_order_index
> moving_order
&& u
->cur_real_order_index
<= target_order
) {
1207 u
->cur_real_order_index
--;
1208 } else if (u
->cur_real_order_index
< moving_order
&& u
->cur_real_order_index
>= target_order
) {
1209 u
->cur_real_order_index
++;
1212 if (u
->cur_implicit_order_index
== moving_order
) {
1213 u
->cur_implicit_order_index
= target_order
;
1214 } else if (u
->cur_implicit_order_index
> moving_order
&& u
->cur_implicit_order_index
<= target_order
) {
1215 u
->cur_implicit_order_index
--;
1216 } else if (u
->cur_implicit_order_index
< moving_order
&& u
->cur_implicit_order_index
>= target_order
) {
1217 u
->cur_implicit_order_index
++;
1220 assert(v
->orders
.list
== u
->orders
.list
);
1221 /* Update any possible open window of the vehicle */
1222 InvalidateVehicleOrder(u
, moving_order
| (target_order
<< 8));
1225 /* As we move an order, the order to skip to will be 'wrong'. */
1226 for (Order
*order
: v
->Orders()) {
1227 if (order
->IsType(OT_CONDITIONAL
)) {
1228 VehicleOrderID order_id
= order
->GetConditionSkipToOrder();
1229 if (order_id
== moving_order
) {
1230 order_id
= target_order
;
1231 } else if (order_id
> moving_order
&& order_id
<= target_order
) {
1233 } else if (order_id
< moving_order
&& order_id
>= target_order
) {
1236 order
->SetConditionSkipToOrder(order_id
);
1240 /* Make sure to rebuild the whole list */
1241 InvalidateWindowClassesData(GetWindowClassForVehicleType(v
->type
), 0);
1244 return CommandCost();
1248 * Modify an order in the orderlist of a vehicle.
1249 * @param tile unused
1250 * @param flags operation to perform
1251 * @param p1 various bitstuffed elements
1252 * - p1 = (bit 0 - 19) - ID of the vehicle
1253 * - p1 = (bit 24 - 31) - the selected order (if any). If the last order is given,
1254 * the order will be inserted before that one
1255 * the maximum vehicle order id is 254.
1256 * @param p2 various bitstuffed elements
1257 * - p2 = (bit 0 - 3) - what data to modify (@see ModifyOrderFlags)
1258 * - p2 = (bit 4 - 15) - the data to modify
1259 * @param text unused
1260 * @return the cost of this operation or an error
1262 CommandCost
CmdModifyOrder(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const std::string
&text
)
1264 VehicleOrderID sel_ord
= GB(p1
, 20, 8);
1265 VehicleID veh
= GB(p1
, 0, 20);
1266 ModifyOrderFlags mof
= Extract
<ModifyOrderFlags
, 0, 4>(p2
);
1267 uint16 data
= GB(p2
, 4, 11);
1269 if (mof
>= MOF_END
) return CMD_ERROR
;
1271 Vehicle
*v
= Vehicle::GetIfValid(veh
);
1272 if (v
== nullptr || !v
->IsPrimaryVehicle()) return CMD_ERROR
;
1274 CommandCost ret
= CheckOwnership(v
->owner
);
1275 if (ret
.Failed()) return ret
;
1277 /* Is it a valid order? */
1278 if (sel_ord
>= v
->GetNumOrders()) return CMD_ERROR
;
1280 Order
*order
= v
->GetOrder(sel_ord
);
1281 switch (order
->GetType()) {
1282 case OT_GOTO_STATION
:
1283 if (mof
!= MOF_NON_STOP
&& mof
!= MOF_STOP_LOCATION
&& mof
!= MOF_UNLOAD
&& mof
!= MOF_LOAD
) return CMD_ERROR
;
1287 if (mof
!= MOF_NON_STOP
&& mof
!= MOF_DEPOT_ACTION
) return CMD_ERROR
;
1290 case OT_GOTO_WAYPOINT
:
1291 if (mof
!= MOF_NON_STOP
) return CMD_ERROR
;
1294 case OT_CONDITIONAL
:
1295 if (mof
!= MOF_COND_VARIABLE
&& mof
!= MOF_COND_COMPARATOR
&& mof
!= MOF_COND_VALUE
&& mof
!= MOF_COND_DESTINATION
) return CMD_ERROR
;
1303 default: NOT_REACHED();
1306 if (!v
->IsGroundVehicle()) return CMD_ERROR
;
1307 if (data
>= ONSF_END
) return CMD_ERROR
;
1308 if (data
== order
->GetNonStopType()) return CMD_ERROR
;
1311 case MOF_STOP_LOCATION
:
1312 if (v
->type
!= VEH_TRAIN
) return CMD_ERROR
;
1313 if (data
>= OSL_END
) return CMD_ERROR
;
1317 if (order
->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION
) return CMD_ERROR
;
1318 if ((data
& ~(OUFB_UNLOAD
| OUFB_TRANSFER
| OUFB_NO_UNLOAD
)) != 0) return CMD_ERROR
;
1319 /* Unload and no-unload are mutual exclusive and so are transfer and no unload. */
1320 if (data
!= 0 && ((data
& (OUFB_UNLOAD
| OUFB_TRANSFER
)) != 0) == ((data
& OUFB_NO_UNLOAD
) != 0)) return CMD_ERROR
;
1321 if (data
== order
->GetUnloadType()) return CMD_ERROR
;
1325 if (order
->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION
) return CMD_ERROR
;
1326 if (data
> OLFB_NO_LOAD
|| data
== 1) return CMD_ERROR
;
1327 if (data
== order
->GetLoadType()) return CMD_ERROR
;
1330 case MOF_DEPOT_ACTION
:
1331 if (data
>= DA_END
) return CMD_ERROR
;
1334 case MOF_COND_VARIABLE
:
1335 if (data
>= OCV_END
) return CMD_ERROR
;
1338 case MOF_COND_COMPARATOR
:
1339 if (data
>= OCC_END
) return CMD_ERROR
;
1340 switch (order
->GetConditionVariable()) {
1341 case OCV_UNCONDITIONALLY
: return CMD_ERROR
;
1343 case OCV_REQUIRES_SERVICE
:
1344 if (data
!= OCC_IS_TRUE
&& data
!= OCC_IS_FALSE
) return CMD_ERROR
;
1348 if (data
== OCC_IS_TRUE
|| data
== OCC_IS_FALSE
) return CMD_ERROR
;
1353 case MOF_COND_VALUE
:
1354 switch (order
->GetConditionVariable()) {
1355 case OCV_UNCONDITIONALLY
:
1356 case OCV_REQUIRES_SERVICE
:
1359 case OCV_LOAD_PERCENTAGE
:
1360 case OCV_RELIABILITY
:
1361 if (data
> 100) return CMD_ERROR
;
1365 if (data
> 2047) return CMD_ERROR
;
1370 case MOF_COND_DESTINATION
:
1371 if (data
>= v
->GetNumOrders()) return CMD_ERROR
;
1375 if (flags
& DC_EXEC
) {
1378 order
->SetNonStopType((OrderNonStopFlags
)data
);
1379 if (data
& ONSF_NO_STOP_AT_DESTINATION_STATION
) {
1380 order
->SetRefit(CT_NO_REFIT
);
1381 order
->SetLoadType(OLF_LOAD_IF_POSSIBLE
);
1382 order
->SetUnloadType(OUF_UNLOAD_IF_POSSIBLE
);
1386 case MOF_STOP_LOCATION
:
1387 order
->SetStopLocation((OrderStopLocation
)data
);
1391 order
->SetUnloadType((OrderUnloadFlags
)data
);
1395 order
->SetLoadType((OrderLoadFlags
)data
);
1396 if (data
& OLFB_NO_LOAD
) order
->SetRefit(CT_NO_REFIT
);
1399 case MOF_DEPOT_ACTION
: {
1402 order
->SetDepotOrderType((OrderDepotTypeFlags
)(order
->GetDepotOrderType() & ~ODTFB_SERVICE
));
1403 order
->SetDepotActionType((OrderDepotActionFlags
)(order
->GetDepotActionType() & ~ODATFB_HALT
));
1407 order
->SetDepotOrderType((OrderDepotTypeFlags
)(order
->GetDepotOrderType() | ODTFB_SERVICE
));
1408 order
->SetDepotActionType((OrderDepotActionFlags
)(order
->GetDepotActionType() & ~ODATFB_HALT
));
1409 order
->SetRefit(CT_NO_REFIT
);
1413 order
->SetDepotOrderType((OrderDepotTypeFlags
)(order
->GetDepotOrderType() & ~ODTFB_SERVICE
));
1414 order
->SetDepotActionType((OrderDepotActionFlags
)(order
->GetDepotActionType() | ODATFB_HALT
));
1415 order
->SetRefit(CT_NO_REFIT
);
1424 case MOF_COND_VARIABLE
: {
1425 order
->SetConditionVariable((OrderConditionVariable
)data
);
1427 OrderConditionComparator occ
= order
->GetConditionComparator();
1428 switch (order
->GetConditionVariable()) {
1429 case OCV_UNCONDITIONALLY
:
1430 order
->SetConditionComparator(OCC_EQUALS
);
1431 order
->SetConditionValue(0);
1434 case OCV_REQUIRES_SERVICE
:
1435 if (occ
!= OCC_IS_TRUE
&& occ
!= OCC_IS_FALSE
) order
->SetConditionComparator(OCC_IS_TRUE
);
1436 order
->SetConditionValue(0);
1439 case OCV_LOAD_PERCENTAGE
:
1440 case OCV_RELIABILITY
:
1441 if (order
->GetConditionValue() > 100) order
->SetConditionValue(100);
1445 if (occ
== OCC_IS_TRUE
|| occ
== OCC_IS_FALSE
) order
->SetConditionComparator(OCC_EQUALS
);
1451 case MOF_COND_COMPARATOR
:
1452 order
->SetConditionComparator((OrderConditionComparator
)data
);
1455 case MOF_COND_VALUE
:
1456 order
->SetConditionValue(data
);
1459 case MOF_COND_DESTINATION
:
1460 order
->SetConditionSkipToOrder(data
);
1463 default: NOT_REACHED();
1466 /* Update the windows and full load flags, also for vehicles that share the same order list */
1467 Vehicle
*u
= v
->FirstShared();
1468 DeleteOrderWarnings(u
);
1469 for (; u
!= nullptr; u
= u
->NextShared()) {
1470 /* Toggle u->current_order "Full load" flag if it changed.
1471 * However, as the same flag is used for depot orders, check
1472 * whether we are not going to a depot as there are three
1473 * cases where the full load flag can be active and only
1474 * one case where the flag is used for depot orders. In the
1475 * other cases for the OrderType the flags are not used,
1476 * so do not care and those orders should not be active
1477 * when this function is called.
1479 if (sel_ord
== u
->cur_real_order_index
&&
1480 (u
->current_order
.IsType(OT_GOTO_STATION
) || u
->current_order
.IsType(OT_LOADING
)) &&
1481 u
->current_order
.GetLoadType() != order
->GetLoadType()) {
1482 u
->current_order
.SetLoadType(order
->GetLoadType());
1484 InvalidateVehicleOrder(u
, VIWD_MODIFY_ORDERS
);
1488 return CommandCost();
1492 * Check if an aircraft has enough range for an order list.
1493 * @param v_new Aircraft to check.
1494 * @param v_order Vehicle currently holding the order list.
1495 * @param first First order in the source order list.
1496 * @return True if the aircraft has enough range for the orders, false otherwise.
1498 static bool CheckAircraftOrderDistance(const Aircraft
*v_new
, const Vehicle
*v_order
, const Order
*first
)
1500 if (first
== nullptr || v_new
->acache
.cached_max_range
== 0) return true;
1502 /* Iterate over all orders to check the distance between all
1503 * 'goto' orders and their respective next order (of any type). */
1504 for (const Order
*o
= first
; o
!= nullptr; o
= o
->next
) {
1505 switch (o
->GetType()) {
1506 case OT_GOTO_STATION
:
1508 case OT_GOTO_WAYPOINT
:
1509 /* If we don't have a next order, we've reached the end and must check the first order instead. */
1510 if (GetOrderDistance(o
, o
->next
!= nullptr ? o
->next
: first
, v_order
) > v_new
->acache
.cached_max_range_sqr
) return false;
1521 * Clone/share/copy an order-list of another vehicle.
1522 * @param tile unused
1523 * @param flags operation to perform
1524 * @param p1 various bitstuffed elements
1525 * - p1 = (bit 0-19) - destination vehicle to clone orders to
1526 * - p1 = (bit 30-31) - action to perform
1527 * @param p2 source vehicle to clone orders from, if any (none for CO_UNSHARE)
1528 * @param text unused
1529 * @return the cost of this operation or an error
1531 CommandCost
CmdCloneOrder(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const std::string
&text
)
1533 VehicleID veh_src
= GB(p2
, 0, 20);
1534 VehicleID veh_dst
= GB(p1
, 0, 20);
1536 Vehicle
*dst
= Vehicle::GetIfValid(veh_dst
);
1537 if (dst
== nullptr || !dst
->IsPrimaryVehicle()) return CMD_ERROR
;
1539 CommandCost ret
= CheckOwnership(dst
->owner
);
1540 if (ret
.Failed()) return ret
;
1542 switch (GB(p1
, 30, 2)) {
1544 Vehicle
*src
= Vehicle::GetIfValid(veh_src
);
1547 if (src
== nullptr || !src
->IsPrimaryVehicle() || dst
->type
!= src
->type
|| dst
== src
) return CMD_ERROR
;
1549 CommandCost ret
= CheckOwnership(src
->owner
);
1550 if (ret
.Failed()) return ret
;
1552 /* Trucks can't share orders with busses (and visa versa) */
1553 if (src
->type
== VEH_ROAD
&& RoadVehicle::From(src
)->IsBus() != RoadVehicle::From(dst
)->IsBus()) {
1557 /* Is the vehicle already in the shared list? */
1558 if (src
->FirstShared() == dst
->FirstShared()) return CMD_ERROR
;
1560 for (const Order
*order
: src
->Orders()) {
1561 if (!OrderGoesToStation(dst
, order
)) continue;
1563 /* Allow copying unreachable destinations if they were already unreachable for the source.
1564 * This is basically to allow cloning / autorenewing / autoreplacing vehicles, while the stations
1565 * are temporarily invalid due to reconstruction. */
1566 const Station
*st
= Station::Get(order
->GetDestination());
1567 if (CanVehicleUseStation(src
, st
) && !CanVehicleUseStation(dst
, st
)) {
1568 return_cmd_error(STR_ERROR_CAN_T_COPY_SHARE_ORDER
);
1572 /* Check for aircraft range limits. */
1573 if (dst
->type
== VEH_AIRCRAFT
&& !CheckAircraftOrderDistance(Aircraft::From(dst
), src
, src
->GetFirstOrder())) {
1574 return_cmd_error(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE
);
1577 if (src
->orders
.list
== nullptr && !OrderList::CanAllocateItem()) {
1578 return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS
);
1581 if (flags
& DC_EXEC
) {
1582 /* If the destination vehicle had a OrderList, destroy it.
1583 * We only reset the order indices, if the new orders are obviously different.
1584 * (We mainly do this to keep the order indices valid and in range.) */
1585 DeleteVehicleOrders(dst
, false, dst
->GetNumOrders() != src
->GetNumOrders());
1587 dst
->orders
.list
= src
->orders
.list
;
1589 /* Link this vehicle in the shared-list */
1590 dst
->AddToShared(src
);
1592 InvalidateVehicleOrder(dst
, VIWD_REMOVE_ALL_ORDERS
);
1593 InvalidateVehicleOrder(src
, VIWD_MODIFY_ORDERS
);
1595 InvalidateWindowClassesData(GetWindowClassForVehicleType(dst
->type
), 0);
1601 Vehicle
*src
= Vehicle::GetIfValid(veh_src
);
1604 if (src
== nullptr || !src
->IsPrimaryVehicle() || dst
->type
!= src
->type
|| dst
== src
) return CMD_ERROR
;
1606 CommandCost ret
= CheckOwnership(src
->owner
);
1607 if (ret
.Failed()) return ret
;
1609 /* Trucks can't copy all the orders from busses (and visa versa),
1610 * and neither can helicopters and aircraft. */
1611 for (const Order
*order
: src
->Orders()) {
1612 if (OrderGoesToStation(dst
, order
) &&
1613 !CanVehicleUseStation(dst
, Station::Get(order
->GetDestination()))) {
1614 return_cmd_error(STR_ERROR_CAN_T_COPY_SHARE_ORDER
);
1618 /* Check for aircraft range limits. */
1619 if (dst
->type
== VEH_AIRCRAFT
&& !CheckAircraftOrderDistance(Aircraft::From(dst
), src
, src
->GetFirstOrder())) {
1620 return_cmd_error(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE
);
1623 /* make sure there are orders available */
1624 if (!Order::CanAllocateItem(src
->GetNumOrders()) || !OrderList::CanAllocateItem()) {
1625 return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS
);
1628 if (flags
& DC_EXEC
) {
1629 Order
*first
= nullptr;
1632 /* If the destination vehicle had an order list, destroy the chain but keep the OrderList.
1633 * We only reset the order indices, if the new orders are obviously different.
1634 * (We mainly do this to keep the order indices valid and in range.) */
1635 DeleteVehicleOrders(dst
, true, dst
->GetNumOrders() != src
->GetNumOrders());
1638 for (const Order
*order
: src
->Orders()) {
1639 *order_dst
= new Order();
1640 (*order_dst
)->AssignOrder(*order
);
1641 order_dst
= &(*order_dst
)->next
;
1643 if (dst
->orders
.list
== nullptr) {
1644 dst
->orders
.list
= new OrderList(first
, dst
);
1646 assert(dst
->orders
.list
->GetFirstOrder() == nullptr);
1647 assert(!dst
->orders
.list
->IsShared());
1648 delete dst
->orders
.list
;
1649 assert(OrderList::CanAllocateItem());
1650 dst
->orders
.list
= new OrderList(first
, dst
);
1653 InvalidateVehicleOrder(dst
, VIWD_REMOVE_ALL_ORDERS
);
1655 InvalidateWindowClassesData(GetWindowClassForVehicleType(dst
->type
), 0);
1660 case CO_UNSHARE
: return DecloneOrder(dst
, flags
);
1661 default: return CMD_ERROR
;
1664 return CommandCost();
1668 * Add/remove refit orders from an order
1669 * @param tile Not used
1670 * @param flags operation to perform
1671 * @param p1 VehicleIndex of the vehicle having the order
1674 * - bit 16-23 number of order to modify
1675 * @param text unused
1676 * @return the cost of this operation or an error
1678 CommandCost
CmdOrderRefit(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const std::string
&text
)
1680 VehicleID veh
= GB(p1
, 0, 20);
1681 VehicleOrderID order_number
= GB(p2
, 16, 8);
1682 CargoID cargo
= GB(p2
, 0, 8);
1684 if (cargo
>= NUM_CARGO
&& cargo
!= CT_NO_REFIT
&& cargo
!= CT_AUTO_REFIT
) return CMD_ERROR
;
1686 const Vehicle
*v
= Vehicle::GetIfValid(veh
);
1687 if (v
== nullptr || !v
->IsPrimaryVehicle()) return CMD_ERROR
;
1689 CommandCost ret
= CheckOwnership(v
->owner
);
1690 if (ret
.Failed()) return ret
;
1692 Order
*order
= v
->GetOrder(order_number
);
1693 if (order
== nullptr) return CMD_ERROR
;
1695 /* Automatic refit cargo is only supported for goto station orders. */
1696 if (cargo
== CT_AUTO_REFIT
&& !order
->IsType(OT_GOTO_STATION
)) return CMD_ERROR
;
1698 if (order
->GetLoadType() & OLFB_NO_LOAD
) return CMD_ERROR
;
1700 if (flags
& DC_EXEC
) {
1701 order
->SetRefit(cargo
);
1703 /* Make the depot order an 'always go' order. */
1704 if (cargo
!= CT_NO_REFIT
&& order
->IsType(OT_GOTO_DEPOT
)) {
1705 order
->SetDepotOrderType((OrderDepotTypeFlags
)(order
->GetDepotOrderType() & ~ODTFB_SERVICE
));
1706 order
->SetDepotActionType((OrderDepotActionFlags
)(order
->GetDepotActionType() & ~ODATFB_HALT
));
1709 for (Vehicle
*u
= v
->FirstShared(); u
!= nullptr; u
= u
->NextShared()) {
1710 /* Update any possible open window of the vehicle */
1711 InvalidateVehicleOrder(u
, VIWD_MODIFY_ORDERS
);
1713 /* If the vehicle already got the current depot set as current order, then update current order as well */
1714 if (u
->cur_real_order_index
== order_number
&& (u
->current_order
.GetDepotOrderType() & ODTFB_PART_OF_ORDERS
)) {
1715 u
->current_order
.SetRefit(cargo
);
1720 return CommandCost();
1726 * Check the orders of a vehicle, to see if there are invalid orders and stuff
1729 void CheckOrders(const Vehicle
*v
)
1731 /* Does the user wants us to check things? */
1732 if (_settings_client
.gui
.order_review_system
== 0) return;
1734 /* Do nothing for crashed vehicles */
1735 if (v
->vehstatus
& VS_CRASHED
) return;
1737 /* Do nothing for stopped vehicles if setting is '1' */
1738 if (_settings_client
.gui
.order_review_system
== 1 && (v
->vehstatus
& VS_STOPPED
)) return;
1740 /* do nothing we we're not the first vehicle in a share-chain */
1741 if (v
->FirstShared() != v
) return;
1743 /* Only check every 20 days, so that we don't flood the message log */
1744 if (v
->owner
== _local_company
&& v
->day_counter
% 20 == 0) {
1745 StringID message
= INVALID_STRING_ID
;
1747 /* Check the order list */
1750 for (const Order
*order
: v
->Orders()) {
1752 if (order
->IsType(OT_DUMMY
)) {
1753 message
= STR_NEWS_VEHICLE_HAS_VOID_ORDER
;
1756 /* Does station have a load-bay for this vehicle? */
1757 if (order
->IsType(OT_GOTO_STATION
)) {
1758 const Station
*st
= Station::Get(order
->GetDestination());
1761 if (!CanVehicleUseStation(v
, st
)) {
1762 message
= STR_NEWS_VEHICLE_HAS_INVALID_ENTRY
;
1763 } else if (v
->type
== VEH_AIRCRAFT
&&
1764 (AircraftVehInfo(v
->engine_type
)->subtype
& AIR_FAST
) &&
1765 (st
->airport
.GetFTA()->flags
& AirportFTAClass::SHORT_STRIP
) &&
1766 !_cheats
.no_jetcrash
.value
&&
1767 message
== INVALID_STRING_ID
) {
1768 message
= STR_NEWS_PLANE_USES_TOO_SHORT_RUNWAY
;
1773 /* Check if the last and the first order are the same */
1774 if (v
->GetNumOrders() > 1) {
1775 const Order
*last
= v
->GetLastOrder();
1777 if (v
->orders
.list
->GetFirstOrder()->Equals(*last
)) {
1778 message
= STR_NEWS_VEHICLE_HAS_DUPLICATE_ENTRY
;
1782 /* Do we only have 1 station in our order list? */
1783 if (n_st
< 2 && message
== INVALID_STRING_ID
) message
= STR_NEWS_VEHICLE_HAS_TOO_FEW_ORDERS
;
1786 if (v
->orders
.list
!= nullptr) v
->orders
.list
->DebugCheckSanity();
1789 /* We don't have a problem */
1790 if (message
== INVALID_STRING_ID
) return;
1792 SetDParam(0, v
->index
);
1793 AddVehicleAdviceNewsItem(message
, v
->index
);
1798 * Removes an order from all vehicles. Triggers when, say, a station is removed.
1799 * @param type The type of the order (OT_GOTO_[STATION|DEPOT|WAYPOINT]).
1800 * @param destination The destination. Can be a StationID, DepotID or WaypointID.
1801 * @param hangar Only used for airports in the destination.
1802 * When false, remove airport and hangar orders.
1803 * When true, remove either airport or hangar order.
1805 void RemoveOrderFromAllVehicles(OrderType type
, DestinationID destination
, bool hangar
)
1807 /* Aircraft have StationIDs for depot orders and never use DepotIDs
1808 * This fact is handled specially below
1811 /* Go through all vehicles */
1812 for (Vehicle
*v
: Vehicle::Iterate()) {
1815 order
= &v
->current_order
;
1816 if ((v
->type
== VEH_AIRCRAFT
&& order
->IsType(OT_GOTO_DEPOT
) && !hangar
? OT_GOTO_STATION
: order
->GetType()) == type
&&
1817 (!hangar
|| v
->type
== VEH_AIRCRAFT
) && v
->current_order
.GetDestination() == destination
) {
1819 SetWindowDirty(WC_VEHICLE_VIEW
, v
->index
);
1822 /* Clear the order from the order-list */
1824 for (Order
*order
: v
->Orders()) {
1828 OrderType ot
= order
->GetType();
1829 if (ot
== OT_GOTO_DEPOT
&& (order
->GetDepotActionType() & ODATFB_NEAREST_DEPOT
) != 0) continue;
1830 if (ot
== OT_GOTO_DEPOT
&& hangar
&& v
->type
!= VEH_AIRCRAFT
) continue; // Not an aircraft? Can't have a hangar order.
1831 if (ot
== OT_IMPLICIT
|| (v
->type
== VEH_AIRCRAFT
&& ot
== OT_GOTO_DEPOT
&& !hangar
)) ot
= OT_GOTO_STATION
;
1832 if (ot
== type
&& order
->GetDestination() == destination
) {
1833 /* We want to clear implicit orders, but we don't want to make them
1834 * dummy orders. They should just vanish. Also check the actual order
1835 * type as ot is currently OT_GOTO_STATION. */
1836 if (order
->IsType(OT_IMPLICIT
)) {
1837 order
= order
->next
; // DeleteOrder() invalidates current order
1839 if (order
!= nullptr) goto restart
;
1843 /* Clear wait time */
1844 v
->orders
.list
->UpdateTotalDuration(-order
->GetWaitTime());
1845 if (order
->IsWaitTimetabled()) {
1846 v
->orders
.list
->UpdateTimetableDuration(-order
->GetTimetabledWait());
1847 order
->SetWaitTimetabled(false);
1849 order
->SetWaitTime(0);
1851 /* Clear order, preserving travel time */
1852 bool travel_timetabled
= order
->IsTravelTimetabled();
1854 order
->SetTravelTimetabled(travel_timetabled
);
1856 for (const Vehicle
*w
= v
->FirstShared(); w
!= nullptr; w
= w
->NextShared()) {
1857 /* In GUI, simulate by removing the order and adding it back */
1858 InvalidateVehicleOrder(w
, id
| (INVALID_VEH_ORDER_ID
<< 8));
1859 InvalidateVehicleOrder(w
, (INVALID_VEH_ORDER_ID
<< 8) | id
);
1865 OrderBackup::RemoveOrder(type
, destination
, hangar
);
1869 * Checks if a vehicle has a depot in its order list.
1870 * @return True iff at least one order is a depot order.
1872 bool Vehicle::HasDepotOrder() const
1874 for (const Order
*order
: this->Orders()) {
1875 if (order
->IsType(OT_GOTO_DEPOT
)) return true;
1882 * Delete all orders from a vehicle
1883 * @param v Vehicle whose orders to reset
1884 * @param keep_orderlist If true, do not free the order list, only empty it.
1885 * @param reset_order_indices If true, reset cur_implicit_order_index and cur_real_order_index
1886 * and cancel the current full load order (if the vehicle is loading).
1887 * If false, _you_ have to make sure the order indices are valid after
1888 * your messing with them!
1890 void DeleteVehicleOrders(Vehicle
*v
, bool keep_orderlist
, bool reset_order_indices
)
1892 DeleteOrderWarnings(v
);
1894 if (v
->IsOrderListShared()) {
1895 /* Remove ourself from the shared order list. */
1896 v
->RemoveFromShared();
1897 v
->orders
.list
= nullptr;
1898 } else if (v
->orders
.list
!= nullptr) {
1899 /* Remove the orders */
1900 v
->orders
.list
->FreeChain(keep_orderlist
);
1901 if (!keep_orderlist
) v
->orders
.list
= nullptr;
1904 if (reset_order_indices
) {
1905 v
->cur_implicit_order_index
= v
->cur_real_order_index
= 0;
1906 if (v
->current_order
.IsType(OT_LOADING
)) {
1907 CancelLoadingDueToDeletedOrder(v
);
1913 * Clamp the service interval to the correct min/max. The actual min/max values
1914 * depend on whether it's in percent or days.
1915 * @param interval proposed service interval
1916 * @return Clamped service interval
1918 uint16
GetServiceIntervalClamped(uint interval
, bool ispercent
)
1920 return ispercent
? Clamp(interval
, MIN_SERVINT_PERCENT
, MAX_SERVINT_PERCENT
) : Clamp(interval
, MIN_SERVINT_DAYS
, MAX_SERVINT_DAYS
);
1925 * Check if a vehicle has any valid orders
1927 * @return false if there are no valid orders
1928 * @note Conditional orders are not considered valid destination orders
1931 static bool CheckForValidOrders(const Vehicle
*v
)
1933 for (const Order
*order
: v
->Orders()) {
1934 switch (order
->GetType()) {
1935 case OT_GOTO_STATION
:
1937 case OT_GOTO_WAYPOINT
:
1949 * Compare the variable and value based on the given comparator.
1951 static bool OrderConditionCompare(OrderConditionComparator occ
, int variable
, int value
)
1954 case OCC_EQUALS
: return variable
== value
;
1955 case OCC_NOT_EQUALS
: return variable
!= value
;
1956 case OCC_LESS_THAN
: return variable
< value
;
1957 case OCC_LESS_EQUALS
: return variable
<= value
;
1958 case OCC_MORE_THAN
: return variable
> value
;
1959 case OCC_MORE_EQUALS
: return variable
>= value
;
1960 case OCC_IS_TRUE
: return variable
!= 0;
1961 case OCC_IS_FALSE
: return variable
== 0;
1962 default: NOT_REACHED();
1967 * Process a conditional order and determine the next order.
1968 * @param order the order the vehicle currently has
1969 * @param v the vehicle to update
1970 * @return index of next order to jump to, or INVALID_VEH_ORDER_ID to use the next order
1972 VehicleOrderID
ProcessConditionalOrder(const Order
*order
, const Vehicle
*v
)
1974 if (order
->GetType() != OT_CONDITIONAL
) return INVALID_VEH_ORDER_ID
;
1976 bool skip_order
= false;
1977 OrderConditionComparator occ
= order
->GetConditionComparator();
1978 uint16 value
= order
->GetConditionValue();
1980 switch (order
->GetConditionVariable()) {
1981 case OCV_LOAD_PERCENTAGE
: skip_order
= OrderConditionCompare(occ
, CalcPercentVehicleFilled(v
, nullptr), value
); break;
1982 case OCV_RELIABILITY
: skip_order
= OrderConditionCompare(occ
, ToPercent16(v
->reliability
), value
); break;
1983 case OCV_MAX_RELIABILITY
: skip_order
= OrderConditionCompare(occ
, ToPercent16(v
->GetEngine()->reliability
), value
); break;
1984 case OCV_MAX_SPEED
: skip_order
= OrderConditionCompare(occ
, v
->GetDisplayMaxSpeed() * 10 / 16, value
); break;
1985 case OCV_AGE
: skip_order
= OrderConditionCompare(occ
, v
->age
/ DAYS_IN_LEAP_YEAR
, value
); break;
1986 case OCV_REQUIRES_SERVICE
: skip_order
= OrderConditionCompare(occ
, v
->NeedsServicing(), value
); break;
1987 case OCV_UNCONDITIONALLY
: skip_order
= true; break;
1988 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;
1989 default: NOT_REACHED();
1992 return skip_order
? order
->GetConditionSkipToOrder() : (VehicleOrderID
)INVALID_VEH_ORDER_ID
;
1996 * Update the vehicle's destination tile from an order.
1997 * @param order the order the vehicle currently has
1998 * @param v the vehicle to update
1999 * @param conditional_depth the depth (amount of steps) to go with conditional orders. This to prevent infinite loops.
2000 * @param pbs_look_ahead Whether we are forecasting orders for pbs reservations in advance. If true, the order indices must not be modified.
2002 bool UpdateOrderDest(Vehicle
*v
, const Order
*order
, int conditional_depth
, bool pbs_look_ahead
)
2004 if (conditional_depth
> v
->GetNumOrders()) {
2005 v
->current_order
.Free();
2010 switch (order
->GetType()) {
2011 case OT_GOTO_STATION
:
2012 v
->SetDestTile(v
->GetOrderStationLocation(order
->GetDestination()));
2016 if ((order
->GetDepotOrderType() & ODTFB_SERVICE
) && !v
->NeedsServicing()) {
2017 assert(!pbs_look_ahead
);
2018 UpdateVehicleTimetable(v
, true);
2019 v
->IncrementRealOrderIndex();
2023 if (v
->current_order
.GetDepotActionType() & ODATFB_NEAREST_DEPOT
) {
2024 /* We need to search for the nearest depot (hangar). */
2026 DestinationID destination
;
2029 if (v
->FindClosestDepot(&location
, &destination
, &reverse
)) {
2030 /* PBS reservations cannot reverse */
2031 if (pbs_look_ahead
&& reverse
) return false;
2033 v
->SetDestTile(location
);
2034 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());
2036 /* If there is no depot in front, reverse automatically (trains only) */
2037 if (v
->type
== VEH_TRAIN
&& reverse
) DoCommand(v
->tile
, v
->index
, 0, DC_EXEC
, CMD_REVERSE_TRAIN_DIRECTION
);
2039 if (v
->type
== VEH_AIRCRAFT
) {
2040 Aircraft
*a
= Aircraft::From(v
);
2041 if (a
->state
== FLYING
&& a
->targetairport
!= destination
) {
2042 /* The aircraft is now heading for a different hangar than the next in the orders */
2043 extern void AircraftNextAirportPos_and_Order(Aircraft
*a
);
2044 AircraftNextAirportPos_and_Order(a
);
2050 /* If there is no depot, we cannot help PBS either. */
2051 if (pbs_look_ahead
) return false;
2053 UpdateVehicleTimetable(v
, true);
2054 v
->IncrementRealOrderIndex();
2056 if (v
->type
!= VEH_AIRCRAFT
) {
2057 v
->SetDestTile(Depot::Get(order
->GetDestination())->xy
);
2059 Aircraft
*a
= Aircraft::From(v
);
2060 DestinationID destination
= a
->current_order
.GetDestination();
2061 if (a
->targetairport
!= destination
) {
2062 /* The aircraft is now heading for a different hangar than the next in the orders */
2063 a
->SetDestTile(a
->GetOrderStationLocation(destination
));
2070 case OT_GOTO_WAYPOINT
:
2071 v
->SetDestTile(Waypoint::Get(order
->GetDestination())->xy
);
2074 case OT_CONDITIONAL
: {
2075 assert(!pbs_look_ahead
);
2076 VehicleOrderID next_order
= ProcessConditionalOrder(order
, v
);
2077 if (next_order
!= INVALID_VEH_ORDER_ID
) {
2078 /* Jump to next_order. cur_implicit_order_index becomes exactly that order,
2079 * cur_real_order_index might come after next_order. */
2080 UpdateVehicleTimetable(v
, false);
2081 v
->cur_implicit_order_index
= v
->cur_real_order_index
= next_order
;
2082 v
->UpdateRealOrderIndex();
2083 v
->current_order_time
+= v
->GetOrder(v
->cur_real_order_index
)->GetTimetabledTravel();
2085 /* Disable creation of implicit orders.
2086 * When inserting them we do not know that we would have to make the conditional orders point to them. */
2087 if (v
->IsGroundVehicle()) {
2088 uint16
&gv_flags
= v
->GetGroundVehicleFlags();
2089 SetBit(gv_flags
, GVF_SUPPRESS_IMPLICIT_ORDERS
);
2092 UpdateVehicleTimetable(v
, true);
2093 v
->IncrementRealOrderIndex();
2103 assert(v
->cur_implicit_order_index
< v
->GetNumOrders());
2104 assert(v
->cur_real_order_index
< v
->GetNumOrders());
2106 /* Get the current order */
2107 order
= v
->GetOrder(v
->cur_real_order_index
);
2108 if (order
!= nullptr && order
->IsType(OT_IMPLICIT
)) {
2109 assert(v
->GetNumManualOrders() == 0);
2113 if (order
== nullptr) {
2114 v
->current_order
.Free();
2119 v
->current_order
= *order
;
2120 return UpdateOrderDest(v
, order
, conditional_depth
+ 1, pbs_look_ahead
);
2124 * Handle the orders of a vehicle and determine the next place
2125 * to go to if needed.
2126 * @param v the vehicle to do this for.
2127 * @return true *if* the vehicle is eligible for reversing
2128 * (basically only when leaving a station).
2130 bool ProcessOrders(Vehicle
*v
)
2132 switch (v
->current_order
.GetType()) {
2134 /* Let a depot order in the orderlist interrupt. */
2135 if (!(v
->current_order
.GetDepotOrderType() & ODTFB_PART_OF_ORDERS
)) return false;
2141 case OT_LEAVESTATION
:
2142 if (v
->type
!= VEH_AIRCRAFT
) return false;
2149 * Reversing because of order change is allowed only just after leaving a
2150 * station (and the difficulty setting to allowed, of course)
2151 * this can be detected because only after OT_LEAVESTATION, current_order
2152 * will be reset to nothing. (That also happens if no order, but in that case
2153 * it won't hit the point in code where may_reverse is checked)
2155 bool may_reverse
= v
->current_order
.IsType(OT_NOTHING
);
2157 /* Check if we've reached a 'via' destination. */
2158 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
)) &&
2159 IsTileType(v
->tile
, MP_STATION
) &&
2160 v
->current_order
.GetDestination() == GetStationIndex(v
->tile
)) {
2161 v
->DeleteUnreachedImplicitOrders();
2162 /* We set the last visited station here because we do not want
2163 * the train to stop at this 'via' station if the next order
2164 * is a no-non-stop order; in that case not setting the last
2165 * visited station will cause the vehicle to still stop. */
2166 v
->last_station_visited
= v
->current_order
.GetDestination();
2167 UpdateVehicleTimetable(v
, true);
2168 v
->IncrementImplicitOrderIndex();
2171 /* Get the current order */
2172 assert(v
->cur_implicit_order_index
== 0 || v
->cur_implicit_order_index
< v
->GetNumOrders());
2173 v
->UpdateRealOrderIndex();
2175 const Order
*order
= v
->GetOrder(v
->cur_real_order_index
);
2176 if (order
!= nullptr && order
->IsType(OT_IMPLICIT
)) {
2177 assert(v
->GetNumManualOrders() == 0);
2181 /* If no order, do nothing. */
2182 if (order
== nullptr || (v
->type
== VEH_AIRCRAFT
&& !CheckForValidOrders(v
))) {
2183 if (v
->type
== VEH_AIRCRAFT
) {
2184 /* Aircraft do something vastly different here, so handle separately */
2185 extern void HandleMissingAircraftOrders(Aircraft
*v
);
2186 HandleMissingAircraftOrders(Aircraft::From(v
));
2190 v
->current_order
.Free();
2195 /* If it is unchanged, keep it. */
2196 if (order
->Equals(v
->current_order
) && (v
->type
== VEH_AIRCRAFT
|| v
->dest_tile
!= 0) &&
2197 (v
->type
!= VEH_SHIP
|| !order
->IsType(OT_GOTO_STATION
) || Station::Get(order
->GetDestination())->ship_station
.tile
!= INVALID_TILE
)) {
2201 /* Otherwise set it, and determine the destination tile. */
2202 v
->current_order
= *order
;
2204 InvalidateVehicleOrder(v
, VIWD_MODIFY_ORDERS
);
2215 SetWindowClassesDirty(GetWindowClassForVehicleType(v
->type
));
2219 return UpdateOrderDest(v
, order
) && may_reverse
;
2223 * Check whether the given vehicle should stop at the given station
2224 * based on this order and the non-stop settings.
2225 * @param v the vehicle that might be stopping.
2226 * @param station the station to stop at.
2227 * @return true if the vehicle should stop.
2229 bool Order::ShouldStopAtStation(const Vehicle
*v
, StationID station
) const
2231 bool is_dest_station
= this->IsType(OT_GOTO_STATION
) && this->dest
== station
;
2233 return (!this->IsType(OT_GOTO_DEPOT
) || (this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS
) != 0) &&
2234 v
->last_station_visited
!= station
&& // Do stop only when we've not just been there
2235 /* Finally do stop when there is no non-stop flag set for this type of station. */
2236 !(this->GetNonStopType() & (is_dest_station
? ONSF_NO_STOP_AT_DESTINATION_STATION
: ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS
));
2239 bool Order::CanLoadOrUnload() const
2241 return (this->IsType(OT_GOTO_STATION
) || this->IsType(OT_IMPLICIT
)) &&
2242 (this->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION
) == 0 &&
2243 ((this->GetLoadType() & OLFB_NO_LOAD
) == 0 ||
2244 (this->GetUnloadType() & OUFB_NO_UNLOAD
) == 0);
2248 * A vehicle can leave the current station with cargo if:
2249 * 1. it can load cargo here OR
2250 * 2a. it could leave the last station with cargo AND
2251 * 2b. it doesn't have to unload all cargo here.
2253 bool Order::CanLeaveWithCargo(bool has_cargo
) const
2255 return (this->GetLoadType() & OLFB_NO_LOAD
) == 0 || (has_cargo
&&
2256 (this->GetUnloadType() & (OUFB_UNLOAD
| OUFB_TRANSFER
)) == 0);