Invalidate the right goal list when changing goals
[openttd/fttd.git] / src / order_cmd.cpp
blob142a00367c9dfdfd3d614c9dd1417037f1eccf14
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 "vehicle_func.h"
21 #include "depot_base.h"
22 #include "core/pool_func.hpp"
23 #include "core/random_func.hpp"
24 #include "aircraft.h"
25 #include "roadveh.h"
26 #include "station_base.h"
27 #include "waypoint_base.h"
28 #include "company_base.h"
29 #include "order_backup.h"
31 #include "table/strings.h"
33 /* DestinationID must be at least as large as every these below, because it can
34 * be any of them
36 assert_compile(sizeof(DestinationID) >= sizeof(DepotID));
37 assert_compile(sizeof(DestinationID) >= sizeof(StationID));
39 template<> Order::Pool Order::PoolItem::pool ("Order");
40 INSTANTIATE_POOL_METHODS(Order)
41 template<> OrderList::Pool OrderList::PoolItem::pool ("OrderList");
42 INSTANTIATE_POOL_METHODS(OrderList)
44 /** Clean everything up. */
45 Order::~Order()
47 if (CleaningPool()) return;
49 /* We can visit oil rigs and buoys that are not our own. They will be shown in
50 * the list of stations. So, we need to invalidate that window if needed. */
51 if (this->IsType(OT_GOTO_STATION) || this->IsType(OT_GOTO_WAYPOINT)) {
52 BaseStation *bs = BaseStation::GetIfValid(this->GetDestination());
53 if (bs != NULL && bs->owner == OWNER_NONE) InvalidateWindowClassesData(WC_STATION_LIST, 0);
57 /**
58 * 'Free' the order
59 * @note ONLY use on "current_order" vehicle orders!
61 void Order::Free()
63 this->type = OT_NOTHING;
64 this->flags = 0;
65 this->dest = 0;
66 this->next = NULL;
69 /**
70 * Makes this order a Go To Station order.
71 * @param destination the station to go to.
73 void Order::MakeGoToStation(StationID destination)
75 this->type = OT_GOTO_STATION;
76 this->flags = 0;
77 this->dest = destination;
80 /**
81 * Makes this order a Go To Depot order.
82 * @param destination the depot to go to.
83 * @param order is this order a 'default' order, or an overridden vehicle order?
84 * @param non_stop_type how to get to the depot?
85 * @param action what to do in the depot?
86 * @param cargo the cargo type to change to.
88 void Order::MakeGoToDepot(DepotID destination, OrderDepotTypeFlags order, OrderNonStopFlags non_stop_type, OrderDepotActionFlags action, CargoID cargo)
90 this->type = OT_GOTO_DEPOT;
91 this->SetDepotOrderType(order);
92 this->SetDepotActionType(action);
93 this->SetNonStopType(non_stop_type);
94 this->dest = destination;
95 this->SetRefit(cargo);
98 /**
99 * Makes this order a Go To Waypoint order.
100 * @param destination the waypoint to go to.
102 void Order::MakeGoToWaypoint(StationID destination)
104 this->type = OT_GOTO_WAYPOINT;
105 this->flags = 0;
106 this->dest = destination;
110 * Makes this order a Loading order.
111 * @param ordered is this an ordered stop?
113 void Order::MakeLoading(bool ordered)
115 this->type = OT_LOADING;
116 if (!ordered) this->flags = 0;
120 * Makes this order a Leave Station order.
122 void Order::MakeLeaveStation()
124 this->type = OT_LEAVESTATION;
125 this->flags = 0;
129 * Makes this order a Dummy order.
131 void Order::MakeDummy()
133 this->type = OT_DUMMY;
134 this->flags = 0;
138 * Makes this order an conditional order.
139 * @param order the order to jump to.
141 void Order::MakeConditional(VehicleOrderID order)
143 this->type = OT_CONDITIONAL;
144 this->flags = order;
145 this->dest = 0;
149 * Makes this order an implicit order.
150 * @param destination the station to go to.
152 void Order::MakeImplicit(StationID destination)
154 this->type = OT_IMPLICIT;
155 this->dest = destination;
159 * Make this depot/station order also a refit order.
160 * @param cargo the cargo type to change to.
161 * @pre IsType(OT_GOTO_DEPOT) || IsType(OT_GOTO_STATION).
163 void Order::SetRefit(CargoID cargo)
165 this->refit_cargo = cargo;
169 * Does this order have the same type, flags and destination?
170 * @param other the second order to compare to.
171 * @return true if the type, flags and destination match.
173 bool Order::Equals(const Order &other) const
175 /* In case of go to nearest depot orders we need "only" compare the flags
176 * with the other and not the nearest depot order bit or the actual
177 * destination because those get clear/filled in during the order
178 * evaluation. If we do not do this the order will continuously be seen as
179 * a different order and it will try to find a "nearest depot" every tick. */
180 if ((this->IsType(OT_GOTO_DEPOT) && this->type == other.type) &&
181 ((this->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0 ||
182 (other.GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0)) {
183 return this->GetDepotOrderType() == other.GetDepotOrderType() &&
184 (this->GetDepotActionType() & ~ODATFB_NEAREST_DEPOT) == (other.GetDepotActionType() & ~ODATFB_NEAREST_DEPOT);
187 return this->type == other.type && this->flags == other.flags && this->dest == other.dest;
191 * Pack this order into a 32 bits integer, or actually only
192 * the type, flags and destination.
193 * @return the packed representation.
194 * @note unpacking is done in the constructor.
196 uint32 Order::Pack() const
198 return this->dest << 16 | this->flags << 8 | this->type;
202 * Pack this order into a 16 bits integer as close to the TTD
203 * representation as possible.
204 * @return the TTD-like packed representation.
206 uint16 Order::MapOldOrder() const
208 uint16 order = this->GetType();
209 switch (this->type) {
210 case OT_GOTO_STATION:
211 if (this->GetUnloadType() & OUFB_UNLOAD) SetBit(order, 5);
212 if (this->GetLoadType() & OLFB_FULL_LOAD) SetBit(order, 6);
213 if (this->GetNonStopType() & ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS) SetBit(order, 7);
214 order |= GB(this->GetDestination(), 0, 8) << 8;
215 break;
216 case OT_GOTO_DEPOT:
217 if (!(this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) SetBit(order, 6);
218 SetBit(order, 7);
219 order |= GB(this->GetDestination(), 0, 8) << 8;
220 break;
221 case OT_LOADING:
222 if (this->GetLoadType() & OLFB_FULL_LOAD) SetBit(order, 6);
223 break;
225 return order;
229 * Create an order based on a packed representation of that order.
230 * @param packed the packed representation.
232 Order::Order(uint32 packed)
234 this->type = (OrderType)GB(packed, 0, 8);
235 this->flags = GB(packed, 8, 8);
236 this->dest = GB(packed, 16, 16);
237 this->next = NULL;
238 this->refit_cargo = CT_NO_REFIT;
239 this->wait_time = 0;
240 this->travel_time = 0;
241 this->max_speed = UINT16_MAX;
246 * Updates the widgets of a vehicle which contains the order-data
249 void InvalidateVehicleOrder(const Vehicle *v, int data)
251 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
253 if (data != 0) {
254 /* Calls SetDirty() too */
255 InvalidateWindowData(WC_VEHICLE_ORDERS, v->index, data);
256 InvalidateWindowData(WC_VEHICLE_TIMETABLE, v->index, data);
257 return;
260 SetWindowDirty(WC_VEHICLE_ORDERS, v->index);
261 SetWindowDirty(WC_VEHICLE_TIMETABLE, v->index);
266 * Assign data to an order (from another order)
267 * This function makes sure that the index is maintained correctly
268 * @param other the data to copy (except next pointer).
271 void Order::AssignOrder(const Order &other)
273 this->type = other.type;
274 this->flags = other.flags;
275 this->dest = other.dest;
277 this->refit_cargo = other.refit_cargo;
279 this->wait_time = other.wait_time;
280 this->travel_time = other.travel_time;
281 this->max_speed = other.max_speed;
285 * Recomputes everything.
286 * @param chain first order in the chain
287 * @param v one of vehicle that is using this orderlist
289 void OrderList::Initialize(Order *chain, Vehicle *v)
291 this->first = chain;
292 this->first_shared = v;
294 this->num_orders = 0;
295 this->num_manual_orders = 0;
296 this->num_vehicles = 1;
297 this->timetable_duration = 0;
299 for (Order *o = this->first; o != NULL; o = o->next) {
300 ++this->num_orders;
301 if (!o->IsType(OT_IMPLICIT)) ++this->num_manual_orders;
302 this->timetable_duration += o->wait_time + o->travel_time;
305 for (Vehicle *u = this->first_shared->PreviousShared(); u != NULL; u = u->PreviousShared()) {
306 ++this->num_vehicles;
307 this->first_shared = u;
310 for (const Vehicle *u = v->NextShared(); u != NULL; u = u->NextShared()) ++this->num_vehicles;
314 * Free a complete order chain.
315 * @param keep_orderlist If this is true only delete the orders, otherwise also delete the OrderList.
316 * @note do not use on "current_order" vehicle orders!
318 void OrderList::FreeChain(bool keep_orderlist)
320 Order *next;
321 for (Order *o = this->first; o != NULL; o = next) {
322 next = o->next;
323 delete o;
326 if (keep_orderlist) {
327 this->first = NULL;
328 this->num_orders = 0;
329 this->num_manual_orders = 0;
330 this->timetable_duration = 0;
331 } else {
332 delete this;
337 * Get a certain order of the order chain.
338 * @param index zero-based index of the order within the chain.
339 * @return the order at position index.
341 Order *OrderList::GetOrderAt(int index) const
343 if (index < 0) return NULL;
345 Order *order = this->first;
347 while (order != NULL && index-- > 0) {
348 order = order->next;
350 return order;
354 * Get the next order which will make the given vehicle stop at a station
355 * or refit at a depot or evaluate a non-trivial condition.
356 * @param next The order to start looking at.
357 * @param hops The number of orders we have already looked at.
358 * @return Either of
359 * \li a station order
360 * \li a refitting depot order
361 * \li a non-trivial conditional order
362 * \li NULL if the vehicle won't stop anymore.
364 const Order *OrderList::GetNextDecisionNode(const Order *next, uint hops) const
366 if (hops > this->GetNumOrders() || next == NULL) return NULL;
368 if (next->IsType(OT_CONDITIONAL)) {
369 if (next->GetConditionVariable() != OCV_UNCONDITIONALLY) return next;
371 /* We can evaluate trivial conditions right away. They're conceptually
372 * the same as regular order progression. */
373 return this->GetNextDecisionNode(
374 this->GetOrderAt(next->GetConditionSkipToOrder()),
375 hops + 1);
378 if (next->IsType(OT_GOTO_DEPOT)) {
379 if (next->GetDepotActionType() == ODATFB_HALT) return NULL;
380 if (next->IsRefit()) return next;
383 if (!next->CanLoadOrUnload()) {
384 return this->GetNextDecisionNode(this->GetNext(next), hops + 1);
387 return next;
391 * Recursively determine the next deterministic station to stop at.
392 * @param v The vehicle we're looking at.
393 * @param first Order to start searching at or NULL to start at cur_implicit_order_index + 1.
394 * @param hops Number of orders we have already looked at.
395 * @return Next stoppping station or INVALID_STATION.
396 * @pre The vehicle is currently loading and v->last_station_visited is meaningful.
397 * @note This function may draw a random number. Don't use it from the GUI.
399 StationIDStack OrderList::GetNextStoppingStation(const Vehicle *v, const Order *first, uint hops) const
402 const Order *next = first;
403 if (first == NULL) {
404 next = this->GetOrderAt(v->cur_implicit_order_index);
405 if (next == NULL) {
406 next = this->GetFirstOrder();
407 if (next == NULL) return INVALID_STATION;
408 } else {
409 /* GetNext never returns NULL if there is a valid station in the list.
410 * As the given "next" is already valid and a station in the list, we
411 * don't have to check for NULL here. */
412 next = this->GetNext(next);
413 assert(next != NULL);
417 do {
418 next = this->GetNextDecisionNode(next, ++hops);
420 /* Resolve possibly nested conditionals by estimation. */
421 while (next != NULL && next->IsType(OT_CONDITIONAL)) {
422 /* We return both options of conditional orders. */
423 const Order *skip_to = this->GetNextDecisionNode(
424 this->GetOrderAt(next->GetConditionSkipToOrder()), hops);
425 const Order *advance = this->GetNextDecisionNode(
426 this->GetNext(next), hops);
427 if (advance == NULL || advance == first || skip_to == advance) {
428 next = (skip_to == first) ? NULL : skip_to;
429 } else if (skip_to == NULL || skip_to == first) {
430 next = (advance == first) ? NULL : advance;
431 } else {
432 StationIDStack st1 = this->GetNextStoppingStation(v, skip_to, hops);
433 StationIDStack st2 = this->GetNextStoppingStation(v, advance, hops);
434 while (!st2.IsEmpty()) st1.Push(st2.Pop());
435 return st1;
437 ++hops;
440 /* Don't return a next stop if the vehicle has to unload everything. */
441 if (next == NULL || ((next->IsType(OT_GOTO_STATION) || next->IsType(OT_IMPLICIT)) &&
442 next->GetDestination() == v->last_station_visited &&
443 (next->GetUnloadType() & (OUFB_TRANSFER | OUFB_UNLOAD)) != 0)) {
444 return INVALID_STATION;
446 } while (next->IsType(OT_GOTO_DEPOT) || next->GetDestination() == v->last_station_visited);
448 return next->GetDestination();
452 * Insert a new order into the order chain.
453 * @param new_order is the order to insert into the chain.
454 * @param index is the position where the order is supposed to be inserted.
456 void OrderList::InsertOrderAt(Order *new_order, int index)
458 if (this->first == NULL) {
459 this->first = new_order;
460 } else {
461 if (index == 0) {
462 /* Insert as first or only order */
463 new_order->next = this->first;
464 this->first = new_order;
465 } else if (index >= this->num_orders) {
466 /* index is after the last order, add it to the end */
467 this->GetLastOrder()->next = new_order;
468 } else {
469 /* Put the new order in between */
470 Order *order = this->GetOrderAt(index - 1);
471 new_order->next = order->next;
472 order->next = new_order;
475 ++this->num_orders;
476 if (!new_order->IsType(OT_IMPLICIT)) ++this->num_manual_orders;
477 this->timetable_duration += new_order->wait_time + new_order->travel_time;
479 /* We can visit oil rigs and buoys that are not our own. They will be shown in
480 * the list of stations. So, we need to invalidate that window if needed. */
481 if (new_order->IsType(OT_GOTO_STATION) || new_order->IsType(OT_GOTO_WAYPOINT)) {
482 BaseStation *bs = BaseStation::Get(new_order->GetDestination());
483 if (bs->owner == OWNER_NONE) InvalidateWindowClassesData(WC_STATION_LIST, 0);
490 * Remove an order from the order list and delete it.
491 * @param index is the position of the order which is to be deleted.
493 void OrderList::DeleteOrderAt(int index)
495 if (index >= this->num_orders) return;
497 Order *to_remove;
499 if (index == 0) {
500 to_remove = this->first;
501 this->first = to_remove->next;
502 } else {
503 Order *prev = GetOrderAt(index - 1);
504 to_remove = prev->next;
505 prev->next = to_remove->next;
507 --this->num_orders;
508 if (!to_remove->IsType(OT_IMPLICIT)) --this->num_manual_orders;
509 this->timetable_duration -= (to_remove->wait_time + to_remove->travel_time);
510 delete to_remove;
514 * Move an order to another position within the order list.
515 * @param from is the zero-based position of the order to move.
516 * @param to is the zero-based position where the order is moved to.
518 void OrderList::MoveOrder(int from, int to)
520 if (from >= this->num_orders || to >= this->num_orders || from == to) return;
522 Order *moving_one;
524 /* Take the moving order out of the pointer-chain */
525 if (from == 0) {
526 moving_one = this->first;
527 this->first = moving_one->next;
528 } else {
529 Order *one_before = GetOrderAt(from - 1);
530 moving_one = one_before->next;
531 one_before->next = moving_one->next;
534 /* Insert the moving_order again in the pointer-chain */
535 if (to == 0) {
536 moving_one->next = this->first;
537 this->first = moving_one;
538 } else {
539 Order *one_before = GetOrderAt(to - 1);
540 moving_one->next = one_before->next;
541 one_before->next = moving_one;
546 * Removes the vehicle from the shared order list.
547 * @note This is supposed to be called when the vehicle is still in the chain
548 * @param v vehicle to remove from the list
550 void OrderList::RemoveVehicle(Vehicle *v)
552 --this->num_vehicles;
553 if (v == this->first_shared) this->first_shared = v->NextShared();
557 * Checks whether a vehicle is part of the shared vehicle chain.
558 * @param v is the vehicle to search in the shared vehicle chain.
560 bool OrderList::IsVehicleInSharedOrdersList(const Vehicle *v) const
562 for (const Vehicle *v_shared = this->first_shared; v_shared != NULL; v_shared = v_shared->NextShared()) {
563 if (v_shared == v) return true;
566 return false;
570 * Gets the position of the given vehicle within the shared order vehicle list.
571 * @param v is the vehicle of which to get the position
572 * @return position of v within the shared vehicle chain.
574 int OrderList::GetPositionInSharedOrderList(const Vehicle *v) const
576 int count = 0;
577 for (const Vehicle *v_shared = v->PreviousShared(); v_shared != NULL; v_shared = v_shared->PreviousShared()) count++;
578 return count;
582 * Checks whether all orders of the list have a filled timetable.
583 * @return whether all orders have a filled timetable.
585 bool OrderList::IsCompleteTimetable() const
587 for (Order *o = this->first; o != NULL; o = o->next) {
588 /* Implicit orders are, by definition, not timetabled. */
589 if (o->IsType(OT_IMPLICIT)) continue;
590 if (!o->IsCompletelyTimetabled()) return false;
592 return true;
596 * Checks for internal consistency of order list. Triggers assertion if something is wrong.
598 void OrderList::DebugCheckSanity() const
600 VehicleOrderID check_num_orders = 0;
601 VehicleOrderID check_num_manual_orders = 0;
602 uint check_num_vehicles = 0;
603 Ticks check_timetable_duration = 0;
605 DEBUG(misc, 6, "Checking OrderList %hu for sanity...", this->index);
607 for (const Order *o = this->first; o != NULL; o = o->next) {
608 ++check_num_orders;
609 if (!o->IsType(OT_IMPLICIT)) ++check_num_manual_orders;
610 check_timetable_duration += o->wait_time + o->travel_time;
612 assert(this->num_orders == check_num_orders);
613 assert(this->num_manual_orders == check_num_manual_orders);
614 assert(this->timetable_duration == check_timetable_duration);
616 for (const Vehicle *v = this->first_shared; v != NULL; v = v->NextShared()) {
617 ++check_num_vehicles;
618 assert(v->orders.list == this);
620 assert(this->num_vehicles == check_num_vehicles);
621 DEBUG(misc, 6, "... detected %u orders (%u manual), %u vehicles, %i ticks",
622 (uint)this->num_orders, (uint)this->num_manual_orders,
623 this->num_vehicles, this->timetable_duration);
627 * Checks whether the order goes to a station or not, i.e. whether the
628 * destination is a station
629 * @param v the vehicle to check for
630 * @param o the order to check
631 * @return true if the destination is a station
633 static inline bool OrderGoesToStation(const Vehicle *v, const Order *o)
635 return o->IsType(OT_GOTO_STATION) ||
636 (v->type == VEH_AIRCRAFT && o->IsType(OT_GOTO_DEPOT) && !(o->GetDepotActionType() & ODATFB_NEAREST_DEPOT));
640 * Delete all news items regarding defective orders about a vehicle
641 * This could kill still valid warnings (for example about void order when just
642 * another order gets added), but assume the company will notice the problems,
643 * when (s)he's changing the orders.
645 static void DeleteOrderWarnings(const Vehicle *v)
647 DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_TOO_FEW_ORDERS);
648 DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_VOID_ORDER);
649 DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_DUPLICATE_ENTRY);
650 DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_INVALID_ENTRY);
654 * Returns a tile somewhat representing the order destination (not suitable for pathfinding).
655 * @param v The vehicle to get the location for.
656 * @param airport Get the airport tile and not the station location for aircraft.
657 * @return destination of order, or INVALID_TILE if none.
659 TileIndex Order::GetLocation(const Vehicle *v, bool airport) const
661 switch (this->GetType()) {
662 case OT_GOTO_WAYPOINT:
663 case OT_GOTO_STATION:
664 case OT_IMPLICIT:
665 if (airport && v->type == VEH_AIRCRAFT) return Station::Get(this->GetDestination())->airport.tile;
666 return BaseStation::Get(this->GetDestination())->xy;
668 case OT_GOTO_DEPOT:
669 if ((this->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0) return INVALID_TILE;
670 return (v->type == VEH_AIRCRAFT) ? Station::Get(this->GetDestination())->xy : Depot::Get(this->GetDestination())->xy;
672 default:
673 return INVALID_TILE;
678 * Get the distance between two orders of a vehicle. Conditional orders are resolved
679 * and the bigger distance of the two order branches is returned.
680 * @param prev Origin order.
681 * @param cur Destination order.
682 * @param v The vehicle to get the distance for.
683 * @param conditional_depth Internal param for resolving conditional orders.
684 * @return Maximum distance between the two orders.
686 uint GetOrderDistance(const Order *prev, const Order *cur, const Vehicle *v, int conditional_depth)
688 if (cur->IsType(OT_CONDITIONAL)) {
689 if (conditional_depth > v->GetNumOrders()) return 0;
691 conditional_depth++;
693 int dist1 = GetOrderDistance(prev, v->GetOrder(cur->GetConditionSkipToOrder()), v, conditional_depth);
694 int dist2 = GetOrderDistance(prev, cur->next == NULL ? v->orders.list->GetFirstOrder() : cur->next, v, conditional_depth);
695 return max(dist1, dist2);
698 TileIndex prev_tile = prev->GetLocation(v, true);
699 TileIndex cur_tile = cur->GetLocation(v, true);
700 if (prev_tile == INVALID_TILE || cur_tile == INVALID_TILE) return 0;
701 return v->type == VEH_AIRCRAFT ? DistanceSquare(prev_tile, cur_tile) : DistanceManhattan(prev_tile, cur_tile);
705 * Add an order to the orderlist of a vehicle.
706 * @param tile unused
707 * @param flags operation to perform
708 * @param p1 various bitstuffed elements
709 * - p1 = (bit 0 - 19) - ID of the vehicle
710 * - p1 = (bit 24 - 31) - the selected order (if any). If the last order is given,
711 * the order will be inserted before that one
712 * the maximum vehicle order id is 254.
713 * @param p2 packed order to insert
714 * @param text unused
715 * @return the cost of this operation or an error
717 CommandCost CmdInsertOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
719 VehicleID veh = GB(p1, 0, 20);
720 VehicleOrderID sel_ord = GB(p1, 20, 8);
721 Order new_order(p2);
723 Vehicle *v = Vehicle::GetIfValid(veh);
724 if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
726 CommandCost ret = CheckOwnership(v->owner);
727 if (ret.Failed()) return ret;
729 /* Check if the inserted order is to the correct destination (owner, type),
730 * and has the correct flags if any */
731 switch (new_order.GetType()) {
732 case OT_GOTO_STATION: {
733 const Station *st = Station::GetIfValid(new_order.GetDestination());
734 if (st == NULL) return CMD_ERROR;
736 if (st->owner != OWNER_NONE) {
737 CommandCost ret = CheckOwnership(st->owner);
738 if (ret.Failed()) return ret;
741 if (!CanVehicleUseStation(v, st)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
742 for (Vehicle *u = v->FirstShared(); u != NULL; u = u->NextShared()) {
743 if (!CanVehicleUseStation(u, st)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER_SHARED);
746 /* Non stop only allowed for ground vehicles. */
747 if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && !v->IsGroundVehicle()) return CMD_ERROR;
749 /* Filter invalid load/unload types. */
750 switch (new_order.GetLoadType()) {
751 case OLF_LOAD_IF_POSSIBLE: case OLFB_FULL_LOAD: case OLF_FULL_LOAD_ANY: case OLFB_NO_LOAD: break;
752 default: return CMD_ERROR;
754 switch (new_order.GetUnloadType()) {
755 case OUF_UNLOAD_IF_POSSIBLE: case OUFB_UNLOAD: case OUFB_TRANSFER: case OUFB_NO_UNLOAD: break;
756 default: return CMD_ERROR;
759 /* Filter invalid stop locations */
760 switch (new_order.GetStopLocation()) {
761 case OSL_PLATFORM_NEAR_END:
762 case OSL_PLATFORM_MIDDLE:
763 if (v->type != VEH_TRAIN) return CMD_ERROR;
764 /* FALL THROUGH */
765 case OSL_PLATFORM_FAR_END:
766 break;
768 default:
769 return CMD_ERROR;
772 break;
775 case OT_GOTO_DEPOT: {
776 if ((new_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) == 0) {
777 if (v->type == VEH_AIRCRAFT) {
778 const Station *st = Station::GetIfValid(new_order.GetDestination());
780 if (st == NULL) return CMD_ERROR;
782 CommandCost ret = CheckOwnership(st->owner);
783 if (ret.Failed()) return ret;
785 if (!CanVehicleUseStation(v, st) || !st->airport.HasHangar()) {
786 return CMD_ERROR;
788 } else {
789 const Depot *dp = Depot::GetIfValid(new_order.GetDestination());
791 if (dp == NULL) return CMD_ERROR;
793 CommandCost ret = CheckOwnership(GetTileOwner(dp->xy));
794 if (ret.Failed()) return ret;
796 switch (v->type) {
797 case VEH_TRAIN:
798 if (!IsRailDepotTile(dp->xy)) return CMD_ERROR;
799 break;
801 case VEH_ROAD:
802 if (!IsRoadDepotTile(dp->xy)) return CMD_ERROR;
803 break;
805 case VEH_SHIP:
806 if (!IsShipDepotTile(dp->xy)) return CMD_ERROR;
807 break;
809 default: return CMD_ERROR;
814 if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && !v->IsGroundVehicle()) return CMD_ERROR;
815 if (new_order.GetDepotOrderType() & ~(ODTFB_PART_OF_ORDERS | ((new_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS) != 0 ? ODTFB_SERVICE : 0))) return CMD_ERROR;
816 if (new_order.GetDepotActionType() & ~(ODATFB_HALT | ODATFB_NEAREST_DEPOT)) return CMD_ERROR;
817 if ((new_order.GetDepotOrderType() & ODTFB_SERVICE) && (new_order.GetDepotActionType() & ODATFB_HALT)) return CMD_ERROR;
818 break;
821 case OT_GOTO_WAYPOINT: {
822 const Waypoint *wp = Waypoint::GetIfValid(new_order.GetDestination());
823 if (wp == NULL) return CMD_ERROR;
825 switch (v->type) {
826 default: return CMD_ERROR;
828 case VEH_TRAIN: {
829 if (!(wp->facilities & FACIL_TRAIN)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
831 CommandCost ret = CheckOwnership(wp->owner);
832 if (ret.Failed()) return ret;
833 break;
836 case VEH_SHIP:
837 if (!(wp->facilities & FACIL_DOCK)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
838 if (wp->owner != OWNER_NONE) {
839 CommandCost ret = CheckOwnership(wp->owner);
840 if (ret.Failed()) return ret;
842 break;
845 /* Order flags can be any of the following for waypoints:
846 * [non-stop]
847 * non-stop orders (if any) are only valid for trains */
848 if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && v->type != VEH_TRAIN) return CMD_ERROR;
849 break;
852 case OT_CONDITIONAL: {
853 VehicleOrderID skip_to = new_order.GetConditionSkipToOrder();
854 if (skip_to != 0 && skip_to >= v->GetNumOrders()) return CMD_ERROR; // Always allow jumping to the first (even when there is no order).
855 if (new_order.GetConditionVariable() >= OCV_END) return CMD_ERROR;
857 OrderConditionComparator occ = new_order.GetConditionComparator();
858 if (occ >= OCC_END) return CMD_ERROR;
859 switch (new_order.GetConditionVariable()) {
860 case OCV_REQUIRES_SERVICE:
861 if (occ != OCC_IS_TRUE && occ != OCC_IS_FALSE) return CMD_ERROR;
862 break;
864 case OCV_UNCONDITIONALLY:
865 if (occ != OCC_EQUALS) return CMD_ERROR;
866 if (new_order.GetConditionValue() != 0) return CMD_ERROR;
867 break;
869 case OCV_LOAD_PERCENTAGE:
870 case OCV_RELIABILITY:
871 if (new_order.GetConditionValue() > 100) return CMD_ERROR;
872 /* FALL THROUGH */
873 default:
874 if (occ == OCC_IS_TRUE || occ == OCC_IS_FALSE) return CMD_ERROR;
875 break;
877 break;
880 default: return CMD_ERROR;
883 if (sel_ord > v->GetNumOrders()) return CMD_ERROR;
885 if (v->GetNumOrders() >= MAX_VEH_ORDER_ID) return_cmd_error(STR_ERROR_TOO_MANY_ORDERS);
886 if (!Order::CanAllocateItem()) return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
887 if (v->orders.list == NULL && !OrderList::CanAllocateItem()) return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
889 if (v->type == VEH_SHIP) {
890 /* Make sure the new destination is not too far away from the previous */
891 const Order *prev = NULL;
892 uint n = 0;
894 /* Find the last goto station or depot order before the insert location.
895 * If the order is to be inserted at the beginning of the order list this
896 * finds the last order in the list. */
897 const Order *o;
898 FOR_VEHICLE_ORDERS(v, o) {
899 switch (o->GetType()) {
900 case OT_GOTO_STATION:
901 case OT_GOTO_DEPOT:
902 case OT_GOTO_WAYPOINT:
903 prev = o;
904 break;
906 default: break;
908 if (++n == sel_ord && prev != NULL) break;
910 if (prev != NULL) {
911 uint dist;
912 if (new_order.IsType(OT_CONDITIONAL)) {
913 /* The order is not yet inserted, so we have to do the first iteration here. */
914 dist = GetOrderDistance(prev, v->GetOrder(new_order.GetConditionSkipToOrder()), v);
915 } else {
916 dist = GetOrderDistance(prev, &new_order, v);
919 if (dist >= 130) {
920 return_cmd_error(STR_ERROR_TOO_FAR_FROM_PREVIOUS_DESTINATION);
925 if (flags & DC_EXEC) {
926 Order *new_o = new Order();
927 new_o->AssignOrder(new_order);
928 InsertOrder(v, new_o, sel_ord);
931 return CommandCost();
935 * Insert a new order but skip the validation.
936 * @param v The vehicle to insert the order to.
937 * @param new_o The new order.
938 * @param sel_ord The position the order should be inserted at.
940 void InsertOrder(Vehicle *v, Order *new_o, VehicleOrderID sel_ord)
942 /* Create new order and link in list */
943 if (v->orders.list == NULL) {
944 v->orders.list = new OrderList(new_o, v);
945 } else {
946 v->orders.list->InsertOrderAt(new_o, sel_ord);
949 Vehicle *u = v->FirstShared();
950 DeleteOrderWarnings(u);
951 for (; u != NULL; u = u->NextShared()) {
952 assert(v->orders.list == u->orders.list);
954 /* If there is added an order before the current one, we need
955 * to update the selected order. We do not change implicit/real order indices though.
956 * If the new order is between the current implicit order and real order, the implicit order will
957 * later skip the inserted order. */
958 if (sel_ord <= u->cur_real_order_index) {
959 uint cur = u->cur_real_order_index + 1;
960 /* Check if we don't go out of bound */
961 if (cur < u->GetNumOrders()) {
962 u->cur_real_order_index = cur;
965 if (sel_ord == u->cur_implicit_order_index && u->IsGroundVehicle()) {
966 /* We are inserting an order just before the current implicit order.
967 * We do not know whether we will reach current implicit or the newly inserted order first.
968 * So, disable creation of implicit orders until we are on track again. */
969 uint16 &gv_flags = u->GetGroundVehicleFlags();
970 SetBit(gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
972 if (sel_ord <= u->cur_implicit_order_index) {
973 uint cur = u->cur_implicit_order_index + 1;
974 /* Check if we don't go out of bound */
975 if (cur < u->GetNumOrders()) {
976 u->cur_implicit_order_index = cur;
979 /* Update any possible open window of the vehicle */
980 InvalidateVehicleOrder(u, INVALID_VEH_ORDER_ID | (sel_ord << 8));
983 /* As we insert an order, the order to skip to will be 'wrong'. */
984 VehicleOrderID cur_order_id = 0;
985 Order *order;
986 FOR_VEHICLE_ORDERS(v, order) {
987 if (order->IsType(OT_CONDITIONAL)) {
988 VehicleOrderID order_id = order->GetConditionSkipToOrder();
989 if (order_id >= sel_ord) {
990 order->SetConditionSkipToOrder(order_id + 1);
992 if (order_id == cur_order_id) {
993 order->SetConditionSkipToOrder((order_id + 1) % v->GetNumOrders());
996 cur_order_id++;
999 /* Make sure to rebuild the whole list */
1000 InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
1004 * Declone an order-list
1005 * @param *dst delete the orders of this vehicle
1006 * @param flags execution flags
1008 static CommandCost DecloneOrder(Vehicle *dst, DoCommandFlag flags)
1010 if (flags & DC_EXEC) {
1011 DeleteVehicleOrders(dst);
1012 InvalidateVehicleOrder(dst, VIWD_REMOVE_ALL_ORDERS);
1013 InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
1015 return CommandCost();
1019 * Delete an order from the orderlist of a vehicle.
1020 * @param tile unused
1021 * @param flags operation to perform
1022 * @param p1 the ID of the vehicle
1023 * @param p2 the order to delete (max 255)
1024 * @param text unused
1025 * @return the cost of this operation or an error
1027 CommandCost CmdDeleteOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1029 VehicleID veh_id = GB(p1, 0, 20);
1030 VehicleOrderID sel_ord = GB(p2, 0, 8);
1032 Vehicle *v = Vehicle::GetIfValid(veh_id);
1034 if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
1036 CommandCost ret = CheckOwnership(v->owner);
1037 if (ret.Failed()) return ret;
1039 /* If we did not select an order, we maybe want to de-clone the orders */
1040 if (sel_ord >= v->GetNumOrders()) return DecloneOrder(v, flags);
1042 if (v->GetOrder(sel_ord) == NULL) return CMD_ERROR;
1044 if (flags & DC_EXEC) DeleteOrder(v, sel_ord);
1045 return CommandCost();
1049 * Cancel the current loading order of the vehicle as the order was deleted.
1050 * @param v the vehicle
1052 static void CancelLoadingDueToDeletedOrder(Vehicle *v)
1054 assert(v->current_order.IsType(OT_LOADING));
1055 /* NON-stop flag is misused to see if a train is in a station that is
1056 * on his order list or not */
1057 v->current_order.SetNonStopType(ONSF_STOP_EVERYWHERE);
1058 /* When full loading, "cancel" that order so the vehicle doesn't
1059 * stay indefinitely at this station anymore. */
1060 if (v->current_order.GetLoadType() & OLFB_FULL_LOAD) v->current_order.SetLoadType(OLF_LOAD_IF_POSSIBLE);
1064 * Delete an order but skip the parameter validation.
1065 * @param v The vehicle to delete the order from.
1066 * @param sel_ord The id of the order to be deleted.
1068 void DeleteOrder(Vehicle *v, VehicleOrderID sel_ord)
1070 v->orders.list->DeleteOrderAt(sel_ord);
1072 Vehicle *u = v->FirstShared();
1073 DeleteOrderWarnings(u);
1074 for (; u != NULL; u = u->NextShared()) {
1075 assert(v->orders.list == u->orders.list);
1077 if (sel_ord == u->cur_real_order_index && u->current_order.IsType(OT_LOADING)) {
1078 CancelLoadingDueToDeletedOrder(u);
1081 if (sel_ord < u->cur_real_order_index) {
1082 u->cur_real_order_index--;
1083 } else if (sel_ord == u->cur_real_order_index) {
1084 u->UpdateRealOrderIndex();
1087 if (sel_ord < u->cur_implicit_order_index) {
1088 u->cur_implicit_order_index--;
1089 } else if (sel_ord == u->cur_implicit_order_index) {
1090 /* Make sure the index is valid */
1091 if (u->cur_implicit_order_index >= u->GetNumOrders()) u->cur_implicit_order_index = 0;
1093 /* Skip non-implicit orders for the implicit-order-index (e.g. if the current implicit order was deleted */
1094 while (u->cur_implicit_order_index != u->cur_real_order_index && !u->GetOrder(u->cur_implicit_order_index)->IsType(OT_IMPLICIT)) {
1095 u->cur_implicit_order_index++;
1096 if (u->cur_implicit_order_index >= u->GetNumOrders()) u->cur_implicit_order_index = 0;
1100 /* Update any possible open window of the vehicle */
1101 InvalidateVehicleOrder(u, sel_ord | (INVALID_VEH_ORDER_ID << 8));
1104 /* As we delete an order, the order to skip to will be 'wrong'. */
1105 VehicleOrderID cur_order_id = 0;
1106 Order *order = NULL;
1107 FOR_VEHICLE_ORDERS(v, order) {
1108 if (order->IsType(OT_CONDITIONAL)) {
1109 VehicleOrderID order_id = order->GetConditionSkipToOrder();
1110 if (order_id >= sel_ord) {
1111 order_id = max(order_id - 1, 0);
1113 if (order_id == cur_order_id) {
1114 order_id = (order_id + 1) % v->GetNumOrders();
1116 order->SetConditionSkipToOrder(order_id);
1118 cur_order_id++;
1121 InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
1125 * Goto order of order-list.
1126 * @param tile unused
1127 * @param flags operation to perform
1128 * @param p1 The ID of the vehicle which order is skipped
1129 * @param p2 the selected order to which we want to skip
1130 * @param text unused
1131 * @return the cost of this operation or an error
1133 CommandCost CmdSkipToOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1135 VehicleID veh_id = GB(p1, 0, 20);
1136 VehicleOrderID sel_ord = GB(p2, 0, 8);
1138 Vehicle *v = Vehicle::GetIfValid(veh_id);
1140 if (v == NULL || !v->IsPrimaryVehicle() || sel_ord == v->cur_implicit_order_index || sel_ord >= v->GetNumOrders() || v->GetNumOrders() < 2) return CMD_ERROR;
1142 CommandCost ret = CheckOwnership(v->owner);
1143 if (ret.Failed()) return ret;
1145 if (flags & DC_EXEC) {
1146 if (v->current_order.IsType(OT_LOADING)) v->LeaveStation();
1148 v->cur_implicit_order_index = v->cur_real_order_index = sel_ord;
1149 v->UpdateRealOrderIndex();
1151 InvalidateVehicleOrder(v, VIWD_MODIFY_ORDERS);
1154 /* We have an aircraft/ship, they have a mini-schedule, so update them all */
1155 if (v->type == VEH_AIRCRAFT) SetWindowClassesDirty(WC_AIRCRAFT_LIST);
1156 if (v->type == VEH_SHIP) SetWindowClassesDirty(WC_SHIPS_LIST);
1158 return CommandCost();
1162 * Move an order inside the orderlist
1163 * @param tile unused
1164 * @param flags operation to perform
1165 * @param p1 the ID of the vehicle
1166 * @param p2 order to move and target
1167 * bit 0-15 : the order to move
1168 * bit 16-31 : the target order
1169 * @param text unused
1170 * @return the cost of this operation or an error
1171 * @note The target order will move one place down in the orderlist
1172 * if you move the order upwards else it'll move it one place down
1174 CommandCost CmdMoveOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1176 VehicleID veh = GB(p1, 0, 20);
1177 VehicleOrderID moving_order = GB(p2, 0, 16);
1178 VehicleOrderID target_order = GB(p2, 16, 16);
1180 Vehicle *v = Vehicle::GetIfValid(veh);
1181 if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
1183 CommandCost ret = CheckOwnership(v->owner);
1184 if (ret.Failed()) return ret;
1186 /* Don't make senseless movements */
1187 if (moving_order >= v->GetNumOrders() || target_order >= v->GetNumOrders() ||
1188 moving_order == target_order || v->GetNumOrders() <= 1) return CMD_ERROR;
1190 Order *moving_one = v->GetOrder(moving_order);
1191 /* Don't move an empty order */
1192 if (moving_one == NULL) return CMD_ERROR;
1194 if (flags & DC_EXEC) {
1195 v->orders.list->MoveOrder(moving_order, target_order);
1197 /* Update shared list */
1198 Vehicle *u = v->FirstShared();
1200 DeleteOrderWarnings(u);
1202 for (; u != NULL; u = u->NextShared()) {
1203 /* Update the current order.
1204 * There are multiple ways to move orders, which result in cur_implicit_order_index
1205 * and cur_real_order_index to not longer make any sense. E.g. moving another
1206 * real order between them.
1208 * Basically one could choose to preserve either of them, but not both.
1209 * While both ways are suitable in this or that case from a human point of view, neither
1210 * of them makes really sense.
1211 * However, from an AI point of view, preserving cur_real_order_index is the most
1212 * predictable and transparent behaviour.
1214 * With that decision it basically does not matter what we do to cur_implicit_order_index.
1215 * If we change orders between the implicit- and real-index, the implicit orders are mostly likely
1216 * completely out-dated anyway. So, keep it simple and just keep cur_implicit_order_index as well.
1217 * The worst which can happen is that a lot of implicit orders are removed when reaching current_order.
1219 if (u->cur_real_order_index == moving_order) {
1220 u->cur_real_order_index = target_order;
1221 } else if (u->cur_real_order_index > moving_order && u->cur_real_order_index <= target_order) {
1222 u->cur_real_order_index--;
1223 } else if (u->cur_real_order_index < moving_order && u->cur_real_order_index >= target_order) {
1224 u->cur_real_order_index++;
1227 if (u->cur_implicit_order_index == moving_order) {
1228 u->cur_implicit_order_index = target_order;
1229 } else if (u->cur_implicit_order_index > moving_order && u->cur_implicit_order_index <= target_order) {
1230 u->cur_implicit_order_index--;
1231 } else if (u->cur_implicit_order_index < moving_order && u->cur_implicit_order_index >= target_order) {
1232 u->cur_implicit_order_index++;
1235 assert(v->orders.list == u->orders.list);
1236 /* Update any possible open window of the vehicle */
1237 InvalidateVehicleOrder(u, moving_order | (target_order << 8));
1240 /* As we move an order, the order to skip to will be 'wrong'. */
1241 Order *order;
1242 FOR_VEHICLE_ORDERS(v, order) {
1243 if (order->IsType(OT_CONDITIONAL)) {
1244 VehicleOrderID order_id = order->GetConditionSkipToOrder();
1245 if (order_id == moving_order) {
1246 order_id = target_order;
1247 } else if (order_id > moving_order && order_id <= target_order) {
1248 order_id--;
1249 } else if (order_id < moving_order && order_id >= target_order) {
1250 order_id++;
1252 order->SetConditionSkipToOrder(order_id);
1256 /* Make sure to rebuild the whole list */
1257 InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
1260 return CommandCost();
1264 * Modify an order in the orderlist of a vehicle.
1265 * @param tile unused
1266 * @param flags operation to perform
1267 * @param p1 various bitstuffed elements
1268 * - p1 = (bit 0 - 19) - ID of the vehicle
1269 * - p1 = (bit 24 - 31) - the selected order (if any). If the last order is given,
1270 * the order will be inserted before that one
1271 * the maximum vehicle order id is 254.
1272 * @param p2 various bitstuffed elements
1273 * - p2 = (bit 0 - 3) - what data to modify (@see ModifyOrderFlags)
1274 * - p2 = (bit 4 - 15) - the data to modify
1275 * @param text unused
1276 * @return the cost of this operation or an error
1278 CommandCost CmdModifyOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1280 VehicleOrderID sel_ord = GB(p1, 20, 8);
1281 VehicleID veh = GB(p1, 0, 20);
1282 ModifyOrderFlags mof = Extract<ModifyOrderFlags, 0, 4>(p2);
1283 uint16 data = GB(p2, 4, 11);
1285 if (mof >= MOF_END) return CMD_ERROR;
1287 Vehicle *v = Vehicle::GetIfValid(veh);
1288 if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
1290 CommandCost ret = CheckOwnership(v->owner);
1291 if (ret.Failed()) return ret;
1293 /* Is it a valid order? */
1294 if (sel_ord >= v->GetNumOrders()) return CMD_ERROR;
1296 Order *order = v->GetOrder(sel_ord);
1297 switch (order->GetType()) {
1298 case OT_GOTO_STATION:
1299 if (mof != MOF_NON_STOP && mof != MOF_STOP_LOCATION && mof != MOF_UNLOAD && mof != MOF_LOAD) return CMD_ERROR;
1300 break;
1302 case OT_GOTO_DEPOT:
1303 if (mof != MOF_NON_STOP && mof != MOF_DEPOT_ACTION) return CMD_ERROR;
1304 break;
1306 case OT_GOTO_WAYPOINT:
1307 if (mof != MOF_NON_STOP) return CMD_ERROR;
1308 break;
1310 case OT_CONDITIONAL:
1311 if (mof != MOF_COND_VARIABLE && mof != MOF_COND_COMPARATOR && mof != MOF_COND_VALUE && mof != MOF_COND_DESTINATION) return CMD_ERROR;
1312 break;
1314 default:
1315 return CMD_ERROR;
1318 switch (mof) {
1319 default: NOT_REACHED();
1321 case MOF_NON_STOP:
1322 if (!v->IsGroundVehicle()) return CMD_ERROR;
1323 if (data >= ONSF_END) return CMD_ERROR;
1324 if (data == order->GetNonStopType()) return CMD_ERROR;
1325 break;
1327 case MOF_STOP_LOCATION:
1328 if (v->type != VEH_TRAIN) return CMD_ERROR;
1329 if (data >= OSL_END) return CMD_ERROR;
1330 break;
1332 case MOF_UNLOAD:
1333 if (order->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) return CMD_ERROR;
1334 if ((data & ~(OUFB_UNLOAD | OUFB_TRANSFER | OUFB_NO_UNLOAD)) != 0) return CMD_ERROR;
1335 /* Unload and no-unload are mutual exclusive and so are transfer and no unload. */
1336 if (data != 0 && ((data & (OUFB_UNLOAD | OUFB_TRANSFER)) != 0) == ((data & OUFB_NO_UNLOAD) != 0)) return CMD_ERROR;
1337 if (data == order->GetUnloadType()) return CMD_ERROR;
1338 break;
1340 case MOF_LOAD:
1341 if (order->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) return CMD_ERROR;
1342 if (data > OLFB_NO_LOAD || data == 1) return CMD_ERROR;
1343 if (data == order->GetLoadType()) return CMD_ERROR;
1344 break;
1346 case MOF_DEPOT_ACTION:
1347 if (data >= DA_END) return CMD_ERROR;
1348 break;
1350 case MOF_COND_VARIABLE:
1351 if (data >= OCV_END) return CMD_ERROR;
1352 break;
1354 case MOF_COND_COMPARATOR:
1355 if (data >= OCC_END) return CMD_ERROR;
1356 switch (order->GetConditionVariable()) {
1357 case OCV_UNCONDITIONALLY: return CMD_ERROR;
1359 case OCV_REQUIRES_SERVICE:
1360 if (data != OCC_IS_TRUE && data != OCC_IS_FALSE) return CMD_ERROR;
1361 break;
1363 default:
1364 if (data == OCC_IS_TRUE || data == OCC_IS_FALSE) return CMD_ERROR;
1365 break;
1367 break;
1369 case MOF_COND_VALUE:
1370 switch (order->GetConditionVariable()) {
1371 case OCV_UNCONDITIONALLY:
1372 case OCV_REQUIRES_SERVICE:
1373 return CMD_ERROR;
1375 case OCV_LOAD_PERCENTAGE:
1376 case OCV_RELIABILITY:
1377 if (data > 100) return CMD_ERROR;
1378 break;
1380 default:
1381 if (data > 2047) return CMD_ERROR;
1382 break;
1384 break;
1386 case MOF_COND_DESTINATION:
1387 if (data >= v->GetNumOrders()) return CMD_ERROR;
1388 break;
1391 if (flags & DC_EXEC) {
1392 switch (mof) {
1393 case MOF_NON_STOP:
1394 order->SetNonStopType((OrderNonStopFlags)data);
1395 if (data & ONSF_NO_STOP_AT_DESTINATION_STATION) {
1396 order->SetRefit(CT_NO_REFIT);
1397 order->SetLoadType(OLF_LOAD_IF_POSSIBLE);
1398 order->SetUnloadType(OUF_UNLOAD_IF_POSSIBLE);
1400 break;
1402 case MOF_STOP_LOCATION:
1403 order->SetStopLocation((OrderStopLocation)data);
1404 break;
1406 case MOF_UNLOAD:
1407 order->SetUnloadType((OrderUnloadFlags)data);
1408 break;
1410 case MOF_LOAD:
1411 order->SetLoadType((OrderLoadFlags)data);
1412 if (data & OLFB_NO_LOAD) order->SetRefit(CT_NO_REFIT);
1413 break;
1415 case MOF_DEPOT_ACTION: {
1416 switch (data) {
1417 case DA_ALWAYS_GO:
1418 order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
1419 order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
1420 break;
1422 case DA_SERVICE:
1423 order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() | ODTFB_SERVICE));
1424 order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
1425 order->SetRefit(CT_NO_REFIT);
1426 break;
1428 case DA_STOP:
1429 order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
1430 order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() | ODATFB_HALT));
1431 order->SetRefit(CT_NO_REFIT);
1432 break;
1434 default:
1435 NOT_REACHED();
1437 break;
1440 case MOF_COND_VARIABLE: {
1441 order->SetConditionVariable((OrderConditionVariable)data);
1443 OrderConditionComparator occ = order->GetConditionComparator();
1444 switch (order->GetConditionVariable()) {
1445 case OCV_UNCONDITIONALLY:
1446 order->SetConditionComparator(OCC_EQUALS);
1447 order->SetConditionValue(0);
1448 break;
1450 case OCV_REQUIRES_SERVICE:
1451 if (occ != OCC_IS_TRUE && occ != OCC_IS_FALSE) order->SetConditionComparator(OCC_IS_TRUE);
1452 order->SetConditionValue(0);
1453 break;
1455 case OCV_LOAD_PERCENTAGE:
1456 case OCV_RELIABILITY:
1457 if (order->GetConditionValue() > 100) order->SetConditionValue(100);
1458 /* FALL THROUGH */
1459 default:
1460 if (occ == OCC_IS_TRUE || occ == OCC_IS_FALSE) order->SetConditionComparator(OCC_EQUALS);
1461 break;
1463 break;
1466 case MOF_COND_COMPARATOR:
1467 order->SetConditionComparator((OrderConditionComparator)data);
1468 break;
1470 case MOF_COND_VALUE:
1471 order->SetConditionValue(data);
1472 break;
1474 case MOF_COND_DESTINATION:
1475 order->SetConditionSkipToOrder(data);
1476 break;
1478 default: NOT_REACHED();
1481 /* Update the windows and full load flags, also for vehicles that share the same order list */
1482 Vehicle *u = v->FirstShared();
1483 DeleteOrderWarnings(u);
1484 for (; u != NULL; u = u->NextShared()) {
1485 /* Toggle u->current_order "Full load" flag if it changed.
1486 * However, as the same flag is used for depot orders, check
1487 * whether we are not going to a depot as there are three
1488 * cases where the full load flag can be active and only
1489 * one case where the flag is used for depot orders. In the
1490 * other cases for the OrderTypeByte the flags are not used,
1491 * so do not care and those orders should not be active
1492 * when this function is called.
1494 if (sel_ord == u->cur_real_order_index &&
1495 (u->current_order.IsType(OT_GOTO_STATION) || u->current_order.IsType(OT_LOADING)) &&
1496 u->current_order.GetLoadType() != order->GetLoadType()) {
1497 u->current_order.SetLoadType(order->GetLoadType());
1499 InvalidateVehicleOrder(u, VIWD_MODIFY_ORDERS);
1503 return CommandCost();
1507 * Check if an aircraft has enough range for an order list.
1508 * @param v_new Aircraft to check.
1509 * @param v_order Vehicle currently holding the order list.
1510 * @param first First order in the source order list.
1511 * @return True if the aircraft has enough range for the orders, false otherwise.
1513 static bool CheckAircraftOrderDistance(const Aircraft *v_new, const Vehicle *v_order, const Order *first)
1515 if (first == NULL || v_new->acache.cached_max_range == 0) return true;
1517 /* Iterate over all orders to check the distance between all
1518 * 'goto' orders and their respective next order (of any type). */
1519 for (const Order *o = first; o != NULL; o = o->next) {
1520 switch (o->GetType()) {
1521 case OT_GOTO_STATION:
1522 case OT_GOTO_DEPOT:
1523 case OT_GOTO_WAYPOINT:
1524 /* If we don't have a next order, we've reached the end and must check the first order instead. */
1525 if (GetOrderDistance(o, o->next != NULL ? o->next : first, v_order) > v_new->acache.cached_max_range_sqr) return false;
1526 break;
1528 default: break;
1532 return true;
1536 * Clone/share/copy an order-list of another vehicle.
1537 * @param tile unused
1538 * @param flags operation to perform
1539 * @param p1 various bitstuffed elements
1540 * - p1 = (bit 0-19) - destination vehicle to clone orders to
1541 * - p1 = (bit 30-31) - action to perform
1542 * @param p2 source vehicle to clone orders from, if any (none for CO_UNSHARE)
1543 * @param text unused
1544 * @return the cost of this operation or an error
1546 CommandCost CmdCloneOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1548 VehicleID veh_src = GB(p2, 0, 20);
1549 VehicleID veh_dst = GB(p1, 0, 20);
1551 Vehicle *dst = Vehicle::GetIfValid(veh_dst);
1552 if (dst == NULL || !dst->IsPrimaryVehicle()) return CMD_ERROR;
1554 CommandCost ret = CheckOwnership(dst->owner);
1555 if (ret.Failed()) return ret;
1557 switch (GB(p1, 30, 2)) {
1558 case CO_SHARE: {
1559 Vehicle *src = Vehicle::GetIfValid(veh_src);
1561 /* Sanity checks */
1562 if (src == NULL || !src->IsPrimaryVehicle() || dst->type != src->type || dst == src) return CMD_ERROR;
1564 CommandCost ret = CheckOwnership(src->owner);
1565 if (ret.Failed()) return ret;
1567 /* Trucks can't share orders with busses (and visa versa) */
1568 if (src->type == VEH_ROAD && RoadVehicle::From(src)->IsBus() != RoadVehicle::From(dst)->IsBus()) {
1569 return CMD_ERROR;
1572 /* Is the vehicle already in the shared list? */
1573 if (src->FirstShared() == dst->FirstShared()) return CMD_ERROR;
1575 const Order *order;
1577 FOR_VEHICLE_ORDERS(src, order) {
1578 if (!OrderGoesToStation(dst, order)) continue;
1580 /* Allow copying unreachable destinations if they were already unreachable for the source.
1581 * This is basically to allow cloning / autorenewing / autoreplacing vehicles, while the stations
1582 * are temporarily invalid due to reconstruction. */
1583 const Station *st = Station::Get(order->GetDestination());
1584 if (CanVehicleUseStation(src, st) && !CanVehicleUseStation(dst, st)) {
1585 return_cmd_error(STR_ERROR_CAN_T_COPY_SHARE_ORDER);
1589 /* Check for aircraft range limits. */
1590 if (dst->type == VEH_AIRCRAFT && !CheckAircraftOrderDistance(Aircraft::From(dst), src, src->GetFirstOrder())) {
1591 return_cmd_error(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE);
1594 if (src->orders.list == NULL && !OrderList::CanAllocateItem()) {
1595 return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
1598 if (flags & DC_EXEC) {
1599 /* If the destination vehicle had a OrderList, destroy it.
1600 * We only reset the order indices, if the new orders are obviously different.
1601 * (We mainly do this to keep the order indices valid and in range.) */
1602 DeleteVehicleOrders(dst, false, dst->GetNumOrders() != src->GetNumOrders());
1604 dst->orders.list = src->orders.list;
1606 /* Link this vehicle in the shared-list */
1607 dst->AddToShared(src);
1609 InvalidateVehicleOrder(dst, VIWD_REMOVE_ALL_ORDERS);
1610 InvalidateVehicleOrder(src, VIWD_MODIFY_ORDERS);
1612 InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
1614 break;
1617 case CO_COPY: {
1618 Vehicle *src = Vehicle::GetIfValid(veh_src);
1620 /* Sanity checks */
1621 if (src == NULL || !src->IsPrimaryVehicle() || dst->type != src->type || dst == src) return CMD_ERROR;
1623 CommandCost ret = CheckOwnership(src->owner);
1624 if (ret.Failed()) return ret;
1626 /* Trucks can't copy all the orders from busses (and visa versa),
1627 * and neither can helicopters and aircraft. */
1628 const Order *order;
1629 FOR_VEHICLE_ORDERS(src, order) {
1630 if (OrderGoesToStation(dst, order) &&
1631 !CanVehicleUseStation(dst, Station::Get(order->GetDestination()))) {
1632 return_cmd_error(STR_ERROR_CAN_T_COPY_SHARE_ORDER);
1636 /* Check for aircraft range limits. */
1637 if (dst->type == VEH_AIRCRAFT && !CheckAircraftOrderDistance(Aircraft::From(dst), src, src->GetFirstOrder())) {
1638 return_cmd_error(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE);
1641 /* make sure there are orders available */
1642 if (!Order::CanAllocateItem(src->GetNumOrders()) || !OrderList::CanAllocateItem()) {
1643 return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
1646 if (flags & DC_EXEC) {
1647 const Order *order;
1648 Order *first = NULL;
1649 Order **order_dst;
1651 /* If the destination vehicle had an order list, destroy the chain but keep the OrderList.
1652 * We only reset the order indices, if the new orders are obviously different.
1653 * (We mainly do this to keep the order indices valid and in range.) */
1654 DeleteVehicleOrders(dst, true, dst->GetNumOrders() != src->GetNumOrders());
1656 order_dst = &first;
1657 FOR_VEHICLE_ORDERS(src, order) {
1658 *order_dst = new Order();
1659 (*order_dst)->AssignOrder(*order);
1660 order_dst = &(*order_dst)->next;
1662 if (dst->orders.list == NULL) {
1663 dst->orders.list = new OrderList(first, dst);
1664 } else {
1665 assert(dst->orders.list->GetFirstOrder() == NULL);
1666 assert(!dst->orders.list->IsShared());
1667 delete dst->orders.list;
1668 assert(OrderList::CanAllocateItem());
1669 dst->orders.list = new OrderList(first, dst);
1672 InvalidateVehicleOrder(dst, VIWD_REMOVE_ALL_ORDERS);
1674 InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
1676 break;
1679 case CO_UNSHARE: return DecloneOrder(dst, flags);
1680 default: return CMD_ERROR;
1683 return CommandCost();
1687 * Add/remove refit orders from an order
1688 * @param tile Not used
1689 * @param flags operation to perform
1690 * @param p1 VehicleIndex of the vehicle having the order
1691 * @param p2 bitmask
1692 * - bit 0-7 CargoID
1693 * - bit 16-23 number of order to modify
1694 * @param text unused
1695 * @return the cost of this operation or an error
1697 CommandCost CmdOrderRefit(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1699 VehicleID veh = GB(p1, 0, 20);
1700 VehicleOrderID order_number = GB(p2, 16, 8);
1701 CargoID cargo = GB(p2, 0, 8);
1703 if (cargo >= NUM_CARGO && cargo != CT_NO_REFIT && cargo != CT_AUTO_REFIT) return CMD_ERROR;
1705 const Vehicle *v = Vehicle::GetIfValid(veh);
1706 if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
1708 CommandCost ret = CheckOwnership(v->owner);
1709 if (ret.Failed()) return ret;
1711 Order *order = v->GetOrder(order_number);
1712 if (order == NULL) return CMD_ERROR;
1714 /* Automatic refit cargo is only supported for goto station orders. */
1715 if (cargo == CT_AUTO_REFIT && !order->IsType(OT_GOTO_STATION)) return CMD_ERROR;
1717 if (order->GetLoadType() & OLFB_NO_LOAD) return CMD_ERROR;
1719 if (flags & DC_EXEC) {
1720 order->SetRefit(cargo);
1722 /* Make the depot order an 'always go' order. */
1723 if (cargo != CT_NO_REFIT && order->IsType(OT_GOTO_DEPOT)) {
1724 order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
1725 order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
1728 for (Vehicle *u = v->FirstShared(); u != NULL; u = u->NextShared()) {
1729 /* Update any possible open window of the vehicle */
1730 InvalidateVehicleOrder(u, VIWD_MODIFY_ORDERS);
1732 /* If the vehicle already got the current depot set as current order, then update current order as well */
1733 if (u->cur_real_order_index == order_number && (u->current_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) {
1734 u->current_order.SetRefit(cargo);
1739 return CommandCost();
1745 * Check the orders of a vehicle, to see if there are invalid orders and stuff
1748 void CheckOrders(const Vehicle *v)
1750 /* Does the user wants us to check things? */
1751 if (_settings_client.gui.order_review_system == 0) return;
1753 /* Do nothing for crashed vehicles */
1754 if (v->vehstatus & VS_CRASHED) return;
1756 /* Do nothing for stopped vehicles if setting is '1' */
1757 if (_settings_client.gui.order_review_system == 1 && (v->vehstatus & VS_STOPPED)) return;
1759 /* do nothing we we're not the first vehicle in a share-chain */
1760 if (v->FirstShared() != v) return;
1762 /* Only check every 20 days, so that we don't flood the message log */
1763 if (v->owner == _local_company && v->day_counter % 20 == 0) {
1764 int n_st, problem_type = -1;
1765 const Order *order;
1766 int message = 0;
1768 /* Check the order list */
1769 n_st = 0;
1771 FOR_VEHICLE_ORDERS(v, order) {
1772 /* Dummy order? */
1773 if (order->IsType(OT_DUMMY)) {
1774 problem_type = 1;
1775 break;
1777 /* Does station have a load-bay for this vehicle? */
1778 if (order->IsType(OT_GOTO_STATION)) {
1779 const Station *st = Station::Get(order->GetDestination());
1781 n_st++;
1782 if (!CanVehicleUseStation(v, st)) problem_type = 3;
1786 /* Check if the last and the first order are the same */
1787 if (v->GetNumOrders() > 1) {
1788 const Order *last = v->GetLastOrder();
1790 if (v->orders.list->GetFirstOrder()->Equals(*last)) {
1791 problem_type = 2;
1795 /* Do we only have 1 station in our order list? */
1796 if (n_st < 2 && problem_type == -1) problem_type = 0;
1798 #ifndef NDEBUG
1799 if (v->orders.list != NULL) v->orders.list->DebugCheckSanity();
1800 #endif
1802 /* We don't have a problem */
1803 if (problem_type < 0) return;
1805 message = STR_NEWS_VEHICLE_HAS_TOO_FEW_ORDERS + problem_type;
1806 //DEBUG(misc, 3, "Triggered News Item for vehicle %d", v->index);
1808 SetDParam(0, v->index);
1809 AddVehicleAdviceNewsItem(message, v->index);
1814 * Removes an order from all vehicles. Triggers when, say, a station is removed.
1815 * @param type The type of the order (OT_GOTO_[STATION|DEPOT|WAYPOINT]).
1816 * @param destination The destination. Can be a StationID, DepotID or WaypointID.
1818 void RemoveOrderFromAllVehicles(OrderType type, DestinationID destination)
1820 Vehicle *v;
1822 /* Aircraft have StationIDs for depot orders and never use DepotIDs
1823 * This fact is handled specially below
1826 /* Go through all vehicles */
1827 FOR_ALL_VEHICLES(v) {
1828 Order *order;
1830 order = &v->current_order;
1831 if ((v->type == VEH_AIRCRAFT && order->IsType(OT_GOTO_DEPOT) ? OT_GOTO_STATION : order->GetType()) == type &&
1832 v->current_order.GetDestination() == destination) {
1833 order->MakeDummy();
1834 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
1837 /* Clear the order from the order-list */
1838 int id = -1;
1839 FOR_VEHICLE_ORDERS(v, order) {
1840 id++;
1841 restart:
1843 OrderType ot = order->GetType();
1844 if (ot == OT_GOTO_DEPOT && (order->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0) continue;
1845 if (ot == OT_IMPLICIT || (v->type == VEH_AIRCRAFT && ot == OT_GOTO_DEPOT)) ot = OT_GOTO_STATION;
1846 if (ot == type && order->GetDestination() == destination) {
1847 /* We want to clear implicit orders, but we don't want to make them
1848 * dummy orders. They should just vanish. Also check the actual order
1849 * type as ot is currently OT_GOTO_STATION. */
1850 if (order->IsType(OT_IMPLICIT)) {
1851 order = order->next; // DeleteOrder() invalidates current order
1852 DeleteOrder(v, id);
1853 if (order != NULL) goto restart;
1854 break;
1857 order->MakeDummy();
1858 for (const Vehicle *w = v->FirstShared(); w != NULL; w = w->NextShared()) {
1859 /* In GUI, simulate by removing the order and adding it back */
1860 InvalidateVehicleOrder(w, id | (INVALID_VEH_ORDER_ID << 8));
1861 InvalidateVehicleOrder(w, (INVALID_VEH_ORDER_ID << 8) | id);
1867 OrderBackup::RemoveOrder(type, destination);
1871 * Checks if a vehicle has a depot in its order list.
1872 * @return True iff at least one order is a depot order.
1874 bool Vehicle::HasDepotOrder() const
1876 const Order *order;
1878 FOR_VEHICLE_ORDERS(this, order) {
1879 if (order->IsType(OT_GOTO_DEPOT)) return true;
1882 return false;
1886 * Delete all orders from a vehicle
1887 * @param v Vehicle whose orders to reset
1888 * @param keep_orderlist If true, do not free the order list, only empty it.
1889 * @param reset_order_indices If true, reset cur_implicit_order_index and cur_real_order_index
1890 * and cancel the current full load order (if the vehicle is loading).
1891 * If false, _you_ have to make sure the order indices are valid after
1892 * your messing with them!
1894 void DeleteVehicleOrders(Vehicle *v, bool keep_orderlist, bool reset_order_indices)
1896 DeleteOrderWarnings(v);
1898 if (v->IsOrderListShared()) {
1899 /* Remove ourself from the shared order list. */
1900 v->RemoveFromShared();
1901 v->orders.list = NULL;
1902 } else if (v->orders.list != NULL) {
1903 /* Remove the orders */
1904 v->orders.list->FreeChain(keep_orderlist);
1905 if (!keep_orderlist) v->orders.list = NULL;
1908 if (reset_order_indices) {
1909 v->cur_implicit_order_index = v->cur_real_order_index = 0;
1910 if (v->current_order.IsType(OT_LOADING)) {
1911 CancelLoadingDueToDeletedOrder(v);
1917 * Clamp the service interval to the correct min/max. The actual min/max values
1918 * depend on whether it's in percent or days.
1919 * @param interval proposed service interval
1920 * @param company_id the owner of the vehicle
1921 * @return Clamped service interval
1923 uint16 GetServiceIntervalClamped(uint interval, bool ispercent)
1925 return ispercent ? Clamp(interval, MIN_SERVINT_PERCENT, MAX_SERVINT_PERCENT) : Clamp(interval, MIN_SERVINT_DAYS, MAX_SERVINT_DAYS);
1930 * Check if a vehicle has any valid orders
1932 * @return false if there are no valid orders
1933 * @note Conditional orders are not considered valid destination orders
1936 static bool CheckForValidOrders(const Vehicle *v)
1938 const Order *order;
1940 FOR_VEHICLE_ORDERS(v, order) {
1941 switch (order->GetType()) {
1942 case OT_GOTO_STATION:
1943 case OT_GOTO_DEPOT:
1944 case OT_GOTO_WAYPOINT:
1945 return true;
1947 default:
1948 break;
1952 return false;
1956 * Compare the variable and value based on the given comparator.
1958 static bool OrderConditionCompare(OrderConditionComparator occ, int variable, int value)
1960 switch (occ) {
1961 case OCC_EQUALS: return variable == value;
1962 case OCC_NOT_EQUALS: return variable != value;
1963 case OCC_LESS_THAN: return variable < value;
1964 case OCC_LESS_EQUALS: return variable <= value;
1965 case OCC_MORE_THAN: return variable > value;
1966 case OCC_MORE_EQUALS: return variable >= value;
1967 case OCC_IS_TRUE: return variable != 0;
1968 case OCC_IS_FALSE: return variable == 0;
1969 default: NOT_REACHED();
1974 * Process a conditional order and determine the next order.
1975 * @param order the order the vehicle currently has
1976 * @param v the vehicle to update
1977 * @return index of next order to jump to, or INVALID_VEH_ORDER_ID to use the next order
1979 VehicleOrderID ProcessConditionalOrder(const Order *order, const Vehicle *v)
1981 if (order->GetType() != OT_CONDITIONAL) return INVALID_VEH_ORDER_ID;
1983 bool skip_order = false;
1984 OrderConditionComparator occ = order->GetConditionComparator();
1985 uint16 value = order->GetConditionValue();
1987 switch (order->GetConditionVariable()) {
1988 case OCV_LOAD_PERCENTAGE: skip_order = OrderConditionCompare(occ, CalcPercentVehicleFilled(v, NULL), value); break;
1989 case OCV_RELIABILITY: skip_order = OrderConditionCompare(occ, ToPercent16(v->reliability), value); break;
1990 case OCV_MAX_SPEED: skip_order = OrderConditionCompare(occ, v->GetDisplayMaxSpeed() * 10 / 16, value); break;
1991 case OCV_AGE: skip_order = OrderConditionCompare(occ, v->age / DAYS_IN_LEAP_YEAR, value); break;
1992 case OCV_REQUIRES_SERVICE: skip_order = OrderConditionCompare(occ, v->NeedsServicing(), value); break;
1993 case OCV_UNCONDITIONALLY: skip_order = true; break;
1994 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;
1995 default: NOT_REACHED();
1998 return skip_order ? order->GetConditionSkipToOrder() : (VehicleOrderID)INVALID_VEH_ORDER_ID;
2002 * Update the vehicle's destination tile from an order.
2003 * @param order the order the vehicle currently has
2004 * @param v the vehicle to update
2005 * @param conditional_depth the depth (amount of steps) to go with conditional orders. This to prevent infinite loops.
2006 * @param pbs_look_ahead Whether we are forecasting orders for pbs reservations in advance. If true, the order indices must not be modified.
2008 bool UpdateOrderDest(Vehicle *v, const Order *order, int conditional_depth, bool pbs_look_ahead)
2010 if (conditional_depth > v->GetNumOrders()) {
2011 v->current_order.Free();
2012 v->dest_tile = 0;
2013 return false;
2016 switch (order->GetType()) {
2017 case OT_GOTO_STATION:
2018 v->dest_tile = v->GetOrderStationLocation(order->GetDestination());
2019 return true;
2021 case OT_GOTO_DEPOT:
2022 if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !v->NeedsServicing()) {
2023 assert(!pbs_look_ahead);
2024 UpdateVehicleTimetable(v, true);
2025 v->IncrementRealOrderIndex();
2026 break;
2029 if (v->current_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) {
2030 /* We need to search for the nearest depot (hangar). */
2031 TileIndex location;
2032 DestinationID destination;
2033 bool reverse;
2035 if (v->FindClosestDepot(&location, &destination, &reverse)) {
2036 /* PBS reservations cannot reverse */
2037 if (pbs_look_ahead && reverse) return false;
2039 v->dest_tile = location;
2040 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());
2042 /* If there is no depot in front, reverse automatically (trains only) */
2043 if (v->type == VEH_TRAIN && reverse) DoCommand(v->tile, v->index, 0, DC_EXEC, CMD_REVERSE_TRAIN_DIRECTION);
2045 if (v->type == VEH_AIRCRAFT) {
2046 Aircraft *a = Aircraft::From(v);
2047 if (a->state == FLYING && a->targetairport != destination) {
2048 /* The aircraft is now heading for a different hangar than the next in the orders */
2049 extern void AircraftNextAirportPos_and_Order(Aircraft *a);
2050 AircraftNextAirportPos_and_Order(a);
2053 return true;
2056 /* If there is no depot, we cannot help PBS either. */
2057 if (pbs_look_ahead) return false;
2059 UpdateVehicleTimetable(v, true);
2060 v->IncrementRealOrderIndex();
2061 } else {
2062 if (v->type != VEH_AIRCRAFT) {
2063 v->dest_tile = Depot::Get(order->GetDestination())->xy;
2065 return true;
2067 break;
2069 case OT_GOTO_WAYPOINT:
2070 v->dest_tile = Waypoint::Get(order->GetDestination())->xy;
2071 return true;
2073 case OT_CONDITIONAL: {
2074 assert(!pbs_look_ahead);
2075 VehicleOrderID next_order = ProcessConditionalOrder(order, v);
2076 if (next_order != INVALID_VEH_ORDER_ID) {
2077 /* Jump to next_order. cur_implicit_order_index becomes exactly that order,
2078 * cur_real_order_index might come after next_order. */
2079 UpdateVehicleTimetable(v, false);
2080 v->cur_implicit_order_index = v->cur_real_order_index = next_order;
2081 v->UpdateRealOrderIndex();
2082 v->current_order_time += v->GetOrder(v->cur_real_order_index)->travel_time;
2084 /* Disable creation of implicit orders.
2085 * When inserting them we do not know that we would have to make the conditional orders point to them. */
2086 if (v->IsGroundVehicle()) {
2087 uint16 &gv_flags = v->GetGroundVehicleFlags();
2088 SetBit(gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
2090 } else {
2091 UpdateVehicleTimetable(v, true);
2092 v->IncrementRealOrderIndex();
2094 break;
2097 default:
2098 v->dest_tile = 0;
2099 return false;
2102 assert(v->cur_implicit_order_index < v->GetNumOrders());
2103 assert(v->cur_real_order_index < v->GetNumOrders());
2105 /* Get the current order */
2106 order = v->GetOrder(v->cur_real_order_index);
2107 if (order != NULL && order->IsType(OT_IMPLICIT)) {
2108 assert(v->GetNumManualOrders() == 0);
2109 order = NULL;
2112 if (order == NULL) {
2113 v->current_order.Free();
2114 v->dest_tile = 0;
2115 return false;
2118 v->current_order = *order;
2119 return UpdateOrderDest(v, order, conditional_depth + 1, pbs_look_ahead);
2123 * Handle the orders of a vehicle and determine the next place
2124 * to go to if needed.
2125 * @param v the vehicle to do this for.
2126 * @return true *if* the vehicle is eligible for reversing
2127 * (basically only when leaving a station).
2129 bool ProcessOrders(Vehicle *v)
2131 switch (v->current_order.GetType()) {
2132 case OT_GOTO_DEPOT:
2133 /* Let a depot order in the orderlist interrupt. */
2134 if (!(v->current_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) return false;
2135 break;
2137 case OT_LOADING:
2138 return false;
2140 case OT_LEAVESTATION:
2141 if (v->type != VEH_AIRCRAFT) return false;
2142 break;
2144 default: break;
2148 * Reversing because of order change is allowed only just after leaving a
2149 * station (and the difficulty setting to allowed, of course)
2150 * this can be detected because only after OT_LEAVESTATION, current_order
2151 * will be reset to nothing. (That also happens if no order, but in that case
2152 * it won't hit the point in code where may_reverse is checked)
2154 bool may_reverse = v->current_order.IsType(OT_NOTHING);
2156 /* Check if we've reached a 'via' destination. */
2157 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)) &&
2158 IsStationTile(v->tile) &&
2159 v->current_order.GetDestination() == GetStationIndex(v->tile)) {
2160 v->DeleteUnreachedImplicitOrders();
2161 /* We set the last visited station here because we do not want
2162 * the train to stop at this 'via' station if the next order
2163 * is a no-non-stop order; in that case not setting the last
2164 * visited station will cause the vehicle to still stop. */
2165 v->last_station_visited = v->current_order.GetDestination();
2166 UpdateVehicleTimetable(v, true);
2167 v->IncrementImplicitOrderIndex();
2170 /* Get the current order */
2171 assert(v->cur_implicit_order_index == 0 || v->cur_implicit_order_index < v->GetNumOrders());
2172 v->UpdateRealOrderIndex();
2174 const Order *order = v->GetOrder(v->cur_real_order_index);
2175 if (order != NULL && order->IsType(OT_IMPLICIT)) {
2176 assert(v->GetNumManualOrders() == 0);
2177 order = NULL;
2180 /* If no order, do nothing. */
2181 if (order == NULL || (v->type == VEH_AIRCRAFT && !CheckForValidOrders(v))) {
2182 if (v->type == VEH_AIRCRAFT) {
2183 /* Aircraft do something vastly different here, so handle separately */
2184 extern void HandleMissingAircraftOrders(Aircraft *v);
2185 HandleMissingAircraftOrders(Aircraft::From(v));
2186 return false;
2189 v->current_order.Free();
2190 v->dest_tile = 0;
2191 return false;
2194 /* If it is unchanged, keep it. */
2195 if (order->Equals(v->current_order) && (v->type == VEH_AIRCRAFT || v->dest_tile != 0) &&
2196 (v->type != VEH_SHIP || !order->IsType(OT_GOTO_STATION) || Station::Get(order->GetDestination())->docks != NULL)) {
2197 return false;
2200 /* Otherwise set it, and determine the destination tile. */
2201 v->current_order = *order;
2203 InvalidateVehicleOrder(v, VIWD_MODIFY_ORDERS);
2204 switch (v->type) {
2205 default:
2206 NOT_REACHED();
2208 case VEH_ROAD:
2209 case VEH_TRAIN:
2210 break;
2212 case VEH_AIRCRAFT:
2213 case VEH_SHIP:
2214 SetWindowClassesDirty(GetWindowClassForVehicleType(v->type));
2215 break;
2218 return UpdateOrderDest(v, order) && may_reverse;
2222 * Check whether the given vehicle should stop at the given station
2223 * based on this order and the non-stop settings.
2224 * @param v the vehicle that might be stopping.
2225 * @param station the station to stop at.
2226 * @return true if the vehicle should stop.
2228 bool Order::ShouldStopAtStation(const Vehicle *v, StationID station) const
2230 bool is_dest_station = this->IsType(OT_GOTO_STATION) && this->dest == station;
2232 return (!this->IsType(OT_GOTO_DEPOT) || (this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS) != 0) &&
2233 v->last_station_visited != station && // Do stop only when we've not just been there
2234 /* Finally do stop when there is no non-stop flag set for this type of station. */
2235 !(this->GetNonStopType() & (is_dest_station ? ONSF_NO_STOP_AT_DESTINATION_STATION : ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS));
2238 bool Order::CanLoadOrUnload() const
2240 return (this->IsType(OT_GOTO_STATION) || this->IsType(OT_IMPLICIT)) &&
2241 (this->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) == 0 &&
2242 ((this->GetLoadType() & OLFB_NO_LOAD) == 0 ||
2243 (this->GetUnloadType() & OUFB_NO_UNLOAD) == 0);
2247 * A vehicle can leave the current station with cargo if:
2248 * 1. it can load cargo here OR
2249 * 2a. it could leave the last station with cargo AND
2250 * 2b. it doesn't have to unload all cargo here.
2252 bool Order::CanLeaveWithCargo(bool has_cargo) const
2254 return (this->GetLoadType() & OLFB_NO_LOAD) == 0 || (has_cargo &&
2255 (this->GetUnloadType() & (OUFB_UNLOAD | OUFB_TRANSFER)) == 0);