4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
10 /** @file timetable_cmd.cpp Commands related to time tabling. */
13 #include "command_func.h"
14 #include "company_func.h"
15 #include "date_func.h"
16 #include "window_func.h"
17 #include "vehicle_base.h"
18 #include "cmd_helper.h"
19 #include "core/sort_func.hpp"
21 #include "table/strings.h"
23 #include "safeguards.h"
26 * Change/update a particular timetable entry.
27 * @param v The vehicle to change the timetable of.
28 * @param order_number The index of the timetable in the order list.
29 * @param val The new data of the timetable entry.
30 * @param mtf Which part of the timetable entry to change.
31 * @param timetabled If the new value is explicitly timetabled.
33 static void ChangeTimetable(Vehicle
*v
, VehicleOrderID order_number
, uint16 val
, ModifyTimetableFlags mtf
, bool timetabled
)
35 Order
*order
= v
->GetOrder(order_number
);
37 int timetable_delta
= 0;
41 total_delta
= val
- order
->GetWaitTime();
42 timetable_delta
= (timetabled
? val
: 0) - order
->GetTimetabledWait();
43 order
->SetWaitTime(val
);
44 order
->SetWaitTimetabled(timetabled
);
48 total_delta
= val
- order
->GetTravelTime();
49 timetable_delta
= (timetabled
? val
: 0) - order
->GetTimetabledTravel();
50 order
->SetTravelTime(val
);
51 order
->SetTravelTimetabled(timetabled
);
54 case MTF_TRAVEL_SPEED
:
55 order
->SetMaxSpeed(val
);
61 v
->orders
.list
->UpdateTotalDuration(total_delta
);
62 v
->orders
.list
->UpdateTimetableDuration(timetable_delta
);
64 for (v
= v
->FirstShared(); v
!= nullptr; v
= v
->NextShared()) {
65 if (v
->cur_real_order_index
== order_number
&& v
->current_order
.Equals(*order
)) {
68 v
->current_order
.SetWaitTime(val
);
69 v
->current_order
.SetWaitTimetabled(timetabled
);
73 v
->current_order
.SetTravelTime(val
);
74 v
->current_order
.SetTravelTimetabled(timetabled
);
77 case MTF_TRAVEL_SPEED
:
78 v
->current_order
.SetMaxSpeed(val
);
85 SetWindowDirty(WC_VEHICLE_TIMETABLE
, v
->index
);
90 * Change timetable data of an order.
91 * @param tile Not used.
92 * @param flags Operation to perform.
93 * @param p1 Various bitstuffed elements
94 * - p1 = (bit 0-19) - Vehicle with the orders to change.
95 * - p1 = (bit 20-27) - Order index to modify.
96 * - p1 = (bit 28-29) - Timetable data to change (@see ModifyTimetableFlags)
97 * @param p2 The amount of time to wait.
98 * - p2 = (bit 0-15) - The data to modify as specified by p1 bits 28-29.
99 * 0 to clear times, UINT16_MAX to clear speed limit.
101 * @return the cost of this operation or an error
103 CommandCost
CmdChangeTimetable(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
105 VehicleID veh
= GB(p1
, 0, 20);
107 Vehicle
*v
= Vehicle::GetIfValid(veh
);
108 if (v
== nullptr || !v
->IsPrimaryVehicle()) return CMD_ERROR
;
110 CommandCost ret
= CheckOwnership(v
->owner
);
111 if (ret
.Failed()) return ret
;
113 VehicleOrderID order_number
= GB(p1
, 20, 8);
114 Order
*order
= v
->GetOrder(order_number
);
115 if (order
== nullptr || order
->IsType(OT_IMPLICIT
)) return CMD_ERROR
;
117 ModifyTimetableFlags mtf
= Extract
<ModifyTimetableFlags
, 28, 2>(p1
);
118 if (mtf
>= MTF_END
) return CMD_ERROR
;
120 int wait_time
= order
->GetWaitTime();
121 int travel_time
= order
->GetTravelTime();
122 int max_speed
= order
->GetMaxSpeed();
125 wait_time
= GB(p2
, 0, 16);
128 case MTF_TRAVEL_TIME
:
129 travel_time
= GB(p2
, 0, 16);
132 case MTF_TRAVEL_SPEED
:
133 max_speed
= GB(p2
, 0, 16);
134 if (max_speed
== 0) max_speed
= UINT16_MAX
; // Disable speed limit.
141 if (wait_time
!= order
->GetWaitTime()) {
142 switch (order
->GetType()) {
143 case OT_GOTO_STATION
:
144 if (order
->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION
) return_cmd_error(STR_ERROR_TIMETABLE_NOT_STOPPING_HERE
);
150 default: return_cmd_error(STR_ERROR_TIMETABLE_ONLY_WAIT_AT_STATIONS
);
154 if (travel_time
!= order
->GetTravelTime() && order
->IsType(OT_CONDITIONAL
)) return CMD_ERROR
;
155 if (max_speed
!= order
->GetMaxSpeed() && (order
->IsType(OT_CONDITIONAL
) || v
->type
== VEH_AIRCRAFT
)) return CMD_ERROR
;
157 if (flags
& DC_EXEC
) {
160 /* Set time if changing the value or confirming an estimated time as timetabled. */
161 if (wait_time
!= order
->GetWaitTime() || (wait_time
> 0 && !order
->IsWaitTimetabled())) {
162 ChangeTimetable(v
, order_number
, wait_time
, MTF_WAIT_TIME
, wait_time
> 0);
166 case MTF_TRAVEL_TIME
:
167 /* Set time if changing the value or confirming an estimated time as timetabled. */
168 if (travel_time
!= order
->GetTravelTime() || (travel_time
> 0 && !order
->IsTravelTimetabled())) {
169 ChangeTimetable(v
, order_number
, travel_time
, MTF_TRAVEL_TIME
, travel_time
> 0);
173 case MTF_TRAVEL_SPEED
:
174 if (max_speed
!= order
->GetMaxSpeed()) {
175 ChangeTimetable(v
, order_number
, max_speed
, MTF_TRAVEL_SPEED
, max_speed
!= UINT16_MAX
);
184 return CommandCost();
188 * Clear the lateness counter to make the vehicle on time.
189 * @param tile Not used.
190 * @param flags Operation to perform.
191 * @param p1 Various bitstuffed elements
192 * - p1 = (bit 0-19) - Vehicle with the orders to change.
195 * @return the cost of this operation or an error
197 CommandCost
CmdSetVehicleOnTime(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
199 VehicleID veh
= GB(p1
, 0, 20);
201 Vehicle
*v
= Vehicle::GetIfValid(veh
);
202 if (v
== nullptr || !v
->IsPrimaryVehicle() || v
->orders
.list
== nullptr) return CMD_ERROR
;
204 CommandCost ret
= CheckOwnership(v
->owner
);
205 if (ret
.Failed()) return ret
;
207 if (flags
& DC_EXEC
) {
208 v
->lateness_counter
= 0;
209 SetWindowDirty(WC_VEHICLE_TIMETABLE
, v
->index
);
212 return CommandCost();
216 * Order vehicles based on their timetable. The vehicles will be sorted in order
217 * they would reach the first station.
219 * @param ap First Vehicle pointer.
220 * @param bp Second Vehicle pointer.
221 * @return Comparison value.
223 static int CDECL
VehicleTimetableSorter(Vehicle
* const *ap
, Vehicle
* const *bp
)
225 const Vehicle
*a
= *ap
;
226 const Vehicle
*b
= *bp
;
228 VehicleOrderID a_order
= a
->cur_real_order_index
;
229 VehicleOrderID b_order
= b
->cur_real_order_index
;
230 int j
= (int)b_order
- (int)a_order
;
232 /* Are we currently at an ordered station (un)loading? */
233 bool a_load
= a
->current_order
.IsType(OT_LOADING
) && a
->current_order
.GetNonStopType() != ONSF_STOP_EVERYWHERE
;
234 bool b_load
= b
->current_order
.IsType(OT_LOADING
) && b
->current_order
.GetNonStopType() != ONSF_STOP_EVERYWHERE
;
236 /* If the current order is not loading at the ordered station, decrease the order index by one since we have
237 * not yet arrived at the station (and thus the timetable entry; still in the travelling of the previous one).
238 * Since the ?_order variables are unsigned the -1 will flow under and place the vehicles going to order #0 at
239 * the begin of the list with vehicles arriving at #0. */
240 if (!a_load
) a_order
--;
241 if (!b_load
) b_order
--;
243 /* First check the order index that accounted for loading, then just the raw one. */
244 int i
= (int)b_order
- (int)a_order
;
245 if (i
!= 0) return i
;
246 if (j
!= 0) return j
;
248 /* Look at the time we spent in this order; the higher, the closer to its destination. */
249 i
= b
->current_order_time
- a
->current_order_time
;
250 if (i
!= 0) return i
;
252 /* If all else is equal, use some unique index to sort it the same way. */
253 return b
->unitnumber
- a
->unitnumber
;
257 * Set the start date of the timetable.
258 * @param tile Not used.
259 * @param flags Operation to perform.
260 * @param p2 Various bitstuffed elements
261 * - p2 = (bit 0-19) - Vehicle ID.
262 * - p2 = (bit 20) - Set to 1 to set timetable start for all vehicles sharing this order
263 * @param p2 The timetable start date.
264 * @param text Not used.
265 * @return The error or cost of the operation.
267 CommandCost
CmdSetTimetableStart(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
269 bool timetable_all
= HasBit(p1
, 20);
270 Vehicle
*v
= Vehicle::GetIfValid(GB(p1
, 0, 20));
271 if (v
== nullptr || !v
->IsPrimaryVehicle() || v
->orders
.list
== nullptr) return CMD_ERROR
;
273 CommandCost ret
= CheckOwnership(v
->owner
);
274 if (ret
.Failed()) return ret
;
276 /* Don't let a timetable start more than 15 years into the future or 1 year in the past. */
277 Date start_date
= (Date
)p2
;
278 if (start_date
< 0 || start_date
> MAX_DAY
) return CMD_ERROR
;
279 if (start_date
- _date
> 15 * DAYS_IN_LEAP_YEAR
) return CMD_ERROR
;
280 if (_date
- start_date
> DAYS_IN_LEAP_YEAR
) return CMD_ERROR
;
281 if (timetable_all
&& !v
->orders
.list
->IsCompleteTimetable()) return CMD_ERROR
;
283 if (flags
& DC_EXEC
) {
284 std::vector
<Vehicle
*> vehs
;
287 for (Vehicle
*w
= v
->orders
.list
->GetFirstSharedVehicle(); w
!= nullptr; w
= w
->NextShared()) {
294 int total_duration
= v
->orders
.list
->GetTimetableTotalDuration();
295 int num_vehs
= (uint
)vehs
.size();
298 QSortT(vehs
.data(), vehs
.size(), &VehicleTimetableSorter
);
301 int idx
= vehs
.begin() - std::find(vehs
.begin(), vehs
.end(), v
);
303 for (Vehicle
*w
: vehs
) {
305 w
->lateness_counter
= 0;
306 ClrBit(w
->vehicle_flags
, VF_TIMETABLE_STARTED
);
307 /* Do multiplication, then division to reduce rounding errors. */
308 w
->timetable_start
= start_date
+ idx
* total_duration
/ num_vehs
/ DAY_TICKS
;
309 SetWindowDirty(WC_VEHICLE_TIMETABLE
, w
->index
);
315 return CommandCost();
320 * Start or stop filling the timetable automatically from the time the vehicle
321 * actually takes to complete it. When starting to autofill the current times
322 * are cleared and the timetable will start again from scratch.
323 * @param tile Not used.
324 * @param flags Operation to perform.
325 * @param p1 Vehicle index.
326 * @param p2 Various bitstuffed elements
327 * - p2 = (bit 0) - Set to 1 to enable, 0 to disable autofill.
328 * - p2 = (bit 1) - Set to 1 to preserve waiting times in non-destructive mode
330 * @return the cost of this operation or an error
332 CommandCost
CmdAutofillTimetable(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
334 VehicleID veh
= GB(p1
, 0, 20);
336 Vehicle
*v
= Vehicle::GetIfValid(veh
);
337 if (v
== nullptr || !v
->IsPrimaryVehicle() || v
->orders
.list
== nullptr) return CMD_ERROR
;
339 CommandCost ret
= CheckOwnership(v
->owner
);
340 if (ret
.Failed()) return ret
;
342 if (flags
& DC_EXEC
) {
344 /* Start autofilling the timetable, which clears the
345 * "timetable has started" bit. Times are not cleared anymore, but are
346 * overwritten when the order is reached now. */
347 SetBit(v
->vehicle_flags
, VF_AUTOFILL_TIMETABLE
);
348 ClrBit(v
->vehicle_flags
, VF_TIMETABLE_STARTED
);
350 /* Overwrite waiting times only if they got longer */
351 if (HasBit(p2
, 1)) SetBit(v
->vehicle_flags
, VF_AUTOFILL_PRES_WAIT_TIME
);
353 v
->timetable_start
= 0;
354 v
->lateness_counter
= 0;
356 ClrBit(v
->vehicle_flags
, VF_AUTOFILL_TIMETABLE
);
357 ClrBit(v
->vehicle_flags
, VF_AUTOFILL_PRES_WAIT_TIME
);
360 for (Vehicle
*v2
= v
->FirstShared(); v2
!= nullptr; v2
= v2
->NextShared()) {
362 /* Stop autofilling; only one vehicle at a time can perform autofill */
363 ClrBit(v2
->vehicle_flags
, VF_AUTOFILL_TIMETABLE
);
364 ClrBit(v2
->vehicle_flags
, VF_AUTOFILL_PRES_WAIT_TIME
);
366 SetWindowDirty(WC_VEHICLE_TIMETABLE
, v2
->index
);
370 return CommandCost();
374 * Update the timetable for the vehicle.
375 * @param v The vehicle to update the timetable for.
376 * @param travelling Whether we just travelled or waited at a station.
378 void UpdateVehicleTimetable(Vehicle
*v
, bool travelling
)
380 uint time_taken
= v
->current_order_time
;
382 v
->current_order_time
= 0;
384 if (v
->current_order
.IsType(OT_IMPLICIT
)) return; // no timetabling of auto orders
386 if (v
->cur_real_order_index
>= v
->GetNumOrders()) return;
387 Order
*real_current_order
= v
->GetOrder(v
->cur_real_order_index
);
389 VehicleOrderID first_manual_order
= 0;
390 for (Order
*o
= v
->GetFirstOrder(); o
!= nullptr && o
->IsType(OT_IMPLICIT
); o
= o
->next
) {
391 ++first_manual_order
;
394 bool just_started
= false;
396 /* This vehicle is arriving at the first destination in the timetable. */
397 if (v
->cur_real_order_index
== first_manual_order
&& travelling
) {
398 /* If the start date hasn't been set, or it was set automatically when
399 * the vehicle last arrived at the first destination, update it to the
400 * current time. Otherwise set the late counter appropriately to when
401 * the vehicle should have arrived. */
402 just_started
= !HasBit(v
->vehicle_flags
, VF_TIMETABLE_STARTED
);
404 if (v
->timetable_start
!= 0) {
405 v
->lateness_counter
= (_date
- v
->timetable_start
) * DAY_TICKS
+ _date_fract
;
406 v
->timetable_start
= 0;
409 SetBit(v
->vehicle_flags
, VF_TIMETABLE_STARTED
);
410 SetWindowDirty(WC_VEHICLE_TIMETABLE
, v
->index
);
413 if (!HasBit(v
->vehicle_flags
, VF_TIMETABLE_STARTED
)) return;
415 bool autofilling
= HasBit(v
->vehicle_flags
, VF_AUTOFILL_TIMETABLE
);
416 bool remeasure_wait_time
= !real_current_order
->IsWaitTimetabled() ||
417 (autofilling
&& !HasBit(v
->vehicle_flags
, VF_AUTOFILL_PRES_WAIT_TIME
));
419 if (travelling
&& remeasure_wait_time
) {
420 /* We just finished travelling and want to remeasure the loading time,
421 * so do not apply any restrictions for the loading to finish. */
422 v
->current_order
.SetWaitTime(0);
425 if (just_started
) return;
427 /* Before modifying waiting times, check whether we want to preserve bigger ones. */
428 if (!real_current_order
->IsType(OT_CONDITIONAL
) &&
429 (travelling
|| time_taken
> real_current_order
->GetWaitTime() || remeasure_wait_time
)) {
430 /* Round the time taken up to the nearest day, as this will avoid
431 * confusion for people who are timetabling in days, and can be
432 * adjusted later by people who aren't.
433 * For trains/aircraft multiple movement cycles are done in one
434 * tick. This makes it possible to leave the station and process
435 * e.g. a depot order in the same tick, causing it to not fill
436 * the timetable entry like is done for road vehicles/ships.
437 * Thus always make sure at least one tick is used between the
438 * processing of different orders when filling the timetable. */
439 uint time_to_set
= CeilDiv(max(time_taken
, 1U), DAY_TICKS
) * DAY_TICKS
;
441 if (travelling
&& (autofilling
|| !real_current_order
->IsTravelTimetabled())) {
442 ChangeTimetable(v
, v
->cur_real_order_index
, time_to_set
, MTF_TRAVEL_TIME
, autofilling
);
443 } else if (!travelling
&& (autofilling
|| !real_current_order
->IsWaitTimetabled())) {
444 ChangeTimetable(v
, v
->cur_real_order_index
, time_to_set
, MTF_WAIT_TIME
, autofilling
);
448 if (v
->cur_real_order_index
== first_manual_order
&& travelling
) {
449 /* If we just started we would have returned earlier and have not reached
450 * this code. So obviously, we have completed our round: So turn autofill
452 ClrBit(v
->vehicle_flags
, VF_AUTOFILL_TIMETABLE
);
453 ClrBit(v
->vehicle_flags
, VF_AUTOFILL_PRES_WAIT_TIME
);
456 if (autofilling
) return;
458 uint timetabled
= travelling
? real_current_order
->GetTimetabledTravel() :
459 real_current_order
->GetTimetabledWait();
461 /* Vehicles will wait at stations if they arrive early even if they are not
462 * timetabled to wait there, so make sure the lateness counter is updated
463 * when this happens. */
464 if (timetabled
== 0 && (travelling
|| v
->lateness_counter
>= 0)) return;
466 v
->lateness_counter
-= (timetabled
- time_taken
);
468 /* When we are more late than this timetabled bit takes we (somewhat expensively)
469 * check how many ticks the (fully filled) timetable has. If a timetable cycle is
470 * shorter than the amount of ticks we are late we reduce the lateness by the
471 * length of a full cycle till lateness is less than the length of a timetable
472 * cycle. When the timetable isn't fully filled the cycle will be INVALID_TICKS. */
473 if (v
->lateness_counter
> (int)timetabled
) {
474 Ticks cycle
= v
->orders
.list
->GetTimetableTotalDuration();
475 if (cycle
!= INVALID_TICKS
&& v
->lateness_counter
> cycle
) {
476 v
->lateness_counter
%= cycle
;
480 for (v
= v
->FirstShared(); v
!= nullptr; v
= v
->NextShared()) {
481 SetWindowDirty(WC_VEHICLE_TIMETABLE
, v
->index
);