2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 /** @file timetable_cmd.cpp Commands related to time tabling. */
11 #include "command_func.h"
12 #include "company_func.h"
13 #include "timer/timer_game_tick.h"
14 #include "timer/timer_game_economy.h"
15 #include "window_func.h"
16 #include "vehicle_base.h"
17 #include "timetable_cmd.h"
18 #include "timetable.h"
20 #include "table/strings.h"
22 #include "safeguards.h"
25 * Get the TimerGameTick::TickCounter tick of a given date.
26 * @param start_date The date when the timetable starts.
27 * @return The first tick of this date.
29 TimerGameTick::TickCounter
GetStartTickFromDate(TimerGameEconomy::Date start_date
)
31 /* Calculate the offset in ticks from the current date. */
32 TimerGameTick::Ticks tick_offset
= (start_date
- TimerGameEconomy::date
).base() * Ticks::DAY_TICKS
;
34 /* Compensate for the current date_fract. */
35 tick_offset
-= TimerGameEconomy::date_fract
;
37 /* Return the current tick plus the offset. */
38 return TimerGameTick::counter
+ tick_offset
;
42 * Get a date from a given start tick of timetable.
43 * @param start_tick The TimerGameTick::TickCounter when the timetable starts.
44 * @return The date when we reach this tick.
46 TimerGameEconomy::Date
GetDateFromStartTick(TimerGameTick::TickCounter start_tick
)
48 /* Calculate the offset in ticks from the current counter tick. */
49 TimerGameTick::Ticks tick_offset
= start_tick
- TimerGameTick::counter
;
51 /* Compensate for the current date_fract. */
52 tick_offset
+= TimerGameEconomy::date_fract
;
54 /* Return the current date plus the offset in days. */
55 return TimerGameEconomy::date
+ (tick_offset
/ Ticks::DAY_TICKS
);
59 * Change/update a particular timetable entry.
60 * @param v The vehicle to change the timetable of.
61 * @param order_number The index of the timetable in the order list.
62 * @param val The new data of the timetable entry.
63 * @param mtf Which part of the timetable entry to change.
64 * @param timetabled If the new value is explicitly timetabled.
66 static void ChangeTimetable(Vehicle
*v
, VehicleOrderID order_number
, uint16_t val
, ModifyTimetableFlags mtf
, bool timetabled
)
68 Order
*order
= v
->GetOrder(order_number
);
69 assert(order
!= nullptr);
71 int timetable_delta
= 0;
75 total_delta
= val
- order
->GetWaitTime();
76 timetable_delta
= (timetabled
? val
: 0) - order
->GetTimetabledWait();
77 order
->SetWaitTime(val
);
78 order
->SetWaitTimetabled(timetabled
);
82 total_delta
= val
- order
->GetTravelTime();
83 timetable_delta
= (timetabled
? val
: 0) - order
->GetTimetabledTravel();
84 order
->SetTravelTime(val
);
85 order
->SetTravelTimetabled(timetabled
);
88 case MTF_TRAVEL_SPEED
:
89 order
->SetMaxSpeed(val
);
95 v
->orders
->UpdateTotalDuration(total_delta
);
96 v
->orders
->UpdateTimetableDuration(timetable_delta
);
98 for (v
= v
->FirstShared(); v
!= nullptr; v
= v
->NextShared()) {
99 if (v
->cur_real_order_index
== order_number
&& v
->current_order
.Equals(*order
)) {
102 v
->current_order
.SetWaitTime(val
);
103 v
->current_order
.SetWaitTimetabled(timetabled
);
106 case MTF_TRAVEL_TIME
:
107 v
->current_order
.SetTravelTime(val
);
108 v
->current_order
.SetTravelTimetabled(timetabled
);
111 case MTF_TRAVEL_SPEED
:
112 v
->current_order
.SetMaxSpeed(val
);
119 SetWindowDirty(WC_VEHICLE_TIMETABLE
, v
->index
);
124 * Change timetable data of an order.
125 * @param flags Operation to perform.
126 * @param veh Vehicle with the orders to change.
127 * @param order_number Order index to modify.
128 * @param mtf Timetable data to change (@see ModifyTimetableFlags)
129 * @param data The data to modify as specified by \c mtf.
130 * 0 to clear times, UINT16_MAX to clear speed limit.
131 * @return the cost of this operation or an error
133 CommandCost
CmdChangeTimetable(DoCommandFlag flags
, VehicleID veh
, VehicleOrderID order_number
, ModifyTimetableFlags mtf
, uint16_t data
)
135 Vehicle
*v
= Vehicle::GetIfValid(veh
);
136 if (v
== nullptr || !v
->IsPrimaryVehicle()) return CMD_ERROR
;
138 CommandCost ret
= CheckOwnership(v
->owner
);
139 if (ret
.Failed()) return ret
;
141 Order
*order
= v
->GetOrder(order_number
);
142 if (order
== nullptr || order
->IsType(OT_IMPLICIT
)) return CMD_ERROR
;
144 if (mtf
>= MTF_END
) return CMD_ERROR
;
146 int wait_time
= order
->GetWaitTime();
147 int travel_time
= order
->GetTravelTime();
148 int max_speed
= order
->GetMaxSpeed();
154 case MTF_TRAVEL_TIME
:
158 case MTF_TRAVEL_SPEED
:
160 if (max_speed
== 0) max_speed
= UINT16_MAX
; // Disable speed limit.
167 if (wait_time
!= order
->GetWaitTime()) {
168 switch (order
->GetType()) {
169 case OT_GOTO_STATION
:
170 if (order
->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION
) return_cmd_error(STR_ERROR_TIMETABLE_NOT_STOPPING_HERE
);
176 default: return_cmd_error(STR_ERROR_TIMETABLE_ONLY_WAIT_AT_STATIONS
);
180 if (travel_time
!= order
->GetTravelTime() && order
->IsType(OT_CONDITIONAL
)) return CMD_ERROR
;
181 if (max_speed
!= order
->GetMaxSpeed() && (order
->IsType(OT_CONDITIONAL
) || v
->type
== VEH_AIRCRAFT
)) return CMD_ERROR
;
183 if (flags
& DC_EXEC
) {
186 /* Set time if changing the value or confirming an estimated time as timetabled. */
187 if (wait_time
!= order
->GetWaitTime() || (wait_time
> 0 && !order
->IsWaitTimetabled())) {
188 ChangeTimetable(v
, order_number
, wait_time
, MTF_WAIT_TIME
, wait_time
> 0);
192 case MTF_TRAVEL_TIME
:
193 /* Set time if changing the value or confirming an estimated time as timetabled. */
194 if (travel_time
!= order
->GetTravelTime() || (travel_time
> 0 && !order
->IsTravelTimetabled())) {
195 ChangeTimetable(v
, order_number
, travel_time
, MTF_TRAVEL_TIME
, travel_time
> 0);
199 case MTF_TRAVEL_SPEED
:
200 if (max_speed
!= order
->GetMaxSpeed()) {
201 ChangeTimetable(v
, order_number
, max_speed
, MTF_TRAVEL_SPEED
, max_speed
!= UINT16_MAX
);
209 /* Unbunching data is no longer valid for any vehicle in this shared order group. */
210 Vehicle
*u
= v
->FirstShared();
211 for (; u
!= nullptr; u
= u
->NextShared()) {
212 u
->ResetDepotUnbunching();
216 return CommandCost();
220 * Change timetable data of all orders of a vehicle.
221 * @param flags Operation to perform.
222 * @param veh Vehicle with the orders to change.
223 * @param mtf Timetable data to change (@see ModifyTimetableFlags)
224 * @param data The data to modify as specified by \c mtf.
225 * 0 to clear times, UINT16_MAX to clear speed limit.
226 * @return the cost of this operation or an error
228 CommandCost
CmdBulkChangeTimetable(DoCommandFlag flags
, VehicleID veh
, ModifyTimetableFlags mtf
, uint16_t data
)
230 Vehicle
*v
= Vehicle::GetIfValid(veh
);
231 if (v
== nullptr || !v
->IsPrimaryVehicle()) return CMD_ERROR
;
233 CommandCost ret
= CheckOwnership(v
->owner
);
234 if (ret
.Failed()) return ret
;
236 if (mtf
>= MTF_END
) return CMD_ERROR
;
238 if (v
->GetNumOrders() == 0) return CMD_ERROR
;
240 if (flags
& DC_EXEC
) {
241 for (VehicleOrderID order_number
= 0; order_number
< v
->GetNumOrders(); order_number
++) {
242 Order
*order
= v
->GetOrder(order_number
);
243 if (order
== nullptr || order
->IsType(OT_IMPLICIT
)) continue;
245 Command
<CMD_CHANGE_TIMETABLE
>::Do(DC_EXEC
, v
->index
, order_number
, mtf
, data
);
249 return CommandCost();
253 * Clear the lateness counter to make the vehicle on time.
254 * @param flags Operation to perform.
255 * @param veh Vehicle with the orders to change.
256 * @param apply_to_group Set to reset the late counter for all vehicles sharing the orders.
257 * @return the cost of this operation or an error
259 CommandCost
CmdSetVehicleOnTime(DoCommandFlag flags
, VehicleID veh
, bool apply_to_group
)
261 Vehicle
*v
= Vehicle::GetIfValid(veh
);
262 if (v
== nullptr || !v
->IsPrimaryVehicle() || v
->orders
== nullptr) return CMD_ERROR
;
264 /* A vehicle can't be late if its timetable hasn't started.
265 * If we're setting all vehicles in the group, we handle that below. */
266 if (!apply_to_group
&& !HasBit(v
->vehicle_flags
, VF_TIMETABLE_STARTED
)) return CommandCost(STR_ERROR_TIMETABLE_NOT_STARTED
);
268 CommandCost ret
= CheckOwnership(v
->owner
);
269 if (ret
.Failed()) return ret
;
271 if (flags
& DC_EXEC
) {
272 if (apply_to_group
) {
273 TimerGameTick::Ticks most_late
= 0;
274 for (Vehicle
*u
= v
->FirstShared(); u
!= nullptr; u
= u
->NextShared()) {
275 /* A vehicle can't be late if its timetable hasn't started. */
276 if (!HasBit(v
->vehicle_flags
, VF_TIMETABLE_STARTED
)) continue;
278 if (u
->lateness_counter
> most_late
) {
279 most_late
= u
->lateness_counter
;
282 /* Unbunching data is no longer valid. */
283 u
->ResetDepotUnbunching();
286 for (Vehicle
*u
= v
->FirstShared(); u
!= nullptr; u
= u
->NextShared()) {
287 /* A vehicle can't be late if its timetable hasn't started. */
288 if (!HasBit(v
->vehicle_flags
, VF_TIMETABLE_STARTED
)) continue;
290 u
->lateness_counter
-= most_late
;
291 SetWindowDirty(WC_VEHICLE_TIMETABLE
, u
->index
);
295 v
->lateness_counter
= 0;
296 /* Unbunching data is no longer valid. */
297 v
->ResetDepotUnbunching();
298 SetWindowDirty(WC_VEHICLE_TIMETABLE
, v
->index
);
302 return CommandCost();
306 * Order vehicles based on their timetable. The vehicles will be sorted in order
307 * they would reach the first station.
309 * @param a First Vehicle pointer.
310 * @param b Second Vehicle pointer.
311 * @return Comparison value.
313 static bool VehicleTimetableSorter(Vehicle
* const &a
, Vehicle
* const &b
)
315 VehicleOrderID a_order
= a
->cur_real_order_index
;
316 VehicleOrderID b_order
= b
->cur_real_order_index
;
317 int j
= (int)b_order
- (int)a_order
;
319 /* Are we currently at an ordered station (un)loading? */
320 bool a_load
= a
->current_order
.IsType(OT_LOADING
) && a
->current_order
.GetNonStopType() != ONSF_STOP_EVERYWHERE
;
321 bool b_load
= b
->current_order
.IsType(OT_LOADING
) && b
->current_order
.GetNonStopType() != ONSF_STOP_EVERYWHERE
;
323 /* If the current order is not loading at the ordered station, decrease the order index by one since we have
324 * not yet arrived at the station (and thus the timetable entry; still in the travelling of the previous one).
325 * Since the ?_order variables are unsigned the -1 will flow under and place the vehicles going to order #0 at
326 * the begin of the list with vehicles arriving at #0. */
327 if (!a_load
) a_order
--;
328 if (!b_load
) b_order
--;
330 /* First check the order index that accounted for loading, then just the raw one. */
331 int i
= (int)b_order
- (int)a_order
;
332 if (i
!= 0) return i
< 0;
333 if (j
!= 0) return j
< 0;
335 /* Look at the time we spent in this order; the higher, the closer to its destination. */
336 i
= b
->current_order_time
- a
->current_order_time
;
337 if (i
!= 0) return i
< 0;
339 /* If all else is equal, use some unique index to sort it the same way. */
340 return b
->unitnumber
< a
->unitnumber
;
344 * Set the start date of the timetable.
345 * @param flags Operation to perform.
346 * @param veh_id Vehicle ID.
347 * @param timetable_all Set to set timetable start for all vehicles sharing this order
348 * @param start_tick The TimerGameTick::counter tick when the timetable starts.
349 * @return The error or cost of the operation.
351 CommandCost
CmdSetTimetableStart(DoCommandFlag flags
, VehicleID veh_id
, bool timetable_all
, TimerGameTick::TickCounter start_tick
)
353 Vehicle
*v
= Vehicle::GetIfValid(veh_id
);
354 if (v
== nullptr || !v
->IsPrimaryVehicle() || v
->orders
== nullptr) return CMD_ERROR
;
356 CommandCost ret
= CheckOwnership(v
->owner
);
357 if (ret
.Failed()) return ret
;
359 TimerGameTick::Ticks total_duration
= v
->orders
->GetTimetableTotalDuration();
361 TimerGameEconomy::Date start_date
= GetDateFromStartTick(start_tick
);
363 /* Don't let a timetable start at an invalid date. */
364 if (start_date
< 0 || start_date
> EconomyTime::MAX_DATE
) return CMD_ERROR
;
366 /* Don't let a timetable start more than 15 years into the future... */
367 if (start_date
- TimerGameEconomy::date
> TimerGameEconomy::DateAtStartOfYear(MAX_TIMETABLE_START_YEARS
)) return CMD_ERROR
;
368 /* ...or 1 year in the past. */
369 if (TimerGameEconomy::date
- start_date
> EconomyTime::DAYS_IN_LEAP_YEAR
) return CMD_ERROR
;
371 /* If trying to distribute start dates over a shared order group, we need to know the total duration. */
372 if (timetable_all
&& !v
->orders
->IsCompleteTimetable()) return CommandCost(STR_ERROR_TIMETABLE_INCOMPLETE
);
374 /* Don't allow invalid start dates for other vehicles in the shared order group. */
375 if (timetable_all
&& start_date
+ (total_duration
/ Ticks::DAY_TICKS
) > EconomyTime::MAX_DATE
) return CMD_ERROR
;
377 if (flags
& DC_EXEC
) {
378 std::vector
<Vehicle
*> vehs
;
381 for (Vehicle
*w
= v
->orders
->GetFirstSharedVehicle(); w
!= nullptr; w
= w
->NextShared()) {
388 int num_vehs
= (uint
)vehs
.size();
391 std::sort(vehs
.begin(), vehs
.end(), &VehicleTimetableSorter
);
396 for (Vehicle
*w
: vehs
) {
397 w
->lateness_counter
= 0;
398 ClrBit(w
->vehicle_flags
, VF_TIMETABLE_STARTED
);
399 /* Do multiplication, then division to reduce rounding errors. */
400 w
->timetable_start
= start_tick
+ (idx
* total_duration
/ num_vehs
);
402 /* Unbunching data is no longer valid. */
403 v
->ResetDepotUnbunching();
405 SetWindowDirty(WC_VEHICLE_TIMETABLE
, w
->index
);
411 return CommandCost();
416 * Start or stop filling the timetable automatically from the time the vehicle
417 * actually takes to complete it. When starting to autofill the current times
418 * are cleared and the timetable will start again from scratch.
419 * @param flags Operation to perform.
420 * @param veh Vehicle index.
421 * @param autofill Enable or disable autofill
422 * @param preserve_wait_time Set to preserve waiting times in non-destructive mode
423 * @return the cost of this operation or an error
425 CommandCost
CmdAutofillTimetable(DoCommandFlag flags
, VehicleID veh
, bool autofill
, bool preserve_wait_time
)
427 Vehicle
*v
= Vehicle::GetIfValid(veh
);
428 if (v
== nullptr || !v
->IsPrimaryVehicle() || v
->orders
== nullptr) return CMD_ERROR
;
430 CommandCost ret
= CheckOwnership(v
->owner
);
431 if (ret
.Failed()) return ret
;
433 if (flags
& DC_EXEC
) {
435 /* Start autofilling the timetable, which clears the
436 * "timetable has started" bit. Times are not cleared anymore, but are
437 * overwritten when the order is reached now. */
438 SetBit(v
->vehicle_flags
, VF_AUTOFILL_TIMETABLE
);
439 ClrBit(v
->vehicle_flags
, VF_TIMETABLE_STARTED
);
441 /* Overwrite waiting times only if they got longer */
442 if (preserve_wait_time
) SetBit(v
->vehicle_flags
, VF_AUTOFILL_PRES_WAIT_TIME
);
444 v
->timetable_start
= 0;
445 v
->lateness_counter
= 0;
447 ClrBit(v
->vehicle_flags
, VF_AUTOFILL_TIMETABLE
);
448 ClrBit(v
->vehicle_flags
, VF_AUTOFILL_PRES_WAIT_TIME
);
451 for (Vehicle
*v2
= v
->FirstShared(); v2
!= nullptr; v2
= v2
->NextShared()) {
453 /* Stop autofilling; only one vehicle at a time can perform autofill */
454 ClrBit(v2
->vehicle_flags
, VF_AUTOFILL_TIMETABLE
);
455 ClrBit(v2
->vehicle_flags
, VF_AUTOFILL_PRES_WAIT_TIME
);
457 SetWindowDirty(WC_VEHICLE_TIMETABLE
, v2
->index
);
461 return CommandCost();
465 * Update the timetable for the vehicle.
466 * @param v The vehicle to update the timetable for.
467 * @param travelling Whether we just travelled or waited at a station.
469 void UpdateVehicleTimetable(Vehicle
*v
, bool travelling
)
471 TimerGameTick::Ticks time_taken
= v
->current_order_time
;
473 v
->current_order_time
= 0;
475 if (v
->current_order
.IsType(OT_IMPLICIT
)) return; // no timetabling of auto orders
477 if (v
->cur_real_order_index
>= v
->GetNumOrders()) return;
478 Order
*real_current_order
= v
->GetOrder(v
->cur_real_order_index
);
479 assert(real_current_order
!= nullptr);
481 VehicleOrderID first_manual_order
= 0;
482 for (Order
*o
= v
->GetFirstOrder(); o
!= nullptr && o
->IsType(OT_IMPLICIT
); o
= o
->next
) {
483 ++first_manual_order
;
486 bool just_started
= false;
488 /* This vehicle is arriving at the first destination in the timetable. */
489 if (v
->cur_real_order_index
== first_manual_order
&& travelling
) {
490 /* If the start date hasn't been set, or it was set automatically when
491 * the vehicle last arrived at the first destination, update it to the
492 * current time. Otherwise set the late counter appropriately to when
493 * the vehicle should have arrived. */
494 just_started
= !HasBit(v
->vehicle_flags
, VF_TIMETABLE_STARTED
);
496 if (v
->timetable_start
!= 0) {
497 v
->lateness_counter
= TimerGameTick::counter
- v
->timetable_start
;
498 v
->timetable_start
= 0;
501 SetBit(v
->vehicle_flags
, VF_TIMETABLE_STARTED
);
502 SetWindowDirty(WC_VEHICLE_TIMETABLE
, v
->index
);
505 if (!HasBit(v
->vehicle_flags
, VF_TIMETABLE_STARTED
)) return;
507 bool autofilling
= HasBit(v
->vehicle_flags
, VF_AUTOFILL_TIMETABLE
);
508 bool remeasure_wait_time
= !real_current_order
->IsWaitTimetabled() ||
509 (autofilling
&& !HasBit(v
->vehicle_flags
, VF_AUTOFILL_PRES_WAIT_TIME
));
511 if (travelling
&& remeasure_wait_time
) {
512 /* We just finished travelling and want to remeasure the loading time,
513 * so do not apply any restrictions for the loading to finish. */
514 v
->current_order
.SetWaitTime(0);
517 if (just_started
) return;
519 /* Before modifying waiting times, check whether we want to preserve bigger ones. */
520 if (!real_current_order
->IsType(OT_CONDITIONAL
) &&
521 (travelling
|| time_taken
> real_current_order
->GetWaitTime() || remeasure_wait_time
)) {
522 /* Round up to the smallest unit of time commonly shown in the GUI (seconds) to avoid confusion.
523 * Players timetabling in Ticks can adjust later.
524 * For trains/aircraft multiple movement cycles are done in one
525 * tick. This makes it possible to leave the station and process
526 * e.g. a depot order in the same tick, causing it to not fill
527 * the timetable entry like is done for road vehicles/ships.
528 * Thus always make sure at least one tick is used between the
529 * processing of different orders when filling the timetable. */
530 uint time_to_set
= CeilDiv(std::max(time_taken
, 1), Ticks::TICKS_PER_SECOND
) * Ticks::TICKS_PER_SECOND
;
532 if (travelling
&& (autofilling
|| !real_current_order
->IsTravelTimetabled())) {
533 ChangeTimetable(v
, v
->cur_real_order_index
, time_to_set
, MTF_TRAVEL_TIME
, autofilling
);
534 } else if (!travelling
&& (autofilling
|| !real_current_order
->IsWaitTimetabled())) {
535 ChangeTimetable(v
, v
->cur_real_order_index
, time_to_set
, MTF_WAIT_TIME
, autofilling
);
539 if (v
->cur_real_order_index
== first_manual_order
&& travelling
) {
540 /* If we just started we would have returned earlier and have not reached
541 * this code. So obviously, we have completed our round: So turn autofill
543 ClrBit(v
->vehicle_flags
, VF_AUTOFILL_TIMETABLE
);
544 ClrBit(v
->vehicle_flags
, VF_AUTOFILL_PRES_WAIT_TIME
);
547 if (autofilling
) return;
549 TimerGameTick::Ticks timetabled
= travelling
? real_current_order
->GetTimetabledTravel() :
550 real_current_order
->GetTimetabledWait();
552 /* Vehicles will wait at stations if they arrive early even if they are not
553 * timetabled to wait there, so make sure the lateness counter is updated
554 * when this happens. */
555 if (timetabled
== 0 && (travelling
|| v
->lateness_counter
>= 0)) return;
557 v
->lateness_counter
-= (timetabled
- time_taken
);
559 /* When we are more late than this timetabled bit takes we (somewhat expensively)
560 * check how many ticks the (fully filled) timetable has. If a timetable cycle is
561 * shorter than the amount of ticks we are late we reduce the lateness by the
562 * length of a full cycle till lateness is less than the length of a timetable
563 * cycle. When the timetable isn't fully filled the cycle will be Ticks::INVALID_TICKS. */
564 if (v
->lateness_counter
> timetabled
) {
565 TimerGameTick::Ticks cycle
= v
->orders
->GetTimetableTotalDuration();
566 if (cycle
!= Ticks::INVALID_TICKS
&& v
->lateness_counter
> cycle
) {
567 v
->lateness_counter
%= cycle
;
571 for (v
= v
->FirstShared(); v
!= nullptr; v
= v
->NextShared()) {
572 SetWindowDirty(WC_VEHICLE_TIMETABLE
, v
->index
);