4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
10 /** @file order_cmd.cpp Handling of orders. */
14 #include "cmd_helper.h"
15 #include "command_func.h"
16 #include "company_func.h"
17 #include "news_func.h"
18 #include "strings_func.h"
19 #include "timetable.h"
20 #include "station_base.h"
21 #include "station_map.h"
22 #include "station_func.h"
24 #include "cargotype.h"
25 #include "vehicle_func.h"
26 #include "depot_base.h"
27 #include "core/bitmath_func.hpp"
28 #include "core/pool_func.hpp"
29 #include "core/random_func.hpp"
32 #include "station_base.h"
33 #include "waypoint_base.h"
34 #include "company_base.h"
35 #include "order_backup.h"
36 #include "cheat_type.h"
37 #include "viewport_func.h"
38 #include "tracerestrict.h"
40 #include "table/strings.h"
42 #include "safeguards.h"
44 /* DestinationID must be at least as large as every these below, because it can
47 assert_compile(sizeof(DestinationID
) >= sizeof(DepotID
));
48 assert_compile(sizeof(DestinationID
) >= sizeof(StationID
));
50 OrderPool
_order_pool("Order");
51 INSTANTIATE_POOL_METHODS(Order
)
52 OrderListPool
_orderlist_pool("OrderList");
53 INSTANTIATE_POOL_METHODS(OrderList
)
55 /** Clean everything up. */
58 if (CleaningPool()) return;
60 /* We can visit oil rigs and buoys that are not our own. They will be shown in
61 * the list of stations. So, we need to invalidate that window if needed. */
62 if (this->IsType(OT_GOTO_STATION
) || this->IsType(OT_GOTO_WAYPOINT
)) {
63 BaseStation
*bs
= BaseStation::GetIfValid(this->GetDestination());
64 if (bs
!= nullptr && bs
->owner
== OWNER_NONE
) InvalidateWindowClassesData(WC_STATION_LIST
, 0);
70 * @note ONLY use on "current_order" vehicle orders!
74 this->type
= OT_NOTHING
;
82 * Makes this order a Go To Station order.
83 * @param destination the station to go to.
85 void Order::MakeGoToStation(StationID destination
)
87 this->type
= OT_GOTO_STATION
;
89 this->dest
= destination
;
93 * Makes this order a Go To Depot order.
94 * @param destination the depot to go to.
95 * @param order is this order a 'default' order, or an overridden vehicle order?
96 * @param non_stop_type how to get to the depot?
97 * @param action what to do in the depot?
98 * @param cargo the cargo type to change to.
100 void Order::MakeGoToDepot(DepotID destination
, OrderDepotTypeFlags order
, OrderNonStopFlags non_stop_type
, OrderDepotActionFlags action
, CargoID cargo
)
102 this->type
= OT_GOTO_DEPOT
;
103 this->SetDepotOrderType(order
);
104 this->SetDepotActionType(action
);
105 this->SetNonStopType(non_stop_type
);
106 this->dest
= destination
;
107 this->SetRefit(cargo
);
111 * Makes this order a Go To Waypoint order.
112 * @param destination the waypoint to go to.
114 void Order::MakeGoToWaypoint(StationID destination
)
116 this->type
= OT_GOTO_WAYPOINT
;
118 this->dest
= destination
;
122 * Makes this order a Loading order.
123 * @param ordered is this an ordered stop?
125 void Order::MakeLoading(bool ordered
)
127 this->type
= OT_LOADING
;
128 if (!ordered
) this->flags
= 0;
131 bool Order::UpdateJumpCounter(byte percent
)
133 if(this->jump_counter
>= 0) {
134 this->jump_counter
+= (percent
- 100);
137 this->jump_counter
+= percent
;
142 * Makes this order a Leave Station order.
144 void Order::MakeLeaveStation()
146 this->type
= OT_LEAVESTATION
;
151 * Makes this order a Dummy order.
153 void Order::MakeDummy()
155 this->type
= OT_DUMMY
;
160 * Makes this order an conditional order.
161 * @param order the order to jump to.
163 void Order::MakeConditional(VehicleOrderID order
)
165 this->type
= OT_CONDITIONAL
;
171 * Makes this order an implicit order.
172 * @param destination the station to go to.
174 void Order::MakeImplicit(StationID destination
)
176 this->type
= OT_IMPLICIT
;
177 this->dest
= destination
;
180 void Order::MakeWaiting()
182 this->type
= OT_WAITING
;
186 * Make this depot/station order also a refit order.
187 * @param cargo the cargo type to change to.
188 * @pre IsType(OT_GOTO_DEPOT) || IsType(OT_GOTO_STATION).
190 void Order::SetRefit(CargoID cargo
)
192 this->refit_cargo
= cargo
;
196 * Does this order have the same type, flags and destination?
197 * @param other the second order to compare to.
198 * @return true if the type, flags and destination match.
200 bool Order::Equals(const Order
&other
) const
202 /* In case of go to nearest depot orders we need "only" compare the flags
203 * with the other and not the nearest depot order bit or the actual
204 * destination because those get clear/filled in during the order
205 * evaluation. If we do not do this the order will continuously be seen as
206 * a different order and it will try to find a "nearest depot" every tick. */
207 if ((this->IsType(OT_GOTO_DEPOT
) && this->type
== other
.type
) &&
208 ((this->GetDepotActionType() & ODATFB_NEAREST_DEPOT
) != 0 ||
209 (other
.GetDepotActionType() & ODATFB_NEAREST_DEPOT
) != 0)) {
210 return this->GetDepotOrderType() == other
.GetDepotOrderType() &&
211 (this->GetDepotActionType() & ~ODATFB_NEAREST_DEPOT
) == (other
.GetDepotActionType() & ~ODATFB_NEAREST_DEPOT
);
214 return this->type
== other
.type
&& this->flags
== other
.flags
&& this->dest
== other
.dest
;
218 * Pack this order into a 32 bits integer, or actually only
219 * the type, flags and destination.
220 * @return the packed representation.
221 * @note unpacking is done in the constructor.
223 uint32
Order::Pack() const
225 return this->dest
<< 16 | this->flags
<< 8 | this->type
;
229 * Pack this order into a 16 bits integer as close to the TTD
230 * representation as possible.
231 * @return the TTD-like packed representation.
233 uint16
Order::MapOldOrder() const
235 uint16 order
= this->GetType();
236 switch (this->type
) {
237 case OT_GOTO_STATION
:
238 if (this->GetUnloadType() & OUFB_UNLOAD
) SetBit(order
, 5);
239 if (this->GetLoadType() & OLFB_FULL_LOAD
) SetBit(order
, 6);
240 if (this->GetNonStopType() & ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS
) SetBit(order
, 7);
241 order
|= GB(this->GetDestination(), 0, 8) << 8;
244 if (!(this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS
)) SetBit(order
, 6);
246 order
|= GB(this->GetDestination(), 0, 8) << 8;
249 if (this->GetLoadType() & OLFB_FULL_LOAD
) SetBit(order
, 6);
256 * Create an order based on a packed representation of that order.
257 * @param packed the packed representation.
259 Order::Order(uint32 packed
)
261 this->type
= (OrderType
)GB(packed
, 0, 8);
262 this->flags
= GB(packed
, 8, 8);
263 this->dest
= GB(packed
, 16, 16);
264 this->extra
= nullptr;
265 this->next
= nullptr;
266 this->refit_cargo
= CT_NO_REFIT
;
268 this->travel_time
= 0;
269 this->jump_counter
= 0;
270 this->max_speed
= UINT16_MAX
;
275 * Updates the widgets of a vehicle which contains the order-data
278 void InvalidateVehicleOrder(const Vehicle
*v
, int data
)
280 SetWindowDirty(WC_VEHICLE_VIEW
, v
->index
);
283 /* Calls SetDirty() too */
284 InvalidateWindowData(WC_VEHICLE_ORDERS
, v
->index
, data
);
285 InvalidateWindowData(WC_VEHICLE_TIMETABLE
, v
->index
, data
);
286 InvalidateWindowData(WC_VEHICLE_TRIP_HISTORY
, v
->index
, data
);
290 SetWindowDirty(WC_VEHICLE_ORDERS
, v
->index
);
291 SetWindowDirty(WC_VEHICLE_TIMETABLE
, v
->index
);
292 SetWindowDirty(WC_VEHICLE_TRIP_HISTORY
, v
->index
);
297 * Assign data to an order (from another order)
298 * This function makes sure that the index is maintained correctly
299 * @param other the data to copy (except next pointer).
302 void Order::AssignOrder(const Order
&other
)
304 this->type
= other
.type
;
305 this->flags
= other
.flags
;
306 this->dest
= other
.dest
;
308 this->refit_cargo
= other
.refit_cargo
;
310 this->wait_time
= other
.wait_time
;
311 this->jump_counter
= other
.jump_counter
;
312 this->travel_time
= other
.travel_time
;
313 this->max_speed
= other
.max_speed
;
315 if ((this->GetUnloadType() == OUFB_CARGO_TYPE_UNLOAD
|| this->GetLoadType() == OLFB_CARGO_TYPE_LOAD
) && other
.extra
!= nullptr) {
316 this->AllocExtraInfo();
317 *(this->extra
) = *(other
.extra
);
319 this->DeAllocExtraInfo();
323 void Order::AllocExtraInfo()
326 this->extra
.reset(new OrderExtraInfo());
330 void Order::DeAllocExtraInfo()
335 void CargoStationIDStackSet::FillNextStoppingStation(const Vehicle
*v
, const OrderList
*o
, const Order
*first
, uint hops
)
338 this->first
= o
->GetNextStoppingStation(v
, ~0, first
, hops
);
339 if (this->first
.cargo_mask
!= (uint32
) ~0) {
340 uint32 have_cargoes
= this->first
.cargo_mask
;
342 this->more
.push_back(o
->GetNextStoppingStation(v
, ~have_cargoes
, first
, hops
));
343 have_cargoes
|= this->more
.back().cargo_mask
;
344 } while (have_cargoes
!= (uint32
) ~0);
349 * Recomputes everything.
350 * @param chain first order in the chain
351 * @param v one of vehicle that is using this orderlist
353 void OrderList::Initialize(Order
*chain
, Vehicle
*v
)
356 this->first_shared
= v
;
358 this->num_orders
= 0;
359 this->num_manual_orders
= 0;
360 this->num_vehicles
= 1;
361 this->timetable_duration
= 0;
362 this->total_duration
= 0;
364 for (Order
*o
= this->first
; o
!= nullptr; o
= o
->next
) {
366 if (!o
->IsType(OT_IMPLICIT
)) ++this->num_manual_orders
;
367 if (!o
->IsType(OT_CONDITIONAL
)) {
368 this->timetable_duration
+= o
->GetTimetabledWait() + o
->GetTimetabledTravel();
369 this->total_duration
+= o
->GetWaitTime() + o
->GetTravelTime();
373 for (Vehicle
*u
= this->first_shared
->PreviousShared(); u
!= nullptr; u
= u
->PreviousShared()) {
374 ++this->num_vehicles
;
375 this->first_shared
= u
;
378 for (const Vehicle
*u
= v
->NextShared(); u
!= nullptr; u
= u
->NextShared()) ++this->num_vehicles
;
382 * Free a complete order chain.
383 * @param keep_orderlist If this is true only delete the orders, otherwise also delete the OrderList.
384 * @note do not use on "current_order" vehicle orders!
386 void OrderList::FreeChain(bool keep_orderlist
)
389 for (Order
*o
= this->first
; o
!= nullptr; o
= next
) {
394 if (keep_orderlist
) {
395 this->first
= nullptr;
396 this->num_orders
= 0;
397 this->num_manual_orders
= 0;
398 this->timetable_duration
= 0;
405 * Get a certain order of the order chain.
406 * @param index zero-based index of the order within the chain.
407 * @return the order at position index.
409 Order
*OrderList::GetOrderAt(int index
) const
411 if (index
< 0) return nullptr;
413 Order
*order
= this->first
;
415 while (order
!= nullptr && index
-- > 0) {
422 * Get the index of an order of the order chain, or INVALID_VEH_ORDER_ID.
423 * @param order order to get the index of.
424 * @return the position index of the given order, or INVALID_VEH_ORDER_ID.
426 VehicleOrderID
OrderList::GetIndexOfOrder(const Order
*order
) const
428 VehicleOrderID index
= 0;
429 const Order
*o
= this->first
;
430 while (o
!= nullptr) {
431 if (o
== order
) return index
;
436 return INVALID_VEH_ORDER_ID
;
440 * Get the next order which will make the given vehicle stop at a station
441 * or refit at a depot or evaluate a non-trivial condition.
442 * @param next The order to start looking at.
443 * @param hops The number of orders we have already looked at.
444 * @param cargo_mask The bit set of cargoes that the we are looking at, this may be reduced to indicate the set of cargoes that the result is valid for.
446 * \li a station order
447 * \li a refitting depot order
448 * \li a non-trivial conditional order
449 * \li nullptr if the vehicle won't stop anymore.
451 const Order
*OrderList::GetNextDecisionNode(const Order
*next
, uint hops
, uint32
&cargo_mask
) const
453 assert(cargo_mask
!= 0);
455 if (hops
> this->GetNumOrders() || next
== nullptr) return nullptr;
457 if (next
->IsType(OT_CONDITIONAL
)) {
458 if (next
->GetConditionVariable() != OCV_UNCONDITIONALLY
) return next
;
460 /* We can evaluate trivial conditions right away. They're conceptually
461 * the same as regular order progression. */
462 return this->GetNextDecisionNode(
463 this->GetOrderAt(next
->GetConditionSkipToOrder()),
464 hops
+ 1, cargo_mask
);
467 if (next
->IsType(OT_GOTO_DEPOT
)) {
468 if (next
->GetDepotActionType() & ODATFB_HALT
) return nullptr;
469 if (next
->IsRefit()) return next
;
473 bool can_load_or_unload
= false;
474 if ((next
->IsType(OT_GOTO_STATION
) || next
->IsType(OT_IMPLICIT
)) &&
475 (next
->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION
) == 0) {
476 if (next
->GetUnloadType() == OUFB_CARGO_TYPE_UNLOAD
|| next
->GetLoadType() == OLFB_CARGO_TYPE_LOAD
) {
477 /* This is a cargo-specific load/unload order.
478 * If the first cargo is both a no-load and no-unload order, skip it.
479 * Drop cargoes which don't match the first one. */
480 can_load_or_unload
= CargoMaskValueFilter
<bool>(cargo_mask
, [&](CargoID cargo
) {
481 return ((next
->GetCargoLoadType(cargo
) & OLFB_NO_LOAD
) == 0 || (next
->GetCargoUnloadType(cargo
) & OUFB_NO_UNLOAD
) == 0);
483 } else if ((next
->GetLoadType() & OLFB_NO_LOAD
) == 0 || (next
->GetUnloadType() & OUFB_NO_UNLOAD
) == 0) {
484 can_load_or_unload
= true;
488 if (!can_load_or_unload
) {
489 return this->GetNextDecisionNode(this->GetNext(next
), hops
+ 1, cargo_mask
);
496 * Recursively determine the next deterministic station to stop at.
497 * @param v The vehicle we're looking at.
498 * @param uint32 cargo_mask Bit-set of the cargo IDs of interest.
499 * @param first Order to start searching at or nullptr to start at cur_implicit_order_index + 1.
500 * @param hops Number of orders we have already looked at.
501 * @return A CargoMaskedStationIDStack of the cargo mask the result is valid for, and the next stoppping station or INVALID_STATION.
502 * @pre The vehicle is currently loading and v->last_station_visited is meaningful.
503 * @note This function may draw a random number. Don't use it from the GUI.
505 CargoMaskedStationIDStack
OrderList::GetNextStoppingStation(const Vehicle
*v
, uint32 cargo_mask
, const Order
*first
, uint hops
) const
507 assert(cargo_mask
!= 0);
509 const Order
*next
= first
;
510 if (first
== nullptr) {
511 next
= this->GetOrderAt(v
->cur_implicit_order_index
);
512 if (next
== nullptr) {
513 next
= this->GetFirstOrder();
514 if (next
== nullptr) return CargoMaskedStationIDStack(cargo_mask
, INVALID_STATION
);
516 /* GetNext never returns nullptr if there is a valid station in the list.
517 * As the given "next" is already valid and a station in the list, we
518 * don't have to check for nullptr here. */
519 next
= this->GetNext(next
);
520 assert(next
!= nullptr);
525 next
= this->GetNextDecisionNode(next
, ++hops
, cargo_mask
);
527 /* Resolve possibly nested conditionals by estimation. */
528 while (next
!= nullptr && next
->IsType(OT_CONDITIONAL
)) {
529 /* We return both options of conditional orders. */
530 const Order
*skip_to
= this->GetNextDecisionNode(
531 this->GetOrderAt(next
->GetConditionSkipToOrder()), hops
, cargo_mask
);
532 const Order
*advance
= this->GetNextDecisionNode(
533 this->GetNext(next
), hops
, cargo_mask
);
534 if (advance
== nullptr || advance
== first
|| skip_to
== advance
) {
535 next
= (skip_to
== first
) ? nullptr : skip_to
;
536 } else if (skip_to
== nullptr || skip_to
== first
) {
537 next
= (advance
== first
) ? nullptr : advance
;
539 CargoMaskedStationIDStack st1
= this->GetNextStoppingStation(v
, cargo_mask
, skip_to
, hops
);
540 cargo_mask
&= st1
.cargo_mask
;
541 CargoMaskedStationIDStack st2
= this->GetNextStoppingStation(v
, cargo_mask
, advance
, hops
);
542 st1
.cargo_mask
&= st2
.cargo_mask
;
543 while (!st2
.station
.IsEmpty()) st1
.station
.Push(st2
.station
.Pop());
549 if (next
== nullptr) return CargoMaskedStationIDStack(cargo_mask
, INVALID_STATION
);
551 /* Don't return a next stop if the vehicle has to unload everything. */
552 if ((next
->IsType(OT_GOTO_STATION
) || next
->IsType(OT_IMPLICIT
)) &&
553 next
->GetDestination() == v
->last_station_visited
) {
554 /* This is a cargo-specific load/unload order.
555 * Don't return a next stop if first cargo has transfer or unload set.
556 * Drop cargoes which don't match the first one. */
557 bool invalid
= CargoMaskValueFilter
<bool>(cargo_mask
, [&](CargoID cargo
) {
558 return ((next
->GetCargoUnloadType(cargo
) & (OUFB_TRANSFER
| OUFB_UNLOAD
)) != 0);
560 if (invalid
) return CargoMaskedStationIDStack(cargo_mask
, INVALID_STATION
);
562 } while (next
->IsType(OT_GOTO_DEPOT
) || next
->GetDestination() == v
->last_station_visited
);
564 return CargoMaskedStationIDStack(cargo_mask
, next
->GetDestination());
568 * Insert a new order into the order chain.
569 * @param new_order is the order to insert into the chain.
570 * @param index is the position where the order is supposed to be inserted.
572 void OrderList::InsertOrderAt(Order
*new_order
, int index
)
574 if (this->first
== nullptr) {
575 this->first
= new_order
;
578 /* Insert as first or only order */
579 new_order
->next
= this->first
;
580 this->first
= new_order
;
581 } else if (index
>= this->num_orders
) {
582 /* index is after the last order, add it to the end */
583 this->GetLastOrder()->next
= new_order
;
585 /* Put the new order in between */
586 Order
*order
= this->GetOrderAt(index
- 1);
587 new_order
->next
= order
->next
;
588 order
->next
= new_order
;
592 if (!new_order
->IsType(OT_IMPLICIT
)) ++this->num_manual_orders
;
593 if (!new_order
->IsType(OT_CONDITIONAL
)) {
594 this->timetable_duration
+= new_order
->GetTimetabledWait() + new_order
->GetTimetabledTravel();
595 this->total_duration
+= new_order
->GetWaitTime() + new_order
->GetTravelTime();
598 /* We can visit oil rigs and buoys that are not our own. They will be shown in
599 * the list of stations. So, we need to invalidate that window if needed. */
600 if (new_order
->IsType(OT_GOTO_STATION
) || new_order
->IsType(OT_GOTO_WAYPOINT
)) {
601 BaseStation
*bs
= BaseStation::Get(new_order
->GetDestination());
602 if (bs
->owner
== OWNER_NONE
) InvalidateWindowClassesData(WC_STATION_LIST
, 0);
609 * Remove an order from the order list and delete it.
610 * @param index is the position of the order which is to be deleted.
612 void OrderList::DeleteOrderAt(int index
)
614 if (index
>= this->num_orders
) return;
619 to_remove
= this->first
;
620 this->first
= to_remove
->next
;
622 Order
*prev
= GetOrderAt(index
- 1);
623 to_remove
= prev
->next
;
624 prev
->next
= to_remove
->next
;
627 if (!to_remove
->IsType(OT_IMPLICIT
)) --this->num_manual_orders
;
628 if (!to_remove
->IsType(OT_CONDITIONAL
)) {
629 this->timetable_duration
-= (to_remove
->GetTimetabledWait() + to_remove
->GetTimetabledTravel());
630 this->total_duration
-= (to_remove
->GetWaitTime() + to_remove
->GetTravelTime());
636 * Move an order to another position within the order list.
637 * @param from is the zero-based position of the order to move.
638 * @param to is the zero-based position where the order is moved to.
640 void OrderList::MoveOrder(int from
, int to
)
642 if (from
>= this->num_orders
|| to
>= this->num_orders
|| from
== to
) return;
646 /* Take the moving order out of the pointer-chain */
648 moving_one
= this->first
;
649 this->first
= moving_one
->next
;
651 Order
*one_before
= GetOrderAt(from
- 1);
652 moving_one
= one_before
->next
;
653 one_before
->next
= moving_one
->next
;
656 /* Insert the moving_order again in the pointer-chain */
658 moving_one
->next
= this->first
;
659 this->first
= moving_one
;
661 Order
*one_before
= GetOrderAt(to
- 1);
662 moving_one
->next
= one_before
->next
;
663 one_before
->next
= moving_one
;
668 * Removes the vehicle from the shared order list.
669 * @note This is supposed to be called when the vehicle is still in the chain
670 * @param v vehicle to remove from the list
672 void OrderList::RemoveVehicle(Vehicle
*v
)
674 --this->num_vehicles
;
675 if (v
== this->first_shared
) this->first_shared
= v
->NextShared();
679 * Checks whether a vehicle is part of the shared vehicle chain.
680 * @param v is the vehicle to search in the shared vehicle chain.
682 bool OrderList::IsVehicleInSharedOrdersList(const Vehicle
*v
) const
684 for (const Vehicle
*v_shared
= this->first_shared
; v_shared
!= nullptr; v_shared
= v_shared
->NextShared()) {
685 if (v_shared
== v
) return true;
692 * Gets the position of the given vehicle within the shared order vehicle list.
693 * @param v is the vehicle of which to get the position
694 * @return position of v within the shared vehicle chain.
696 int OrderList::GetPositionInSharedOrderList(const Vehicle
*v
) const
699 for (const Vehicle
*v_shared
= v
->PreviousShared(); v_shared
!= nullptr; v_shared
= v_shared
->PreviousShared()) count
++;
704 * Checks whether all orders of the list have a filled timetable.
705 * @return whether all orders have a filled timetable.
707 bool OrderList::IsCompleteTimetable() const
709 for (Order
*o
= this->first
; o
!= nullptr; o
= o
->next
) {
710 /* Implicit orders are, by definition, not timetabled. */
711 if (o
->IsType(OT_IMPLICIT
)) continue;
712 if (!o
->IsCompletelyTimetabled()) return false;
718 * Checks for internal consistency of order list. Triggers assertion if something is wrong.
720 void OrderList::DebugCheckSanity() const
722 VehicleOrderID check_num_orders
= 0;
723 VehicleOrderID check_num_manual_orders
= 0;
724 uint check_num_vehicles
= 0;
725 Ticks check_timetable_duration
= 0;
726 Ticks check_total_duration
= 0;
728 DEBUG(misc
, 6, "Checking OrderList %hu for sanity...", this->index
);
730 for (const Order
*o
= this->first
; o
!= nullptr; o
= o
->next
) {
732 if (!o
->IsType(OT_IMPLICIT
)) ++check_num_manual_orders
;
733 if (!o
->IsType(OT_CONDITIONAL
)) {
734 check_timetable_duration
+= o
->GetTimetabledWait() + o
->GetTimetabledTravel();
735 check_total_duration
+= o
->GetWaitTime() + o
->GetTravelTime();
738 assert(this->num_orders
== check_num_orders
);
739 assert(this->num_manual_orders
== check_num_manual_orders
);
740 assert(this->timetable_duration
== check_timetable_duration
);
741 assert(this->total_duration
== check_total_duration
);
743 for (const Vehicle
*v
= this->first_shared
; v
!= nullptr; v
= v
->NextShared()) {
744 ++check_num_vehicles
;
745 assert(v
->HasSpecificOrderList(this));
747 assert(this->num_vehicles
== check_num_vehicles
);
748 DEBUG(misc
, 6, "... detected %u orders (%u manual), %u vehicles, %i timetabled, %i total",
749 (uint
)this->num_orders
, (uint
)this->num_manual_orders
,
750 this->num_vehicles
, this->timetable_duration
, this->total_duration
);
753 /** Returns the number of running (i.e. not stopped) vehicles in the shared orders list. */
754 int OrderList::GetNumRunningVehicles()
756 int num_running_vehicles
= 0;
758 for (const Vehicle
*v
= this->first_shared
; v
!= nullptr; v
= v
->NextShared()) {
759 if (!(v
->vehstatus
& (VS_STOPPED
| VS_CRASHED
)) || v
->current_order
.IsType(OT_WAITING
)) {
760 num_running_vehicles
++;
764 return num_running_vehicles
;
767 /** (Re-)Initializes Separation if necessary and possible. */
768 void OrderList::InitializeSeparation()
770 // Check whether separation can be used at all
771 if (!this->IsCompleteTimetable() || this->current_sep_mode
== TTS_MODE_OFF
) {
772 this->is_separation_valid
= false;
776 // Save current tick count as reference for future timetable start dates and reset the separation counter.
777 this->last_timetable_init
= GetCurrentTickCount();
778 this->separation_counter
= 0;
780 this->UpdateSeparationTime();
782 this->is_separation_valid
= true;
785 void OrderList::UpdateSeparationTime()
787 // Calculate separation amount depending on mode of operation.
788 switch (current_sep_mode
) {
789 case TTS_MODE_AUTO
: {
790 int num_running_vehicles
= this->GetNumRunningVehicles();
791 assert(num_running_vehicles
> 0);
793 this->current_separation
= this->GetTimetableTotalDuration() / num_running_vehicles
;
798 this->current_separation
= this->GetTimetableTotalDuration() / this->num_sep_vehicles
;
802 // separation is set manually -> nothing to do
805 case TTS_MODE_BUFFERED_AUTO
: {
806 int num_running_vehicles
= this->GetNumRunningVehicles();
807 assert(num_running_vehicles
> 0);
809 if (num_running_vehicles
> 1)
810 num_running_vehicles
--;
812 this->current_separation
= this->GetTimetableTotalDuration() / num_running_vehicles
;
823 * Returns the delay setting required for correct separation and increases the separation counter by 1.
824 * @return the delay setting required for correct separation. */
825 Ticks
OrderList::SeparateVehicle()
827 if (!this->is_separation_valid
|| this->current_sep_mode
== TTS_MODE_OFF
)
828 return INVALID_TICKS
;
830 UpdateSeparationTime();
832 Ticks result
= GetCurrentTickCount() - (this->separation_counter
* this->current_separation
+ this->last_timetable_init
);
833 this->IncreaseSeparationCounter();
834 if (this->separation_counter
== UINT16_MAX
) {
835 this->MarkSeparationInvalid();
842 * Returns the current separation settings.
843 * @return the current separation settings.
845 TTSepSettings
OrderList::GetSepSettings()
847 TTSepSettings result
;
849 result
.mode
= this->current_sep_mode
;
850 result
.sep_ticks
= GetSepTime();
852 // Depending on the operation mode return either the user setting or the true amount of vehicles running the timetable.
853 result
.num_veh
= (result
.mode
== TTS_MODE_MAN_N
) ? this->num_sep_vehicles
: GetNumVehicles();
858 * Sets new separation settings.
859 * @param mode Contains the operation mode that is to be used for separation.
860 * @param parameter Depending on the operation mode this contains either the number of vehicles (#TTS_MODE_MAN_N)
861 * or the time between vehicles in ticks (#TTS_MODE_MAN_T). For other modes, this is undefined.
863 void OrderList::SetSepSettings(TTSepMode mode
, uint32 parameter
)
865 this->current_sep_mode
= mode
;
867 switch (this->current_sep_mode
)
870 this->current_separation
= this->GetTimetableTotalDuration() / parameter
;
871 this->num_sep_vehicles
= parameter
;
875 this->current_separation
= parameter
;
876 this->num_sep_vehicles
= this->GetTimetableTotalDuration() / this->current_separation
;
880 case TTS_MODE_BUFFERED_AUTO
:
890 this->is_separation_valid
= false;
895 * Checks whether the order goes to a station or not, i.e. whether the
896 * destination is a station
897 * @param v the vehicle to check for
898 * @param o the order to check
899 * @return true if the destination is a station
901 static inline bool OrderGoesToStation(const Vehicle
*v
, const Order
*o
)
903 return o
->IsType(OT_GOTO_STATION
) ||
904 (v
->type
== VEH_AIRCRAFT
&& o
->IsType(OT_GOTO_DEPOT
) && !(o
->GetDepotActionType() & ODATFB_NEAREST_DEPOT
));
908 * Delete all news items regarding defective orders about a vehicle
909 * This could kill still valid warnings (for example about void order when just
910 * another order gets added), but assume the company will notice the problems,
911 * when (s)he's changing the orders.
913 void DeleteOrderWarnings(const Vehicle
*v
)
915 DeleteVehicleNews(v
->index
, STR_NEWS_VEHICLE_HAS_TOO_FEW_ORDERS
);
916 DeleteVehicleNews(v
->index
, STR_NEWS_VEHICLE_HAS_VOID_ORDER
);
917 DeleteVehicleNews(v
->index
, STR_NEWS_VEHICLE_HAS_DUPLICATE_ENTRY
);
918 DeleteVehicleNews(v
->index
, STR_NEWS_VEHICLE_HAS_INVALID_ENTRY
);
919 DeleteVehicleNews(v
->index
, STR_NEWS_PLANE_USES_TOO_SHORT_RUNWAY
);
923 * Returns a tile somewhat representing the order destination (not suitable for pathfinding).
924 * @param v The vehicle to get the location for.
925 * @param airport Get the airport tile and not the station location for aircraft.
926 * @return destination of order, or INVALID_TILE if none.
928 TileIndex
Order::GetLocation(const Vehicle
*v
, bool airport
) const
930 switch (this->GetType()) {
931 case OT_GOTO_WAYPOINT
:
932 case OT_GOTO_STATION
:
934 if (airport
&& v
->type
== VEH_AIRCRAFT
) return Station::Get(this->GetDestination())->airport
.tile
;
935 return BaseStation::Get(this->GetDestination())->xy
;
938 if ((this->GetDepotActionType() & ODATFB_NEAREST_DEPOT
) != 0) return INVALID_TILE
;
939 return (v
->type
== VEH_AIRCRAFT
) ? Station::Get(this->GetDestination())->xy
: Depot::Get(this->GetDestination())->xy
;
947 * Get the distance between two orders of a vehicle. Conditional orders are resolved
948 * and the bigger distance of the two order branches is returned.
949 * @param prev Origin order.
950 * @param cur Destination order.
951 * @param v The vehicle to get the distance for.
952 * @param conditional_depth Internal param for resolving conditional orders.
953 * @return Maximum distance between the two orders.
955 uint
GetOrderDistance(const Order
*prev
, const Order
*cur
, const Vehicle
*v
, int conditional_depth
)
957 if (cur
->IsType(OT_CONDITIONAL
)) {
958 if (conditional_depth
> v
->GetNumOrders()) return 0;
962 int dist1
= GetOrderDistance(prev
, v
->GetOrder(cur
->GetConditionSkipToOrder()), v
, conditional_depth
);
963 int dist2
= GetOrderDistance(prev
, cur
->next
== nullptr ? v
->GetFirstOrder() : cur
->next
, v
, conditional_depth
);
964 return max(dist1
, dist2
);
967 TileIndex prev_tile
= prev
->GetLocation(v
, true);
968 TileIndex cur_tile
= cur
->GetLocation(v
, true);
969 if (prev_tile
== INVALID_TILE
|| cur_tile
== INVALID_TILE
) return 0;
970 return v
->type
== VEH_AIRCRAFT
? DistanceSquare(prev_tile
, cur_tile
) : DistanceManhattan(prev_tile
, cur_tile
);
974 * Add an order to the orderlist of a vehicle.
976 * @param flags operation to perform
977 * @param p1 various bitstuffed elements
978 * - p1 = (bit 0 - 19) - ID of the vehicle
979 * - p1 = (bit 24 - 31) - the selected order (if any). If the last order is given,
980 * the order will be inserted before that one
981 * the maximum vehicle order id is 254.
982 * @param p2 packed order to insert
984 * @return the cost of this operation or an error
986 CommandCost
CmdInsertOrder(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
988 VehicleID veh
= GB(p1
, 0, 20);
989 VehicleOrderID sel_ord
= GB(p1
, 20, 8);
992 Vehicle
*v
= Vehicle::GetIfValid(veh
);
993 if (v
== nullptr || !v
->IsPrimaryVehicle()) return CommandError();
995 CommandCost ret
= CheckOwnership(v
->owner
);
996 if (ret
.Failed()) return ret
;
998 /* Check if the inserted order is to the correct destination (owner, type),
999 * and has the correct flags if any */
1000 switch (new_order
.GetType()) {
1001 case OT_GOTO_STATION
: {
1002 const Station
*st
= Station::GetIfValid(new_order
.GetDestination());
1003 if (st
== nullptr) return CommandError();
1005 if (st
->owner
!= OWNER_NONE
) {
1006 CommandCost ret
= CheckOwnership(st
->owner
);
1007 if (ret
.Failed()) return ret
;
1010 if (!CanVehicleUseStation(v
, st
)) return CommandError(STR_ERROR_CAN_T_ADD_ORDER
);
1011 for (Vehicle
*u
= v
->FirstShared(); u
!= nullptr; u
= u
->NextShared()) {
1012 if (!CanVehicleUseStation(u
, st
)) return CommandError(STR_ERROR_CAN_T_ADD_ORDER_SHARED
);
1015 /* Non stop only allowed for ground vehicles. */
1016 if (new_order
.GetNonStopType() != ONSF_STOP_EVERYWHERE
&& !v
->IsGroundVehicle()) return CommandError();
1018 /* Filter invalid load/unload types. */
1019 switch (new_order
.GetLoadType()) {
1020 case OLF_LOAD_IF_POSSIBLE
: case OLFB_FULL_LOAD
: case OLF_FULL_LOAD_ANY
: case OLFB_NO_LOAD
: break;
1021 default: return CommandError();
1023 switch (new_order
.GetUnloadType()) {
1024 case OUF_UNLOAD_IF_POSSIBLE
: case OUFB_UNLOAD
: case OUFB_TRANSFER
: case OUFB_NO_UNLOAD
: break;
1025 default: return CommandError();
1028 /* Filter invalid stop locations */
1029 switch (new_order
.GetStopLocation()) {
1030 case OSL_PLATFORM_NEAR_END
:
1031 case OSL_PLATFORM_MIDDLE
:
1032 if (v
->type
!= VEH_TRAIN
) return CommandError();
1035 case OSL_PLATFORM_FAR_END
:
1039 return CommandError();
1045 case OT_GOTO_DEPOT
: {
1046 if ((new_order
.GetDepotActionType() & ODATFB_NEAREST_DEPOT
) == 0) {
1047 if (v
->type
== VEH_AIRCRAFT
) {
1048 const Station
*st
= Station::GetIfValid(new_order
.GetDestination());
1050 if (st
== nullptr) return CommandError();
1052 CommandCost ret
= CheckOwnership(st
->owner
);
1053 if (ret
.Failed()) return ret
;
1055 if (!CanVehicleUseStation(v
, st
) || !st
->airport
.HasHangar()) {
1056 return CommandError();
1059 const Depot
*dp
= Depot::GetIfValid(new_order
.GetDestination());
1061 if (dp
== nullptr) return CommandError();
1063 CommandCost ret
= CheckOwnership(GetTileOwner(dp
->xy
));
1064 if (ret
.Failed()) return ret
;
1068 if (!IsRailDepotTile(dp
->xy
)) return CommandError();
1072 if (!IsRoadDepotTile(dp
->xy
)) return CommandError();
1076 if (!IsShipDepotTile(dp
->xy
)) return CommandError();
1079 default: return CommandError();
1084 if (new_order
.GetNonStopType() != ONSF_STOP_EVERYWHERE
&& !v
->IsGroundVehicle()) return CommandError();
1085 if (new_order
.GetDepotOrderType() & ~(ODTFB_PART_OF_ORDERS
| ((new_order
.GetDepotOrderType() & ODTFB_PART_OF_ORDERS
) != 0 ? ODTFB_SERVICE
: 0))) return CommandError();
1086 if (new_order
.GetDepotActionType() & ~(ODATFB_HALT
| ODATFB_NEAREST_DEPOT
)) return CommandError();
1087 if ((new_order
.GetDepotOrderType() & ODTFB_SERVICE
) && (new_order
.GetDepotActionType() & ODATFB_HALT
)) return CommandError();
1091 case OT_GOTO_WAYPOINT
: {
1092 const Waypoint
*wp
= Waypoint::GetIfValid(new_order
.GetDestination());
1093 if (wp
== nullptr) return CommandError();
1096 default: return CommandError();
1099 if (!(wp
->facilities
& FACIL_TRAIN
)) return CommandError(STR_ERROR_CAN_T_ADD_ORDER
);
1101 CommandCost ret
= CheckOwnership(wp
->owner
);
1102 if (ret
.Failed()) return ret
;
1107 if (!(wp
->facilities
& FACIL_DOCK
)) return CommandError(STR_ERROR_CAN_T_ADD_ORDER
);
1108 if (wp
->owner
!= OWNER_NONE
) {
1109 CommandCost ret
= CheckOwnership(wp
->owner
);
1110 if (ret
.Failed()) return ret
;
1115 /* Order flags can be any of the following for waypoints:
1117 * non-stop orders (if any) are only valid for trains */
1118 if (new_order
.GetNonStopType() != ONSF_STOP_EVERYWHERE
&& v
->type
!= VEH_TRAIN
) return CommandError();
1122 case OT_CONDITIONAL
: {
1123 VehicleOrderID skip_to
= new_order
.GetConditionSkipToOrder();
1124 if (skip_to
!= 0 && skip_to
>= v
->GetNumOrders()) return CommandError(); // Always allow jumping to the first (even when there is no order).
1125 if (new_order
.GetConditionVariable() >= OCV_END
) return CommandError();
1127 OrderConditionComparator occ
= new_order
.GetConditionComparator();
1128 if (occ
>= OCC_END
) return CommandError();
1129 switch (new_order
.GetConditionVariable()) {
1130 case OCV_SLOT_OCCUPANCY
: {
1131 TraceRestrictSlotID slot
= new_order
.GetXData();
1132 if (slot
!= INVALID_TRACE_RESTRICT_SLOT_ID
&& !TraceRestrictSlot::IsValidID(slot
)) return CommandError();
1133 if (occ
!= OCC_IS_TRUE
&& occ
!= OCC_IS_FALSE
) return CommandError();
1136 case OCV_CARGO_WAITING
:
1137 case OCV_CARGO_ACCEPTANCE
:
1138 if (!CargoSpec::Get(new_order
.GetConditionValue())->IsValid()) return CommandError();
1141 case OCV_REQUIRES_SERVICE
:
1142 if (occ
!= OCC_IS_TRUE
&& occ
!= OCC_IS_FALSE
) return CommandError();
1145 case OCV_UNCONDITIONALLY
:
1146 if (occ
!= OCC_EQUALS
) return CommandError();
1147 if (new_order
.GetConditionValue() != 0) return CommandError();
1150 case OCV_FREE_PLATFORMS
:
1151 if (v
->type
!= VEH_TRAIN
) return CommandError();
1152 if (occ
== OCC_IS_TRUE
|| occ
== OCC_IS_FALSE
) return CommandError();
1156 if (occ
!= OCC_EQUALS
) return CommandError();
1159 case OCV_LOAD_PERCENTAGE
:
1160 case OCV_RELIABILITY
:
1161 if (new_order
.GetConditionValue() > 100) return CommandError();
1165 if (occ
== OCC_IS_TRUE
|| occ
== OCC_IS_FALSE
) return CommandError();
1171 default: return CommandError();
1174 if (sel_ord
> v
->GetNumOrders()) return CommandError();
1176 if (v
->GetNumOrders() >= MAX_VEH_ORDER_ID
) return CommandError(STR_ERROR_TOO_MANY_ORDERS
);
1177 if (!Order::CanAllocateItem()) return CommandError(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS
);
1178 if (!v
->HasOrdersList() && !OrderList::CanAllocateItem()) return CommandError(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS
);
1180 if (v
->type
== VEH_SHIP
&& _settings_game
.pf
.pathfinder_for_ships
!= VPF_NPF
) {
1181 /* Make sure the new destination is not too far away from the previous */
1182 const Order
*prev
= nullptr;
1185 /* Find the last goto station or depot order before the insert location.
1186 * If the order is to be inserted at the beginning of the order list this
1187 * finds the last order in the list. */
1189 FOR_VEHICLE_ORDERS(v
, o
) {
1190 switch (o
->GetType()) {
1191 case OT_GOTO_STATION
:
1193 case OT_GOTO_WAYPOINT
:
1199 if (++n
== sel_ord
&& prev
!= nullptr) break;
1201 if (prev
!= nullptr) {
1203 if (new_order
.IsType(OT_CONDITIONAL
)) {
1204 /* The order is not yet inserted, so we have to do the first iteration here. */
1205 dist
= GetOrderDistance(prev
, v
->GetOrder(new_order
.GetConditionSkipToOrder()), v
);
1207 dist
= GetOrderDistance(prev
, &new_order
, v
);
1211 return CommandError(STR_ERROR_TOO_FAR_FROM_PREVIOUS_DESTINATION
);
1216 if (flags
& DC_EXEC
) {
1217 Order
*new_o
= new Order();
1218 new_o
->AssignOrder(new_order
);
1219 InsertOrder(v
, new_o
, sel_ord
);
1220 CheckMarkDirtyFocusedRoutePaths(v
);
1223 return CommandCost();
1227 * Insert a new order but skip the validation.
1228 * @param v The vehicle to insert the order to.
1229 * @param new_o The new order.
1230 * @param sel_ord The position the order should be inserted at.
1232 void InsertOrder(Vehicle
*v
, Order
*new_o
, VehicleOrderID sel_ord
)
1234 /* Create new order and link in list */
1235 if (!v
->HasOrdersList()) {
1236 v
->SetOrdersList(new OrderList(new_o
, v
));
1238 v
->InsertOrderAt(new_o
, sel_ord
);
1241 Vehicle
*u
= v
->FirstShared();
1242 DeleteOrderWarnings(u
);
1243 for (; u
!= nullptr; u
= u
->NextShared()) {
1244 assert(v
->IsSharingOrdersWith(u
));
1246 /* If there is added an order before the current one, we need
1247 * to update the selected order. We do not change implicit/real order indices though.
1248 * If the new order is between the current implicit order and real order, the implicit order will
1249 * later skip the inserted order. */
1250 if (sel_ord
<= u
->cur_real_order_index
) {
1251 uint cur
= u
->cur_real_order_index
+ 1;
1252 /* Check if we don't go out of bound */
1253 if (cur
< u
->GetNumOrders()) {
1254 u
->cur_real_order_index
= cur
;
1257 if (sel_ord
== u
->cur_implicit_order_index
&& u
->IsGroundVehicle()) {
1258 /* We are inserting an order just before the current implicit order.
1259 * We do not know whether we will reach current implicit or the newly inserted order first.
1260 * So, disable creation of implicit orders until we are on track again. */
1261 uint16
&gv_flags
= u
->GetGroundVehicleFlags();
1262 SetBit(gv_flags
, GVF_SUPPRESS_IMPLICIT_ORDERS
);
1264 if (sel_ord
<= u
->cur_implicit_order_index
) {
1265 uint cur
= u
->cur_implicit_order_index
+ 1;
1266 /* Check if we don't go out of bound */
1267 if (cur
< u
->GetNumOrders()) {
1268 u
->cur_implicit_order_index
= cur
;
1271 if (u
->cur_timetable_order_index
!= INVALID_VEH_ORDER_ID
&& sel_ord
<= u
->cur_timetable_order_index
) {
1272 uint cur
= u
->cur_timetable_order_index
+ 1;
1273 /* Check if we don't go out of bound */
1274 if (cur
< u
->GetNumOrders()) {
1275 u
->cur_timetable_order_index
= cur
;
1278 /* Update any possible open window of the vehicle */
1279 InvalidateVehicleOrder(u
, INVALID_VEH_ORDER_ID
| (sel_ord
<< 8));
1282 /* As we insert an order, the order to skip to will be 'wrong'. */
1283 VehicleOrderID cur_order_id
= 0;
1285 FOR_VEHICLE_ORDERS(v
, order
) {
1286 if (order
->IsType(OT_CONDITIONAL
)) {
1287 VehicleOrderID order_id
= order
->GetConditionSkipToOrder();
1288 if (order_id
>= sel_ord
) {
1289 order
->SetConditionSkipToOrder(order_id
+ 1);
1291 if (order_id
== cur_order_id
) {
1292 order
->SetConditionSkipToOrder((order_id
+ 1) % v
->GetNumOrders());
1298 /* Make sure to rebuild the whole list */
1299 InvalidateWindowClassesData(GetWindowClassForVehicleType(v
->type
), 0);
1303 * Declone an order-list
1304 * @param *dst delete the orders of this vehicle
1305 * @param flags execution flags
1307 static CommandCost
DecloneOrder(Vehicle
*dst
, DoCommandFlag flags
)
1309 if (flags
& DC_EXEC
) {
1310 dst
->DeleteVehicleOrders();
1311 InvalidateVehicleOrder(dst
, VIWD_REMOVE_ALL_ORDERS
);
1312 InvalidateWindowClassesData(GetWindowClassForVehicleType(dst
->type
), 0);
1313 CheckMarkDirtyFocusedRoutePaths(dst
);
1315 return CommandCost();
1319 * Get the first cargoID that points to a valid cargo (usually 0)
1321 static CargoID
GetFirstValidCargo()
1323 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
1324 if (CargoSpec::Get(i
)->IsValid()) return i
;
1326 /* No cargoes defined -> 'Houston, we have a problem!' */
1328 /* Return something to avoid compiler warning */
1333 * Get the first valid TraceRestrictSlot. Or INVALID_TRACE_RESTRICT_SLOT_ID if no slots are defined.
1335 static TraceRestrictSlotID
GetFirstValidTraceRestrictSlot()
1337 const TraceRestrictSlot
* slot
;
1338 FOR_ALL_TRACE_RESTRICT_SLOTS(slot
)
1340 // Stupid way to get the first valid slot but there is no "GetFirstValidSlot()".
1344 return INVALID_TRACE_RESTRICT_SLOT_ID
;
1348 * Delete an order from the orderlist of a vehicle.
1349 * @param tile unused
1350 * @param flags operation to perform
1351 * @param p1 the ID of the vehicle
1352 * @param p2 the order to delete (max 255)
1353 * @param text unused
1354 * @return the cost of this operation or an error
1356 CommandCost
CmdDeleteOrder(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1358 VehicleID veh_id
= GB(p1
, 0, 20);
1359 VehicleOrderID sel_ord
= GB(p2
, 0, 8);
1361 Vehicle
*v
= Vehicle::GetIfValid(veh_id
);
1363 if (v
== nullptr || !v
->IsPrimaryVehicle()) return CommandError();
1365 CommandCost ret
= CheckOwnership(v
->owner
);
1366 if (ret
.Failed()) return ret
;
1368 /* If we did not select an order, we maybe want to de-clone the orders */
1369 if (sel_ord
>= v
->GetNumOrders()) return DecloneOrder(v
, flags
);
1371 if (v
->GetOrder(sel_ord
) == nullptr) return CommandError();
1373 if (flags
& DC_EXEC
) {
1374 DeleteOrder(v
, sel_ord
);
1375 CheckMarkDirtyFocusedRoutePaths(v
);
1377 return CommandCost();
1381 * Cancel the current loading order of the vehicle as the order was deleted.
1382 * @param v the vehicle
1384 void CancelLoadingDueToDeletedOrder(Vehicle
*v
)
1386 assert(v
->current_order
.IsType(OT_LOADING
));
1387 /* NON-stop flag is misused to see if a train is in a station that is
1388 * on his order list or not */
1389 v
->current_order
.SetNonStopType(ONSF_STOP_EVERYWHERE
);
1390 /* When full loading, "cancel" that order so the vehicle doesn't
1391 * stay indefinitely at this station anymore. */
1392 if (v
->current_order
.GetLoadType() & OLFB_FULL_LOAD
) v
->current_order
.SetLoadType(OLF_LOAD_IF_POSSIBLE
);
1396 * Delete an order but skip the parameter validation.
1397 * @param v The vehicle to delete the order from.
1398 * @param sel_ord The id of the order to be deleted.
1400 void DeleteOrder(Vehicle
*v
, VehicleOrderID sel_ord
)
1402 v
->DeleteOrderAt(sel_ord
);
1404 Vehicle
*u
= v
->FirstShared();
1405 DeleteOrderWarnings(u
);
1406 for (; u
!= nullptr; u
= u
->NextShared()) {
1407 assert(v
->IsSharingOrdersWith(u
));
1409 if (sel_ord
== u
->cur_real_order_index
&& u
->current_order
.IsType(OT_LOADING
)) {
1410 CancelLoadingDueToDeletedOrder(u
);
1413 if (sel_ord
< u
->cur_real_order_index
) {
1414 u
->cur_real_order_index
--;
1415 } else if (sel_ord
== u
->cur_real_order_index
) {
1416 u
->UpdateRealOrderIndex();
1419 if (sel_ord
< u
->cur_implicit_order_index
) {
1420 u
->cur_implicit_order_index
--;
1421 } else if (sel_ord
== u
->cur_implicit_order_index
) {
1422 /* Make sure the index is valid */
1423 if (u
->cur_implicit_order_index
>= u
->GetNumOrders()) u
->cur_implicit_order_index
= 0;
1425 /* Skip non-implicit orders for the implicit-order-index (e.g. if the current implicit order was deleted */
1426 while (u
->cur_implicit_order_index
!= u
->cur_real_order_index
&& !u
->GetOrder(u
->cur_implicit_order_index
)->IsType(OT_IMPLICIT
)) {
1427 u
->cur_implicit_order_index
++;
1428 if (u
->cur_implicit_order_index
>= u
->GetNumOrders()) u
->cur_implicit_order_index
= 0;
1432 if (u
->cur_timetable_order_index
!= INVALID_VEH_ORDER_ID
) {
1433 if (sel_ord
< u
->cur_timetable_order_index
) {
1434 u
->cur_timetable_order_index
--;
1435 } else if (sel_ord
== u
->cur_timetable_order_index
) {
1436 u
->cur_timetable_order_index
= INVALID_VEH_ORDER_ID
;
1440 /* Update any possible open window of the vehicle */
1441 InvalidateVehicleOrder(u
, sel_ord
| (INVALID_VEH_ORDER_ID
<< 8));
1444 /* As we delete an order, the order to skip to will be 'wrong'. */
1445 VehicleOrderID cur_order_id
= 0;
1446 Order
*order
= nullptr;
1447 FOR_VEHICLE_ORDERS(v
, order
) {
1448 if (order
->IsType(OT_CONDITIONAL
)) {
1449 VehicleOrderID order_id
= order
->GetConditionSkipToOrder();
1450 if (order_id
>= sel_ord
) {
1451 order_id
= max(order_id
- 1, 0);
1453 if (order_id
== cur_order_id
) {
1454 order_id
= (order_id
+ 1) % v
->GetNumOrders();
1456 order
->SetConditionSkipToOrder(order_id
);
1461 InvalidateWindowClassesData(GetWindowClassForVehicleType(v
->type
), 0);
1462 CheckMarkDirtyFocusedRoutePaths(v
);
1466 * Goto order of order-list.
1467 * @param tile unused
1468 * @param flags operation to perform
1469 * @param p1 The ID of the vehicle which order is skipped
1470 * @param p2 the selected order to which we want to skip
1471 * @param text unused
1472 * @return the cost of this operation or an error
1474 CommandCost
CmdSkipToOrder(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1476 VehicleID veh_id
= GB(p1
, 0, 20);
1477 VehicleOrderID sel_ord
= GB(p2
, 0, 8);
1479 Vehicle
*v
= Vehicle::GetIfValid(veh_id
);
1481 if (v
== nullptr || !v
->IsPrimaryVehicle() || sel_ord
== v
->cur_implicit_order_index
|| sel_ord
>= v
->GetNumOrders() || v
->GetNumOrders() < 2) return CommandError();
1483 CommandCost ret
= CheckOwnership(v
->owner
);
1484 if (ret
.Failed()) return ret
;
1486 if (flags
& DC_EXEC
) {
1487 if (v
->current_order
.IsType(OT_LOADING
)) v
->LeaveStation();
1488 if (v
->current_order
.IsType(OT_WAITING
)) v
->HandleWaiting(true);
1490 v
->cur_implicit_order_index
= v
->cur_real_order_index
= sel_ord
;
1491 v
->UpdateRealOrderIndex();
1492 v
->cur_timetable_order_index
= INVALID_VEH_ORDER_ID
;
1494 InvalidateVehicleOrder(v
, VIWD_MODIFY_ORDERS
);
1497 /* We have an aircraft/ship, they have a mini-schedule, so update them all */
1498 if (v
->type
== VEH_AIRCRAFT
) SetWindowClassesDirty(WC_AIRCRAFT_LIST
);
1499 if (v
->type
== VEH_SHIP
) SetWindowClassesDirty(WC_SHIPS_LIST
);
1501 return CommandCost();
1505 * Move an order inside the orderlist
1506 * @param tile unused
1507 * @param flags operation to perform
1508 * @param p1 the ID of the vehicle
1509 * @param p2 order to move and target
1510 * bit 0-15 : the order to move
1511 * bit 16-31 : the target order
1512 * @param text unused
1513 * @return the cost of this operation or an error
1514 * @note The target order will move one place down in the orderlist
1515 * if you move the order upwards else it'll move it one place down
1517 CommandCost
CmdMoveOrder(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1519 VehicleID veh
= GB(p1
, 0, 20);
1520 VehicleOrderID moving_order
= GB(p2
, 0, 16);
1521 VehicleOrderID target_order
= GB(p2
, 16, 16);
1523 Vehicle
*v
= Vehicle::GetIfValid(veh
);
1524 if (v
== nullptr || !v
->IsPrimaryVehicle()) return CommandError();
1526 CommandCost ret
= CheckOwnership(v
->owner
);
1527 if (ret
.Failed()) return ret
;
1529 /* Don't make senseless movements */
1530 if (moving_order
>= v
->GetNumOrders() || target_order
>= v
->GetNumOrders() ||
1531 moving_order
== target_order
|| v
->GetNumOrders() <= 1) return CommandError();
1533 Order
*moving_one
= v
->GetOrder(moving_order
);
1534 /* Don't move an empty order */
1535 if (moving_one
== nullptr) return CommandError();
1537 if (flags
& DC_EXEC
) {
1538 v
->MoveOrder(moving_order
, target_order
);
1540 /* Update shared list */
1541 Vehicle
*u
= v
->FirstShared();
1543 DeleteOrderWarnings(u
);
1545 for (; u
!= nullptr; u
= u
->NextShared()) {
1546 /* Update the current order.
1547 * There are multiple ways to move orders, which result in cur_implicit_order_index
1548 * and cur_real_order_index to not longer make any sense. E.g. moving another
1549 * real order between them.
1551 * Basically one could choose to preserve either of them, but not both.
1552 * While both ways are suitable in this or that case from a human point of view, neither
1553 * of them makes really sense.
1554 * However, from an AI point of view, preserving cur_real_order_index is the most
1555 * predictable and transparent behaviour.
1557 * With that decision it basically does not matter what we do to cur_implicit_order_index.
1558 * If we change orders between the implicit- and real-index, the implicit orders are mostly likely
1559 * completely out-dated anyway. So, keep it simple and just keep cur_implicit_order_index as well.
1560 * The worst which can happen is that a lot of implicit orders are removed when reaching current_order.
1562 if (u
->cur_real_order_index
== moving_order
) {
1563 u
->cur_real_order_index
= target_order
;
1564 } else if (u
->cur_real_order_index
> moving_order
&& u
->cur_real_order_index
<= target_order
) {
1565 u
->cur_real_order_index
--;
1566 } else if (u
->cur_real_order_index
< moving_order
&& u
->cur_real_order_index
>= target_order
) {
1567 u
->cur_real_order_index
++;
1570 if (u
->cur_implicit_order_index
== moving_order
) {
1571 u
->cur_implicit_order_index
= target_order
;
1572 } else if (u
->cur_implicit_order_index
> moving_order
&& u
->cur_implicit_order_index
<= target_order
) {
1573 u
->cur_implicit_order_index
--;
1574 } else if (u
->cur_implicit_order_index
< moving_order
&& u
->cur_implicit_order_index
>= target_order
) {
1575 u
->cur_implicit_order_index
++;
1578 u
->cur_timetable_order_index
= INVALID_VEH_ORDER_ID
;
1580 assert(v
->IsSharingOrdersWith(u
));
1582 /* Update any possible open window of the vehicle */
1583 InvalidateVehicleOrder(u
, moving_order
| (target_order
<< 8));
1586 /* As we move an order, the order to skip to will be 'wrong'. */
1588 FOR_VEHICLE_ORDERS(v
, order
) {
1589 if (order
->IsType(OT_CONDITIONAL
)) {
1590 VehicleOrderID order_id
= order
->GetConditionSkipToOrder();
1591 if (order_id
== moving_order
) {
1592 order_id
= target_order
;
1593 } else if (order_id
> moving_order
&& order_id
<= target_order
) {
1595 } else if (order_id
< moving_order
&& order_id
>= target_order
) {
1598 order
->SetConditionSkipToOrder(order_id
);
1602 /* Make sure to rebuild the whole list */
1603 InvalidateWindowClassesData(GetWindowClassForVehicleType(v
->type
), 0);
1606 return CommandCost();
1610 * Modify an order in the orderlist of a vehicle.
1611 * @param tile unused
1612 * @param flags operation to perform
1613 * @param p1 various bitstuffed elements
1614 * - p1 = (bit 0 - 19) - ID of the vehicle
1615 * - p1 = (bit 20 - 27) - the selected order (if any). If the last order is given,
1616 * the order will be inserted before that one
1617 * the maximum vehicle order id is 254.
1618 * @param p2 various bitstuffed elements
1619 * - p2 = (bit 0 - 3) - what data to modify (@see ModifyOrderFlags)
1620 * - p2 = (bit 4 - 19) - the data to modify
1621 * - p2 = (bit 20 - 27) - a CargoID for cargo type orders (MOF_CARGO_TYPE_UNLOAD or MOF_CARGO_TYPE_LOAD)
1622 * @param text unused
1623 * @return the cost of this operation or an error
1625 CommandCost
CmdModifyOrder(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1627 VehicleOrderID sel_ord
= GB(p1
, 20, 8);
1628 VehicleID veh
= GB(p1
, 0, 20);
1629 ModifyOrderFlags mof
= Extract
<ModifyOrderFlags
, 0, 4>(p2
);
1630 uint16 data
= GB(p2
, 4, 16);
1631 CargoID cargo_id
= (mof
== MOF_CARGO_TYPE_UNLOAD
|| mof
== MOF_CARGO_TYPE_LOAD
) ? (CargoID
)GB(p2
, 20, 8) : (CargoID
)CT_INVALID
;
1633 if (mof
>= MOF_END
) return CommandError();
1635 Vehicle
*v
= Vehicle::GetIfValid(veh
);
1636 if (v
== nullptr || !v
->IsPrimaryVehicle()) return CommandError();
1638 CommandCost ret
= CheckOwnership(v
->owner
);
1639 if (ret
.Failed()) return ret
;
1641 /* Is it a valid order? */
1642 if (sel_ord
>= v
->GetNumOrders()) return CommandError();
1644 Order
*order
= v
->GetOrder(sel_ord
);
1645 switch (order
->GetType()) {
1646 case OT_GOTO_STATION
:
1647 if (mof
!= MOF_NON_STOP
&& mof
!= MOF_STOP_LOCATION
&& mof
!= MOF_UNLOAD
&& mof
!= MOF_LOAD
&& mof
!= MOF_CARGO_TYPE_UNLOAD
&& mof
!= MOF_CARGO_TYPE_LOAD
) return CommandError();
1651 if (mof
!= MOF_NON_STOP
&& mof
!= MOF_DEPOT_ACTION
) return CommandError();
1654 case OT_GOTO_WAYPOINT
:
1655 if (mof
!= MOF_NON_STOP
&& mof
!= MOF_WAYPOINT_FLAGS
) return CommandError();
1658 case OT_CONDITIONAL
:
1659 if (mof
!= MOF_COND_VARIABLE
&& mof
!= MOF_COND_COMPARATOR
&& mof
!= MOF_COND_VALUE
&& mof
!= MOF_COND_DESTINATION
) return CommandError();
1663 return CommandError();
1667 default: NOT_REACHED();
1670 if (!v
->IsGroundVehicle()) return CommandError();
1671 if (data
>= ONSF_END
) return CommandError();
1672 if (data
== order
->GetNonStopType()) return CommandError();
1675 case MOF_STOP_LOCATION
:
1676 if (v
->type
!= VEH_TRAIN
) return CommandError();
1677 if (data
>= OSL_END
) return CommandError();
1680 case MOF_CARGO_TYPE_UNLOAD
:
1681 if (cargo_id
>= NUM_CARGO
) return CommandError();
1682 if (data
== OUFB_CARGO_TYPE_UNLOAD
) return CommandError();
1685 if (order
->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION
) return CommandError();
1686 if ((data
& ~(OUFB_UNLOAD
| OUFB_TRANSFER
| OUFB_NO_UNLOAD
| OUFB_CARGO_TYPE_UNLOAD
)) != 0) return CommandError();
1687 /* Unload and no-unload are mutual exclusive and so are transfer and no unload. */
1688 if (data
!= 0 && (data
& OUFB_CARGO_TYPE_UNLOAD
) == 0 && ((data
& (OUFB_UNLOAD
| OUFB_TRANSFER
)) != 0) == ((data
& OUFB_NO_UNLOAD
) != 0)) return CommandError();
1689 /* Cargo-type-unload exclude all the other flags. */
1690 if ((data
& OUFB_CARGO_TYPE_UNLOAD
) != 0 && data
!= OUFB_CARGO_TYPE_UNLOAD
) return CommandError();
1691 if (data
== order
->GetUnloadType()) return CommandError();
1694 case MOF_CARGO_TYPE_LOAD
:
1695 if (cargo_id
>= NUM_CARGO
) return CommandError();
1696 if (data
== OLFB_CARGO_TYPE_LOAD
|| data
== OLF_FULL_LOAD_ANY
) return CommandError();
1699 if (order
->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION
) return CommandError();
1700 if ((data
> OLFB_NO_LOAD
&& data
!= OLFB_CARGO_TYPE_LOAD
) || data
== 1) return CommandError();
1701 if (data
== order
->GetLoadType()) return CommandError();
1704 case MOF_DEPOT_ACTION
:
1705 if (data
>= DA_END
) return CommandError();
1708 case MOF_COND_VARIABLE
:
1709 if (data
== OCV_FREE_PLATFORMS
&& v
->type
!= VEH_TRAIN
) return CommandError();
1710 if (data
>= OCV_END
) return CommandError();
1713 case MOF_COND_COMPARATOR
:
1714 if (data
>= OCC_END
) return CommandError();
1715 switch (order
->GetConditionVariable()) {
1716 case OCV_UNCONDITIONALLY
:
1718 return CommandError();
1720 case OCV_REQUIRES_SERVICE
:
1721 case OCV_CARGO_ACCEPTANCE
:
1722 case OCV_CARGO_WAITING
:
1723 case OCV_SLOT_OCCUPANCY
:
1724 if (data
!= OCC_IS_TRUE
&& data
!= OCC_IS_FALSE
) return CommandError();
1728 if (data
== OCC_IS_TRUE
|| data
== OCC_IS_FALSE
) return CommandError();
1733 case MOF_COND_VALUE
:
1734 switch (order
->GetConditionVariable()) {
1735 case OCV_UNCONDITIONALLY
:
1736 case OCV_REQUIRES_SERVICE
:
1737 return CommandError();
1739 case OCV_LOAD_PERCENTAGE
:
1740 case OCV_RELIABILITY
:
1742 if (data
> 100) return CommandError();
1745 case OCV_SLOT_OCCUPANCY
:
1746 if (data
!= INVALID_TRACE_RESTRICT_SLOT_ID
&& !TraceRestrictSlot::IsValidID(data
)) return CommandError();
1749 case OCV_CARGO_ACCEPTANCE
:
1750 case OCV_CARGO_WAITING
:
1751 if (!(data
< NUM_CARGO
&& CargoSpec::Get(data
)->IsValid())) return CommandError();
1755 if (data
> 2047) return CommandError();
1760 case MOF_COND_DESTINATION
:
1761 if (data
>= v
->GetNumOrders()) return CommandError();
1764 case MOF_WAYPOINT_FLAGS
:
1765 if (data
!= (data
& OWF_REVERSE
)) return CommandError();
1769 if (flags
& DC_EXEC
) {
1772 order
->SetNonStopType((OrderNonStopFlags
)data
);
1773 if (data
& ONSF_NO_STOP_AT_DESTINATION_STATION
) {
1774 order
->SetRefit(CT_NO_REFIT
);
1775 order
->SetLoadType(OLF_LOAD_IF_POSSIBLE
);
1776 order
->SetUnloadType(OUF_UNLOAD_IF_POSSIBLE
);
1780 case MOF_STOP_LOCATION
:
1781 order
->SetStopLocation((OrderStopLocation
)data
);
1785 order
->SetUnloadType((OrderUnloadFlags
)data
);
1788 case MOF_CARGO_TYPE_UNLOAD
:
1789 order
->SetUnloadType((OrderUnloadFlags
)data
, cargo_id
);
1793 order
->SetLoadType((OrderLoadFlags
)data
);
1794 if (data
& OLFB_NO_LOAD
) order
->SetRefit(CT_NO_REFIT
);
1797 case MOF_CARGO_TYPE_LOAD
:
1798 order
->SetLoadType((OrderLoadFlags
)data
, cargo_id
);
1801 case MOF_DEPOT_ACTION
: {
1804 order
->SetDepotOrderType((OrderDepotTypeFlags
)(order
->GetDepotOrderType() & ~ODTFB_SERVICE
));
1805 order
->SetDepotActionType((OrderDepotActionFlags
)(order
->GetDepotActionType() & ~ODATFB_HALT
));
1809 order
->SetDepotOrderType((OrderDepotTypeFlags
)(order
->GetDepotOrderType() | ODTFB_SERVICE
));
1810 order
->SetDepotActionType((OrderDepotActionFlags
)(order
->GetDepotActionType() & ~ODATFB_HALT
));
1811 order
->SetRefit(CT_NO_REFIT
);
1815 order
->SetDepotOrderType((OrderDepotTypeFlags
)(order
->GetDepotOrderType() & ~ODTFB_SERVICE
));
1816 order
->SetDepotActionType((OrderDepotActionFlags
)(order
->GetDepotActionType() | ODATFB_HALT
));
1817 order
->SetRefit(CT_NO_REFIT
);
1826 case MOF_COND_VARIABLE
: {
1827 /* Check whether old conditional variable had a cargo as value */
1828 bool old_var_was_cargo
= (order
->GetConditionVariable() == OCV_CARGO_ACCEPTANCE
|| order
->GetConditionVariable() == OCV_CARGO_WAITING
);
1829 bool old_var_was_slot
= (order
->GetConditionVariable() == OCV_SLOT_OCCUPANCY
);
1830 order
->SetConditionVariable((OrderConditionVariable
)data
);
1832 OrderConditionComparator occ
= order
->GetConditionComparator();
1833 switch (order
->GetConditionVariable()) {
1834 case OCV_UNCONDITIONALLY
:
1835 order
->SetConditionComparator(OCC_EQUALS
);
1836 order
->SetConditionValue(0);
1839 case OCV_SLOT_OCCUPANCY
:
1840 if (!old_var_was_slot
) order
->GetXDataRef() = INVALID_TRACE_RESTRICT_SLOT_ID
;
1841 if (occ
!= OCC_IS_TRUE
&& occ
!= OCC_IS_FALSE
) order
->SetConditionComparator(OCC_IS_TRUE
);
1844 case OCV_CARGO_ACCEPTANCE
:
1845 case OCV_CARGO_WAITING
:
1846 if (!old_var_was_cargo
) order
->SetConditionValue((uint16
) GetFirstValidCargo());
1847 if (occ
!= OCC_IS_TRUE
&& occ
!= OCC_IS_FALSE
) order
->SetConditionComparator(OCC_IS_TRUE
);
1850 case OCV_REQUIRES_SERVICE
:
1851 if (old_var_was_cargo
|| old_var_was_slot
) order
->SetConditionValue(0);
1852 if (occ
!= OCC_IS_TRUE
&& occ
!= OCC_IS_FALSE
) order
->SetConditionComparator(OCC_IS_TRUE
);
1853 order
->SetConditionValue(0);
1857 order
->SetConditionComparator(OCC_EQUALS
);
1860 case OCV_LOAD_PERCENTAGE
:
1861 case OCV_RELIABILITY
:
1862 if (order
->GetConditionValue() > 100) order
->SetConditionValue(100);
1866 if (old_var_was_cargo
|| old_var_was_slot
) order
->SetConditionValue(0);
1867 if (occ
== OCC_IS_TRUE
|| occ
== OCC_IS_FALSE
) order
->SetConditionComparator(OCC_EQUALS
);
1873 case MOF_COND_COMPARATOR
:
1874 order
->SetConditionComparator((OrderConditionComparator
)data
);
1877 case MOF_COND_VALUE
:
1878 switch (order
->GetConditionVariable()) {
1879 case OCV_SLOT_OCCUPANCY
:
1880 order
->GetXDataRef() = data
;
1884 order
->SetConditionValue(data
);
1889 case MOF_COND_DESTINATION
:
1890 order
->SetConditionSkipToOrder(data
);
1893 case MOF_WAYPOINT_FLAGS
:
1894 order
->SetWaypointFlags((OrderWaypointFlags
)data
);
1897 default: NOT_REACHED();
1900 /* Update the windows and full load flags, also for vehicles that share the same order list */
1901 Vehicle
*u
= v
->FirstShared();
1902 DeleteOrderWarnings(u
);
1903 for (; u
!= nullptr; u
= u
->NextShared()) {
1904 /* Toggle u->current_order "Full load" flag if it changed.
1905 * However, as the same flag is used for depot orders, check
1906 * whether we are not going to a depot as there are three
1907 * cases where the full load flag can be active and only
1908 * one case where the flag is used for depot orders. In the
1909 * other cases for the OrderTypeByte the flags are not used,
1910 * so do not care and those orders should not be active
1911 * when this function is called.
1913 if (sel_ord
== u
->cur_real_order_index
&&
1914 (u
->current_order
.IsType(OT_GOTO_STATION
) || u
->current_order
.IsType(OT_LOADING
)) &&
1915 u
->current_order
.GetLoadType() != order
->GetLoadType()) {
1916 u
->current_order
.SetLoadType(order
->GetLoadType());
1918 InvalidateVehicleOrder(u
, VIWD_MODIFY_ORDERS
);
1920 CheckMarkDirtyFocusedRoutePaths(v
);
1923 return CommandCost();
1927 * Check if an aircraft has enough range for an order list.
1928 * @param v_new Aircraft to check.
1929 * @param v_order Vehicle currently holding the order list.
1930 * @param first First order in the source order list.
1931 * @return True if the aircraft has enough range for the orders, false otherwise.
1933 static bool CheckAircraftOrderDistance(const Aircraft
*v_new
, const Vehicle
*v_order
, const Order
*first
)
1935 if (first
== nullptr || v_new
->acache
.cached_max_range
== 0) return true;
1937 /* Iterate over all orders to check the distance between all
1938 * 'goto' orders and their respective next order (of any type). */
1939 for (const Order
*o
= first
; o
!= nullptr; o
= o
->next
) {
1940 switch (o
->GetType()) {
1941 case OT_GOTO_STATION
:
1943 case OT_GOTO_WAYPOINT
:
1944 /* If we don't have a next order, we've reached the end and must check the first order instead. */
1945 if (GetOrderDistance(o
, o
->next
!= nullptr ? o
->next
: first
, v_order
) > v_new
->acache
.cached_max_range_sqr
) return false;
1956 * Clone/share/copy an order-list of another vehicle.
1957 * @param tile unused
1958 * @param flags operation to perform
1959 * @param p1 various bitstuffed elements
1960 * - p1 = (bit 0-19) - destination vehicle to clone orders to
1961 * - p1 = (bit 30-31) - action to perform
1962 * @param p2 source vehicle to clone orders from, if any (none for CO_UNSHARE)
1963 * @param text unused
1964 * @return the cost of this operation or an error
1966 CommandCost
CmdCloneOrder(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1968 VehicleID veh_src
= GB(p2
, 0, 20);
1969 VehicleID veh_dst
= GB(p1
, 0, 20);
1971 Vehicle
*dst
= Vehicle::GetIfValid(veh_dst
);
1972 if (dst
== nullptr || !dst
->IsPrimaryVehicle()) return CommandError();
1974 CommandCost ret
= CheckOwnership(dst
->owner
);
1975 if (ret
.Failed()) return ret
;
1977 switch (GB(p1
, 30, 2)) {
1979 Vehicle
*src
= Vehicle::GetIfValid(veh_src
);
1982 if (src
== nullptr || !src
->IsPrimaryVehicle() || dst
->type
!= src
->type
|| dst
== src
) return CommandError();
1984 CommandCost ret
= CheckOwnership(src
->owner
);
1985 if (ret
.Failed()) return ret
;
1987 /* Trucks can't share orders with busses (and visa versa) */
1988 if (src
->type
== VEH_ROAD
&& RoadVehicle::From(src
)->IsBus() != RoadVehicle::From(dst
)->IsBus()) {
1989 return CommandError();
1992 /* Is the vehicle already in the shared list? */
1993 if (src
->FirstShared() == dst
->FirstShared()) return CommandError();
1997 FOR_VEHICLE_ORDERS(src
, order
) {
1998 if (!OrderGoesToStation(dst
, order
)) continue;
2000 /* Allow copying unreachable destinations if they were already unreachable for the source.
2001 * This is basically to allow cloning / autorenewing / autoreplacing vehicles, while the stations
2002 * are temporarily invalid due to reconstruction. */
2003 const Station
*st
= Station::Get(order
->GetDestination());
2004 if (CanVehicleUseStation(src
, st
) && !CanVehicleUseStation(dst
, st
)) {
2005 return CommandError(STR_ERROR_CAN_T_COPY_SHARE_ORDER
);
2009 /* Check for aircraft range limits. */
2010 if (dst
->type
== VEH_AIRCRAFT
&& !CheckAircraftOrderDistance(Aircraft::From(dst
), src
, src
->GetFirstOrder())) {
2011 return CommandError(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE
);
2014 if (!src
->HasOrdersList() && !OrderList::CanAllocateItem()) {
2015 return CommandError(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS
);
2018 if (flags
& DC_EXEC
) {
2019 /* If the destination vehicle had a OrderList, destroy it.
2020 * We only reset the order indices, if the new orders are obviously different.
2021 * (We mainly do this to keep the order indices valid and in range.) */
2022 dst
->DeleteVehicleOrders(false, dst
->GetNumOrders() != src
->GetNumOrders());
2024 dst
->ShareOrdersWith(src
);
2026 /* Link this vehicle in the shared-list */
2027 dst
->AddToShared(src
);
2029 /* Set automation bit if target has it. */
2030 if (HasBit(src
->vehicle_flags
, VF_AUTOMATE_TIMETABLE
)) {
2031 SetBit(dst
->vehicle_flags
, VF_AUTOMATE_TIMETABLE
);
2034 ClrBit(dst
->vehicle_flags
, VF_AUTOMATE_TIMETABLE
);
2037 if (HasBit(src
->vehicle_flags
, VF_AUTOMATE_PRES_WAIT_TIME
)) {
2038 SetBit(dst
->vehicle_flags
, VF_AUTOMATE_PRES_WAIT_TIME
);
2041 ClrBit(dst
->vehicle_flags
, VF_AUTOMATE_PRES_WAIT_TIME
);
2044 InvalidateVehicleOrder(dst
, VIWD_REMOVE_ALL_ORDERS
);
2045 InvalidateVehicleOrder(src
, VIWD_MODIFY_ORDERS
);
2047 InvalidateWindowClassesData(GetWindowClassForVehicleType(dst
->type
), 0);
2048 CheckMarkDirtyFocusedRoutePaths(dst
);
2054 Vehicle
*src
= Vehicle::GetIfValid(veh_src
);
2057 if (src
== nullptr || !src
->IsPrimaryVehicle() || dst
->type
!= src
->type
|| dst
== src
) return CommandError();
2059 CommandCost ret
= CheckOwnership(src
->owner
);
2060 if (ret
.Failed()) return ret
;
2062 /* Trucks can't copy all the orders from busses (and visa versa),
2063 * and neither can helicopters and aircraft. */
2065 FOR_VEHICLE_ORDERS(src
, order
) {
2066 if (OrderGoesToStation(dst
, order
) &&
2067 !CanVehicleUseStation(dst
, Station::Get(order
->GetDestination()))) {
2068 return CommandError(STR_ERROR_CAN_T_COPY_SHARE_ORDER
);
2072 /* Check for aircraft range limits. */
2073 if (dst
->type
== VEH_AIRCRAFT
&& !CheckAircraftOrderDistance(Aircraft::From(dst
), src
, src
->GetFirstOrder())) {
2074 return CommandError(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE
);
2077 /* make sure there are orders available */
2078 if (!Order::CanAllocateItem(src
->GetNumOrders()) || !OrderList::CanAllocateItem()) {
2079 return CommandError(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS
);
2082 if (flags
& DC_EXEC
) {
2084 Order
*first
= nullptr;
2087 /* If the destination vehicle had an order list, destroy the chain but keep the OrderList.
2088 * We only reset the order indices, if the new orders are obviously different.
2089 * (We mainly do this to keep the order indices valid and in range.) */
2090 dst
->DeleteVehicleOrders(true, dst
->GetNumOrders() != src
->GetNumOrders());
2093 FOR_VEHICLE_ORDERS(src
, order
) {
2094 *order_dst
= new Order();
2095 (*order_dst
)->AssignOrder(*order
);
2096 order_dst
= &(*order_dst
)->next
;
2098 if (!dst
->HasOrdersList()) {
2099 dst
->SetOrdersList(new OrderList(first
, dst
));
2101 assert(dst
->GetFirstOrder() == nullptr);
2102 assert(!dst
->HasSharedOrdersList());
2103 dst
->DeleteAndReplaceOrdersList(new OrderList(first
, dst
));
2106 /* Set automation bit if target has it. */
2107 if (HasBit(src
->vehicle_flags
, VF_AUTOMATE_TIMETABLE
)) {
2108 SetBit(dst
->vehicle_flags
, VF_AUTOMATE_TIMETABLE
);
2111 ClrBit(dst
->vehicle_flags
, VF_AUTOMATE_TIMETABLE
);
2114 if (HasBit(src
->vehicle_flags
, VF_AUTOMATE_PRES_WAIT_TIME
)) {
2115 SetBit(dst
->vehicle_flags
, VF_AUTOMATE_PRES_WAIT_TIME
);
2118 ClrBit(dst
->vehicle_flags
, VF_AUTOMATE_PRES_WAIT_TIME
);
2121 InvalidateVehicleOrder(dst
, VIWD_REMOVE_ALL_ORDERS
);
2123 InvalidateWindowClassesData(GetWindowClassForVehicleType(dst
->type
), 0);
2124 CheckMarkDirtyFocusedRoutePaths(dst
);
2129 case CO_UNSHARE
: return DecloneOrder(dst
, flags
);
2130 default: return CommandError();
2133 return CommandCost();
2137 * Add/remove refit orders from an order
2138 * @param tile Not used
2139 * @param flags operation to perform
2140 * @param p1 VehicleIndex of the vehicle having the order
2143 * - bit 16-23 number of order to modify
2144 * @param text unused
2145 * @return the cost of this operation or an error
2147 CommandCost
CmdOrderRefit(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2149 VehicleID veh
= GB(p1
, 0, 20);
2150 VehicleOrderID order_number
= GB(p2
, 16, 8);
2151 CargoID cargo
= GB(p2
, 0, 8);
2153 if (cargo
>= NUM_CARGO
&& cargo
!= CT_NO_REFIT
&& cargo
!= CT_AUTO_REFIT
) return CommandError();
2155 const Vehicle
*v
= Vehicle::GetIfValid(veh
);
2156 if (v
== nullptr || !v
->IsPrimaryVehicle()) return CommandError();
2158 CommandCost ret
= CheckOwnership(v
->owner
);
2159 if (ret
.Failed()) return ret
;
2161 Order
*order
= v
->GetOrder(order_number
);
2162 if (order
== nullptr) return CommandError();
2164 /* Automatic refit cargo is only supported for goto station orders. */
2165 if (cargo
== CT_AUTO_REFIT
&& !order
->IsType(OT_GOTO_STATION
)) return CommandError();
2167 if (order
->GetLoadType() & OLFB_NO_LOAD
) return CommandError();
2169 if (flags
& DC_EXEC
) {
2170 order
->SetRefit(cargo
);
2172 /* Make the depot order an 'always go' order. */
2173 if (cargo
!= CT_NO_REFIT
&& order
->IsType(OT_GOTO_DEPOT
)) {
2174 order
->SetDepotOrderType((OrderDepotTypeFlags
)(order
->GetDepotOrderType() & ~ODTFB_SERVICE
));
2175 order
->SetDepotActionType((OrderDepotActionFlags
)(order
->GetDepotActionType() & ~ODATFB_HALT
));
2178 for (Vehicle
*u
= v
->FirstShared(); u
!= nullptr; u
= u
->NextShared()) {
2179 /* Update any possible open window of the vehicle */
2180 InvalidateVehicleOrder(u
, VIWD_MODIFY_ORDERS
);
2182 /* If the vehicle already got the current depot set as current order, then update current order as well */
2183 if (u
->cur_real_order_index
== order_number
&& (u
->current_order
.GetDepotOrderType() & ODTFB_PART_OF_ORDERS
)) {
2184 u
->current_order
.SetRefit(cargo
);
2187 CheckMarkDirtyFocusedRoutePaths(v
);
2190 return CommandCost();
2196 * Check the orders of a vehicle, to see if there are invalid orders and stuff
2199 void CheckOrders(const Vehicle
*v
)
2201 /* Does the user wants us to check things? */
2202 if (_settings_client
.gui
.order_review_system
== 0) return;
2204 /* Do nothing for crashed vehicles */
2205 if (v
->vehstatus
& VS_CRASHED
) return;
2207 /* Do nothing for stopped vehicles if setting is '1' */
2208 if (_settings_client
.gui
.order_review_system
== 1 && (v
->vehstatus
& VS_STOPPED
)) return;
2210 /* do nothing we we're not the first vehicle in a share-chain */
2211 if (v
->FirstShared() != v
) return;
2213 /* Only check every 20 days, so that we don't flood the message log */
2214 /* The check is skipped entirely in case the current vehicle is virtual (a.k.a a 'template train') */
2215 if (v
->owner
== _local_company
&& v
->day_counter
% 20 == 0 && !HasBit(v
->subtype
, GVSF_VIRTUAL
) ) {
2217 StringID message
= INVALID_STRING_ID
;
2219 /* Check the order list */
2222 FOR_VEHICLE_ORDERS(v
, order
) {
2224 if (order
->IsType(OT_DUMMY
)) {
2225 message
= STR_NEWS_VEHICLE_HAS_VOID_ORDER
;
2228 /* Does station have a load-bay for this vehicle? */
2229 if (order
->IsType(OT_GOTO_STATION
)) {
2230 const Station
*st
= Station::Get(order
->GetDestination());
2233 if (!CanVehicleUseStation(v
, st
)) {
2234 message
= STR_NEWS_VEHICLE_HAS_INVALID_ENTRY
;
2235 } else if (v
->type
== VEH_AIRCRAFT
&&
2236 (AircraftVehInfo(v
->engine_type
)->subtype
& AIR_FAST
) &&
2237 (st
->airport
.GetFTA()->flags
& AirportFTAClass::SHORT_STRIP
) &&
2238 _settings_game
.vehicle
.plane_crashes
!= 0 &&
2239 !_cheats
.no_jetcrash
.value
&&
2240 message
== INVALID_STRING_ID
) {
2241 message
= STR_NEWS_PLANE_USES_TOO_SHORT_RUNWAY
;
2246 /* Check if the last and the first order are the same */
2247 if (v
->GetNumOrders() > 1) {
2248 const Order
*last
= v
->GetLastOrder();
2250 if (v
->GetFirstOrder()->Equals(*last
)) {
2251 message
= STR_NEWS_VEHICLE_HAS_DUPLICATE_ENTRY
;
2255 /* Do we only have 1 station in our order list? */
2256 if (n_st
< 2 && message
== INVALID_STRING_ID
) message
= STR_NEWS_VEHICLE_HAS_TOO_FEW_ORDERS
;
2259 v
->DebugCheckSanity();
2262 /* We don't have a problem */
2263 if (message
== INVALID_STRING_ID
) return;
2265 SetDParam(0, v
->index
);
2266 AddVehicleAdviceNewsItem(message
, v
->index
);
2271 * Removes an order from all vehicles. Triggers when, say, a station is removed.
2272 * @param type The type of the order (OT_GOTO_[STATION|DEPOT|WAYPOINT]).
2273 * @param destination The destination. Can be a StationID, DepotID or WaypointID.
2275 void RemoveOrderFromAllVehicles(OrderType type
, DestinationID destination
)
2279 /* Aircraft have StationIDs for depot orders and never use DepotIDs
2280 * This fact is handled specially below
2283 /* Go through all vehicles */
2284 FOR_ALL_VEHICLES(v
) {
2287 order
= &v
->current_order
;
2288 if ((v
->type
== VEH_AIRCRAFT
&& order
->IsType(OT_GOTO_DEPOT
) ? OT_GOTO_STATION
: order
->GetType()) == type
&&
2289 v
->current_order
.GetDestination() == destination
) {
2291 SetWindowDirty(WC_VEHICLE_VIEW
, v
->index
);
2294 /* Clear the order from the order-list */
2296 FOR_VEHICLE_ORDERS(v
, order
) {
2300 OrderType ot
= order
->GetType();
2301 if (ot
== OT_GOTO_DEPOT
&& (order
->GetDepotActionType() & ODATFB_NEAREST_DEPOT
) != 0) continue;
2302 if (ot
== OT_IMPLICIT
|| (v
->type
== VEH_AIRCRAFT
&& ot
== OT_GOTO_DEPOT
)) ot
= OT_GOTO_STATION
;
2303 if (ot
== type
&& order
->GetDestination() == destination
) {
2304 /* We want to clear implicit orders, but we don't want to make them
2305 * dummy orders. They should just vanish. Also check the actual order
2306 * type as ot is currently OT_GOTO_STATION. */
2307 if (order
->IsType(OT_IMPLICIT
)) {
2308 order
= order
->next
; // DeleteOrder() invalidates current order
2310 if (order
!= nullptr) goto restart
;
2314 /* Clear wait time */
2315 v
->UpdateTotalDuration(-order
->GetWaitTime());
2316 if (order
->IsWaitTimetabled()) {
2317 v
->UpdateTimetableDuration(-order
->GetTimetabledWait());
2318 order
->SetWaitTimetabled(false);
2320 order
->SetWaitTime(0);
2322 /* Clear order, preserving travel time */
2323 bool travel_timetabled
= order
->IsTravelTimetabled();
2325 order
->SetTravelTimetabled(travel_timetabled
);
2327 for (const Vehicle
*w
= v
->FirstShared(); w
!= nullptr; w
= w
->NextShared()) {
2328 /* In GUI, simulate by removing the order and adding it back */
2329 InvalidateVehicleOrder(w
, id
| (INVALID_VEH_ORDER_ID
<< 8));
2330 InvalidateVehicleOrder(w
, (INVALID_VEH_ORDER_ID
<< 8) | id
);
2336 OrderBackup::RemoveOrder(type
, destination
);
2340 * Checks if a vehicle has a depot in its order list.
2341 * @return True iff at least one order is a depot order.
2343 bool Vehicle::HasDepotOrder() const
2347 FOR_VEHICLE_ORDERS(this, order
) {
2348 if (order
->IsType(OT_GOTO_DEPOT
)) return true;
2355 * Clamp the service interval to the correct min/max. The actual min/max values
2356 * depend on whether it's in percent or days.
2357 * @param interval proposed service interval
2358 * @param company_id the owner of the vehicle
2359 * @return Clamped service interval
2361 uint16
GetServiceIntervalClamped(uint interval
, bool ispercent
)
2363 return ispercent
? Clamp(interval
, MIN_SERVINT_PERCENT
, MAX_SERVINT_PERCENT
) : Clamp(interval
, MIN_SERVINT_DAYS
, MAX_SERVINT_DAYS
);
2368 * Check if a vehicle has any valid orders
2370 * @return false if there are no valid orders
2371 * @note Conditional orders are not considered valid destination orders
2374 static bool CheckForValidOrders(const Vehicle
*v
)
2378 FOR_VEHICLE_ORDERS(v
, order
) {
2379 switch (order
->GetType()) {
2380 case OT_GOTO_STATION
:
2382 case OT_GOTO_WAYPOINT
:
2394 * Compare the variable and value based on the given comparator.
2396 static bool OrderConditionCompare(OrderConditionComparator occ
, int variable
, int value
)
2399 case OCC_EQUALS
: return variable
== value
;
2400 case OCC_NOT_EQUALS
: return variable
!= value
;
2401 case OCC_LESS_THAN
: return variable
< value
;
2402 case OCC_LESS_EQUALS
: return variable
<= value
;
2403 case OCC_MORE_THAN
: return variable
> value
;
2404 case OCC_MORE_EQUALS
: return variable
>= value
;
2405 case OCC_IS_TRUE
: return variable
!= 0;
2406 case OCC_IS_FALSE
: return variable
== 0;
2407 default: NOT_REACHED();
2411 /* Get the number of free (train) platforms in a station.
2412 * @param st_id The StationID of the station.
2413 * @return The number of free train platforms.
2415 static uint16
GetFreeStationPlatforms(StationID st_id
)
2417 assert(Station::IsValidID(st_id
));
2418 const Station
*st
= Station::Get(st_id
);
2419 if (!(st
->facilities
& FACIL_TRAIN
)) return 0;
2423 TILE_AREA_LOOP(t1
, st
->train_station
) {
2424 if (st
->TileBelongsToRailStation(t1
)) {
2425 /* We only proceed if this tile is a track tile and the north(-east/-west) end of the platform */
2426 if (IsCompatibleTrainStationTile(t1
+ TileOffsByDiagDir(GetRailStationAxis(t1
) == AXIS_X
? DIAGDIR_NE
: DIAGDIR_NW
), t1
) || IsStationTileBlocked(t1
)) continue;
2430 if (GetStationReservationTrackBits(t2
)) {
2434 t2
+= TileOffsByDiagDir(GetRailStationAxis(t1
) == AXIS_X
? DIAGDIR_SW
: DIAGDIR_SE
);
2435 } while (IsCompatibleTrainStationTile(t2
, t1
));
2436 if (is_free
) counter
++;
2442 /** Gets the next 'real' station in the order list
2443 * @param v the vehicle in question
2444 * @param order the current (conditional) order
2445 * @return the StationID of the next valid station in the order list, or INVALID_STATION if there is none.
2447 static StationID
GetNextRealStation(const Vehicle
*v
, const Order
*order
, int conditional_depth
= 0)
2449 if (order
->IsType(OT_GOTO_STATION
)) {
2450 if (Station::IsValidID(order
->GetDestination())) return order
->GetDestination();
2452 //nothing conditional about this
2453 if (conditional_depth
> v
->GetNumOrders()) return INVALID_STATION
;
2454 return GetNextRealStation(v
, (order
->next
!= nullptr) ? order
->next
: v
->GetFirstOrder(), ++conditional_depth
);
2458 * Process a conditional order and determine the next order.
2459 * @param order the order the vehicle currently has
2460 * @param v the vehicle to update
2461 * @return index of next order to jump to, or INVALID_VEH_ORDER_ID to use the next order
2463 VehicleOrderID
ProcessConditionalOrder(const Order
*order
, const Vehicle
*v
)
2465 if (order
->GetType() != OT_CONDITIONAL
) return INVALID_VEH_ORDER_ID
;
2467 bool skip_order
= false;
2468 OrderConditionComparator occ
= order
->GetConditionComparator();
2469 uint16 value
= order
->GetConditionValue();
2470 bool has_manual_depot_order
= (HasBit(v
->vehicle_flags
, VF_SHOULD_GOTO_DEPOT
) || HasBit(v
->vehicle_flags
, VF_SHOULD_SERVICE_AT_DEPOT
));
2472 // OrderConditionCompare ignores the last parameter for occ == OCC_IS_TRUE or occ == OCC_IS_FALSE.
2473 switch (order
->GetConditionVariable()) {
2474 case OCV_LOAD_PERCENTAGE
: skip_order
= OrderConditionCompare(occ
, CalcPercentVehicleFilled(v
, nullptr), value
); break;
2475 case OCV_RELIABILITY
: skip_order
= OrderConditionCompare(occ
, ToPercent16(v
->reliability
), value
); break;
2476 case OCV_MAX_SPEED
: skip_order
= OrderConditionCompare(occ
, v
->GetDisplayMaxSpeed() * 10 / 16, value
); break;
2477 case OCV_AGE
: skip_order
= OrderConditionCompare(occ
, v
->age
/ DAYS_IN_LEAP_YEAR
, value
); break;
2478 case OCV_REQUIRES_SERVICE
: skip_order
= OrderConditionCompare(occ
, has_manual_depot_order
|| v
->NeedsServicing(), value
); break;
2479 case OCV_UNCONDITIONALLY
: skip_order
= true; break;
2480 case OCV_CARGO_WAITING
: {
2481 StationID next_station
= GetNextRealStation(v
, order
);
2482 if (Station::IsValidID(next_station
)) skip_order
= OrderConditionCompare(occ
, Station::Get(next_station
)->goods
[value
].cargo
.AvailableCount() > 0, value
);
2485 case OCV_CARGO_ACCEPTANCE
: {
2486 StationID next_station
= GetNextRealStation(v
, order
);
2487 if (Station::IsValidID(next_station
)) skip_order
= OrderConditionCompare(occ
, HasBit(Station::Get(next_station
)->goods
[value
].status
, GoodsEntry::GES_ACCEPTANCE
), value
);
2490 case OCV_SLOT_OCCUPANCY
: {
2491 const TraceRestrictSlot
* slot
= TraceRestrictSlot::GetIfValid(order
->GetXData());
2492 if (slot
!= nullptr) skip_order
= OrderConditionCompare(occ
, slot
->occupants
.size() >= slot
->max_occupancy
, value
);
2495 case OCV_FREE_PLATFORMS
: {
2496 StationID next_station
= GetNextRealStation(v
, order
);
2497 if (Station::IsValidID(next_station
)) skip_order
= OrderConditionCompare(occ
, GetFreeStationPlatforms(next_station
), value
);
2501 /* get a non-const reference to the current order */
2502 Order
*ord
= (Order
*)order
;
2503 skip_order
= ord
->UpdateJumpCounter((byte
)value
);
2506 case OCV_REMAINING_LIFETIME
: skip_order
= OrderConditionCompare(occ
, max(v
->max_age
- v
->age
+ DAYS_IN_LEAP_YEAR
- 1, 0) / DAYS_IN_LEAP_YEAR
, value
); break;
2507 default: NOT_REACHED();
2510 return skip_order
? order
->GetConditionSkipToOrder() : (VehicleOrderID
)INVALID_VEH_ORDER_ID
;
2514 * Update the vehicle's destination tile from an order.
2515 * @param order the order the vehicle currently has
2516 * @param v the vehicle to update
2517 * @param conditional_depth the depth (amount of steps) to go with conditional orders. This to prevent infinite loops.
2518 * @param pbs_look_ahead Whether we are forecasting orders for pbs reservations in advance. If true, the order indices must not be modified.
2520 bool UpdateOrderDest(Vehicle
*v
, const Order
*order
, int conditional_depth
, bool pbs_look_ahead
)
2522 if (conditional_depth
> v
->GetNumOrders()) {
2523 v
->current_order
.Free();
2528 bool has_manual_depot_order
= (HasBit(v
->vehicle_flags
, VF_SHOULD_GOTO_DEPOT
) || HasBit(v
->vehicle_flags
, VF_SHOULD_SERVICE_AT_DEPOT
));
2530 switch (order
->GetType()) {
2531 case OT_GOTO_STATION
:
2532 v
->dest_tile
= v
->GetOrderStationLocation(order
->GetDestination());
2536 if ((order
->GetDepotOrderType() & ODTFB_SERVICE
) && !(v
->NeedsServicing() || has_manual_depot_order
)) {
2537 assert(!pbs_look_ahead
);
2538 UpdateVehicleTimetable(v
, true);
2539 v
->IncrementRealOrderIndex();
2543 if (v
->current_order
.GetDepotActionType() & ODATFB_NEAREST_DEPOT
) {
2544 /* We need to search for the nearest depot (hangar). */
2546 DestinationID destination
;
2549 if (v
->FindClosestDepot(&location
, &destination
, &reverse
)) {
2550 /* PBS reservations cannot reverse */
2551 if (pbs_look_ahead
&& reverse
) return false;
2553 v
->dest_tile
= location
;
2554 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());
2556 /* If there is no depot in front, reverse automatically (trains only) */
2557 if (v
->type
== VEH_TRAIN
&& reverse
) DoCommand(v
->tile
, v
->index
, 0, DC_EXEC
, CMD_REVERSE_TRAIN_DIRECTION
);
2559 if (v
->type
== VEH_AIRCRAFT
) {
2560 Aircraft
*a
= Aircraft::From(v
);
2561 if (a
->state
== FLYING
&& a
->targetairport
!= destination
) {
2562 /* The aircraft is now heading for a different hangar than the next in the orders */
2563 extern void AircraftNextAirportPos_and_Order(Aircraft
*a
);
2564 AircraftNextAirportPos_and_Order(a
);
2570 /* If there is no depot, we cannot help PBS either. */
2571 if (pbs_look_ahead
) return false;
2573 UpdateVehicleTimetable(v
, true);
2574 v
->IncrementRealOrderIndex();
2576 if (v
->type
!= VEH_AIRCRAFT
) {
2577 v
->dest_tile
= Depot::Get(order
->GetDestination())->xy
;
2583 case OT_GOTO_WAYPOINT
:
2584 v
->dest_tile
= Waypoint::Get(order
->GetDestination())->xy
;
2587 case OT_CONDITIONAL
: {
2588 assert(!pbs_look_ahead
);
2589 VehicleOrderID next_order
= ProcessConditionalOrder(order
, v
);
2590 if (next_order
!= INVALID_VEH_ORDER_ID
) {
2591 /* Jump to next_order. cur_implicit_order_index becomes exactly that order,
2592 * cur_real_order_index might come after next_order. */
2593 UpdateVehicleTimetable(v
, false);
2594 v
->cur_implicit_order_index
= v
->cur_real_order_index
= next_order
;
2595 v
->UpdateRealOrderIndex();
2596 v
->cur_timetable_order_index
= v
->GetIndexOfOrder(order
);
2598 /* Disable creation of implicit orders.
2599 * When inserting them we do not know that we would have to make the conditional orders point to them. */
2600 if (v
->IsGroundVehicle()) {
2601 uint16
&gv_flags
= v
->GetGroundVehicleFlags();
2602 SetBit(gv_flags
, GVF_SUPPRESS_IMPLICIT_ORDERS
);
2605 v
->cur_timetable_order_index
= INVALID_VEH_ORDER_ID
;
2606 UpdateVehicleTimetable(v
, true);
2607 v
->IncrementRealOrderIndex();
2617 assert(v
->cur_implicit_order_index
< v
->GetNumOrders());
2618 assert(v
->cur_real_order_index
< v
->GetNumOrders());
2620 /* Get the current order */
2621 order
= v
->GetOrder(v
->cur_real_order_index
);
2622 if (order
!= nullptr && order
->IsType(OT_IMPLICIT
)) {
2623 assert(v
->GetNumManualOrders() == 0);
2627 if (order
== nullptr) {
2628 v
->current_order
.Free();
2633 v
->current_order
= *order
;
2634 return UpdateOrderDest(v
, order
, conditional_depth
+ 1, pbs_look_ahead
);
2638 * Handle the orders of a vehicle and determine the next place
2639 * to go to if needed.
2640 * @param v the vehicle to do this for.
2641 * @return true *if* the vehicle is eligible for reversing
2642 * (basically only when leaving a station).
2644 bool ProcessOrders(Vehicle
*v
)
2646 // Check if we have an illegal manual depot order. Could happen if we deleted the depot order from the orders list after sending
2647 // the vehicle to the depot.
2648 if (HasBit(v
->vehicle_flags
, VF_SHOULD_GOTO_DEPOT
) || HasBit(v
->vehicle_flags
, VF_SHOULD_SERVICE_AT_DEPOT
)) {
2649 int next_depot_index
= -1;
2651 for (int i
= 0; i
< v
->GetNumOrders(); ++i
) {
2652 Order
* order
= v
->GetOrder(i
);
2654 bool isRegularOrder
= (order
->GetDepotOrderType() & ODTFB_PART_OF_ORDERS
) != 0;
2655 bool isDepotOrder
= order
->GetType() == OT_GOTO_DEPOT
;
2657 if (isRegularOrder
&& isDepotOrder
) {
2658 if (i
>= v
->cur_implicit_order_index
) {
2659 next_depot_index
= i
;
2662 else if (next_depot_index
< 0) {
2663 next_depot_index
= i
;
2668 if (next_depot_index
== -1) {
2669 ClrBit(v
->vehicle_flags
, VF_SHOULD_GOTO_DEPOT
);
2670 ClrBit(v
->vehicle_flags
, VF_SHOULD_SERVICE_AT_DEPOT
);
2674 switch (v
->current_order
.GetType()) {
2676 // Check whether the vehicle was manually ordered to go to the depot on its order list.
2677 // If so mark the current depot order as manual, now that we are processing it.
2678 if (HasBit(v
->vehicle_flags
, VF_SHOULD_GOTO_DEPOT
) || HasBit(v
->vehicle_flags
, VF_SHOULD_SERVICE_AT_DEPOT
)) {
2679 v
->current_order
.SetDepotOrderType(ODTF_MANUAL
);
2680 v
->current_order
.SetDepotActionType(HasBit(v
->vehicle_flags
, VF_SHOULD_SERVICE_AT_DEPOT
) ? ODATF_SERVICE_ONLY
: ODATFB_HALT
);
2683 /* Let a depot order in the order list interrupt. */
2684 if (!(v
->current_order
.GetDepotOrderType() & ODTFB_PART_OF_ORDERS
)) return false;
2694 case OT_LEAVESTATION
:
2695 if (v
->type
!= VEH_AIRCRAFT
) return false;
2702 * Reversing because of order change is allowed only just after leaving a
2703 * station (and the difficulty setting to allowed, of course)
2704 * this can be detected because only after OT_LEAVESTATION, current_order
2705 * will be reset to nothing. (That also happens if no order, but in that case
2706 * it won't hit the point in code where may_reverse is checked)
2708 bool may_reverse
= v
->current_order
.IsType(OT_NOTHING
);
2710 /* Check if we've reached a 'via' destination. */
2711 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
)) &&
2712 IsTileType(v
->tile
, MP_STATION
) &&
2713 v
->current_order
.GetDestination() == GetStationIndex(v
->tile
)) {
2714 v
->DeleteUnreachedImplicitOrders();
2715 /* We set the last visited station here because we do not want
2716 * the train to stop at this 'via' station if the next order
2717 * is a no-non-stop order; in that case not setting the last
2718 * visited station will cause the vehicle to still stop. */
2719 v
->last_station_visited
= v
->current_order
.GetDestination();
2720 UpdateVehicleTimetable(v
, true);
2721 v
->IncrementImplicitOrderIndex();
2724 /* Get the current order */
2725 assert(v
->cur_implicit_order_index
== 0 || v
->cur_implicit_order_index
< v
->GetNumOrders());
2726 v
->UpdateRealOrderIndex();
2728 const Order
*order
= v
->GetOrder(v
->cur_real_order_index
);
2729 if (order
!= nullptr && order
->IsType(OT_IMPLICIT
)) {
2730 assert(v
->GetNumManualOrders() == 0);
2734 /* If no order, do nothing. */
2735 if (order
== nullptr || (v
->type
== VEH_AIRCRAFT
&& !CheckForValidOrders(v
))) {
2736 if (v
->type
== VEH_AIRCRAFT
) {
2737 /* Aircraft do something vastly different here, so handle separately */
2738 extern void HandleMissingAircraftOrders(Aircraft
*v
);
2739 HandleMissingAircraftOrders(Aircraft::From(v
));
2743 v
->current_order
.Free();
2748 /* If it is unchanged, keep it. */
2749 if (order
->Equals(v
->current_order
) && (v
->type
== VEH_AIRCRAFT
|| v
->dest_tile
!= 0) &&
2750 (v
->type
!= VEH_SHIP
|| !order
->IsType(OT_GOTO_STATION
) || Station::Get(order
->GetDestination())->HasFacilities(FACIL_DOCK
))) {
2754 /* Otherwise set it, and determine the destination tile. */
2755 v
->current_order
= *order
;
2757 InvalidateVehicleOrder(v
, VIWD_MODIFY_ORDERS
);
2768 SetWindowClassesDirty(GetWindowClassForVehicleType(v
->type
));
2772 return UpdateOrderDest(v
, order
) && may_reverse
;
2776 * Check whether the given vehicle should stop at the given station
2777 * based on this order and the non-stop settings.
2778 * @param v the vehicle that might be stopping.
2779 * @param station the station to stop at.
2780 * @return true if the vehicle should stop.
2782 bool Order::ShouldStopAtStation(const Vehicle
*v
, StationID station
) const
2784 bool is_dest_station
= this->IsType(OT_GOTO_STATION
) && this->dest
== station
;
2786 return (!this->IsType(OT_GOTO_DEPOT
) || (this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS
) != 0) &&
2787 v
->last_station_visited
!= station
&& // Do stop only when we've not just been there
2788 /* Finally do stop when there is no non-stop flag set for this type of station. */
2789 !(this->GetNonStopType() & (is_dest_station
? ONSF_NO_STOP_AT_DESTINATION_STATION
: ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS
));
2793 * A vehicle can leave the current station with cargo if:
2794 * 1. it can load cargo here OR
2795 * 2a. it could leave the last station with cargo AND
2796 * 2b. it doesn't have to unload all cargo here.
2798 bool Order::CanLeaveWithCargo(bool has_cargo
, CargoID cargo
) const
2800 return (this->GetCargoLoadType(cargo
) & OLFB_NO_LOAD
) == 0 || (has_cargo
&&
2801 (this->GetCargoUnloadType(cargo
) & (OUFB_UNLOAD
| OUFB_TRANSFER
)) == 0);