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"
24 * Change/update a particular timetable entry.
25 * @param v The vehicle to change the timetable of.
26 * @param order_number The index of the timetable in the order list.
27 * @param val The new data of the timetable entry.
28 * @param mtf Which part of the timetable entry to change.
29 * @param timetabled If the new value is explicitly timetabled.
31 static void ChangeTimetable(Vehicle
*v
, VehicleOrderID order_number
, uint16 val
, ModifyTimetableFlags mtf
, bool timetabled
)
33 Order
*order
= v
->GetOrder(order_number
);
35 int timetable_delta
= 0;
39 total_delta
= val
- order
->GetWaitTime();
40 timetable_delta
= (timetabled
? val
: 0) - order
->GetTimetabledWait();
41 order
->SetWaitTime(val
);
42 order
->SetWaitTimetabled(timetabled
);
46 total_delta
= val
- order
->GetTravelTime();
47 timetable_delta
= (timetabled
? val
: 0) - order
->GetTimetabledTravel();
48 order
->SetTravelTime(val
);
49 order
->SetTravelTimetabled(timetabled
);
52 case MTF_TRAVEL_SPEED
:
53 order
->SetMaxSpeed(val
);
59 v
->orders
.list
->UpdateTotalDuration(total_delta
);
60 v
->orders
.list
->UpdateTimetableDuration(timetable_delta
);
62 for (v
= v
->FirstShared(); v
!= NULL
; v
= v
->NextShared()) {
63 if (v
->cur_real_order_index
== order_number
&& v
->current_order
.Equals(*order
)) {
66 v
->current_order
.SetWaitTime(val
);
67 v
->current_order
.SetWaitTimetabled(timetabled
);
71 v
->current_order
.SetTravelTime(val
);
72 v
->current_order
.SetTravelTimetabled(timetabled
);
75 case MTF_TRAVEL_SPEED
:
76 v
->current_order
.SetMaxSpeed(val
);
83 SetWindowDirty(WC_VEHICLE_TIMETABLE
, v
->index
);
88 * Change timetable data of an order.
89 * @param tile Not used.
90 * @param flags Operation to perform.
91 * @param p1 Various bitstuffed elements
92 * - p1 = (bit 0-19) - Vehicle with the orders to change.
93 * - p1 = (bit 20-27) - Order index to modify.
94 * - p1 = (bit 28-29) - Timetable data to change (@see ModifyTimetableFlags)
95 * @param p2 The amount of time to wait.
96 * - p2 = (bit 0-15) - The data to modify as specified by p1 bits 28-29.
97 * 0 to clear times, UINT16_MAX to clear speed limit.
99 * @return the cost of this operation or an error
101 CommandCost
CmdChangeTimetable(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
103 VehicleID veh
= GB(p1
, 0, 20);
105 Vehicle
*v
= Vehicle::GetIfValid(veh
);
106 if (v
== NULL
|| !v
->IsPrimaryVehicle()) return CMD_ERROR
;
108 CommandCost ret
= CheckOwnership(v
->owner
);
109 if (ret
.Failed()) return ret
;
111 VehicleOrderID order_number
= GB(p1
, 20, 8);
112 Order
*order
= v
->GetOrder(order_number
);
113 if (order
== NULL
|| order
->IsType(OT_IMPLICIT
)) return CMD_ERROR
;
115 ModifyTimetableFlags mtf
= Extract
<ModifyTimetableFlags
, 28, 2>(p1
);
117 case MTF_WAIT_TIME
: {
118 int wait_time
= GB(p2
, 0, 16);
120 if (wait_time
!= order
->GetWaitTime()) {
121 switch (order
->GetType()) {
122 case OT_GOTO_STATION
:
123 if (order
->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION
) return_cmd_error(STR_ERROR_TIMETABLE_NOT_STOPPING_HERE
);
129 default: return_cmd_error(STR_ERROR_TIMETABLE_ONLY_WAIT_AT_STATIONS
);
133 if (flags
& DC_EXEC
) {
134 /* Set time if changing the value or confirming an estimated time as timetabled. */
135 if (wait_time
!= order
->GetWaitTime() || (wait_time
> 0 && !order
->IsWaitTimetabled())) {
136 ChangeTimetable(v
, order_number
, wait_time
, MTF_WAIT_TIME
, wait_time
> 0);
142 case MTF_TRAVEL_TIME
: {
143 int travel_time
= GB(p2
, 0, 16);
145 if (travel_time
!= order
->GetTravelTime() && order
->IsType(OT_CONDITIONAL
)) return CMD_ERROR
;
147 if (flags
& DC_EXEC
) {
148 /* Set time if changing the value or confirming an estimated time as timetabled. */
149 if (travel_time
!= order
->GetTravelTime() || (travel_time
> 0 && !order
->IsTravelTimetabled())) {
150 ChangeTimetable(v
, order_number
, travel_time
, MTF_TRAVEL_TIME
, travel_time
> 0);
156 case MTF_TRAVEL_SPEED
: {
157 int max_speed
= GB(p2
, 0, 16);
158 if (max_speed
== 0) max_speed
= UINT16_MAX
; // Disable speed limit.
160 if (max_speed
!= order
->GetMaxSpeed() && (order
->IsType(OT_CONDITIONAL
) || v
->type
== VEH_AIRCRAFT
)) return CMD_ERROR
;
162 if (flags
& DC_EXEC
) {
163 if (max_speed
!= order
->GetMaxSpeed()) {
164 ChangeTimetable(v
, order_number
, max_speed
, MTF_TRAVEL_SPEED
, max_speed
!= UINT16_MAX
);
175 return CommandCost();
179 * Clear the lateness counter to make the vehicle on time.
180 * @param tile Not used.
181 * @param flags Operation to perform.
182 * @param p1 Various bitstuffed elements
183 * - p1 = (bit 0-19) - Vehicle with the orders to change.
186 * @return the cost of this operation or an error
188 CommandCost
CmdSetVehicleOnTime(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
190 VehicleID veh
= GB(p1
, 0, 20);
192 Vehicle
*v
= Vehicle::GetIfValid(veh
);
193 if (v
== NULL
|| !v
->IsPrimaryVehicle() || v
->orders
.list
== NULL
) return CMD_ERROR
;
195 CommandCost ret
= CheckOwnership(v
->owner
);
196 if (ret
.Failed()) return ret
;
198 if (flags
& DC_EXEC
) {
199 v
->lateness_counter
= 0;
200 SetWindowDirty(WC_VEHICLE_TIMETABLE
, v
->index
);
203 return CommandCost();
207 * Order vehicles based on their timetable. The vehicles will be sorted in order
208 * they would reach the first station.
210 * @param ap First Vehicle pointer.
211 * @param bp Second Vehicle pointer.
212 * @return Comparison value.
214 static int CDECL
VehicleTimetableSorter(Vehicle
* const *ap
, Vehicle
* const *bp
)
216 const Vehicle
*a
= *ap
;
217 const Vehicle
*b
= *bp
;
219 VehicleOrderID a_order
= a
->cur_real_order_index
;
220 VehicleOrderID b_order
= b
->cur_real_order_index
;
221 int j
= (int)b_order
- (int)a_order
;
223 /* Are we currently at an ordered station (un)loading? */
224 bool a_load
= a
->current_order
.IsType(OT_LOADING
) && a
->current_order
.GetNonStopType() != ONSF_STOP_EVERYWHERE
;
225 bool b_load
= b
->current_order
.IsType(OT_LOADING
) && b
->current_order
.GetNonStopType() != ONSF_STOP_EVERYWHERE
;
227 /* If the current order is not loading at the ordered station, decrease the order index by one since we have
228 * not yet arrived at the station (and thus the timetable entry; still in the travelling of the previous one).
229 * Since the ?_order variables are unsigned the -1 will flow under and place the vehicles going to order #0 at
230 * the begin of the list with vehicles arriving at #0. */
231 if (!a_load
) a_order
--;
232 if (!b_load
) b_order
--;
234 /* First check the order index that accounted for loading, then just the raw one. */
235 int i
= (int)b_order
- (int)a_order
;
236 if (i
!= 0) return i
;
237 if (j
!= 0) return j
;
239 /* Look at the time we spent in this order; the higher, the closer to its destination. */
240 i
= b
->current_order_time
- a
->current_order_time
;
241 if (i
!= 0) return i
;
243 /* If all else is equal, use some unique index to sort it the same way. */
244 return b
->unitnumber
- a
->unitnumber
;
248 * Set the start date of the timetable.
249 * @param tile Not used.
250 * @param flags Operation to perform.
251 * @param p2 Various bitstuffed elements
252 * - p2 = (bit 0-19) - Vehicle ID.
253 * - p2 = (bit 20) - Set to 1 to set timetable start for all vehicles sharing this order
254 * @param p2 The timetable start date.
255 * @param text Not used.
256 * @return The error or cost of the operation.
258 CommandCost
CmdSetTimetableStart(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
260 bool timetable_all
= HasBit(p1
, 20);
261 Vehicle
*v
= Vehicle::GetIfValid(GB(p1
, 0, 20));
262 if (v
== NULL
|| !v
->IsPrimaryVehicle() || v
->orders
.list
== NULL
) return CMD_ERROR
;
264 CommandCost ret
= CheckOwnership(v
->owner
);
265 if (ret
.Failed()) return ret
;
267 /* Don't let a timetable start more than 15 years into the future or 1 year in the past. */
268 Date start_date
= (Date
)p2
;
269 if (start_date
< 0 || start_date
> MAX_DAY
) return CMD_ERROR
;
270 if (start_date
- _date
> 15 * DAYS_IN_LEAP_YEAR
) return CMD_ERROR
;
271 if (_date
- start_date
> DAYS_IN_LEAP_YEAR
) return CMD_ERROR
;
272 if (timetable_all
&& !v
->orders
.list
->IsCompleteTimetable()) return CMD_ERROR
;
274 if (flags
& DC_EXEC
) {
275 SmallVector
<Vehicle
*, 8> vehs
;
278 for (Vehicle
*w
= v
->orders
.list
->GetFirstSharedVehicle(); w
!= NULL
; w
= w
->NextShared()) {
285 int total_duration
= v
->orders
.list
->GetTimetableTotalDuration();
286 int num_vehs
= vehs
.Length();
289 QSortT(vehs
.Begin(), vehs
.Length(), &VehicleTimetableSorter
);
292 int base
= vehs
.FindIndex(v
);
294 for (Vehicle
**viter
= vehs
.Begin(); viter
!= vehs
.End(); viter
++) {
295 int idx
= (viter
- vehs
.Begin()) - base
;
298 w
->lateness_counter
= 0;
299 ClrBit(w
->vehicle_flags
, VF_TIMETABLE_STARTED
);
300 /* Do multiplication, then division to reduce rounding errors. */
301 w
->timetable_start
= start_date
+ idx
* total_duration
/ num_vehs
/ DAY_TICKS
;
302 SetWindowDirty(WC_VEHICLE_TIMETABLE
, w
->index
);
307 return CommandCost();
312 * Start or stop filling the timetable automatically from the time the vehicle
313 * actually takes to complete it. When starting to autofill the current times
314 * are cleared and the timetable will start again from scratch.
315 * @param tile Not used.
316 * @param flags Operation to perform.
317 * @param p1 Vehicle index.
318 * @param p2 Various bitstuffed elements
319 * - p2 = (bit 0) - Set to 1 to enable, 0 to disable autofill.
320 * - p2 = (bit 1) - Set to 1 to preserve waiting times in non-destructive mode
322 * @return the cost of this operation or an error
324 CommandCost
CmdAutofillTimetable(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
326 VehicleID veh
= GB(p1
, 0, 20);
328 Vehicle
*v
= Vehicle::GetIfValid(veh
);
329 if (v
== NULL
|| !v
->IsPrimaryVehicle() || v
->orders
.list
== NULL
) return CMD_ERROR
;
331 CommandCost ret
= CheckOwnership(v
->owner
);
332 if (ret
.Failed()) return ret
;
334 if (flags
& DC_EXEC
) {
336 /* Start autofilling the timetable, which clears the
337 * "timetable has started" bit. Times are not cleared anymore, but are
338 * overwritten when the order is reached now. */
339 SetBit(v
->vehicle_flags
, VF_AUTOFILL_TIMETABLE
);
340 ClrBit(v
->vehicle_flags
, VF_TIMETABLE_STARTED
);
342 /* Overwrite waiting times only if they got longer */
343 if (HasBit(p2
, 1)) SetBit(v
->vehicle_flags
, VF_AUTOFILL_PRES_WAIT_TIME
);
345 v
->timetable_start
= 0;
346 v
->lateness_counter
= 0;
348 ClrBit(v
->vehicle_flags
, VF_AUTOFILL_TIMETABLE
);
349 ClrBit(v
->vehicle_flags
, VF_AUTOFILL_PRES_WAIT_TIME
);
352 for (Vehicle
*v2
= v
->FirstShared(); v2
!= NULL
; v2
= v2
->NextShared()) {
354 /* Stop autofilling; only one vehicle at a time can perform autofill */
355 ClrBit(v2
->vehicle_flags
, VF_AUTOFILL_TIMETABLE
);
356 ClrBit(v2
->vehicle_flags
, VF_AUTOFILL_PRES_WAIT_TIME
);
358 SetWindowDirty(WC_VEHICLE_TIMETABLE
, v2
->index
);
362 return CommandCost();
366 * Update the timetable for the vehicle.
367 * @param v The vehicle to update the timetable for.
368 * @param travelling Whether we just travelled or waited at a station.
370 void UpdateVehicleTimetable(Vehicle
*v
, bool travelling
)
372 uint time_taken
= v
->current_order_time
;
374 v
->current_order_time
= 0;
376 if (v
->current_order
.IsType(OT_IMPLICIT
)) return; // no timetabling of auto orders
378 if (v
->cur_real_order_index
>= v
->GetNumOrders()) return;
379 Order
*real_current_order
= v
->GetOrder(v
->cur_real_order_index
);
381 VehicleOrderID first_manual_order
= 0;
382 for (Order
*o
= v
->GetFirstOrder(); o
!= NULL
&& o
->IsType(OT_IMPLICIT
); o
= o
->next
) {
383 ++first_manual_order
;
386 bool just_started
= false;
388 /* This vehicle is arriving at the first destination in the timetable. */
389 if (v
->cur_real_order_index
== first_manual_order
&& travelling
) {
390 /* If the start date hasn't been set, or it was set automatically when
391 * the vehicle last arrived at the first destination, update it to the
392 * current time. Otherwise set the late counter appropriately to when
393 * the vehicle should have arrived. */
394 just_started
= !HasBit(v
->vehicle_flags
, VF_TIMETABLE_STARTED
);
396 if (v
->timetable_start
!= 0) {
397 v
->lateness_counter
= (_date
- v
->timetable_start
) * DAY_TICKS
+ _date_fract
;
398 v
->timetable_start
= 0;
401 SetBit(v
->vehicle_flags
, VF_TIMETABLE_STARTED
);
402 SetWindowDirty(WC_VEHICLE_TIMETABLE
, v
->index
);
405 if (!HasBit(v
->vehicle_flags
, VF_TIMETABLE_STARTED
)) return;
407 bool autofilling
= HasBit(v
->vehicle_flags
, VF_AUTOFILL_TIMETABLE
);
408 bool remeasure_wait_time
= !real_current_order
->IsWaitTimetabled() ||
409 (autofilling
&& !HasBit(v
->vehicle_flags
, VF_AUTOFILL_PRES_WAIT_TIME
));
411 if (travelling
&& remeasure_wait_time
) {
412 /* We just finished travelling and want to remeasure the loading time,
413 * so do not apply any restrictions for the loading to finish. */
414 v
->current_order
.SetWaitTime(0);
417 if (just_started
) return;
419 /* Before modifying waiting times, check whether we want to preserve bigger ones. */
420 if (!real_current_order
->IsType(OT_CONDITIONAL
) &&
421 (travelling
|| time_taken
> real_current_order
->GetWaitTime() || remeasure_wait_time
)) {
422 /* Round the time taken up to the nearest day, as this will avoid
423 * confusion for people who are timetabling in days, and can be
424 * adjusted later by people who aren't.
425 * For trains/aircraft multiple movement cycles are done in one
426 * tick. This makes it possible to leave the station and process
427 * e.g. a depot order in the same tick, causing it to not fill
428 * the timetable entry like is done for road vehicles/ships.
429 * Thus always make sure at least one tick is used between the
430 * processing of different orders when filling the timetable. */
431 uint time_to_set
= CeilDiv(max(time_taken
, 1U), DAY_TICKS
) * DAY_TICKS
;
433 if (travelling
&& (autofilling
|| !real_current_order
->IsTravelTimetabled())) {
434 ChangeTimetable(v
, v
->cur_real_order_index
, time_to_set
, MTF_TRAVEL_TIME
, autofilling
);
435 } else if (!travelling
&& (autofilling
|| !real_current_order
->IsWaitTimetabled())) {
436 ChangeTimetable(v
, v
->cur_real_order_index
, time_to_set
, MTF_WAIT_TIME
, autofilling
);
440 if (v
->cur_real_order_index
== first_manual_order
&& travelling
) {
441 /* If we just started we would have returned earlier and have not reached
442 * this code. So obviously, we have completed our round: So turn autofill
444 ClrBit(v
->vehicle_flags
, VF_AUTOFILL_TIMETABLE
);
445 ClrBit(v
->vehicle_flags
, VF_AUTOFILL_PRES_WAIT_TIME
);
448 if (autofilling
) return;
450 uint timetabled
= travelling
? real_current_order
->GetTimetabledTravel() :
451 real_current_order
->GetTimetabledWait();
453 /* Vehicles will wait at stations if they arrive early even if they are not
454 * timetabled to wait there, so make sure the lateness counter is updated
455 * when this happens. */
456 if (timetabled
== 0 && (travelling
|| v
->lateness_counter
>= 0)) return;
458 v
->lateness_counter
-= (timetabled
- time_taken
);
460 /* When we are more late than this timetabled bit takes we (somewhat expensively)
461 * check how many ticks the (fully filled) timetable has. If a timetable cycle is
462 * shorter than the amount of ticks we are late we reduce the lateness by the
463 * length of a full cycle till lateness is less than the length of a timetable
464 * cycle. When the timetable isn't fully filled the cycle will be INVALID_TICKS. */
465 if (v
->lateness_counter
> (int)timetabled
) {
466 Ticks cycle
= v
->orders
.list
->GetTimetableTotalDuration();
467 if (cycle
!= INVALID_TICKS
&& v
->lateness_counter
> cycle
) {
468 v
->lateness_counter
%= cycle
;
472 for (v
= v
->FirstShared(); v
!= NULL
; v
= v
->NextShared()) {
473 SetWindowDirty(WC_VEHICLE_TIMETABLE
, v
->index
);