1 /*
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/>.
6  */
7 
8 /** @file timetable_cmd.cpp Commands related to time tabling. */
9 
10 #include "stdafx.h"
11 #include "command_func.h"
12 #include "company_func.h"
13 #include "date_func.h"
14 #include "window_func.h"
15 #include "vehicle_base.h"
16 #include "cmd_helper.h"
17 
18 #include "table/strings.h"
19 
20 #include "safeguards.h"
21 
22 /**
23  * Change/update a particular timetable entry.
24  * @param v            The vehicle to change the timetable of.
25  * @param order_number The index of the timetable in the order list.
26  * @param val          The new data of the timetable entry.
27  * @param mtf          Which part of the timetable entry to change.
28  * @param timetabled   If the new value is explicitly timetabled.
29  */
ChangeTimetable(Vehicle * v,VehicleOrderID order_number,uint16 val,ModifyTimetableFlags mtf,bool timetabled)30 static void ChangeTimetable(Vehicle *v, VehicleOrderID order_number, uint16 val, ModifyTimetableFlags mtf, bool timetabled)
31 {
32 	Order *order = v->GetOrder(order_number);
33 	int total_delta = 0;
34 	int timetable_delta = 0;
35 
36 	switch (mtf) {
37 		case MTF_WAIT_TIME:
38 			total_delta = val - order->GetWaitTime();
39 			timetable_delta = (timetabled ? val : 0) - order->GetTimetabledWait();
40 			order->SetWaitTime(val);
41 			order->SetWaitTimetabled(timetabled);
42 			break;
43 
44 		case MTF_TRAVEL_TIME:
45 			total_delta = val - order->GetTravelTime();
46 			timetable_delta = (timetabled ? val : 0) - order->GetTimetabledTravel();
47 			order->SetTravelTime(val);
48 			order->SetTravelTimetabled(timetabled);
49 			break;
50 
51 		case MTF_TRAVEL_SPEED:
52 			order->SetMaxSpeed(val);
53 			break;
54 
55 		default:
56 			NOT_REACHED();
57 	}
58 	v->orders.list->UpdateTotalDuration(total_delta);
59 	v->orders.list->UpdateTimetableDuration(timetable_delta);
60 
61 	for (v = v->FirstShared(); v != nullptr; v = v->NextShared()) {
62 		if (v->cur_real_order_index == order_number && v->current_order.Equals(*order)) {
63 			switch (mtf) {
64 				case MTF_WAIT_TIME:
65 					v->current_order.SetWaitTime(val);
66 					v->current_order.SetWaitTimetabled(timetabled);
67 					break;
68 
69 				case MTF_TRAVEL_TIME:
70 					v->current_order.SetTravelTime(val);
71 					v->current_order.SetTravelTimetabled(timetabled);
72 					break;
73 
74 				case MTF_TRAVEL_SPEED:
75 					v->current_order.SetMaxSpeed(val);
76 					break;
77 
78 				default:
79 					NOT_REACHED();
80 			}
81 		}
82 		SetWindowDirty(WC_VEHICLE_TIMETABLE, v->index);
83 	}
84 }
85 
86 /**
87  * Change timetable data of an order.
88  * @param tile Not used.
89  * @param flags Operation to perform.
90  * @param p1 Various bitstuffed elements
91  * - p1 = (bit  0-19) - Vehicle with the orders to change.
92  * - p1 = (bit 20-27) - Order index to modify.
93  * - p1 = (bit 28-29) - Timetable data to change (@see ModifyTimetableFlags)
94  * @param p2 The amount of time to wait.
95  * - p2 = (bit  0-15) - The data to modify as specified by p1 bits 28-29.
96  *                      0 to clear times, UINT16_MAX to clear speed limit.
97  * @param text unused
98  * @return the cost of this operation or an error
99  */
CmdChangeTimetable(TileIndex tile,DoCommandFlag flags,uint32 p1,uint32 p2,const std::string & text)100 CommandCost CmdChangeTimetable(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text)
101 {
102 	VehicleID veh = GB(p1, 0, 20);
103 
104 	Vehicle *v = Vehicle::GetIfValid(veh);
105 	if (v == nullptr || !v->IsPrimaryVehicle()) return CMD_ERROR;
106 
107 	CommandCost ret = CheckOwnership(v->owner);
108 	if (ret.Failed()) return ret;
109 
110 	VehicleOrderID order_number = GB(p1, 20, 8);
111 	Order *order = v->GetOrder(order_number);
112 	if (order == nullptr || order->IsType(OT_IMPLICIT)) return CMD_ERROR;
113 
114 	ModifyTimetableFlags mtf = Extract<ModifyTimetableFlags, 28, 2>(p1);
115 	if (mtf >= MTF_END) return CMD_ERROR;
116 
117 	int wait_time   = order->GetWaitTime();
118 	int travel_time = order->GetTravelTime();
119 	int max_speed   = order->GetMaxSpeed();
120 	switch (mtf) {
121 		case MTF_WAIT_TIME:
122 			wait_time = GB(p2, 0, 16);
123 			break;
124 
125 		case MTF_TRAVEL_TIME:
126 			travel_time = GB(p2, 0, 16);
127 			break;
128 
129 		case MTF_TRAVEL_SPEED:
130 			max_speed = GB(p2, 0, 16);
131 			if (max_speed == 0) max_speed = UINT16_MAX; // Disable speed limit.
132 			break;
133 
134 		default:
135 			NOT_REACHED();
136 	}
137 
138 	if (wait_time != order->GetWaitTime()) {
139 		switch (order->GetType()) {
140 			case OT_GOTO_STATION:
141 				if (order->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) return_cmd_error(STR_ERROR_TIMETABLE_NOT_STOPPING_HERE);
142 				break;
143 
144 			case OT_CONDITIONAL:
145 				break;
146 
147 			default: return_cmd_error(STR_ERROR_TIMETABLE_ONLY_WAIT_AT_STATIONS);
148 		}
149 	}
150 
151 	if (travel_time != order->GetTravelTime() && order->IsType(OT_CONDITIONAL)) return CMD_ERROR;
152 	if (max_speed != order->GetMaxSpeed() && (order->IsType(OT_CONDITIONAL) || v->type == VEH_AIRCRAFT)) return CMD_ERROR;
153 
154 	if (flags & DC_EXEC) {
155 		switch (mtf) {
156 			case MTF_WAIT_TIME:
157 				/* Set time if changing the value or confirming an estimated time as timetabled. */
158 				if (wait_time != order->GetWaitTime() || (wait_time > 0 && !order->IsWaitTimetabled())) {
159 					ChangeTimetable(v, order_number, wait_time, MTF_WAIT_TIME, wait_time > 0);
160 				}
161 				break;
162 
163 			case MTF_TRAVEL_TIME:
164 				/* Set time if changing the value or confirming an estimated time as timetabled. */
165 				if (travel_time != order->GetTravelTime() || (travel_time > 0 && !order->IsTravelTimetabled())) {
166 					ChangeTimetable(v, order_number, travel_time, MTF_TRAVEL_TIME, travel_time > 0);
167 				}
168 				break;
169 
170 			case MTF_TRAVEL_SPEED:
171 				if (max_speed != order->GetMaxSpeed()) {
172 					ChangeTimetable(v, order_number, max_speed, MTF_TRAVEL_SPEED, max_speed != UINT16_MAX);
173 				}
174 				break;
175 
176 			default:
177 				break;
178 		}
179 	}
180 
181 	return CommandCost();
182 }
183 
184 /**
185  * Clear the lateness counter to make the vehicle on time.
186  * @param tile Not used.
187  * @param flags Operation to perform.
188  * @param p1 Various bitstuffed elements
189  * - p1 = (bit  0-19) - Vehicle with the orders to change.
190  * @param p2 unused
191  * @param text unused
192  * @return the cost of this operation or an error
193  */
CmdSetVehicleOnTime(TileIndex tile,DoCommandFlag flags,uint32 p1,uint32 p2,const std::string & text)194 CommandCost CmdSetVehicleOnTime(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text)
195 {
196 	VehicleID veh = GB(p1, 0, 20);
197 
198 	Vehicle *v = Vehicle::GetIfValid(veh);
199 	if (v == nullptr || !v->IsPrimaryVehicle() || v->orders.list == nullptr) return CMD_ERROR;
200 
201 	CommandCost ret = CheckOwnership(v->owner);
202 	if (ret.Failed()) return ret;
203 
204 	if (flags & DC_EXEC) {
205 		v->lateness_counter = 0;
206 		SetWindowDirty(WC_VEHICLE_TIMETABLE, v->index);
207 	}
208 
209 	return CommandCost();
210 }
211 
212 /**
213  * Order vehicles based on their timetable. The vehicles will be sorted in order
214  * they would reach the first station.
215  *
216  * @param a First Vehicle pointer.
217  * @param b Second Vehicle pointer.
218  * @return Comparison value.
219  */
VehicleTimetableSorter(Vehicle * const & a,Vehicle * const & b)220 static bool VehicleTimetableSorter(Vehicle * const &a, Vehicle * const &b)
221 {
222 	VehicleOrderID a_order = a->cur_real_order_index;
223 	VehicleOrderID b_order = b->cur_real_order_index;
224 	int j = (int)b_order - (int)a_order;
225 
226 	/* Are we currently at an ordered station (un)loading? */
227 	bool a_load = a->current_order.IsType(OT_LOADING) && a->current_order.GetNonStopType() != ONSF_STOP_EVERYWHERE;
228 	bool b_load = b->current_order.IsType(OT_LOADING) && b->current_order.GetNonStopType() != ONSF_STOP_EVERYWHERE;
229 
230 	/* If the current order is not loading at the ordered station, decrease the order index by one since we have
231 	 * not yet arrived at the station (and thus the timetable entry; still in the travelling of the previous one).
232 	 * Since the ?_order variables are unsigned the -1 will flow under and place the vehicles going to order #0 at
233 	 * the begin of the list with vehicles arriving at #0. */
234 	if (!a_load) a_order--;
235 	if (!b_load) b_order--;
236 
237 	/* First check the order index that accounted for loading, then just the raw one. */
238 	int i = (int)b_order - (int)a_order;
239 	if (i != 0) return i < 0;
240 	if (j != 0) return j < 0;
241 
242 	/* Look at the time we spent in this order; the higher, the closer to its destination. */
243 	i = b->current_order_time - a->current_order_time;
244 	if (i != 0) return i < 0;
245 
246 	/* If all else is equal, use some unique index to sort it the same way. */
247 	return b->unitnumber < a->unitnumber;
248 }
249 
250 /**
251  * Set the start date of the timetable.
252  * @param tile Not used.
253  * @param flags Operation to perform.
254  * @param p2 Various bitstuffed elements
255  * - p2 = (bit 0-19) - Vehicle ID.
256  * - p2 = (bit 20)   - Set to 1 to set timetable start for all vehicles sharing this order
257  * @param p2 The timetable start date.
258  * @param text Not used.
259  * @return The error or cost of the operation.
260  */
CmdSetTimetableStart(TileIndex tile,DoCommandFlag flags,uint32 p1,uint32 p2,const std::string & text)261 CommandCost CmdSetTimetableStart(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text)
262 {
263 	bool timetable_all = HasBit(p1, 20);
264 	Vehicle *v = Vehicle::GetIfValid(GB(p1, 0, 20));
265 	if (v == nullptr || !v->IsPrimaryVehicle() || v->orders.list == nullptr) return CMD_ERROR;
266 
267 	CommandCost ret = CheckOwnership(v->owner);
268 	if (ret.Failed()) return ret;
269 
270 	/* Don't let a timetable start more than 15 years into the future or 1 year in the past. */
271 	Date start_date = (Date)p2;
272 	if (start_date < 0 || start_date > MAX_DAY) return CMD_ERROR;
273 	if (start_date - _date > 15 * DAYS_IN_LEAP_YEAR) return CMD_ERROR;
274 	if (_date - start_date > DAYS_IN_LEAP_YEAR) return CMD_ERROR;
275 	if (timetable_all && !v->orders.list->IsCompleteTimetable()) return CMD_ERROR;
276 
277 	if (flags & DC_EXEC) {
278 		std::vector<Vehicle *> vehs;
279 
280 		if (timetable_all) {
281 			for (Vehicle *w = v->orders.list->GetFirstSharedVehicle(); w != nullptr; w = w->NextShared()) {
282 				vehs.push_back(w);
283 			}
284 		} else {
285 			vehs.push_back(v);
286 		}
287 
288 		int total_duration = v->orders.list->GetTimetableTotalDuration();
289 		int num_vehs = (uint)vehs.size();
290 
291 		if (num_vehs >= 2) {
292 			std::sort(vehs.begin(), vehs.end(), &VehicleTimetableSorter);
293 		}
294 
295 		int idx = vehs.begin() - std::find(vehs.begin(), vehs.end(), v);
296 
297 		for (Vehicle *w : vehs) {
298 
299 			w->lateness_counter = 0;
300 			ClrBit(w->vehicle_flags, VF_TIMETABLE_STARTED);
301 			/* Do multiplication, then division to reduce rounding errors. */
302 			w->timetable_start = start_date + idx * total_duration / num_vehs / DAY_TICKS;
303 			SetWindowDirty(WC_VEHICLE_TIMETABLE, w->index);
304 			++idx;
305 		}
306 
307 	}
308 
309 	return CommandCost();
310 }
311 
312 
313 /**
314  * Start or stop filling the timetable automatically from the time the vehicle
315  * actually takes to complete it. When starting to autofill the current times
316  * are cleared and the timetable will start again from scratch.
317  * @param tile Not used.
318  * @param flags Operation to perform.
319  * @param p1 Vehicle index.
320  * @param p2 Various bitstuffed elements
321  * - p2 = (bit 0) - Set to 1 to enable, 0 to disable autofill.
322  * - p2 = (bit 1) - Set to 1 to preserve waiting times in non-destructive mode
323  * @param text unused
324  * @return the cost of this operation or an error
325  */
CmdAutofillTimetable(TileIndex tile,DoCommandFlag flags,uint32 p1,uint32 p2,const std::string & text)326 CommandCost CmdAutofillTimetable(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text)
327 {
328 	VehicleID veh = GB(p1, 0, 20);
329 
330 	Vehicle *v = Vehicle::GetIfValid(veh);
331 	if (v == nullptr || !v->IsPrimaryVehicle() || v->orders.list == nullptr) return CMD_ERROR;
332 
333 	CommandCost ret = CheckOwnership(v->owner);
334 	if (ret.Failed()) return ret;
335 
336 	if (flags & DC_EXEC) {
337 		if (HasBit(p2, 0)) {
338 			/* Start autofilling the timetable, which clears the
339 			 * "timetable has started" bit. Times are not cleared anymore, but are
340 			 * overwritten when the order is reached now. */
341 			SetBit(v->vehicle_flags, VF_AUTOFILL_TIMETABLE);
342 			ClrBit(v->vehicle_flags, VF_TIMETABLE_STARTED);
343 
344 			/* Overwrite waiting times only if they got longer */
345 			if (HasBit(p2, 1)) SetBit(v->vehicle_flags, VF_AUTOFILL_PRES_WAIT_TIME);
346 
347 			v->timetable_start = 0;
348 			v->lateness_counter = 0;
349 		} else {
350 			ClrBit(v->vehicle_flags, VF_AUTOFILL_TIMETABLE);
351 			ClrBit(v->vehicle_flags, VF_AUTOFILL_PRES_WAIT_TIME);
352 		}
353 
354 		for (Vehicle *v2 = v->FirstShared(); v2 != nullptr; v2 = v2->NextShared()) {
355 			if (v2 != v) {
356 				/* Stop autofilling; only one vehicle at a time can perform autofill */
357 				ClrBit(v2->vehicle_flags, VF_AUTOFILL_TIMETABLE);
358 				ClrBit(v2->vehicle_flags, VF_AUTOFILL_PRES_WAIT_TIME);
359 			}
360 			SetWindowDirty(WC_VEHICLE_TIMETABLE, v2->index);
361 		}
362 	}
363 
364 	return CommandCost();
365 }
366 
367 /**
368  * Update the timetable for the vehicle.
369  * @param v The vehicle to update the timetable for.
370  * @param travelling Whether we just travelled or waited at a station.
371  */
UpdateVehicleTimetable(Vehicle * v,bool travelling)372 void UpdateVehicleTimetable(Vehicle *v, bool travelling)
373 {
374 	uint time_taken = v->current_order_time;
375 
376 	v->current_order_time = 0;
377 
378 	if (v->current_order.IsType(OT_IMPLICIT)) return; // no timetabling of auto orders
379 
380 	if (v->cur_real_order_index >= v->GetNumOrders()) return;
381 	Order *real_current_order = v->GetOrder(v->cur_real_order_index);
382 
383 	VehicleOrderID first_manual_order = 0;
384 	for (Order *o = v->GetFirstOrder(); o != nullptr && o->IsType(OT_IMPLICIT); o = o->next) {
385 		++first_manual_order;
386 	}
387 
388 	bool just_started = false;
389 
390 	/* This vehicle is arriving at the first destination in the timetable. */
391 	if (v->cur_real_order_index == first_manual_order && travelling) {
392 		/* If the start date hasn't been set, or it was set automatically when
393 		 * the vehicle last arrived at the first destination, update it to the
394 		 * current time. Otherwise set the late counter appropriately to when
395 		 * the vehicle should have arrived. */
396 		just_started = !HasBit(v->vehicle_flags, VF_TIMETABLE_STARTED);
397 
398 		if (v->timetable_start != 0) {
399 			v->lateness_counter = (_date - v->timetable_start) * DAY_TICKS + _date_fract;
400 			v->timetable_start = 0;
401 		}
402 
403 		SetBit(v->vehicle_flags, VF_TIMETABLE_STARTED);
404 		SetWindowDirty(WC_VEHICLE_TIMETABLE, v->index);
405 	}
406 
407 	if (!HasBit(v->vehicle_flags, VF_TIMETABLE_STARTED)) return;
408 
409 	bool autofilling = HasBit(v->vehicle_flags, VF_AUTOFILL_TIMETABLE);
410 	bool remeasure_wait_time = !real_current_order->IsWaitTimetabled() ||
411 			(autofilling && !HasBit(v->vehicle_flags, VF_AUTOFILL_PRES_WAIT_TIME));
412 
413 	if (travelling && remeasure_wait_time) {
414 		/* We just finished travelling and want to remeasure the loading time,
415 		 * so do not apply any restrictions for the loading to finish. */
416 		v->current_order.SetWaitTime(0);
417 	}
418 
419 	if (just_started) return;
420 
421 	/* Before modifying waiting times, check whether we want to preserve bigger ones. */
422 	if (!real_current_order->IsType(OT_CONDITIONAL) &&
423 			(travelling || time_taken > real_current_order->GetWaitTime() || remeasure_wait_time)) {
424 		/* Round the time taken up to the nearest day, as this will avoid
425 		 * confusion for people who are timetabling in days, and can be
426 		 * adjusted later by people who aren't.
427 		 * For trains/aircraft multiple movement cycles are done in one
428 		 * tick. This makes it possible to leave the station and process
429 		 * e.g. a depot order in the same tick, causing it to not fill
430 		 * the timetable entry like is done for road vehicles/ships.
431 		 * Thus always make sure at least one tick is used between the
432 		 * processing of different orders when filling the timetable. */
433 		uint time_to_set = CeilDiv(std::max(time_taken, 1U), DAY_TICKS) * DAY_TICKS;
434 
435 		if (travelling && (autofilling || !real_current_order->IsTravelTimetabled())) {
436 			ChangeTimetable(v, v->cur_real_order_index, time_to_set, MTF_TRAVEL_TIME, autofilling);
437 		} else if (!travelling && (autofilling || !real_current_order->IsWaitTimetabled())) {
438 			ChangeTimetable(v, v->cur_real_order_index, time_to_set, MTF_WAIT_TIME, autofilling);
439 		}
440 	}
441 
442 	if (v->cur_real_order_index == first_manual_order && travelling) {
443 		/* If we just started we would have returned earlier and have not reached
444 		 * this code. So obviously, we have completed our round: So turn autofill
445 		 * off again. */
446 		ClrBit(v->vehicle_flags, VF_AUTOFILL_TIMETABLE);
447 		ClrBit(v->vehicle_flags, VF_AUTOFILL_PRES_WAIT_TIME);
448 	}
449 
450 	if (autofilling) return;
451 
452 	uint timetabled = travelling ? real_current_order->GetTimetabledTravel() :
453 			real_current_order->GetTimetabledWait();
454 
455 	/* Vehicles will wait at stations if they arrive early even if they are not
456 	 * timetabled to wait there, so make sure the lateness counter is updated
457 	 * when this happens. */
458 	if (timetabled == 0 && (travelling || v->lateness_counter >= 0)) return;
459 
460 	v->lateness_counter -= (timetabled - time_taken);
461 
462 	/* When we are more late than this timetabled bit takes we (somewhat expensively)
463 	 * check how many ticks the (fully filled) timetable has. If a timetable cycle is
464 	 * shorter than the amount of ticks we are late we reduce the lateness by the
465 	 * length of a full cycle till lateness is less than the length of a timetable
466 	 * cycle. When the timetable isn't fully filled the cycle will be INVALID_TICKS. */
467 	if (v->lateness_counter > (int)timetabled) {
468 		Ticks cycle = v->orders.list->GetTimetableTotalDuration();
469 		if (cycle != INVALID_TICKS && v->lateness_counter > cycle) {
470 			v->lateness_counter %= cycle;
471 		}
472 	}
473 
474 	for (v = v->FirstShared(); v != nullptr; v = v->NextShared()) {
475 		SetWindowDirty(WC_VEHICLE_TIMETABLE, v->index);
476 	}
477 }
478