Add standard library header includes to precompiled header. Fix several uses of strin...
[openttd-joker.git] / src / order_cmd.cpp
blob7d8a6559e522b0b6c26f53ce031f863cb77288b5
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 */
10 /** @file order_cmd.cpp Handling of orders. */
12 #include "stdafx.h"
13 #include "debug.h"
14 #include "cmd_helper.h"
15 #include "command_func.h"
16 #include "company_func.h"
17 #include "news_func.h"
18 #include "strings_func.h"
19 #include "timetable.h"
20 #include "station_base.h"
21 #include "station_map.h"
22 #include "station_func.h"
23 #include "map_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"
30 #include "aircraft.h"
31 #include "roadveh.h"
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
45 * be any of them
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. */
56 Order::~Order()
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 != NULL && bs->owner == OWNER_NONE) InvalidateWindowClassesData(WC_STATION_LIST, 0);
68 /**
69 * 'Free' the order
70 * @note ONLY use on "current_order" vehicle orders!
72 void Order::Free()
74 this->type = OT_NOTHING;
75 this->flags = 0;
76 this->dest = 0;
77 this->next = NULL;
78 DeAllocExtraInfo();
81 /**
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;
88 this->flags = 0;
89 this->dest = destination;
92 /**
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;
117 this->flags = 0;
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);
135 return true;
137 this->jump_counter += percent;
138 return false;
142 * Makes this order a Leave Station order.
144 void Order::MakeLeaveStation()
146 this->type = OT_LEAVESTATION;
147 this->flags = 0;
151 * Makes this order a Dummy order.
153 void Order::MakeDummy()
155 this->type = OT_DUMMY;
156 this->flags = 0;
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;
166 this->flags = order;
167 this->dest = 0;
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;
242 break;
243 case OT_GOTO_DEPOT:
244 if (!(this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) SetBit(order, 6);
245 SetBit(order, 7);
246 order |= GB(this->GetDestination(), 0, 8) << 8;
247 break;
248 case OT_LOADING:
249 if (this->GetLoadType() & OLFB_FULL_LOAD) SetBit(order, 6);
250 break;
252 return order;
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 = NULL;
265 this->next = NULL;
266 this->refit_cargo = CT_NO_REFIT;
267 this->wait_time = 0;
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);
282 if (data != 0) {
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);
287 return;
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 != NULL) {
316 this->AllocExtraInfo();
317 *(this->extra) = *(other.extra);
318 } else {
319 this->DeAllocExtraInfo();
323 void Order::AllocExtraInfo()
325 if (!this->extra) {
326 this->extra.reset(new OrderExtraInfo());
330 void Order::DeAllocExtraInfo()
332 this->extra.reset();
335 void CargoStationIDStackSet::FillNextStoppingStation(const Vehicle *v, const OrderList *o, const Order *first, uint hops)
337 this->more.clear();
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;
341 do {
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)
355 this->first = chain;
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 != NULL; o = o->next) {
365 ++this->num_orders;
366 if (!o->IsType(OT_IMPLICIT)) ++this->num_manual_orders;
367 this->timetable_duration += o->GetTimetabledWait() + o->GetTimetabledTravel();
368 this->total_duration += o->GetWaitTime() + o->GetTravelTime();
371 for (Vehicle *u = this->first_shared->PreviousShared(); u != NULL; u = u->PreviousShared()) {
372 ++this->num_vehicles;
373 this->first_shared = u;
376 for (const Vehicle *u = v->NextShared(); u != NULL; u = u->NextShared()) ++this->num_vehicles;
380 * Free a complete order chain.
381 * @param keep_orderlist If this is true only delete the orders, otherwise also delete the OrderList.
382 * @note do not use on "current_order" vehicle orders!
384 void OrderList::FreeChain(bool keep_orderlist)
386 Order *next;
387 for (Order *o = this->first; o != NULL; o = next) {
388 next = o->next;
389 delete o;
392 if (keep_orderlist) {
393 this->first = NULL;
394 this->num_orders = 0;
395 this->num_manual_orders = 0;
396 this->timetable_duration = 0;
397 } else {
398 delete this;
403 * Get a certain order of the order chain.
404 * @param index zero-based index of the order within the chain.
405 * @return the order at position index.
407 Order *OrderList::GetOrderAt(int index) const
409 if (index < 0) return NULL;
411 Order *order = this->first;
413 while (order != NULL && index-- > 0) {
414 order = order->next;
416 return order;
420 * Get the next order which will make the given vehicle stop at a station
421 * or refit at a depot or evaluate a non-trivial condition.
422 * @param next The order to start looking at.
423 * @param hops The number of orders we have already looked at.
424 * @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.
425 * @return Either of
426 * \li a station order
427 * \li a refitting depot order
428 * \li a non-trivial conditional order
429 * \li NULL if the vehicle won't stop anymore.
431 const Order *OrderList::GetNextDecisionNode(const Order *next, uint hops, uint32 &cargo_mask) const
433 assert(cargo_mask != 0);
435 if (hops > this->GetNumOrders() || next == NULL) return NULL;
437 if (next->IsType(OT_CONDITIONAL)) {
438 if (next->GetConditionVariable() != OCV_UNCONDITIONALLY) return next;
440 /* We can evaluate trivial conditions right away. They're conceptually
441 * the same as regular order progression. */
442 return this->GetNextDecisionNode(
443 this->GetOrderAt(next->GetConditionSkipToOrder()),
444 hops + 1, cargo_mask);
447 if (next->IsType(OT_GOTO_DEPOT)) {
448 if (next->GetDepotActionType() & ODATFB_HALT) return NULL;
449 if (next->IsRefit()) return next;
453 bool can_load_or_unload = false;
454 if ((next->IsType(OT_GOTO_STATION) || next->IsType(OT_IMPLICIT)) &&
455 (next->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) == 0) {
456 if (next->GetUnloadType() == OUFB_CARGO_TYPE_UNLOAD || next->GetLoadType() == OLFB_CARGO_TYPE_LOAD) {
457 /* This is a cargo-specific load/unload order.
458 * If the first cargo is both a no-load and no-unload order, skip it.
459 * Drop cargoes which don't match the first one. */
460 can_load_or_unload = CargoMaskValueFilter<bool>(cargo_mask, [&](CargoID cargo) {
461 return ((next->GetCargoLoadType(cargo) & OLFB_NO_LOAD) == 0 || (next->GetCargoUnloadType(cargo) & OUFB_NO_UNLOAD) == 0);
463 } else if ((next->GetLoadType() & OLFB_NO_LOAD) == 0 || (next->GetUnloadType() & OUFB_NO_UNLOAD) == 0) {
464 can_load_or_unload = true;
468 if (!can_load_or_unload) {
469 return this->GetNextDecisionNode(this->GetNext(next), hops + 1, cargo_mask);
472 return next;
476 * Recursively determine the next deterministic station to stop at.
477 * @param v The vehicle we're looking at.
478 * @param uint32 cargo_mask Bit-set of the cargo IDs of interest.
479 * @param first Order to start searching at or NULL to start at cur_implicit_order_index + 1.
480 * @param hops Number of orders we have already looked at.
481 * @return A CargoMaskedStationIDStack of the cargo mask the result is valid for, and the next stoppping station or INVALID_STATION.
482 * @pre The vehicle is currently loading and v->last_station_visited is meaningful.
483 * @note This function may draw a random number. Don't use it from the GUI.
485 CargoMaskedStationIDStack OrderList::GetNextStoppingStation(const Vehicle *v, uint32 cargo_mask, const Order *first, uint hops) const
487 assert(cargo_mask != 0);
489 const Order *next = first;
490 if (first == NULL) {
491 next = this->GetOrderAt(v->cur_implicit_order_index);
492 if (next == NULL) {
493 next = this->GetFirstOrder();
494 if (next == NULL) return CargoMaskedStationIDStack(cargo_mask, INVALID_STATION);
495 } else {
496 /* GetNext never returns NULL if there is a valid station in the list.
497 * As the given "next" is already valid and a station in the list, we
498 * don't have to check for NULL here. */
499 next = this->GetNext(next);
500 assert(next != NULL);
504 do {
505 next = this->GetNextDecisionNode(next, ++hops, cargo_mask);
507 /* Resolve possibly nested conditionals by estimation. */
508 while (next != NULL && next->IsType(OT_CONDITIONAL)) {
509 /* We return both options of conditional orders. */
510 const Order *skip_to = this->GetNextDecisionNode(
511 this->GetOrderAt(next->GetConditionSkipToOrder()), hops, cargo_mask);
512 const Order *advance = this->GetNextDecisionNode(
513 this->GetNext(next), hops, cargo_mask);
514 if (advance == NULL || advance == first || skip_to == advance) {
515 next = (skip_to == first) ? NULL : skip_to;
516 } else if (skip_to == NULL || skip_to == first) {
517 next = (advance == first) ? NULL : advance;
518 } else {
519 CargoMaskedStationIDStack st1 = this->GetNextStoppingStation(v, cargo_mask, skip_to, hops);
520 cargo_mask &= st1.cargo_mask;
521 CargoMaskedStationIDStack st2 = this->GetNextStoppingStation(v, cargo_mask, advance, hops);
522 st1.cargo_mask &= st2.cargo_mask;
523 while (!st2.station.IsEmpty()) st1.station.Push(st2.station.Pop());
524 return st1;
526 ++hops;
529 if (next == NULL) return CargoMaskedStationIDStack(cargo_mask, INVALID_STATION);
531 /* Don't return a next stop if the vehicle has to unload everything. */
532 if ((next->IsType(OT_GOTO_STATION) || next->IsType(OT_IMPLICIT)) &&
533 next->GetDestination() == v->last_station_visited) {
534 /* This is a cargo-specific load/unload order.
535 * Don't return a next stop if first cargo has transfer or unload set.
536 * Drop cargoes which don't match the first one. */
537 bool invalid = CargoMaskValueFilter<bool>(cargo_mask, [&](CargoID cargo) {
538 return ((next->GetCargoUnloadType(cargo) & (OUFB_TRANSFER | OUFB_UNLOAD)) != 0);
540 if (invalid) return CargoMaskedStationIDStack(cargo_mask, INVALID_STATION);
542 } while (next->IsType(OT_GOTO_DEPOT) || next->GetDestination() == v->last_station_visited);
544 return CargoMaskedStationIDStack(cargo_mask, next->GetDestination());
548 * Insert a new order into the order chain.
549 * @param new_order is the order to insert into the chain.
550 * @param index is the position where the order is supposed to be inserted.
552 void OrderList::InsertOrderAt(Order *new_order, int index)
554 if (this->first == NULL) {
555 this->first = new_order;
556 } else {
557 if (index == 0) {
558 /* Insert as first or only order */
559 new_order->next = this->first;
560 this->first = new_order;
561 } else if (index >= this->num_orders) {
562 /* index is after the last order, add it to the end */
563 this->GetLastOrder()->next = new_order;
564 } else {
565 /* Put the new order in between */
566 Order *order = this->GetOrderAt(index - 1);
567 new_order->next = order->next;
568 order->next = new_order;
571 ++this->num_orders;
572 if (!new_order->IsType(OT_IMPLICIT)) ++this->num_manual_orders;
573 this->timetable_duration += new_order->GetTimetabledWait() + new_order->GetTimetabledTravel();
574 this->total_duration += new_order->GetWaitTime() + new_order->GetTravelTime();
576 /* We can visit oil rigs and buoys that are not our own. They will be shown in
577 * the list of stations. So, we need to invalidate that window if needed. */
578 if (new_order->IsType(OT_GOTO_STATION) || new_order->IsType(OT_GOTO_WAYPOINT)) {
579 BaseStation *bs = BaseStation::Get(new_order->GetDestination());
580 if (bs->owner == OWNER_NONE) InvalidateWindowClassesData(WC_STATION_LIST, 0);
587 * Remove an order from the order list and delete it.
588 * @param index is the position of the order which is to be deleted.
590 void OrderList::DeleteOrderAt(int index)
592 if (index >= this->num_orders) return;
594 Order *to_remove;
596 if (index == 0) {
597 to_remove = this->first;
598 this->first = to_remove->next;
599 } else {
600 Order *prev = GetOrderAt(index - 1);
601 to_remove = prev->next;
602 prev->next = to_remove->next;
604 --this->num_orders;
605 if (!to_remove->IsType(OT_IMPLICIT)) --this->num_manual_orders;
606 this->timetable_duration -= (to_remove->GetTimetabledWait() + to_remove->GetTimetabledTravel());
607 this->total_duration -= (to_remove->GetWaitTime() + to_remove->GetTravelTime());
608 delete to_remove;
612 * Move an order to another position within the order list.
613 * @param from is the zero-based position of the order to move.
614 * @param to is the zero-based position where the order is moved to.
616 void OrderList::MoveOrder(int from, int to)
618 if (from >= this->num_orders || to >= this->num_orders || from == to) return;
620 Order *moving_one;
622 /* Take the moving order out of the pointer-chain */
623 if (from == 0) {
624 moving_one = this->first;
625 this->first = moving_one->next;
626 } else {
627 Order *one_before = GetOrderAt(from - 1);
628 moving_one = one_before->next;
629 one_before->next = moving_one->next;
632 /* Insert the moving_order again in the pointer-chain */
633 if (to == 0) {
634 moving_one->next = this->first;
635 this->first = moving_one;
636 } else {
637 Order *one_before = GetOrderAt(to - 1);
638 moving_one->next = one_before->next;
639 one_before->next = moving_one;
644 * Removes the vehicle from the shared order list.
645 * @note This is supposed to be called when the vehicle is still in the chain
646 * @param v vehicle to remove from the list
648 void OrderList::RemoveVehicle(Vehicle *v)
650 --this->num_vehicles;
651 if (v == this->first_shared) this->first_shared = v->NextShared();
655 * Checks whether a vehicle is part of the shared vehicle chain.
656 * @param v is the vehicle to search in the shared vehicle chain.
658 bool OrderList::IsVehicleInSharedOrdersList(const Vehicle *v) const
660 for (const Vehicle *v_shared = this->first_shared; v_shared != NULL; v_shared = v_shared->NextShared()) {
661 if (v_shared == v) return true;
664 return false;
668 * Gets the position of the given vehicle within the shared order vehicle list.
669 * @param v is the vehicle of which to get the position
670 * @return position of v within the shared vehicle chain.
672 int OrderList::GetPositionInSharedOrderList(const Vehicle *v) const
674 int count = 0;
675 for (const Vehicle *v_shared = v->PreviousShared(); v_shared != NULL; v_shared = v_shared->PreviousShared()) count++;
676 return count;
680 * Checks whether all orders of the list have a filled timetable.
681 * @return whether all orders have a filled timetable.
683 bool OrderList::IsCompleteTimetable() const
685 for (Order *o = this->first; o != NULL; o = o->next) {
686 /* Implicit orders are, by definition, not timetabled. */
687 if (o->IsType(OT_IMPLICIT)) continue;
688 if (!o->IsCompletelyTimetabled()) return false;
690 return true;
694 * Checks for internal consistency of order list. Triggers assertion if something is wrong.
696 void OrderList::DebugCheckSanity() const
698 VehicleOrderID check_num_orders = 0;
699 VehicleOrderID check_num_manual_orders = 0;
700 uint check_num_vehicles = 0;
701 Ticks check_timetable_duration = 0;
702 Ticks check_total_duration = 0;
704 DEBUG(misc, 6, "Checking OrderList %hu for sanity...", this->index);
706 for (const Order *o = this->first; o != NULL; o = o->next) {
707 ++check_num_orders;
708 if (!o->IsType(OT_IMPLICIT)) ++check_num_manual_orders;
709 check_timetable_duration += o->GetTimetabledWait() + o->GetTimetabledTravel();
710 check_total_duration += o->GetWaitTime() + o->GetTravelTime();
712 assert(this->num_orders == check_num_orders);
713 assert(this->num_manual_orders == check_num_manual_orders);
714 assert(this->timetable_duration == check_timetable_duration);
715 assert(this->total_duration == check_total_duration);
717 for (const Vehicle *v = this->first_shared; v != NULL; v = v->NextShared()) {
718 ++check_num_vehicles;
719 assert(v->HasSpecificOrderList(this));
721 assert(this->num_vehicles == check_num_vehicles);
722 DEBUG(misc, 6, "... detected %u orders (%u manual), %u vehicles, %i timetabled, %i total",
723 (uint)this->num_orders, (uint)this->num_manual_orders,
724 this->num_vehicles, this->timetable_duration, this->total_duration);
727 /** Returns the number of running (i.e. not stopped) vehicles in the shared orders list. */
728 int OrderList::GetNumRunningVehicles()
730 int num_running_vehicles = 0;
732 for (const Vehicle *v = this->first_shared; v != NULL; v = v->NextShared()) {
733 if (!(v->vehstatus & (VS_STOPPED | VS_CRASHED)) || v->current_order.IsType(OT_WAITING)) {
734 num_running_vehicles++;
738 return num_running_vehicles;
741 /** (Re-)Initializes Separation if necessary and possible. */
742 void OrderList::InitializeSeparation()
744 // Check whether separation can be used at all
745 if (!this->IsCompleteTimetable() || this->current_sep_mode == TTS_MODE_OFF) {
746 this->is_separation_valid = false;
747 return;
750 // Save current tick count as reference for future timetable start dates and reset the separation counter.
751 this->last_timetable_init = GetCurrentTickCount();
752 this->separation_counter = 0;
754 this->UpdateSeparationTime();
756 this->is_separation_valid = true;
759 void OrderList::UpdateSeparationTime()
761 // Calculate separation amount depending on mode of operation.
762 switch (current_sep_mode) {
763 case TTS_MODE_AUTO: {
764 int num_running_vehicles = this->GetNumRunningVehicles();
765 assert(num_running_vehicles > 0);
767 this->current_separation = this->GetTimetableTotalDuration() / num_running_vehicles;
768 break;
771 case TTS_MODE_MAN_N:
772 this->current_separation = this->GetTimetableTotalDuration() / this->num_sep_vehicles;
773 break;
775 case TTS_MODE_MAN_T:
776 // separation is set manually -> nothing to do
777 break;
779 case TTS_MODE_BUFFERED_AUTO: {
780 int num_running_vehicles = this->GetNumRunningVehicles();
781 assert(num_running_vehicles > 0);
783 if (num_running_vehicles > 1)
784 num_running_vehicles--;
786 this->current_separation = this->GetTimetableTotalDuration() / num_running_vehicles;
787 break;
790 default:
791 NOT_REACHED();
792 break;
797 * Returns the delay setting required for correct separation and increases the separation counter by 1.
798 * @return the delay setting required for correct separation. */
799 Ticks OrderList::SeparateVehicle()
801 if (!this->is_separation_valid || this->current_sep_mode == TTS_MODE_OFF)
802 return INVALID_TICKS;
804 UpdateSeparationTime();
806 Ticks result = GetCurrentTickCount() - (this->separation_counter * this->current_separation + this->last_timetable_init);
807 this->IncreaseSeparationCounter();
808 if (this->separation_counter == UINT16_MAX) {
809 this->MarkSeparationInvalid();
812 return result;
816 * Returns the current separation settings.
817 * @return the current separation settings.
819 TTSepSettings OrderList::GetSepSettings()
821 TTSepSettings result;
823 result.mode = this->current_sep_mode;
824 result.sep_ticks = GetSepTime();
826 // Depending on the operation mode return either the user setting or the true amount of vehicles running the timetable.
827 result.num_veh = (result.mode == TTS_MODE_MAN_N) ? this->num_sep_vehicles : GetNumVehicles();
828 return result;
832 * Prepares command to set new separation settings.
833 * @param s Contains the new settings to be used for separation.
834 * @todo Clean this up (e.g. via union type)
836 void OrderList::SetSepSettings(TTSepSettings s)
838 uint32 p2 = GB<uint32>(s.mode, 0, 3);
839 AB<uint32, uint>(p2, 3, 29, (s.mode == TTS_MODE_MAN_N) ? s.num_veh : s.sep_ticks);
840 DoCommandP(0, this->first_shared->index, p2, CMD_REINIT_SEPARATION);
844 * Sets new separation settings.
845 * @param mode Contains the operation mode that is to be used for separation.
846 * @param parameter Depending on the operation mode this contains either the number of vehicles (#TTS_MODE_MAN_N)
847 * or the time between vehicles in ticks (#TTS_MODE_MAN_T). For other modes, this is undefined.
849 void OrderList::SetSepSettings(TTSepMode mode, uint32 parameter)
851 this->current_sep_mode = mode;
853 switch (this->current_sep_mode)
855 case TTS_MODE_MAN_N:
856 this->current_separation = this->GetTimetableTotalDuration() / parameter;
857 this->num_sep_vehicles = parameter;
858 break;
860 case TTS_MODE_MAN_T:
861 this->current_separation = parameter;
862 this->num_sep_vehicles = this->GetTimetableTotalDuration() / this->current_separation;
863 break;
865 case TTS_MODE_AUTO:
866 case TTS_MODE_BUFFERED_AUTO:
867 case TTS_MODE_OFF:
868 /* nothing to do */
869 break;
871 default:
872 NOT_REACHED();
873 break;
876 this->is_separation_valid = false;
881 * Checks whether the order goes to a station or not, i.e. whether the
882 * destination is a station
883 * @param v the vehicle to check for
884 * @param o the order to check
885 * @return true if the destination is a station
887 static inline bool OrderGoesToStation(const Vehicle *v, const Order *o)
889 return o->IsType(OT_GOTO_STATION) ||
890 (v->type == VEH_AIRCRAFT && o->IsType(OT_GOTO_DEPOT) && !(o->GetDepotActionType() & ODATFB_NEAREST_DEPOT));
894 * Delete all news items regarding defective orders about a vehicle
895 * This could kill still valid warnings (for example about void order when just
896 * another order gets added), but assume the company will notice the problems,
897 * when (s)he's changing the orders.
899 void DeleteOrderWarnings(const Vehicle *v)
901 DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_TOO_FEW_ORDERS);
902 DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_VOID_ORDER);
903 DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_DUPLICATE_ENTRY);
904 DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_INVALID_ENTRY);
905 DeleteVehicleNews(v->index, STR_NEWS_PLANE_USES_TOO_SHORT_RUNWAY);
909 * Returns a tile somewhat representing the order destination (not suitable for pathfinding).
910 * @param v The vehicle to get the location for.
911 * @param airport Get the airport tile and not the station location for aircraft.
912 * @return destination of order, or INVALID_TILE if none.
914 TileIndex Order::GetLocation(const Vehicle *v, bool airport) const
916 switch (this->GetType()) {
917 case OT_GOTO_WAYPOINT:
918 case OT_GOTO_STATION:
919 case OT_IMPLICIT:
920 if (airport && v->type == VEH_AIRCRAFT) return Station::Get(this->GetDestination())->airport.tile;
921 return BaseStation::Get(this->GetDestination())->xy;
923 case OT_GOTO_DEPOT:
924 if ((this->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0) return INVALID_TILE;
925 return (v->type == VEH_AIRCRAFT) ? Station::Get(this->GetDestination())->xy : Depot::Get(this->GetDestination())->xy;
927 default:
928 return INVALID_TILE;
933 * Get the distance between two orders of a vehicle. Conditional orders are resolved
934 * and the bigger distance of the two order branches is returned.
935 * @param prev Origin order.
936 * @param cur Destination order.
937 * @param v The vehicle to get the distance for.
938 * @param conditional_depth Internal param for resolving conditional orders.
939 * @return Maximum distance between the two orders.
941 uint GetOrderDistance(const Order *prev, const Order *cur, const Vehicle *v, int conditional_depth)
943 if (cur->IsType(OT_CONDITIONAL)) {
944 if (conditional_depth > v->GetNumOrders()) return 0;
946 conditional_depth++;
948 int dist1 = GetOrderDistance(prev, v->GetOrder(cur->GetConditionSkipToOrder()), v, conditional_depth);
949 int dist2 = GetOrderDistance(prev, cur->next == nullptr ? v->GetFirstOrder() : cur->next, v, conditional_depth);
950 return max(dist1, dist2);
953 TileIndex prev_tile = prev->GetLocation(v, true);
954 TileIndex cur_tile = cur->GetLocation(v, true);
955 if (prev_tile == INVALID_TILE || cur_tile == INVALID_TILE) return 0;
956 return v->type == VEH_AIRCRAFT ? DistanceSquare(prev_tile, cur_tile) : DistanceManhattan(prev_tile, cur_tile);
960 * Add an order to the orderlist of a vehicle.
961 * @param tile unused
962 * @param flags operation to perform
963 * @param p1 various bitstuffed elements
964 * - p1 = (bit 0 - 19) - ID of the vehicle
965 * - p1 = (bit 24 - 31) - the selected order (if any). If the last order is given,
966 * the order will be inserted before that one
967 * the maximum vehicle order id is 254.
968 * @param p2 packed order to insert
969 * @param text unused
970 * @return the cost of this operation or an error
972 CommandCost CmdInsertOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
974 VehicleID veh = GB(p1, 0, 20);
975 VehicleOrderID sel_ord = GB(p1, 20, 8);
976 Order new_order(p2);
978 Vehicle *v = Vehicle::GetIfValid(veh);
979 if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
981 CommandCost ret = CheckOwnership(v->owner);
982 if (ret.Failed()) return ret;
984 /* Check if the inserted order is to the correct destination (owner, type),
985 * and has the correct flags if any */
986 switch (new_order.GetType()) {
987 case OT_GOTO_STATION: {
988 const Station *st = Station::GetIfValid(new_order.GetDestination());
989 if (st == NULL) return CMD_ERROR;
991 if (st->owner != OWNER_NONE) {
992 CommandCost ret = CheckOwnership(st->owner);
993 if (ret.Failed()) return ret;
996 if (!CanVehicleUseStation(v, st)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
997 for (Vehicle *u = v->FirstShared(); u != NULL; u = u->NextShared()) {
998 if (!CanVehicleUseStation(u, st)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER_SHARED);
1001 /* Non stop only allowed for ground vehicles. */
1002 if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && !v->IsGroundVehicle()) return CMD_ERROR;
1004 /* Filter invalid load/unload types. */
1005 switch (new_order.GetLoadType()) {
1006 case OLF_LOAD_IF_POSSIBLE: case OLFB_FULL_LOAD: case OLF_FULL_LOAD_ANY: case OLFB_NO_LOAD: break;
1007 default: return CMD_ERROR;
1009 switch (new_order.GetUnloadType()) {
1010 case OUF_UNLOAD_IF_POSSIBLE: case OUFB_UNLOAD: case OUFB_TRANSFER: case OUFB_NO_UNLOAD: break;
1011 default: return CMD_ERROR;
1014 /* Filter invalid stop locations */
1015 switch (new_order.GetStopLocation()) {
1016 case OSL_PLATFORM_NEAR_END:
1017 case OSL_PLATFORM_MIDDLE:
1018 if (v->type != VEH_TRAIN) return CMD_ERROR;
1019 FALLTHROUGH;
1021 case OSL_PLATFORM_FAR_END:
1022 break;
1024 default:
1025 return CMD_ERROR;
1028 break;
1031 case OT_GOTO_DEPOT: {
1032 if ((new_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) == 0) {
1033 if (v->type == VEH_AIRCRAFT) {
1034 const Station *st = Station::GetIfValid(new_order.GetDestination());
1036 if (st == NULL) return CMD_ERROR;
1038 CommandCost ret = CheckOwnership(st->owner);
1039 if (ret.Failed()) return ret;
1041 if (!CanVehicleUseStation(v, st) || !st->airport.HasHangar()) {
1042 return CMD_ERROR;
1044 } else {
1045 const Depot *dp = Depot::GetIfValid(new_order.GetDestination());
1047 if (dp == NULL) return CMD_ERROR;
1049 CommandCost ret = CheckOwnership(GetTileOwner(dp->xy));
1050 if (ret.Failed()) return ret;
1052 switch (v->type) {
1053 case VEH_TRAIN:
1054 if (!IsRailDepotTile(dp->xy)) return CMD_ERROR;
1055 break;
1057 case VEH_ROAD:
1058 if (!IsRoadDepotTile(dp->xy)) return CMD_ERROR;
1059 break;
1061 case VEH_SHIP:
1062 if (!IsShipDepotTile(dp->xy)) return CMD_ERROR;
1063 break;
1065 default: return CMD_ERROR;
1070 if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && !v->IsGroundVehicle()) return CMD_ERROR;
1071 if (new_order.GetDepotOrderType() & ~(ODTFB_PART_OF_ORDERS | ((new_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS) != 0 ? ODTFB_SERVICE : 0))) return CMD_ERROR;
1072 if (new_order.GetDepotActionType() & ~(ODATFB_HALT | ODATFB_NEAREST_DEPOT)) return CMD_ERROR;
1073 if ((new_order.GetDepotOrderType() & ODTFB_SERVICE) && (new_order.GetDepotActionType() & ODATFB_HALT)) return CMD_ERROR;
1074 break;
1077 case OT_GOTO_WAYPOINT: {
1078 const Waypoint *wp = Waypoint::GetIfValid(new_order.GetDestination());
1079 if (wp == NULL) return CMD_ERROR;
1081 switch (v->type) {
1082 default: return CMD_ERROR;
1084 case VEH_TRAIN: {
1085 if (!(wp->facilities & FACIL_TRAIN)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
1087 CommandCost ret = CheckOwnership(wp->owner);
1088 if (ret.Failed()) return ret;
1089 break;
1092 case VEH_SHIP:
1093 if (!(wp->facilities & FACIL_DOCK)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
1094 if (wp->owner != OWNER_NONE) {
1095 CommandCost ret = CheckOwnership(wp->owner);
1096 if (ret.Failed()) return ret;
1098 break;
1101 /* Order flags can be any of the following for waypoints:
1102 * [non-stop]
1103 * non-stop orders (if any) are only valid for trains */
1104 if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && v->type != VEH_TRAIN) return CMD_ERROR;
1105 break;
1108 case OT_CONDITIONAL: {
1109 VehicleOrderID skip_to = new_order.GetConditionSkipToOrder();
1110 if (skip_to != 0 && skip_to >= v->GetNumOrders()) return CMD_ERROR; // Always allow jumping to the first (even when there is no order).
1111 if (new_order.GetConditionVariable() >= OCV_END) return CMD_ERROR;
1113 OrderConditionComparator occ = new_order.GetConditionComparator();
1114 if (occ >= OCC_END) return CMD_ERROR;
1115 switch (new_order.GetConditionVariable()) {
1116 case OCV_SLOT_OCCUPANCY: {
1117 if (!TraceRestrictSlot::IsValidID(new_order.GetConditionValue())) return CMD_ERROR;
1118 if (occ != OCC_IS_TRUE && occ != OCC_IS_FALSE) return CMD_ERROR;
1119 break;
1121 case OCV_CARGO_WAITING:
1122 case OCV_CARGO_ACCEPTANCE:
1123 if (!CargoSpec::Get(new_order.GetConditionValue())->IsValid()) return CMD_ERROR;
1124 /* FALL THROUGH */
1126 case OCV_REQUIRES_SERVICE:
1127 if (occ != OCC_IS_TRUE && occ != OCC_IS_FALSE) return CMD_ERROR;
1128 break;
1130 case OCV_UNCONDITIONALLY:
1131 if (occ != OCC_EQUALS) return CMD_ERROR;
1132 if (new_order.GetConditionValue() != 0) return CMD_ERROR;
1133 break;
1135 case OCV_FREE_PLATFORMS:
1136 if (v->type != VEH_TRAIN) return CMD_ERROR;
1137 if (occ == OCC_IS_TRUE || occ == OCC_IS_FALSE) return CMD_ERROR;
1138 break;
1140 case OCV_PERCENT:
1141 if (occ != OCC_EQUALS) return CMD_ERROR;
1142 /* FALL THROUGH */
1144 case OCV_LOAD_PERCENTAGE:
1145 case OCV_RELIABILITY:
1146 if (new_order.GetConditionValue() > 100) return CMD_ERROR;
1147 FALLTHROUGH;
1149 default:
1150 if (occ == OCC_IS_TRUE || occ == OCC_IS_FALSE) return CMD_ERROR;
1151 break;
1153 break;
1156 default: return CMD_ERROR;
1159 if (sel_ord > v->GetNumOrders()) return CMD_ERROR;
1161 if (v->GetNumOrders() >= MAX_VEH_ORDER_ID) return_cmd_error(STR_ERROR_TOO_MANY_ORDERS);
1162 if (!Order::CanAllocateItem()) return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
1163 if (!v->HasOrdersList() && !OrderList::CanAllocateItem()) return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
1165 if (v->type == VEH_SHIP && _settings_game.pf.pathfinder_for_ships != VPF_NPF) {
1166 /* Make sure the new destination is not too far away from the previous */
1167 const Order *prev = NULL;
1168 uint n = 0;
1170 /* Find the last goto station or depot order before the insert location.
1171 * If the order is to be inserted at the beginning of the order list this
1172 * finds the last order in the list. */
1173 const Order *o;
1174 FOR_VEHICLE_ORDERS(v, o) {
1175 switch (o->GetType()) {
1176 case OT_GOTO_STATION:
1177 case OT_GOTO_DEPOT:
1178 case OT_GOTO_WAYPOINT:
1179 prev = o;
1180 break;
1182 default: break;
1184 if (++n == sel_ord && prev != NULL) break;
1186 if (prev != NULL) {
1187 uint dist;
1188 if (new_order.IsType(OT_CONDITIONAL)) {
1189 /* The order is not yet inserted, so we have to do the first iteration here. */
1190 dist = GetOrderDistance(prev, v->GetOrder(new_order.GetConditionSkipToOrder()), v);
1191 } else {
1192 dist = GetOrderDistance(prev, &new_order, v);
1195 if (dist >= 130) {
1196 return_cmd_error(STR_ERROR_TOO_FAR_FROM_PREVIOUS_DESTINATION);
1201 if (flags & DC_EXEC) {
1202 Order *new_o = new Order();
1203 new_o->AssignOrder(new_order);
1204 InsertOrder(v, new_o, sel_ord);
1205 CheckMarkDirtyFocusedRoutePaths(v);
1208 return CommandCost();
1212 * Insert a new order but skip the validation.
1213 * @param v The vehicle to insert the order to.
1214 * @param new_o The new order.
1215 * @param sel_ord The position the order should be inserted at.
1217 void InsertOrder(Vehicle *v, Order *new_o, VehicleOrderID sel_ord)
1219 /* Create new order and link in list */
1220 if (!v->HasOrdersList()) {
1221 v->SetOrdersList(new OrderList(new_o, v));
1222 } else {
1223 v->InsertOrderAt(new_o, sel_ord);
1226 Vehicle *u = v->FirstShared();
1227 DeleteOrderWarnings(u);
1228 for (; u != NULL; u = u->NextShared()) {
1229 assert(v->IsSharingOrdersWith(u));
1231 /* If there is added an order before the current one, we need
1232 * to update the selected order. We do not change implicit/real order indices though.
1233 * If the new order is between the current implicit order and real order, the implicit order will
1234 * later skip the inserted order. */
1235 if (sel_ord <= u->cur_real_order_index) {
1236 uint cur = u->cur_real_order_index + 1;
1237 /* Check if we don't go out of bound */
1238 if (cur < u->GetNumOrders()) {
1239 u->cur_real_order_index = cur;
1242 if (sel_ord == u->cur_implicit_order_index && u->IsGroundVehicle()) {
1243 /* We are inserting an order just before the current implicit order.
1244 * We do not know whether we will reach current implicit or the newly inserted order first.
1245 * So, disable creation of implicit orders until we are on track again. */
1246 uint16 &gv_flags = u->GetGroundVehicleFlags();
1247 SetBit(gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
1249 if (sel_ord <= u->cur_implicit_order_index) {
1250 uint cur = u->cur_implicit_order_index + 1;
1251 /* Check if we don't go out of bound */
1252 if (cur < u->GetNumOrders()) {
1253 u->cur_implicit_order_index = cur;
1256 /* Update any possible open window of the vehicle */
1257 InvalidateVehicleOrder(u, INVALID_VEH_ORDER_ID | (sel_ord << 8));
1260 /* As we insert an order, the order to skip to will be 'wrong'. */
1261 VehicleOrderID cur_order_id = 0;
1262 Order *order;
1263 FOR_VEHICLE_ORDERS(v, order) {
1264 if (order->IsType(OT_CONDITIONAL)) {
1265 VehicleOrderID order_id = order->GetConditionSkipToOrder();
1266 if (order_id >= sel_ord) {
1267 order->SetConditionSkipToOrder(order_id + 1);
1269 if (order_id == cur_order_id) {
1270 order->SetConditionSkipToOrder((order_id + 1) % v->GetNumOrders());
1273 cur_order_id++;
1276 /* Make sure to rebuild the whole list */
1277 InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
1281 * Declone an order-list
1282 * @param *dst delete the orders of this vehicle
1283 * @param flags execution flags
1285 static CommandCost DecloneOrder(Vehicle *dst, DoCommandFlag flags)
1287 if (flags & DC_EXEC) {
1288 dst->DeleteVehicleOrders();
1289 InvalidateVehicleOrder(dst, VIWD_REMOVE_ALL_ORDERS);
1290 InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
1291 CheckMarkDirtyFocusedRoutePaths(dst);
1293 return CommandCost();
1297 * Get the first cargoID that points to a valid cargo (usually 0)
1299 static CargoID GetFirstValidCargo()
1301 for (CargoID i = 0; i < NUM_CARGO; i++) {
1302 if (CargoSpec::Get(i)->IsValid()) return i;
1304 /* No cargoes defined -> 'Houston, we have a problem!' */
1305 assert(0);
1306 /* Return something to avoid compiler warning */
1307 return 0;
1311 * Get the first valid TraceRestrictSlot. Or INVALID_TRACE_RESTRICT_SLOT_ID if no slots are defined.
1313 static TraceRestrictSlotID GetFirstValidTraceRestrictSlot()
1315 const TraceRestrictSlot* slot;
1316 FOR_ALL_TRACE_RESTRICT_SLOTS(slot)
1318 // Stupid way to get the first valid slot but there is no "GetFirstValidSlot()".
1319 return slot->index;
1322 return INVALID_TRACE_RESTRICT_SLOT_ID;
1326 * Delete an order from the orderlist of a vehicle.
1327 * @param tile unused
1328 * @param flags operation to perform
1329 * @param p1 the ID of the vehicle
1330 * @param p2 the order to delete (max 255)
1331 * @param text unused
1332 * @return the cost of this operation or an error
1334 CommandCost CmdDeleteOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1336 VehicleID veh_id = GB(p1, 0, 20);
1337 VehicleOrderID sel_ord = GB(p2, 0, 8);
1339 Vehicle *v = Vehicle::GetIfValid(veh_id);
1341 if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
1343 CommandCost ret = CheckOwnership(v->owner);
1344 if (ret.Failed()) return ret;
1346 /* If we did not select an order, we maybe want to de-clone the orders */
1347 if (sel_ord >= v->GetNumOrders()) return DecloneOrder(v, flags);
1349 if (v->GetOrder(sel_ord) == NULL) return CMD_ERROR;
1351 if (flags & DC_EXEC) {
1352 DeleteOrder(v, sel_ord);
1353 CheckMarkDirtyFocusedRoutePaths(v);
1355 return CommandCost();
1359 * Cancel the current loading order of the vehicle as the order was deleted.
1360 * @param v the vehicle
1362 void CancelLoadingDueToDeletedOrder(Vehicle *v)
1364 assert(v->current_order.IsType(OT_LOADING));
1365 /* NON-stop flag is misused to see if a train is in a station that is
1366 * on his order list or not */
1367 v->current_order.SetNonStopType(ONSF_STOP_EVERYWHERE);
1368 /* When full loading, "cancel" that order so the vehicle doesn't
1369 * stay indefinitely at this station anymore. */
1370 if (v->current_order.GetLoadType() & OLFB_FULL_LOAD) v->current_order.SetLoadType(OLF_LOAD_IF_POSSIBLE);
1374 * Delete an order but skip the parameter validation.
1375 * @param v The vehicle to delete the order from.
1376 * @param sel_ord The id of the order to be deleted.
1378 void DeleteOrder(Vehicle *v, VehicleOrderID sel_ord)
1380 v->DeleteOrderAt(sel_ord);
1382 Vehicle *u = v->FirstShared();
1383 DeleteOrderWarnings(u);
1384 for (; u != NULL; u = u->NextShared()) {
1385 assert(v->IsSharingOrdersWith(u));
1387 if (sel_ord == u->cur_real_order_index && u->current_order.IsType(OT_LOADING)) {
1388 CancelLoadingDueToDeletedOrder(u);
1391 if (sel_ord < u->cur_real_order_index) {
1392 u->cur_real_order_index--;
1393 } else if (sel_ord == u->cur_real_order_index) {
1394 u->UpdateRealOrderIndex();
1397 if (sel_ord < u->cur_implicit_order_index) {
1398 u->cur_implicit_order_index--;
1399 } else if (sel_ord == u->cur_implicit_order_index) {
1400 /* Make sure the index is valid */
1401 if (u->cur_implicit_order_index >= u->GetNumOrders()) u->cur_implicit_order_index = 0;
1403 /* Skip non-implicit orders for the implicit-order-index (e.g. if the current implicit order was deleted */
1404 while (u->cur_implicit_order_index != u->cur_real_order_index && !u->GetOrder(u->cur_implicit_order_index)->IsType(OT_IMPLICIT)) {
1405 u->cur_implicit_order_index++;
1406 if (u->cur_implicit_order_index >= u->GetNumOrders()) u->cur_implicit_order_index = 0;
1410 /* Update any possible open window of the vehicle */
1411 InvalidateVehicleOrder(u, sel_ord | (INVALID_VEH_ORDER_ID << 8));
1414 /* As we delete an order, the order to skip to will be 'wrong'. */
1415 VehicleOrderID cur_order_id = 0;
1416 Order *order = NULL;
1417 FOR_VEHICLE_ORDERS(v, order) {
1418 if (order->IsType(OT_CONDITIONAL)) {
1419 VehicleOrderID order_id = order->GetConditionSkipToOrder();
1420 if (order_id >= sel_ord) {
1421 order_id = max(order_id - 1, 0);
1423 if (order_id == cur_order_id) {
1424 order_id = (order_id + 1) % v->GetNumOrders();
1426 order->SetConditionSkipToOrder(order_id);
1428 cur_order_id++;
1431 InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
1432 CheckMarkDirtyFocusedRoutePaths(v);
1436 * Goto order of order-list.
1437 * @param tile unused
1438 * @param flags operation to perform
1439 * @param p1 The ID of the vehicle which order is skipped
1440 * @param p2 the selected order to which we want to skip
1441 * @param text unused
1442 * @return the cost of this operation or an error
1444 CommandCost CmdSkipToOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1446 VehicleID veh_id = GB(p1, 0, 20);
1447 VehicleOrderID sel_ord = GB(p2, 0, 8);
1449 Vehicle *v = Vehicle::GetIfValid(veh_id);
1451 if (v == NULL || !v->IsPrimaryVehicle() || sel_ord == v->cur_implicit_order_index || sel_ord >= v->GetNumOrders() || v->GetNumOrders() < 2) return CMD_ERROR;
1453 CommandCost ret = CheckOwnership(v->owner);
1454 if (ret.Failed()) return ret;
1456 if (flags & DC_EXEC) {
1457 if (v->current_order.IsType(OT_LOADING)) v->LeaveStation();
1458 if (v->current_order.IsType(OT_WAITING)) v->HandleWaiting(true);
1460 v->cur_implicit_order_index = v->cur_real_order_index = sel_ord;
1461 v->UpdateRealOrderIndex();
1463 InvalidateVehicleOrder(v, VIWD_MODIFY_ORDERS);
1466 /* We have an aircraft/ship, they have a mini-schedule, so update them all */
1467 if (v->type == VEH_AIRCRAFT) SetWindowClassesDirty(WC_AIRCRAFT_LIST);
1468 if (v->type == VEH_SHIP) SetWindowClassesDirty(WC_SHIPS_LIST);
1470 return CommandCost();
1474 * Move an order inside the orderlist
1475 * @param tile unused
1476 * @param flags operation to perform
1477 * @param p1 the ID of the vehicle
1478 * @param p2 order to move and target
1479 * bit 0-15 : the order to move
1480 * bit 16-31 : the target order
1481 * @param text unused
1482 * @return the cost of this operation or an error
1483 * @note The target order will move one place down in the orderlist
1484 * if you move the order upwards else it'll move it one place down
1486 CommandCost CmdMoveOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1488 VehicleID veh = GB(p1, 0, 20);
1489 VehicleOrderID moving_order = GB(p2, 0, 16);
1490 VehicleOrderID target_order = GB(p2, 16, 16);
1492 Vehicle *v = Vehicle::GetIfValid(veh);
1493 if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
1495 CommandCost ret = CheckOwnership(v->owner);
1496 if (ret.Failed()) return ret;
1498 /* Don't make senseless movements */
1499 if (moving_order >= v->GetNumOrders() || target_order >= v->GetNumOrders() ||
1500 moving_order == target_order || v->GetNumOrders() <= 1) return CMD_ERROR;
1502 Order *moving_one = v->GetOrder(moving_order);
1503 /* Don't move an empty order */
1504 if (moving_one == NULL) return CMD_ERROR;
1506 if (flags & DC_EXEC) {
1507 v->MoveOrder(moving_order, target_order);
1509 /* Update shared list */
1510 Vehicle *u = v->FirstShared();
1512 DeleteOrderWarnings(u);
1514 for (; u != NULL; u = u->NextShared()) {
1515 /* Update the current order.
1516 * There are multiple ways to move orders, which result in cur_implicit_order_index
1517 * and cur_real_order_index to not longer make any sense. E.g. moving another
1518 * real order between them.
1520 * Basically one could choose to preserve either of them, but not both.
1521 * While both ways are suitable in this or that case from a human point of view, neither
1522 * of them makes really sense.
1523 * However, from an AI point of view, preserving cur_real_order_index is the most
1524 * predictable and transparent behaviour.
1526 * With that decision it basically does not matter what we do to cur_implicit_order_index.
1527 * If we change orders between the implicit- and real-index, the implicit orders are mostly likely
1528 * completely out-dated anyway. So, keep it simple and just keep cur_implicit_order_index as well.
1529 * The worst which can happen is that a lot of implicit orders are removed when reaching current_order.
1531 if (u->cur_real_order_index == moving_order) {
1532 u->cur_real_order_index = target_order;
1533 } else if (u->cur_real_order_index > moving_order && u->cur_real_order_index <= target_order) {
1534 u->cur_real_order_index--;
1535 } else if (u->cur_real_order_index < moving_order && u->cur_real_order_index >= target_order) {
1536 u->cur_real_order_index++;
1539 if (u->cur_implicit_order_index == moving_order) {
1540 u->cur_implicit_order_index = target_order;
1541 } else if (u->cur_implicit_order_index > moving_order && u->cur_implicit_order_index <= target_order) {
1542 u->cur_implicit_order_index--;
1543 } else if (u->cur_implicit_order_index < moving_order && u->cur_implicit_order_index >= target_order) {
1544 u->cur_implicit_order_index++;
1547 assert(v->IsSharingOrdersWith(u));
1548 /* Update any possible open window of the vehicle */
1549 InvalidateVehicleOrder(u, moving_order | (target_order << 8));
1552 /* As we move an order, the order to skip to will be 'wrong'. */
1553 Order *order;
1554 FOR_VEHICLE_ORDERS(v, order) {
1555 if (order->IsType(OT_CONDITIONAL)) {
1556 VehicleOrderID order_id = order->GetConditionSkipToOrder();
1557 if (order_id == moving_order) {
1558 order_id = target_order;
1559 } else if (order_id > moving_order && order_id <= target_order) {
1560 order_id--;
1561 } else if (order_id < moving_order && order_id >= target_order) {
1562 order_id++;
1564 order->SetConditionSkipToOrder(order_id);
1568 /* Make sure to rebuild the whole list */
1569 InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
1572 return CommandCost();
1576 * Modify an order in the orderlist of a vehicle.
1577 * @param tile unused
1578 * @param flags operation to perform
1579 * @param p1 various bitstuffed elements
1580 * - p1 = (bit 0 - 19) - ID of the vehicle
1581 * - p1 = (bit 20 - 27) - the selected order (if any). If the last order is given,
1582 * the order will be inserted before that one
1583 * the maximum vehicle order id is 254.
1584 * @param p2 various bitstuffed elements
1585 * - p2 = (bit 0 - 3) - what data to modify (@see ModifyOrderFlags)
1586 * - p2 = (bit 4 - 15) - the data to modify
1587 * - p2 = (bit 16 - 23) - a CargoID for cargo type orders (MOF_CARGO_TYPE_UNLOAD or MOF_CARGO_TYPE_LOAD)
1588 * @param text unused
1589 * @return the cost of this operation or an error
1591 CommandCost CmdModifyOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1593 VehicleOrderID sel_ord = GB(p1, 20, 8);
1594 VehicleID veh = GB(p1, 0, 20);
1595 ModifyOrderFlags mof = Extract<ModifyOrderFlags, 0, 4>(p2);
1596 uint16 data = GB(p2, 4, 11);
1597 CargoID cargo_id = (mof == MOF_CARGO_TYPE_UNLOAD || mof == MOF_CARGO_TYPE_LOAD) ? (CargoID)GB(p2, 16, 8) : (CargoID)CT_INVALID;
1599 if (mof >= MOF_END) return CMD_ERROR;
1601 Vehicle *v = Vehicle::GetIfValid(veh);
1602 if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
1604 CommandCost ret = CheckOwnership(v->owner);
1605 if (ret.Failed()) return ret;
1607 /* Is it a valid order? */
1608 if (sel_ord >= v->GetNumOrders()) return CMD_ERROR;
1610 Order *order = v->GetOrder(sel_ord);
1611 switch (order->GetType()) {
1612 case OT_GOTO_STATION:
1613 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 CMD_ERROR;
1614 break;
1616 case OT_GOTO_DEPOT:
1617 if (mof != MOF_NON_STOP && mof != MOF_DEPOT_ACTION) return CMD_ERROR;
1618 break;
1620 case OT_GOTO_WAYPOINT:
1621 if (mof != MOF_NON_STOP && mof != MOF_WAYPOINT_FLAGS) return CMD_ERROR;
1622 break;
1624 case OT_CONDITIONAL:
1625 if (mof != MOF_COND_VARIABLE && mof != MOF_COND_COMPARATOR && mof != MOF_COND_VALUE && mof != MOF_COND_DESTINATION) return CMD_ERROR;
1626 break;
1628 default:
1629 return CMD_ERROR;
1632 switch (mof) {
1633 default: NOT_REACHED();
1635 case MOF_NON_STOP:
1636 if (!v->IsGroundVehicle()) return CMD_ERROR;
1637 if (data >= ONSF_END) return CMD_ERROR;
1638 if (data == order->GetNonStopType()) return CMD_ERROR;
1639 break;
1641 case MOF_STOP_LOCATION:
1642 if (v->type != VEH_TRAIN) return CMD_ERROR;
1643 if (data >= OSL_END) return CMD_ERROR;
1644 break;
1646 case MOF_CARGO_TYPE_UNLOAD:
1647 if (cargo_id >= NUM_CARGO) return CMD_ERROR;
1648 if (data == OUFB_CARGO_TYPE_UNLOAD) return CMD_ERROR;
1649 /* FALL THROUGH */
1650 case MOF_UNLOAD:
1651 if (order->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) return CMD_ERROR;
1652 if ((data & ~(OUFB_UNLOAD | OUFB_TRANSFER | OUFB_NO_UNLOAD | OUFB_CARGO_TYPE_UNLOAD)) != 0) return CMD_ERROR;
1653 /* Unload and no-unload are mutual exclusive and so are transfer and no unload. */
1654 if (data != 0 && (data & OUFB_CARGO_TYPE_UNLOAD) == 0 && ((data & (OUFB_UNLOAD | OUFB_TRANSFER)) != 0) == ((data & OUFB_NO_UNLOAD) != 0)) return CMD_ERROR;
1655 /* Cargo-type-unload exclude all the other flags. */
1656 if ((data & OUFB_CARGO_TYPE_UNLOAD) != 0 && data != OUFB_CARGO_TYPE_UNLOAD) return CMD_ERROR;
1657 if (data == order->GetUnloadType()) return CMD_ERROR;
1658 break;
1660 case MOF_CARGO_TYPE_LOAD:
1661 if (cargo_id >= NUM_CARGO) return CMD_ERROR;
1662 if (data == OLFB_CARGO_TYPE_LOAD || data == OLF_FULL_LOAD_ANY) return CMD_ERROR;
1663 /* FALL THROUGH */
1664 case MOF_LOAD:
1665 if (order->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) return CMD_ERROR;
1666 if ((data > OLFB_NO_LOAD && data != OLFB_CARGO_TYPE_LOAD) || data == 1) return CMD_ERROR;
1667 if (data == order->GetLoadType()) return CMD_ERROR;
1668 break;
1670 case MOF_DEPOT_ACTION:
1671 if (data >= DA_END) return CMD_ERROR;
1672 break;
1674 case MOF_COND_VARIABLE:
1675 if (data == OCV_FREE_PLATFORMS && v->type != VEH_TRAIN) return CMD_ERROR;
1676 if (data >= OCV_END) return CMD_ERROR;
1677 break;
1679 case MOF_COND_COMPARATOR:
1680 if (data >= OCC_END) return CMD_ERROR;
1681 switch (order->GetConditionVariable()) {
1682 case OCV_UNCONDITIONALLY:
1683 case OCV_PERCENT:
1684 return CMD_ERROR;
1686 case OCV_REQUIRES_SERVICE:
1687 case OCV_CARGO_ACCEPTANCE:
1688 case OCV_CARGO_WAITING:
1689 case OCV_SLOT_OCCUPANCY:
1690 if (data != OCC_IS_TRUE && data != OCC_IS_FALSE) return CMD_ERROR;
1691 break;
1693 default:
1694 if (data == OCC_IS_TRUE || data == OCC_IS_FALSE) return CMD_ERROR;
1695 break;
1697 break;
1699 case MOF_COND_VALUE:
1700 switch (order->GetConditionVariable()) {
1701 case OCV_UNCONDITIONALLY:
1702 case OCV_REQUIRES_SERVICE:
1703 return CMD_ERROR;
1705 case OCV_LOAD_PERCENTAGE:
1706 case OCV_RELIABILITY:
1707 case OCV_PERCENT:
1708 if (data > 100) return CMD_ERROR;
1709 break;
1711 case OCV_SLOT_OCCUPANCY:
1712 // Can't encode more than 2047, even though there could be more slots.
1713 if (data > 2047 || !TraceRestrictSlot::IsValidID(data)) return CMD_ERROR;
1714 break;
1716 case OCV_CARGO_ACCEPTANCE:
1717 case OCV_CARGO_WAITING:
1718 if (!(data < NUM_CARGO && CargoSpec::Get(data)->IsValid())) return CMD_ERROR;
1719 break;
1721 default:
1722 if (data > 2047) return CMD_ERROR;
1723 break;
1725 break;
1727 case MOF_COND_DESTINATION:
1728 if (data >= v->GetNumOrders()) return CMD_ERROR;
1729 break;
1731 case MOF_WAYPOINT_FLAGS:
1732 if (data != (data & OWF_REVERSE)) return CMD_ERROR;
1733 break;
1736 if (flags & DC_EXEC) {
1737 switch (mof) {
1738 case MOF_NON_STOP:
1739 order->SetNonStopType((OrderNonStopFlags)data);
1740 if (data & ONSF_NO_STOP_AT_DESTINATION_STATION) {
1741 order->SetRefit(CT_NO_REFIT);
1742 order->SetLoadType(OLF_LOAD_IF_POSSIBLE);
1743 order->SetUnloadType(OUF_UNLOAD_IF_POSSIBLE);
1745 break;
1747 case MOF_STOP_LOCATION:
1748 order->SetStopLocation((OrderStopLocation)data);
1749 break;
1751 case MOF_UNLOAD:
1752 order->SetUnloadType((OrderUnloadFlags)data);
1753 break;
1755 case MOF_CARGO_TYPE_UNLOAD:
1756 order->SetUnloadType((OrderUnloadFlags)data, cargo_id);
1757 break;
1759 case MOF_LOAD:
1760 order->SetLoadType((OrderLoadFlags)data);
1761 if (data & OLFB_NO_LOAD) order->SetRefit(CT_NO_REFIT);
1762 break;
1764 case MOF_CARGO_TYPE_LOAD:
1765 order->SetLoadType((OrderLoadFlags)data, cargo_id);
1766 break;
1768 case MOF_DEPOT_ACTION: {
1769 switch (data) {
1770 case DA_ALWAYS_GO:
1771 order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
1772 order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
1773 break;
1775 case DA_SERVICE:
1776 order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() | ODTFB_SERVICE));
1777 order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
1778 order->SetRefit(CT_NO_REFIT);
1779 break;
1781 case DA_STOP:
1782 order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
1783 order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() | ODATFB_HALT));
1784 order->SetRefit(CT_NO_REFIT);
1785 break;
1787 default:
1788 NOT_REACHED();
1790 break;
1793 case MOF_COND_VARIABLE: {
1794 /* Check whether old conditional variable had a cargo as value */
1795 bool old_var_was_cargo = (order->GetConditionVariable() == OCV_CARGO_ACCEPTANCE || order->GetConditionVariable() == OCV_CARGO_WAITING);
1796 bool old_var_was_slot = (order->GetConditionVariable() == OCV_SLOT_OCCUPANCY);
1797 order->SetConditionVariable((OrderConditionVariable)data);
1799 OrderConditionComparator occ = order->GetConditionComparator();
1800 switch (order->GetConditionVariable()) {
1801 case OCV_UNCONDITIONALLY:
1802 order->SetConditionComparator(OCC_EQUALS);
1803 order->SetConditionValue(0);
1804 break;
1806 case OCV_SLOT_OCCUPANCY:
1807 if (!old_var_was_slot) order->SetConditionValue((uint16)GetFirstValidTraceRestrictSlot());
1808 if (occ != OCC_IS_TRUE && occ != OCC_IS_FALSE) order->SetConditionComparator(OCC_IS_TRUE);
1809 break;
1811 case OCV_CARGO_ACCEPTANCE:
1812 case OCV_CARGO_WAITING:
1813 if (!old_var_was_cargo) order->SetConditionValue((uint16) GetFirstValidCargo());
1814 if (occ != OCC_IS_TRUE && occ != OCC_IS_FALSE) order->SetConditionComparator(OCC_IS_TRUE);
1815 break;
1817 case OCV_REQUIRES_SERVICE:
1818 if (old_var_was_cargo || old_var_was_slot) order->SetConditionValue(0);
1819 if (occ != OCC_IS_TRUE && occ != OCC_IS_FALSE) order->SetConditionComparator(OCC_IS_TRUE);
1820 order->SetConditionValue(0);
1821 break;
1823 case OCV_PERCENT:
1824 order->SetConditionComparator(OCC_EQUALS);
1825 /* FALL THROUGH */
1827 case OCV_LOAD_PERCENTAGE:
1828 case OCV_RELIABILITY:
1829 if (order->GetConditionValue() > 100) order->SetConditionValue(100);
1830 FALLTHROUGH;
1832 default:
1833 if (old_var_was_cargo || old_var_was_slot) order->SetConditionValue(0);
1834 if (occ == OCC_IS_TRUE || occ == OCC_IS_FALSE) order->SetConditionComparator(OCC_EQUALS);
1835 break;
1837 break;
1840 case MOF_COND_COMPARATOR:
1841 order->SetConditionComparator((OrderConditionComparator)data);
1842 break;
1844 case MOF_COND_VALUE:
1845 order->SetConditionValue(data);
1846 break;
1848 case MOF_COND_DESTINATION:
1849 order->SetConditionSkipToOrder(data);
1850 break;
1852 case MOF_WAYPOINT_FLAGS:
1853 order->SetWaypointFlags((OrderWaypointFlags)data);
1854 break;
1856 default: NOT_REACHED();
1859 /* Update the windows and full load flags, also for vehicles that share the same order list */
1860 Vehicle *u = v->FirstShared();
1861 DeleteOrderWarnings(u);
1862 for (; u != NULL; u = u->NextShared()) {
1863 /* Toggle u->current_order "Full load" flag if it changed.
1864 * However, as the same flag is used for depot orders, check
1865 * whether we are not going to a depot as there are three
1866 * cases where the full load flag can be active and only
1867 * one case where the flag is used for depot orders. In the
1868 * other cases for the OrderTypeByte the flags are not used,
1869 * so do not care and those orders should not be active
1870 * when this function is called.
1872 if (sel_ord == u->cur_real_order_index &&
1873 (u->current_order.IsType(OT_GOTO_STATION) || u->current_order.IsType(OT_LOADING)) &&
1874 u->current_order.GetLoadType() != order->GetLoadType()) {
1875 u->current_order.SetLoadType(order->GetLoadType());
1877 InvalidateVehicleOrder(u, VIWD_MODIFY_ORDERS);
1879 CheckMarkDirtyFocusedRoutePaths(v);
1882 return CommandCost();
1886 * Check if an aircraft has enough range for an order list.
1887 * @param v_new Aircraft to check.
1888 * @param v_order Vehicle currently holding the order list.
1889 * @param first First order in the source order list.
1890 * @return True if the aircraft has enough range for the orders, false otherwise.
1892 static bool CheckAircraftOrderDistance(const Aircraft *v_new, const Vehicle *v_order, const Order *first)
1894 if (first == NULL || v_new->acache.cached_max_range == 0) return true;
1896 /* Iterate over all orders to check the distance between all
1897 * 'goto' orders and their respective next order (of any type). */
1898 for (const Order *o = first; o != NULL; o = o->next) {
1899 switch (o->GetType()) {
1900 case OT_GOTO_STATION:
1901 case OT_GOTO_DEPOT:
1902 case OT_GOTO_WAYPOINT:
1903 /* If we don't have a next order, we've reached the end and must check the first order instead. */
1904 if (GetOrderDistance(o, o->next != NULL ? o->next : first, v_order) > v_new->acache.cached_max_range_sqr) return false;
1905 break;
1907 default: break;
1911 return true;
1915 * Clone/share/copy an order-list of another vehicle.
1916 * @param tile unused
1917 * @param flags operation to perform
1918 * @param p1 various bitstuffed elements
1919 * - p1 = (bit 0-19) - destination vehicle to clone orders to
1920 * - p1 = (bit 30-31) - action to perform
1921 * @param p2 source vehicle to clone orders from, if any (none for CO_UNSHARE)
1922 * @param text unused
1923 * @return the cost of this operation or an error
1925 CommandCost CmdCloneOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1927 VehicleID veh_src = GB(p2, 0, 20);
1928 VehicleID veh_dst = GB(p1, 0, 20);
1930 Vehicle *dst = Vehicle::GetIfValid(veh_dst);
1931 if (dst == NULL || !dst->IsPrimaryVehicle()) return CMD_ERROR;
1933 CommandCost ret = CheckOwnership(dst->owner);
1934 if (ret.Failed()) return ret;
1936 switch (GB(p1, 30, 2)) {
1937 case CO_SHARE: {
1938 Vehicle *src = Vehicle::GetIfValid(veh_src);
1940 /* Sanity checks */
1941 if (src == NULL || !src->IsPrimaryVehicle() || dst->type != src->type || dst == src) return CMD_ERROR;
1943 CommandCost ret = CheckOwnership(src->owner);
1944 if (ret.Failed()) return ret;
1946 /* Trucks can't share orders with busses (and visa versa) */
1947 if (src->type == VEH_ROAD && RoadVehicle::From(src)->IsBus() != RoadVehicle::From(dst)->IsBus()) {
1948 return CMD_ERROR;
1951 /* Is the vehicle already in the shared list? */
1952 if (src->FirstShared() == dst->FirstShared()) return CMD_ERROR;
1954 const Order *order;
1956 FOR_VEHICLE_ORDERS(src, order) {
1957 if (!OrderGoesToStation(dst, order)) continue;
1959 /* Allow copying unreachable destinations if they were already unreachable for the source.
1960 * This is basically to allow cloning / autorenewing / autoreplacing vehicles, while the stations
1961 * are temporarily invalid due to reconstruction. */
1962 const Station *st = Station::Get(order->GetDestination());
1963 if (CanVehicleUseStation(src, st) && !CanVehicleUseStation(dst, st)) {
1964 return_cmd_error(STR_ERROR_CAN_T_COPY_SHARE_ORDER);
1968 /* Check for aircraft range limits. */
1969 if (dst->type == VEH_AIRCRAFT && !CheckAircraftOrderDistance(Aircraft::From(dst), src, src->GetFirstOrder())) {
1970 return_cmd_error(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE);
1973 if (!src->HasOrdersList() && !OrderList::CanAllocateItem()) {
1974 return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
1977 if (flags & DC_EXEC) {
1978 /* If the destination vehicle had a OrderList, destroy it.
1979 * We only reset the order indices, if the new orders are obviously different.
1980 * (We mainly do this to keep the order indices valid and in range.) */
1981 dst->DeleteVehicleOrders(false, dst->GetNumOrders() != src->GetNumOrders());
1983 dst->ShareOrdersWith(src);
1985 /* Link this vehicle in the shared-list */
1986 dst->AddToShared(src);
1988 /* Set automation bit if target has it. */
1989 if (HasBit(src->vehicle_flags, VF_AUTOMATE_TIMETABLE)) {
1990 SetBit(dst->vehicle_flags, VF_AUTOMATE_TIMETABLE);
1992 else {
1993 ClrBit(dst->vehicle_flags, VF_AUTOMATE_TIMETABLE);
1996 if (HasBit(src->vehicle_flags, VF_AUTOMATE_PRES_WAIT_TIME)) {
1997 SetBit(dst->vehicle_flags, VF_AUTOMATE_PRES_WAIT_TIME);
1999 else {
2000 ClrBit(dst->vehicle_flags, VF_AUTOMATE_PRES_WAIT_TIME);
2003 InvalidateVehicleOrder(dst, VIWD_REMOVE_ALL_ORDERS);
2004 InvalidateVehicleOrder(src, VIWD_MODIFY_ORDERS);
2006 InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
2007 CheckMarkDirtyFocusedRoutePaths(dst);
2009 break;
2012 case CO_COPY: {
2013 Vehicle *src = Vehicle::GetIfValid(veh_src);
2015 /* Sanity checks */
2016 if (src == NULL || !src->IsPrimaryVehicle() || dst->type != src->type || dst == src) return CMD_ERROR;
2018 CommandCost ret = CheckOwnership(src->owner);
2019 if (ret.Failed()) return ret;
2021 /* Trucks can't copy all the orders from busses (and visa versa),
2022 * and neither can helicopters and aircraft. */
2023 const Order *order;
2024 FOR_VEHICLE_ORDERS(src, order) {
2025 if (OrderGoesToStation(dst, order) &&
2026 !CanVehicleUseStation(dst, Station::Get(order->GetDestination()))) {
2027 return_cmd_error(STR_ERROR_CAN_T_COPY_SHARE_ORDER);
2031 /* Check for aircraft range limits. */
2032 if (dst->type == VEH_AIRCRAFT && !CheckAircraftOrderDistance(Aircraft::From(dst), src, src->GetFirstOrder())) {
2033 return_cmd_error(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE);
2036 /* make sure there are orders available */
2037 if (!Order::CanAllocateItem(src->GetNumOrders()) || !OrderList::CanAllocateItem()) {
2038 return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
2041 if (flags & DC_EXEC) {
2042 const Order *order;
2043 Order *first = NULL;
2044 Order **order_dst;
2046 /* If the destination vehicle had an order list, destroy the chain but keep the OrderList.
2047 * We only reset the order indices, if the new orders are obviously different.
2048 * (We mainly do this to keep the order indices valid and in range.) */
2049 dst->DeleteVehicleOrders(true, dst->GetNumOrders() != src->GetNumOrders());
2051 order_dst = &first;
2052 FOR_VEHICLE_ORDERS(src, order) {
2053 *order_dst = new Order();
2054 (*order_dst)->AssignOrder(*order);
2055 order_dst = &(*order_dst)->next;
2057 if (!dst->HasOrdersList()) {
2058 dst->SetOrdersList(new OrderList(first, dst));
2059 } else {
2060 assert(dst->GetFirstOrder() == nullptr);
2061 assert(!dst->HasSharedOrdersList());
2062 dst->DeleteAndReplaceOrdersList(new OrderList(first, dst));
2065 /* Set automation bit if target has it. */
2066 if (HasBit(src->vehicle_flags, VF_AUTOMATE_TIMETABLE)) {
2067 SetBit(dst->vehicle_flags, VF_AUTOMATE_TIMETABLE);
2069 else {
2070 ClrBit(dst->vehicle_flags, VF_AUTOMATE_TIMETABLE);
2073 if (HasBit(src->vehicle_flags, VF_AUTOMATE_PRES_WAIT_TIME)) {
2074 SetBit(dst->vehicle_flags, VF_AUTOMATE_PRES_WAIT_TIME);
2076 else {
2077 ClrBit(dst->vehicle_flags, VF_AUTOMATE_PRES_WAIT_TIME);
2080 InvalidateVehicleOrder(dst, VIWD_REMOVE_ALL_ORDERS);
2082 InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
2083 CheckMarkDirtyFocusedRoutePaths(dst);
2085 break;
2088 case CO_UNSHARE: return DecloneOrder(dst, flags);
2089 default: return CMD_ERROR;
2092 return CommandCost();
2096 * Add/remove refit orders from an order
2097 * @param tile Not used
2098 * @param flags operation to perform
2099 * @param p1 VehicleIndex of the vehicle having the order
2100 * @param p2 bitmask
2101 * - bit 0-7 CargoID
2102 * - bit 16-23 number of order to modify
2103 * @param text unused
2104 * @return the cost of this operation or an error
2106 CommandCost CmdOrderRefit(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2108 VehicleID veh = GB(p1, 0, 20);
2109 VehicleOrderID order_number = GB(p2, 16, 8);
2110 CargoID cargo = GB(p2, 0, 8);
2112 if (cargo >= NUM_CARGO && cargo != CT_NO_REFIT && cargo != CT_AUTO_REFIT) return CMD_ERROR;
2114 const Vehicle *v = Vehicle::GetIfValid(veh);
2115 if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
2117 CommandCost ret = CheckOwnership(v->owner);
2118 if (ret.Failed()) return ret;
2120 Order *order = v->GetOrder(order_number);
2121 if (order == NULL) return CMD_ERROR;
2123 /* Automatic refit cargo is only supported for goto station orders. */
2124 if (cargo == CT_AUTO_REFIT && !order->IsType(OT_GOTO_STATION)) return CMD_ERROR;
2126 if (order->GetLoadType() & OLFB_NO_LOAD) return CMD_ERROR;
2128 if (flags & DC_EXEC) {
2129 order->SetRefit(cargo);
2131 /* Make the depot order an 'always go' order. */
2132 if (cargo != CT_NO_REFIT && order->IsType(OT_GOTO_DEPOT)) {
2133 order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
2134 order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
2137 for (Vehicle *u = v->FirstShared(); u != NULL; u = u->NextShared()) {
2138 /* Update any possible open window of the vehicle */
2139 InvalidateVehicleOrder(u, VIWD_MODIFY_ORDERS);
2141 /* If the vehicle already got the current depot set as current order, then update current order as well */
2142 if (u->cur_real_order_index == order_number && (u->current_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) {
2143 u->current_order.SetRefit(cargo);
2146 CheckMarkDirtyFocusedRoutePaths(v);
2149 return CommandCost();
2155 * Check the orders of a vehicle, to see if there are invalid orders and stuff
2158 void CheckOrders(const Vehicle *v)
2160 /* Does the user wants us to check things? */
2161 if (_settings_client.gui.order_review_system == 0) return;
2163 /* Do nothing for crashed vehicles */
2164 if (v->vehstatus & VS_CRASHED) return;
2166 /* Do nothing for stopped vehicles if setting is '1' */
2167 if (_settings_client.gui.order_review_system == 1 && (v->vehstatus & VS_STOPPED)) return;
2169 /* do nothing we we're not the first vehicle in a share-chain */
2170 if (v->FirstShared() != v) return;
2172 /* Only check every 20 days, so that we don't flood the message log */
2173 /* The check is skipped entirely in case the current vehicle is virtual (a.k.a a 'template train') */
2174 if (v->owner == _local_company && v->day_counter % 20 == 0 && !HasBit(v->subtype, GVSF_VIRTUAL) ) {
2175 const Order *order;
2176 StringID message = INVALID_STRING_ID;
2178 /* Check the order list */
2179 int n_st = 0;
2181 FOR_VEHICLE_ORDERS(v, order) {
2182 /* Dummy order? */
2183 if (order->IsType(OT_DUMMY)) {
2184 message = STR_NEWS_VEHICLE_HAS_VOID_ORDER;
2185 break;
2187 /* Does station have a load-bay for this vehicle? */
2188 if (order->IsType(OT_GOTO_STATION)) {
2189 const Station *st = Station::Get(order->GetDestination());
2191 n_st++;
2192 if (!CanVehicleUseStation(v, st)) {
2193 message = STR_NEWS_VEHICLE_HAS_INVALID_ENTRY;
2194 } else if (v->type == VEH_AIRCRAFT &&
2195 (AircraftVehInfo(v->engine_type)->subtype & AIR_FAST) &&
2196 (st->airport.GetFTA()->flags & AirportFTAClass::SHORT_STRIP) &&
2197 _settings_game.vehicle.plane_crashes != 0 &&
2198 !_cheats.no_jetcrash.value &&
2199 message == INVALID_STRING_ID) {
2200 message = STR_NEWS_PLANE_USES_TOO_SHORT_RUNWAY;
2205 /* Check if the last and the first order are the same */
2206 if (v->GetNumOrders() > 1) {
2207 const Order *last = v->GetLastOrder();
2209 if (v->GetFirstOrder()->Equals(*last)) {
2210 message = STR_NEWS_VEHICLE_HAS_DUPLICATE_ENTRY;
2214 /* Do we only have 1 station in our order list? */
2215 if (n_st < 2 && message == INVALID_STRING_ID) message = STR_NEWS_VEHICLE_HAS_TOO_FEW_ORDERS;
2217 #ifndef NDEBUG
2218 v->DebugCheckSanity();
2219 #endif
2221 /* We don't have a problem */
2222 if (message == INVALID_STRING_ID) return;
2224 SetDParam(0, v->index);
2225 AddVehicleAdviceNewsItem(message, v->index);
2230 * Removes an order from all vehicles. Triggers when, say, a station is removed.
2231 * @param type The type of the order (OT_GOTO_[STATION|DEPOT|WAYPOINT]).
2232 * @param destination The destination. Can be a StationID, DepotID or WaypointID.
2234 void RemoveOrderFromAllVehicles(OrderType type, DestinationID destination)
2236 Vehicle *v;
2238 /* Aircraft have StationIDs for depot orders and never use DepotIDs
2239 * This fact is handled specially below
2242 /* Go through all vehicles */
2243 FOR_ALL_VEHICLES(v) {
2244 Order *order;
2246 order = &v->current_order;
2247 if ((v->type == VEH_AIRCRAFT && order->IsType(OT_GOTO_DEPOT) ? OT_GOTO_STATION : order->GetType()) == type &&
2248 v->current_order.GetDestination() == destination) {
2249 order->MakeDummy();
2250 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
2253 /* Clear the order from the order-list */
2254 int id = -1;
2255 FOR_VEHICLE_ORDERS(v, order) {
2256 id++;
2257 restart:
2259 OrderType ot = order->GetType();
2260 if (ot == OT_GOTO_DEPOT && (order->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0) continue;
2261 if (ot == OT_IMPLICIT || (v->type == VEH_AIRCRAFT && ot == OT_GOTO_DEPOT)) ot = OT_GOTO_STATION;
2262 if (ot == type && order->GetDestination() == destination) {
2263 /* We want to clear implicit orders, but we don't want to make them
2264 * dummy orders. They should just vanish. Also check the actual order
2265 * type as ot is currently OT_GOTO_STATION. */
2266 if (order->IsType(OT_IMPLICIT)) {
2267 order = order->next; // DeleteOrder() invalidates current order
2268 DeleteOrder(v, id);
2269 if (order != NULL) goto restart;
2270 break;
2273 /* Clear wait time */
2274 v->UpdateTotalDuration(-order->GetWaitTime());
2275 if (order->IsWaitTimetabled()) {
2276 v->UpdateTimetableDuration(-order->GetTimetabledWait());
2277 order->SetWaitTimetabled(false);
2279 order->SetWaitTime(0);
2281 /* Clear order, preserving travel time */
2282 bool travel_timetabled = order->IsTravelTimetabled();
2283 order->MakeDummy();
2284 order->SetTravelTimetabled(travel_timetabled);
2286 for (const Vehicle *w = v->FirstShared(); w != NULL; w = w->NextShared()) {
2287 /* In GUI, simulate by removing the order and adding it back */
2288 InvalidateVehicleOrder(w, id | (INVALID_VEH_ORDER_ID << 8));
2289 InvalidateVehicleOrder(w, (INVALID_VEH_ORDER_ID << 8) | id);
2295 OrderBackup::RemoveOrder(type, destination);
2299 * Checks if a vehicle has a depot in its order list.
2300 * @return True iff at least one order is a depot order.
2302 bool Vehicle::HasDepotOrder() const
2304 const Order *order;
2306 FOR_VEHICLE_ORDERS(this, order) {
2307 if (order->IsType(OT_GOTO_DEPOT)) return true;
2310 return false;
2314 * Clamp the service interval to the correct min/max. The actual min/max values
2315 * depend on whether it's in percent or days.
2316 * @param interval proposed service interval
2317 * @param company_id the owner of the vehicle
2318 * @return Clamped service interval
2320 uint16 GetServiceIntervalClamped(uint interval, bool ispercent)
2322 return ispercent ? Clamp(interval, MIN_SERVINT_PERCENT, MAX_SERVINT_PERCENT) : Clamp(interval, MIN_SERVINT_DAYS, MAX_SERVINT_DAYS);
2327 * Check if a vehicle has any valid orders
2329 * @return false if there are no valid orders
2330 * @note Conditional orders are not considered valid destination orders
2333 static bool CheckForValidOrders(const Vehicle *v)
2335 const Order *order;
2337 FOR_VEHICLE_ORDERS(v, order) {
2338 switch (order->GetType()) {
2339 case OT_GOTO_STATION:
2340 case OT_GOTO_DEPOT:
2341 case OT_GOTO_WAYPOINT:
2342 return true;
2344 default:
2345 break;
2349 return false;
2353 * Compare the variable and value based on the given comparator.
2355 static bool OrderConditionCompare(OrderConditionComparator occ, int variable, int value)
2357 switch (occ) {
2358 case OCC_EQUALS: return variable == value;
2359 case OCC_NOT_EQUALS: return variable != value;
2360 case OCC_LESS_THAN: return variable < value;
2361 case OCC_LESS_EQUALS: return variable <= value;
2362 case OCC_MORE_THAN: return variable > value;
2363 case OCC_MORE_EQUALS: return variable >= value;
2364 case OCC_IS_TRUE: return variable != 0;
2365 case OCC_IS_FALSE: return variable == 0;
2366 default: NOT_REACHED();
2370 /* Get the number of free (train) platforms in a station.
2371 * @param st_id The StationID of the station.
2372 * @return The number of free train platforms.
2374 static uint16 GetFreeStationPlatforms(StationID st_id)
2376 assert(Station::IsValidID(st_id));
2377 const Station *st = Station::Get(st_id);
2378 if (!(st->facilities & FACIL_TRAIN)) return 0;
2379 bool is_free;
2380 TileIndex t2;
2381 uint16 counter = 0;
2382 TILE_AREA_LOOP(t1, st->train_station) {
2383 if (st->TileBelongsToRailStation(t1)) {
2384 /* We only proceed if this tile is a track tile and the north(-east/-west) end of the platform */
2385 if (IsCompatibleTrainStationTile(t1 + TileOffsByDiagDir(GetRailStationAxis(t1) == AXIS_X ? DIAGDIR_NE : DIAGDIR_NW), t1) || IsStationTileBlocked(t1)) continue;
2386 is_free = true;
2387 t2 = t1;
2388 do {
2389 if (GetStationReservationTrackBits(t2)) {
2390 is_free = false;
2391 break;
2393 t2 += TileOffsByDiagDir(GetRailStationAxis(t1) == AXIS_X ? DIAGDIR_SW : DIAGDIR_SE);
2394 } while (IsCompatibleTrainStationTile(t2, t1));
2395 if (is_free) counter++;
2398 return counter;
2401 /** Gets the next 'real' station in the order list
2402 * @param v the vehicle in question
2403 * @param order the current (conditional) order
2404 * @return the StationID of the next valid station in the order list, or INVALID_STATION if there is none.
2406 static StationID GetNextRealStation(const Vehicle *v, const Order *order, int conditional_depth = 0)
2408 if (order->IsType(OT_GOTO_STATION)) {
2409 if (Station::IsValidID(order->GetDestination())) return order->GetDestination();
2411 //nothing conditional about this
2412 if (conditional_depth > v->GetNumOrders()) return INVALID_STATION;
2413 return GetNextRealStation(v, (order->next != NULL) ? order->next : v->GetFirstOrder(), ++conditional_depth);
2417 * Process a conditional order and determine the next order.
2418 * @param order the order the vehicle currently has
2419 * @param v the vehicle to update
2420 * @return index of next order to jump to, or INVALID_VEH_ORDER_ID to use the next order
2422 VehicleOrderID ProcessConditionalOrder(const Order *order, const Vehicle *v)
2424 if (order->GetType() != OT_CONDITIONAL) return INVALID_VEH_ORDER_ID;
2426 bool skip_order = false;
2427 OrderConditionComparator occ = order->GetConditionComparator();
2428 uint16 value = order->GetConditionValue();
2429 bool has_manual_depot_order = (HasBit(v->vehicle_flags, VF_SHOULD_GOTO_DEPOT) || HasBit(v->vehicle_flags, VF_SHOULD_SERVICE_AT_DEPOT));
2431 // OrderConditionCompare ignores the last parameter for occ == OCC_IS_TRUE or occ == OCC_IS_FALSE.
2432 switch (order->GetConditionVariable()) {
2433 case OCV_LOAD_PERCENTAGE: skip_order = OrderConditionCompare(occ, CalcPercentVehicleFilled(v, NULL), value); break;
2434 case OCV_RELIABILITY: skip_order = OrderConditionCompare(occ, ToPercent16(v->reliability), value); break;
2435 case OCV_MAX_SPEED: skip_order = OrderConditionCompare(occ, v->GetDisplayMaxSpeed() * 10 / 16, value); break;
2436 case OCV_AGE: skip_order = OrderConditionCompare(occ, v->age / DAYS_IN_LEAP_YEAR, value); break;
2437 case OCV_REQUIRES_SERVICE: skip_order = OrderConditionCompare(occ, has_manual_depot_order || v->NeedsServicing(), value); break;
2438 case OCV_UNCONDITIONALLY: skip_order = true; break;
2439 case OCV_CARGO_WAITING: {
2440 StationID next_station = GetNextRealStation(v, order);
2441 if (Station::IsValidID(next_station)) skip_order = OrderConditionCompare(occ, Station::Get(next_station)->goods[value].cargo.AvailableCount() > 0, value);
2442 break;
2444 case OCV_CARGO_ACCEPTANCE: {
2445 StationID next_station = GetNextRealStation(v, order);
2446 if (Station::IsValidID(next_station)) skip_order = OrderConditionCompare(occ, HasBit(Station::Get(next_station)->goods[value].status, GoodsEntry::GES_ACCEPTANCE), value);
2447 break;
2449 case OCV_SLOT_OCCUPANCY: {
2450 const TraceRestrictSlot* slot = TraceRestrictSlot::GetIfValid(value);
2451 if (slot != nullptr) skip_order = OrderConditionCompare(occ, slot->occupants.size() >= slot->max_occupancy, value);
2452 break;
2454 case OCV_FREE_PLATFORMS: {
2455 StationID next_station = GetNextRealStation(v, order);
2456 if (Station::IsValidID(next_station)) skip_order = OrderConditionCompare(occ, GetFreeStationPlatforms(next_station), value);
2457 break;
2459 case OCV_PERCENT: {
2460 /* get a non-const reference to the current order */
2461 Order *ord = (Order *)order;
2462 skip_order = ord->UpdateJumpCounter((byte)value);
2463 break;
2465 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;
2466 default: NOT_REACHED();
2469 return skip_order ? order->GetConditionSkipToOrder() : (VehicleOrderID)INVALID_VEH_ORDER_ID;
2473 * Update the vehicle's destination tile from an order.
2474 * @param order the order the vehicle currently has
2475 * @param v the vehicle to update
2476 * @param conditional_depth the depth (amount of steps) to go with conditional orders. This to prevent infinite loops.
2477 * @param pbs_look_ahead Whether we are forecasting orders for pbs reservations in advance. If true, the order indices must not be modified.
2479 bool UpdateOrderDest(Vehicle *v, const Order *order, int conditional_depth, bool pbs_look_ahead)
2481 if (conditional_depth > v->GetNumOrders()) {
2482 v->current_order.Free();
2483 v->dest_tile = 0;
2484 return false;
2487 bool has_manual_depot_order = (HasBit(v->vehicle_flags, VF_SHOULD_GOTO_DEPOT) || HasBit(v->vehicle_flags, VF_SHOULD_SERVICE_AT_DEPOT));
2489 switch (order->GetType()) {
2490 case OT_GOTO_STATION:
2491 v->dest_tile = v->GetOrderStationLocation(order->GetDestination());
2492 return true;
2494 case OT_GOTO_DEPOT:
2495 if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !(v->NeedsServicing() || has_manual_depot_order)) {
2496 assert(!pbs_look_ahead);
2497 UpdateVehicleTimetable(v, true);
2498 v->IncrementRealOrderIndex();
2499 break;
2502 if (v->current_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) {
2503 /* We need to search for the nearest depot (hangar). */
2504 TileIndex location;
2505 DestinationID destination;
2506 bool reverse;
2508 if (v->FindClosestDepot(&location, &destination, &reverse)) {
2509 /* PBS reservations cannot reverse */
2510 if (pbs_look_ahead && reverse) return false;
2512 v->dest_tile = location;
2513 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());
2515 /* If there is no depot in front, reverse automatically (trains only) */
2516 if (v->type == VEH_TRAIN && reverse) DoCommand(v->tile, v->index, 0, DC_EXEC, CMD_REVERSE_TRAIN_DIRECTION);
2518 if (v->type == VEH_AIRCRAFT) {
2519 Aircraft *a = Aircraft::From(v);
2520 if (a->state == FLYING && a->targetairport != destination) {
2521 /* The aircraft is now heading for a different hangar than the next in the orders */
2522 extern void AircraftNextAirportPos_and_Order(Aircraft *a);
2523 AircraftNextAirportPos_and_Order(a);
2526 return true;
2529 /* If there is no depot, we cannot help PBS either. */
2530 if (pbs_look_ahead) return false;
2532 UpdateVehicleTimetable(v, true);
2533 v->IncrementRealOrderIndex();
2534 } else {
2535 if (v->type != VEH_AIRCRAFT) {
2536 v->dest_tile = Depot::Get(order->GetDestination())->xy;
2538 return true;
2540 break;
2542 case OT_GOTO_WAYPOINT:
2543 v->dest_tile = Waypoint::Get(order->GetDestination())->xy;
2544 return true;
2546 case OT_CONDITIONAL: {
2547 assert(!pbs_look_ahead);
2548 VehicleOrderID next_order = ProcessConditionalOrder(order, v);
2549 if (next_order != INVALID_VEH_ORDER_ID) {
2550 /* Jump to next_order. cur_implicit_order_index becomes exactly that order,
2551 * cur_real_order_index might come after next_order. */
2552 UpdateVehicleTimetable(v, false);
2553 v->cur_implicit_order_index = v->cur_real_order_index = next_order;
2554 v->UpdateRealOrderIndex();
2555 v->current_order_time += v->GetOrder(v->cur_real_order_index)->GetTimetabledTravel();
2557 /* Disable creation of implicit orders.
2558 * When inserting them we do not know that we would have to make the conditional orders point to them. */
2559 if (v->IsGroundVehicle()) {
2560 uint16 &gv_flags = v->GetGroundVehicleFlags();
2561 SetBit(gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
2563 } else {
2564 UpdateVehicleTimetable(v, true);
2565 v->IncrementRealOrderIndex();
2567 break;
2570 default:
2571 v->dest_tile = 0;
2572 return false;
2575 assert(v->cur_implicit_order_index < v->GetNumOrders());
2576 assert(v->cur_real_order_index < v->GetNumOrders());
2578 /* Get the current order */
2579 order = v->GetOrder(v->cur_real_order_index);
2580 if (order != NULL && order->IsType(OT_IMPLICIT)) {
2581 assert(v->GetNumManualOrders() == 0);
2582 order = NULL;
2585 if (order == NULL) {
2586 v->current_order.Free();
2587 v->dest_tile = 0;
2588 return false;
2591 v->current_order = *order;
2592 return UpdateOrderDest(v, order, conditional_depth + 1, pbs_look_ahead);
2596 * Handle the orders of a vehicle and determine the next place
2597 * to go to if needed.
2598 * @param v the vehicle to do this for.
2599 * @return true *if* the vehicle is eligible for reversing
2600 * (basically only when leaving a station).
2602 bool ProcessOrders(Vehicle *v)
2604 // Check if we have an illegal manual depot order. Could happen if we deleted the depot order from the orders list after sending
2605 // the vehicle to the depot.
2606 if (HasBit(v->vehicle_flags, VF_SHOULD_GOTO_DEPOT) || HasBit(v->vehicle_flags, VF_SHOULD_SERVICE_AT_DEPOT)) {
2607 int next_depot_index = -1;
2609 for (int i = 0; i < v->GetNumOrders(); ++i) {
2610 Order* order = v->GetOrder(i);
2612 bool isRegularOrder = (order->GetDepotOrderType() & ODTFB_PART_OF_ORDERS) != 0;
2613 bool isDepotOrder = order->GetType() == OT_GOTO_DEPOT;
2615 if (isRegularOrder && isDepotOrder) {
2616 if (i >= v->cur_implicit_order_index) {
2617 next_depot_index = i;
2618 break;
2620 else if (next_depot_index < 0) {
2621 next_depot_index = i;
2626 if (next_depot_index == -1) {
2627 ClrBit(v->vehicle_flags, VF_SHOULD_GOTO_DEPOT);
2628 ClrBit(v->vehicle_flags, VF_SHOULD_SERVICE_AT_DEPOT);
2632 switch (v->current_order.GetType()) {
2633 case OT_GOTO_DEPOT:
2634 // Check whether the vehicle was manually ordered to go to the depot on its order list.
2635 // If so mark the current depot order as manual, now that we are processing it.
2636 if (HasBit(v->vehicle_flags, VF_SHOULD_GOTO_DEPOT) || HasBit(v->vehicle_flags, VF_SHOULD_SERVICE_AT_DEPOT)) {
2637 v->current_order.SetDepotOrderType(ODTF_MANUAL);
2638 v->current_order.SetDepotActionType(HasBit(v->vehicle_flags, VF_SHOULD_SERVICE_AT_DEPOT) ? ODATF_SERVICE_ONLY : ODATFB_HALT);
2641 /* Let a depot order in the order list interrupt. */
2642 if (!(v->current_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) return false;
2644 break;
2646 case OT_LOADING:
2647 return false;
2649 case OT_WAITING:
2650 return false;
2652 case OT_LEAVESTATION:
2653 if (v->type != VEH_AIRCRAFT) return false;
2654 break;
2656 default: break;
2660 * Reversing because of order change is allowed only just after leaving a
2661 * station (and the difficulty setting to allowed, of course)
2662 * this can be detected because only after OT_LEAVESTATION, current_order
2663 * will be reset to nothing. (That also happens if no order, but in that case
2664 * it won't hit the point in code where may_reverse is checked)
2666 bool may_reverse = v->current_order.IsType(OT_NOTHING);
2668 /* Check if we've reached a 'via' destination. */
2669 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)) &&
2670 IsTileType(v->tile, MP_STATION) &&
2671 v->current_order.GetDestination() == GetStationIndex(v->tile)) {
2672 v->DeleteUnreachedImplicitOrders();
2673 /* We set the last visited station here because we do not want
2674 * the train to stop at this 'via' station if the next order
2675 * is a no-non-stop order; in that case not setting the last
2676 * visited station will cause the vehicle to still stop. */
2677 v->last_station_visited = v->current_order.GetDestination();
2678 UpdateVehicleTimetable(v, true);
2679 v->IncrementImplicitOrderIndex();
2682 /* Get the current order */
2683 assert(v->cur_implicit_order_index == 0 || v->cur_implicit_order_index < v->GetNumOrders());
2684 v->UpdateRealOrderIndex();
2686 const Order *order = v->GetOrder(v->cur_real_order_index);
2687 if (order != NULL && order->IsType(OT_IMPLICIT)) {
2688 assert(v->GetNumManualOrders() == 0);
2689 order = NULL;
2692 /* If no order, do nothing. */
2693 if (order == NULL || (v->type == VEH_AIRCRAFT && !CheckForValidOrders(v))) {
2694 if (v->type == VEH_AIRCRAFT) {
2695 /* Aircraft do something vastly different here, so handle separately */
2696 extern void HandleMissingAircraftOrders(Aircraft *v);
2697 HandleMissingAircraftOrders(Aircraft::From(v));
2698 return false;
2701 v->current_order.Free();
2702 v->dest_tile = 0;
2703 return false;
2706 /* If it is unchanged, keep it. */
2707 if (order->Equals(v->current_order) && (v->type == VEH_AIRCRAFT || v->dest_tile != 0) &&
2708 (v->type != VEH_SHIP || !order->IsType(OT_GOTO_STATION) || Station::Get(order->GetDestination())->HasFacilities(FACIL_DOCK))) {
2709 return false;
2712 /* Otherwise set it, and determine the destination tile. */
2713 v->current_order = *order;
2715 InvalidateVehicleOrder(v, VIWD_MODIFY_ORDERS);
2716 switch (v->type) {
2717 default:
2718 NOT_REACHED();
2720 case VEH_ROAD:
2721 case VEH_TRAIN:
2722 break;
2724 case VEH_AIRCRAFT:
2725 case VEH_SHIP:
2726 SetWindowClassesDirty(GetWindowClassForVehicleType(v->type));
2727 break;
2730 return UpdateOrderDest(v, order) && may_reverse;
2734 * Check whether the given vehicle should stop at the given station
2735 * based on this order and the non-stop settings.
2736 * @param v the vehicle that might be stopping.
2737 * @param station the station to stop at.
2738 * @return true if the vehicle should stop.
2740 bool Order::ShouldStopAtStation(const Vehicle *v, StationID station) const
2742 bool is_dest_station = this->IsType(OT_GOTO_STATION) && this->dest == station;
2744 return (!this->IsType(OT_GOTO_DEPOT) || (this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS) != 0) &&
2745 v->last_station_visited != station && // Do stop only when we've not just been there
2746 /* Finally do stop when there is no non-stop flag set for this type of station. */
2747 !(this->GetNonStopType() & (is_dest_station ? ONSF_NO_STOP_AT_DESTINATION_STATION : ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS));
2751 * A vehicle can leave the current station with cargo if:
2752 * 1. it can load cargo here OR
2753 * 2a. it could leave the last station with cargo AND
2754 * 2b. it doesn't have to unload all cargo here.
2756 bool Order::CanLeaveWithCargo(bool has_cargo, CargoID cargo) const
2758 return (this->GetCargoLoadType(cargo) & OLFB_NO_LOAD) == 0 || (has_cargo &&
2759 (this->GetCargoUnloadType(cargo) & (OUFB_UNLOAD | OUFB_TRANSFER)) == 0);