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 train_cmd.cpp Handling of trains. */
9
10 #include "stdafx.h"
11 #include "error.h"
12 #include "articulated_vehicles.h"
13 #include "command_func.h"
14 #include "pathfinder/npf/npf_func.h"
15 #include "pathfinder/yapf/yapf.hpp"
16 #include "news_func.h"
17 #include "company_func.h"
18 #include "newgrf_sound.h"
19 #include "newgrf_text.h"
20 #include "strings_func.h"
21 #include "viewport_func.h"
22 #include "vehicle_func.h"
23 #include "sound_func.h"
24 #include "ai/ai.hpp"
25 #include "game/game.hpp"
26 #include "newgrf_station.h"
27 #include "effectvehicle_func.h"
28 #include "network/network.h"
29 #include "spritecache.h"
30 #include "core/random_func.hpp"
31 #include "company_base.h"
32 #include "newgrf.h"
33 #include "order_backup.h"
34 #include "zoom_func.h"
35 #include "newgrf_debug.h"
36 #include "framerate_type.h"
37
38 #include "table/strings.h"
39 #include "table/train_cmd.h"
40
41 #include "safeguards.h"
42
43 static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck);
44 static bool TrainCheckIfLineEnds(Train *v, bool reverse = true);
45 bool TrainController(Train *v, Vehicle *nomove, bool reverse = true); // Also used in vehicle_sl.cpp.
46 static TileIndex TrainApproachingCrossingTile(const Train *v);
47 static void CheckIfTrainNeedsService(Train *v);
48 static void CheckNextTrainTile(Train *v);
49
50 static const byte _vehicle_initial_x_fract[4] = {10, 8, 4, 8};
51 static const byte _vehicle_initial_y_fract[4] = { 8, 4, 8, 10};
52
53 template <>
IsValidImageIndex(uint8 image_index)54 bool IsValidImageIndex<VEH_TRAIN>(uint8 image_index)
55 {
56 return image_index < lengthof(_engine_sprite_base);
57 }
58
59
60 /**
61 * Return the cargo weight multiplier to use for a rail vehicle
62 * @param cargo Cargo type to get multiplier for
63 * @return Cargo weight multiplier
64 */
FreightWagonMult(CargoID cargo)65 byte FreightWagonMult(CargoID cargo)
66 {
67 if (!CargoSpec::Get(cargo)->is_freight) return 1;
68 return _settings_game.vehicle.freight_trains;
69 }
70
71 /** Checks if lengths of all rail vehicles are valid. If not, shows an error message. */
CheckTrainsLengths()72 void CheckTrainsLengths()
73 {
74 bool first = true;
75
76 for (const Train *v : Train::Iterate()) {
77 if (v->First() == v && !(v->vehstatus & VS_CRASHED)) {
78 for (const Train *u = v, *w = v->Next(); w != nullptr; u = w, w = w->Next()) {
79 if (u->track != TRACK_BIT_DEPOT) {
80 if ((w->track != TRACK_BIT_DEPOT &&
81 std::max(abs(u->x_pos - w->x_pos), abs(u->y_pos - w->y_pos)) != u->CalcNextVehicleOffset()) ||
82 (w->track == TRACK_BIT_DEPOT && TicksToLeaveDepot(u) <= 0)) {
83 SetDParam(0, v->index);
84 SetDParam(1, v->owner);
85 ShowErrorMessage(STR_BROKEN_VEHICLE_LENGTH, INVALID_STRING_ID, WL_CRITICAL);
86
87 if (!_networking && first) {
88 first = false;
89 DoCommandP(0, PM_PAUSED_ERROR, 1, CMD_PAUSE);
90 }
91 /* Break so we warn only once for each train. */
92 break;
93 }
94 }
95 }
96 }
97 }
98 }
99
100 /**
101 * Recalculates the cached stuff of a train. Should be called each time a vehicle is added
102 * to/removed from the chain, and when the game is loaded.
103 * Note: this needs to be called too for 'wagon chains' (in the depot, without an engine)
104 * @param allowed_changes Stuff that is allowed to change.
105 */
ConsistChanged(ConsistChangeFlags allowed_changes)106 void Train::ConsistChanged(ConsistChangeFlags allowed_changes)
107 {
108 uint16 max_speed = UINT16_MAX;
109
110 assert(this->IsFrontEngine() || this->IsFreeWagon());
111
112 const RailVehicleInfo *rvi_v = RailVehInfo(this->engine_type);
113 EngineID first_engine = this->IsFrontEngine() ? this->engine_type : INVALID_ENGINE;
114 this->gcache.cached_total_length = 0;
115 this->compatible_railtypes = RAILTYPES_NONE;
116
117 bool train_can_tilt = true;
118 int min_curve_speed_mod = INT_MAX;
119
120 for (Train *u = this; u != nullptr; u = u->Next()) {
121 const RailVehicleInfo *rvi_u = RailVehInfo(u->engine_type);
122
123 /* Check the this->first cache. */
124 assert(u->First() == this);
125
126 /* update the 'first engine' */
127 u->gcache.first_engine = this == u ? INVALID_ENGINE : first_engine;
128 u->railtype = rvi_u->railtype;
129
130 if (u->IsEngine()) first_engine = u->engine_type;
131
132 /* Set user defined data to its default value */
133 u->tcache.user_def_data = rvi_u->user_def_data;
134 this->InvalidateNewGRFCache();
135 u->InvalidateNewGRFCache();
136 }
137
138 for (Train *u = this; u != nullptr; u = u->Next()) {
139 /* Update user defined data (must be done before other properties) */
140 u->tcache.user_def_data = GetVehicleProperty(u, PROP_TRAIN_USER_DATA, u->tcache.user_def_data);
141 this->InvalidateNewGRFCache();
142 u->InvalidateNewGRFCache();
143 }
144
145 for (Train *u = this; u != nullptr; u = u->Next()) {
146 const Engine *e_u = u->GetEngine();
147 const RailVehicleInfo *rvi_u = &e_u->u.rail;
148
149 if (!HasBit(e_u->info.misc_flags, EF_RAIL_TILTS)) train_can_tilt = false;
150 min_curve_speed_mod = std::min(min_curve_speed_mod, u->GetCurveSpeedModifier());
151
152 /* Cache wagon override sprite group. nullptr is returned if there is none */
153 u->tcache.cached_override = GetWagonOverrideSpriteSet(u->engine_type, u->cargo_type, u->gcache.first_engine);
154
155 /* Reset colour map */
156 u->colourmap = PAL_NONE;
157
158 /* Update powered-wagon-status and visual effect */
159 u->UpdateVisualEffect(true);
160
161 if (rvi_v->pow_wag_power != 0 && rvi_u->railveh_type == RAILVEH_WAGON &&
162 UsesWagonOverride(u) && !HasBit(u->vcache.cached_vis_effect, VE_DISABLE_WAGON_POWER)) {
163 /* wagon is powered */
164 SetBit(u->flags, VRF_POWEREDWAGON); // cache 'powered' status
165 } else {
166 ClrBit(u->flags, VRF_POWEREDWAGON);
167 }
168
169 if (!u->IsArticulatedPart()) {
170 /* Do not count powered wagons for the compatible railtypes, as wagons always
171 have railtype normal */
172 if (rvi_u->power > 0) {
173 this->compatible_railtypes |= GetRailTypeInfo(u->railtype)->powered_railtypes;
174 }
175
176 /* Some electric engines can be allowed to run on normal rail. It happens to all
177 * existing electric engines when elrails are disabled and then re-enabled */
178 if (HasBit(u->flags, VRF_EL_ENGINE_ALLOWED_NORMAL_RAIL)) {
179 u->railtype = RAILTYPE_RAIL;
180 u->compatible_railtypes |= RAILTYPES_RAIL;
181 }
182
183 /* max speed is the minimum of the speed limits of all vehicles in the consist */
184 if ((rvi_u->railveh_type != RAILVEH_WAGON || _settings_game.vehicle.wagon_speed_limits) && !UsesWagonOverride(u)) {
185 uint16 speed = GetVehicleProperty(u, PROP_TRAIN_SPEED, rvi_u->max_speed);
186 if (speed != 0) max_speed = std::min(speed, max_speed);
187 }
188 }
189
190 uint16 new_cap = e_u->DetermineCapacity(u);
191 if (allowed_changes & CCF_CAPACITY) {
192 /* Update vehicle capacity. */
193 if (u->cargo_cap > new_cap) u->cargo.Truncate(new_cap);
194 u->refit_cap = std::min(new_cap, u->refit_cap);
195 u->cargo_cap = new_cap;
196 } else {
197 /* Verify capacity hasn't changed. */
198 if (new_cap != u->cargo_cap) ShowNewGrfVehicleError(u->engine_type, STR_NEWGRF_BROKEN, STR_NEWGRF_BROKEN_CAPACITY, GBUG_VEH_CAPACITY, true);
199 }
200 u->vcache.cached_cargo_age_period = GetVehicleProperty(u, PROP_TRAIN_CARGO_AGE_PERIOD, e_u->info.cargo_age_period);
201
202 /* check the vehicle length (callback) */
203 uint16 veh_len = CALLBACK_FAILED;
204 if (e_u->GetGRF() != nullptr && e_u->GetGRF()->grf_version >= 8) {
205 /* Use callback 36 */
206 veh_len = GetVehicleProperty(u, PROP_TRAIN_SHORTEN_FACTOR, CALLBACK_FAILED);
207
208 if (veh_len != CALLBACK_FAILED && veh_len >= VEHICLE_LENGTH) {
209 ErrorUnknownCallbackResult(e_u->GetGRFID(), CBID_VEHICLE_LENGTH, veh_len);
210 }
211 } else if (HasBit(e_u->info.callback_mask, CBM_VEHICLE_LENGTH)) {
212 /* Use callback 11 */
213 veh_len = GetVehicleCallback(CBID_VEHICLE_LENGTH, 0, 0, u->engine_type, u);
214 }
215 if (veh_len == CALLBACK_FAILED) veh_len = rvi_u->shorten_factor;
216 veh_len = VEHICLE_LENGTH - Clamp(veh_len, 0, VEHICLE_LENGTH - 1);
217
218 if (allowed_changes & CCF_LENGTH) {
219 /* Update vehicle length. */
220 u->gcache.cached_veh_length = veh_len;
221 } else {
222 /* Verify length hasn't changed. */
223 if (veh_len != u->gcache.cached_veh_length) VehicleLengthChanged(u);
224 }
225
226 this->gcache.cached_total_length += u->gcache.cached_veh_length;
227 this->InvalidateNewGRFCache();
228 u->InvalidateNewGRFCache();
229 }
230
231 /* store consist weight/max speed in cache */
232 this->vcache.cached_max_speed = max_speed;
233 this->tcache.cached_tilt = train_can_tilt;
234 this->tcache.cached_curve_speed_mod = min_curve_speed_mod;
235 this->tcache.cached_max_curve_speed = this->GetCurveSpeedLimit();
236
237 /* recalculate cached weights and power too (we do this *after* the rest, so it is known which wagons are powered and need extra weight added) */
238 this->CargoChanged();
239
240 if (this->IsFrontEngine()) {
241 this->UpdateAcceleration();
242 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
243 InvalidateWindowData(WC_VEHICLE_REFIT, this->index, VIWD_CONSIST_CHANGED);
244 InvalidateWindowData(WC_VEHICLE_ORDERS, this->index, VIWD_CONSIST_CHANGED);
245 InvalidateNewGRFInspectWindow(GSF_TRAINS, this->index);
246 }
247 }
248
249 /**
250 * Get the stop location of (the center) of the front vehicle of a train at
251 * a platform of a station.
252 * @param station_id the ID of the station where we're stopping
253 * @param tile the tile where the vehicle currently is
254 * @param v the vehicle to get the stop location of
255 * @param station_ahead 'return' the amount of 1/16th tiles in front of the train
256 * @param station_length 'return' the station length in 1/16th tiles
257 * @return the location, calculated from the begin of the station to stop at.
258 */
GetTrainStopLocation(StationID station_id,TileIndex tile,const Train * v,int * station_ahead,int * station_length)259 int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *v, int *station_ahead, int *station_length)
260 {
261 const Station *st = Station::Get(station_id);
262 *station_ahead = st->GetPlatformLength(tile, DirToDiagDir(v->direction)) * TILE_SIZE;
263 *station_length = st->GetPlatformLength(tile) * TILE_SIZE;
264
265 /* Default to the middle of the station for stations stops that are not in
266 * the order list like intermediate stations when non-stop is disabled */
267 OrderStopLocation osl = OSL_PLATFORM_MIDDLE;
268 if (v->gcache.cached_total_length >= *station_length) {
269 /* The train is longer than the station, make it stop at the far end of the platform */
270 osl = OSL_PLATFORM_FAR_END;
271 } else if (v->current_order.IsType(OT_GOTO_STATION) && v->current_order.GetDestination() == station_id) {
272 osl = v->current_order.GetStopLocation();
273 }
274
275 /* The stop location of the FRONT! of the train */
276 int stop;
277 switch (osl) {
278 default: NOT_REACHED();
279
280 case OSL_PLATFORM_NEAR_END:
281 stop = v->gcache.cached_total_length;
282 break;
283
284 case OSL_PLATFORM_MIDDLE:
285 stop = *station_length - (*station_length - v->gcache.cached_total_length) / 2;
286 break;
287
288 case OSL_PLATFORM_FAR_END:
289 stop = *station_length;
290 break;
291 }
292
293 /* Subtract half the front vehicle length of the train so we get the real
294 * stop location of the train. */
295 return stop - (v->gcache.cached_veh_length + 1) / 2;
296 }
297
298
299 /**
300 * Computes train speed limit caused by curves
301 * @return imposed speed limit
302 */
GetCurveSpeedLimit() const303 int Train::GetCurveSpeedLimit() const
304 {
305 assert(this->First() == this);
306
307 static const int absolute_max_speed = UINT16_MAX;
308 int max_speed = absolute_max_speed;
309
310 if (_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) return max_speed;
311
312 int curvecount[2] = {0, 0};
313
314 /* first find the curve speed limit */
315 int numcurve = 0;
316 int sum = 0;
317 int pos = 0;
318 int lastpos = -1;
319 for (const Vehicle *u = this; u->Next() != nullptr; u = u->Next(), pos++) {
320 Direction this_dir = u->direction;
321 Direction next_dir = u->Next()->direction;
322
323 DirDiff dirdiff = DirDifference(this_dir, next_dir);
324 if (dirdiff == DIRDIFF_SAME) continue;
325
326 if (dirdiff == DIRDIFF_45LEFT) curvecount[0]++;
327 if (dirdiff == DIRDIFF_45RIGHT) curvecount[1]++;
328 if (dirdiff == DIRDIFF_45LEFT || dirdiff == DIRDIFF_45RIGHT) {
329 if (lastpos != -1) {
330 numcurve++;
331 sum += pos - lastpos;
332 if (pos - lastpos == 1 && max_speed > 88) {
333 max_speed = 88;
334 }
335 }
336 lastpos = pos;
337 }
338
339 /* if we have a 90 degree turn, fix the speed limit to 60 */
340 if (dirdiff == DIRDIFF_90LEFT || dirdiff == DIRDIFF_90RIGHT) {
341 max_speed = 61;
342 }
343 }
344
345 if (numcurve > 0 && max_speed > 88) {
346 if (curvecount[0] == 1 && curvecount[1] == 1) {
347 max_speed = absolute_max_speed;
348 } else {
349 sum /= numcurve;
350 max_speed = 232 - (13 - Clamp(sum, 1, 12)) * (13 - Clamp(sum, 1, 12));
351 }
352 }
353
354 if (max_speed != absolute_max_speed) {
355 /* Apply the current railtype's curve speed advantage */
356 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(this->tile));
357 max_speed += (max_speed / 2) * rti->curve_speed;
358
359 if (this->tcache.cached_tilt) {
360 /* Apply max_speed bonus of 20% for a tilting train */
361 max_speed += max_speed / 5;
362 }
363
364 /* Apply max_speed modifier (cached value is fixed-point binary with 8 fractional bits)
365 * and clamp the result to an acceptable range. */
366 max_speed += (max_speed * this->tcache.cached_curve_speed_mod) / 256;
367 max_speed = Clamp(max_speed, 2, absolute_max_speed);
368 }
369
370 return max_speed;
371 }
372
373 /**
374 * Calculates the maximum speed of the vehicle under its current conditions.
375 * @return Maximum speed of the vehicle.
376 */
GetCurrentMaxSpeed() const377 int Train::GetCurrentMaxSpeed() const
378 {
379 int max_speed = _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL ?
380 this->gcache.cached_max_track_speed :
381 this->tcache.cached_max_curve_speed;
382
383 if (_settings_game.vehicle.train_acceleration_model == AM_REALISTIC && IsRailStationTile(this->tile)) {
384 StationID sid = GetStationIndex(this->tile);
385 if (this->current_order.ShouldStopAtStation(this, sid)) {
386 int station_ahead;
387 int station_length;
388 int stop_at = GetTrainStopLocation(sid, this->tile, this, &station_ahead, &station_length);
389
390 /* The distance to go is whatever is still ahead of the train minus the
391 * distance from the train's stop location to the end of the platform */
392 int distance_to_go = station_ahead / TILE_SIZE - (station_length - stop_at) / TILE_SIZE;
393
394 if (distance_to_go > 0) {
395 int st_max_speed = 120;
396
397 int delta_v = this->cur_speed / (distance_to_go + 1);
398 if (max_speed > (this->cur_speed - delta_v)) {
399 st_max_speed = this->cur_speed - (delta_v / 10);
400 }
401
402 st_max_speed = std::max(st_max_speed, 25 * distance_to_go);
403 max_speed = std::min(max_speed, st_max_speed);
404 }
405 }
406 }
407
408 for (const Train *u = this; u != nullptr; u = u->Next()) {
409 if (_settings_game.vehicle.train_acceleration_model == AM_REALISTIC && u->track == TRACK_BIT_DEPOT) {
410 max_speed = std::min(max_speed, 61);
411 break;
412 }
413
414 /* Vehicle is on the middle part of a bridge. */
415 if (u->track == TRACK_BIT_WORMHOLE && !(u->vehstatus & VS_HIDDEN)) {
416 max_speed = std::min<int>(max_speed, GetBridgeSpec(GetBridgeType(u->tile))->speed);
417 }
418 }
419
420 max_speed = std::min<int>(max_speed, this->current_order.GetMaxSpeed());
421 return std::min<int>(max_speed, this->gcache.cached_max_track_speed);
422 }
423
424 /** Update acceleration of the train from the cached power and weight. */
UpdateAcceleration()425 void Train::UpdateAcceleration()
426 {
427 assert(this->IsFrontEngine() || this->IsFreeWagon());
428
429 uint power = this->gcache.cached_power;
430 uint weight = this->gcache.cached_weight;
431 assert(weight != 0);
432 this->acceleration = Clamp(power / weight * 4, 1, 255);
433 }
434
435 /**
436 * Get the width of a train vehicle image in the GUI.
437 * @param offset Additional offset for positioning the sprite; set to nullptr if not needed
438 * @return Width in pixels
439 */
GetDisplayImageWidth(Point * offset) const440 int Train::GetDisplayImageWidth(Point *offset) const
441 {
442 int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
443 int vehicle_pitch = 0;
444
445 const Engine *e = this->GetEngine();
446 if (e->GetGRF() != nullptr && is_custom_sprite(e->u.rail.image_index)) {
447 reference_width = e->GetGRF()->traininfo_vehicle_width;
448 vehicle_pitch = e->GetGRF()->traininfo_vehicle_pitch;
449 }
450
451 if (offset != nullptr) {
452 offset->x = ScaleGUITrad(reference_width) / 2;
453 offset->y = ScaleGUITrad(vehicle_pitch);
454 }
455 return ScaleGUITrad(this->gcache.cached_veh_length * reference_width / VEHICLE_LENGTH);
456 }
457
GetDefaultTrainSprite(uint8 spritenum,Direction direction)458 static SpriteID GetDefaultTrainSprite(uint8 spritenum, Direction direction)
459 {
460 assert(IsValidImageIndex<VEH_TRAIN>(spritenum));
461 return ((direction + _engine_sprite_add[spritenum]) & _engine_sprite_and[spritenum]) + _engine_sprite_base[spritenum];
462 }
463
464 /**
465 * Get the sprite to display the train.
466 * @param direction Direction of view/travel.
467 * @param image_type Visualisation context.
468 * @return Sprite to display.
469 */
GetImage(Direction direction,EngineImageType image_type,VehicleSpriteSeq * result) const470 void Train::GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const
471 {
472 uint8 spritenum = this->spritenum;
473
474 if (HasBit(this->flags, VRF_REVERSE_DIRECTION)) direction = ReverseDir(direction);
475
476 if (is_custom_sprite(spritenum)) {
477 GetCustomVehicleSprite(this, (Direction)(direction + 4 * IS_CUSTOM_SECONDHEAD_SPRITE(spritenum)), image_type, result);
478 if (result->IsValid()) return;
479
480 spritenum = this->GetEngine()->original_image_index;
481 }
482
483 assert(IsValidImageIndex<VEH_TRAIN>(spritenum));
484 SpriteID sprite = GetDefaultTrainSprite(spritenum, direction);
485
486 if (this->cargo.StoredCount() >= this->cargo_cap / 2U) sprite += _wagon_full_adder[spritenum];
487
488 result->Set(sprite);
489 }
490
GetRailIcon(EngineID engine,bool rear_head,int & y,EngineImageType image_type,VehicleSpriteSeq * result)491 static void GetRailIcon(EngineID engine, bool rear_head, int &y, EngineImageType image_type, VehicleSpriteSeq *result)
492 {
493 const Engine *e = Engine::Get(engine);
494 Direction dir = rear_head ? DIR_E : DIR_W;
495 uint8 spritenum = e->u.rail.image_index;
496
497 if (is_custom_sprite(spritenum)) {
498 GetCustomVehicleIcon(engine, dir, image_type, result);
499 if (result->IsValid()) {
500 if (e->GetGRF() != nullptr) {
501 y += ScaleGUITrad(e->GetGRF()->traininfo_vehicle_pitch);
502 }
503 return;
504 }
505
506 spritenum = Engine::Get(engine)->original_image_index;
507 }
508
509 if (rear_head) spritenum++;
510
511 result->Set(GetDefaultTrainSprite(spritenum, DIR_W));
512 }
513
DrawTrainEngine(int left,int right,int preferred_x,int y,EngineID engine,PaletteID pal,EngineImageType image_type)514 void DrawTrainEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
515 {
516 if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
517 int yf = y;
518 int yr = y;
519
520 VehicleSpriteSeq seqf, seqr;
521 GetRailIcon(engine, false, yf, image_type, &seqf);
522 GetRailIcon(engine, true, yr, image_type, &seqr);
523
524 Rect rectf, rectr;
525 seqf.GetBounds(&rectf);
526 seqr.GetBounds(&rectr);
527
528 preferred_x = Clamp(preferred_x,
529 left - UnScaleGUI(rectf.left) + ScaleGUITrad(14),
530 right - UnScaleGUI(rectr.right) - ScaleGUITrad(15));
531
532 seqf.Draw(preferred_x - ScaleGUITrad(14), yf, pal, pal == PALETTE_CRASH);
533 seqr.Draw(preferred_x + ScaleGUITrad(15), yr, pal, pal == PALETTE_CRASH);
534 } else {
535 VehicleSpriteSeq seq;
536 GetRailIcon(engine, false, y, image_type, &seq);
537
538 Rect rect;
539 seq.GetBounds(&rect);
540 preferred_x = Clamp(preferred_x,
541 left - UnScaleGUI(rect.left),
542 right - UnScaleGUI(rect.right));
543
544 seq.Draw(preferred_x, y, pal, pal == PALETTE_CRASH);
545 }
546 }
547
548 /**
549 * Get the size of the sprite of a train sprite heading west, or both heads (used for lists).
550 * @param engine The engine to get the sprite from.
551 * @param[out] width The width of the sprite.
552 * @param[out] height The height of the sprite.
553 * @param[out] xoffs Number of pixels to shift the sprite to the right.
554 * @param[out] yoffs Number of pixels to shift the sprite downwards.
555 * @param image_type Context the sprite is used in.
556 */
GetTrainSpriteSize(EngineID engine,uint & width,uint & height,int & xoffs,int & yoffs,EngineImageType image_type)557 void GetTrainSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
558 {
559 int y = 0;
560
561 VehicleSpriteSeq seq;
562 GetRailIcon(engine, false, y, image_type, &seq);
563
564 Rect rect;
565 seq.GetBounds(&rect);
566
567 width = UnScaleGUI(rect.right - rect.left + 1);
568 height = UnScaleGUI(rect.bottom - rect.top + 1);
569 xoffs = UnScaleGUI(rect.left);
570 yoffs = UnScaleGUI(rect.top);
571
572 if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
573 GetRailIcon(engine, true, y, image_type, &seq);
574 seq.GetBounds(&rect);
575
576 /* Calculate values relative to an imaginary center between the two sprites. */
577 width = ScaleGUITrad(TRAININFO_DEFAULT_VEHICLE_WIDTH) + UnScaleGUI(rect.right) - xoffs;
578 height = std::max<uint>(height, UnScaleGUI(rect.bottom - rect.top + 1));
579 xoffs = xoffs - ScaleGUITrad(TRAININFO_DEFAULT_VEHICLE_WIDTH) / 2;
580 yoffs = std::min(yoffs, UnScaleGUI(rect.top));
581 }
582 }
583
584 /**
585 * Build a railroad wagon.
586 * @param tile tile of the depot where rail-vehicle is built.
587 * @param flags type of operation.
588 * @param e the engine to build.
589 * @param[out] ret the vehicle that has been built.
590 * @return the cost of this operation or an error.
591 */
CmdBuildRailWagon(TileIndex tile,DoCommandFlag flags,const Engine * e,Vehicle ** ret)592 static CommandCost CmdBuildRailWagon(TileIndex tile, DoCommandFlag flags, const Engine *e, Vehicle **ret)
593 {
594 const RailVehicleInfo *rvi = &e->u.rail;
595
596 /* Check that the wagon can drive on the track in question */
597 if (!IsCompatibleRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
598
599 if (flags & DC_EXEC) {
600 Train *v = new Train();
601 *ret = v;
602 v->spritenum = rvi->image_index;
603
604 v->engine_type = e->index;
605 v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
606
607 DiagDirection dir = GetRailDepotDirection(tile);
608
609 v->direction = DiagDirToDir(dir);
610 v->tile = tile;
611
612 int x = TileX(tile) * TILE_SIZE | _vehicle_initial_x_fract[dir];
613 int y = TileY(tile) * TILE_SIZE | _vehicle_initial_y_fract[dir];
614
615 v->x_pos = x;
616 v->y_pos = y;
617 v->z_pos = GetSlopePixelZ(x, y);
618 v->owner = _current_company;
619 v->track = TRACK_BIT_DEPOT;
620 v->vehstatus = VS_HIDDEN | VS_DEFPAL;
621
622 v->SetWagon();
623
624 v->SetFreeWagon();
625 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
626
627 v->cargo_type = e->GetDefaultCargoType();
628 v->cargo_cap = rvi->capacity;
629 v->refit_cap = 0;
630
631 v->railtype = rvi->railtype;
632
633 v->date_of_last_service = _date;
634 v->build_year = _cur_year;
635 v->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY);
636 v->random_bits = VehicleRandomBits();
637
638 v->group_id = DEFAULT_GROUP;
639
640 AddArticulatedParts(v);
641
642 _new_vehicle_id = v->index;
643
644 v->UpdatePosition();
645 v->First()->ConsistChanged(CCF_ARRANGE);
646 UpdateTrainGroupID(v->First());
647
648 CheckConsistencyOfArticulatedVehicle(v);
649
650 /* Try to connect the vehicle to one of free chains of wagons. */
651 for (Train *w : Train::Iterate()) {
652 if (w->tile == tile && ///< Same depot
653 w->IsFreeWagon() && ///< A free wagon chain
654 w->engine_type == e->index && ///< Same type
655 w->First() != v && ///< Don't connect to ourself
656 !(w->vehstatus & VS_CRASHED)) { ///< Not crashed/flooded
657 if (DoCommand(0, v->index | 1 << 20, w->Last()->index, DC_EXEC, CMD_MOVE_RAIL_VEHICLE).Succeeded()) {
658 break;
659 }
660 }
661 }
662 }
663
664 return CommandCost();
665 }
666
667 /** Move all free vehicles in the depot to the train */
NormalizeTrainVehInDepot(const Train * u)668 static void NormalizeTrainVehInDepot(const Train *u)
669 {
670 for (const Train *v : Train::Iterate()) {
671 if (v->IsFreeWagon() && v->tile == u->tile &&
672 v->track == TRACK_BIT_DEPOT) {
673 if (DoCommand(0, v->index | 1 << 20, u->index, DC_EXEC,
674 CMD_MOVE_RAIL_VEHICLE).Failed())
675 break;
676 }
677 }
678 }
679
AddRearEngineToMultiheadedTrain(Train * v)680 static void AddRearEngineToMultiheadedTrain(Train *v)
681 {
682 Train *u = new Train();
683 v->value >>= 1;
684 u->value = v->value;
685 u->direction = v->direction;
686 u->owner = v->owner;
687 u->tile = v->tile;
688 u->x_pos = v->x_pos;
689 u->y_pos = v->y_pos;
690 u->z_pos = v->z_pos;
691 u->track = TRACK_BIT_DEPOT;
692 u->vehstatus = v->vehstatus & ~VS_STOPPED;
693 u->spritenum = v->spritenum + 1;
694 u->cargo_type = v->cargo_type;
695 u->cargo_subtype = v->cargo_subtype;
696 u->cargo_cap = v->cargo_cap;
697 u->refit_cap = v->refit_cap;
698 u->railtype = v->railtype;
699 u->engine_type = v->engine_type;
700 u->date_of_last_service = v->date_of_last_service;
701 u->build_year = v->build_year;
702 u->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY);
703 u->random_bits = VehicleRandomBits();
704 v->SetMultiheaded();
705 u->SetMultiheaded();
706 v->SetNext(u);
707 u->UpdatePosition();
708
709 /* Now we need to link the front and rear engines together */
710 v->other_multiheaded_part = u;
711 u->other_multiheaded_part = v;
712 }
713
714 /**
715 * Build a railroad vehicle.
716 * @param tile tile of the depot where rail-vehicle is built.
717 * @param flags type of operation.
718 * @param e the engine to build.
719 * @param data bit 0 prevents any free cars from being added to the train.
720 * @param[out] ret the vehicle that has been built.
721 * @return the cost of this operation or an error.
722 */
CmdBuildRailVehicle(TileIndex tile,DoCommandFlag flags,const Engine * e,uint16 data,Vehicle ** ret)723 CommandCost CmdBuildRailVehicle(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **ret)
724 {
725 const RailVehicleInfo *rvi = &e->u.rail;
726
727 if (rvi->railveh_type == RAILVEH_WAGON) return CmdBuildRailWagon(tile, flags, e, ret);
728
729 /* Check if depot and new engine uses the same kind of tracks *
730 * We need to see if the engine got power on the tile to avoid electric engines in non-electric depots */
731 if (!HasPowerOnRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
732
733 if (flags & DC_EXEC) {
734 DiagDirection dir = GetRailDepotDirection(tile);
735 int x = TileX(tile) * TILE_SIZE + _vehicle_initial_x_fract[dir];
736 int y = TileY(tile) * TILE_SIZE + _vehicle_initial_y_fract[dir];
737
738 Train *v = new Train();
739 *ret = v;
740 v->direction = DiagDirToDir(dir);
741 v->tile = tile;
742 v->owner = _current_company;
743 v->x_pos = x;
744 v->y_pos = y;
745 v->z_pos = GetSlopePixelZ(x, y);
746 v->track = TRACK_BIT_DEPOT;
747 v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
748 v->spritenum = rvi->image_index;
749 v->cargo_type = e->GetDefaultCargoType();
750 v->cargo_cap = rvi->capacity;
751 v->refit_cap = 0;
752 v->last_station_visited = INVALID_STATION;
753 v->last_loading_station = INVALID_STATION;
754
755 v->engine_type = e->index;
756 v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
757
758 v->reliability = e->reliability;
759 v->reliability_spd_dec = e->reliability_spd_dec;
760 v->max_age = e->GetLifeLengthInDays();
761
762 v->railtype = rvi->railtype;
763 _new_vehicle_id = v->index;
764
765 v->SetServiceInterval(Company::Get(_current_company)->settings.vehicle.servint_trains);
766 v->date_of_last_service = _date;
767 v->build_year = _cur_year;
768 v->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY);
769 v->random_bits = VehicleRandomBits();
770
771 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
772 v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
773
774 v->group_id = DEFAULT_GROUP;
775
776 v->SetFrontEngine();
777 v->SetEngine();
778
779 v->UpdatePosition();
780
781 if (rvi->railveh_type == RAILVEH_MULTIHEAD) {
782 AddRearEngineToMultiheadedTrain(v);
783 } else {
784 AddArticulatedParts(v);
785 }
786
787 v->ConsistChanged(CCF_ARRANGE);
788 UpdateTrainGroupID(v);
789
790 if (!HasBit(data, 0) && !(flags & DC_AUTOREPLACE)) { // check if the cars should be added to the new vehicle
791 NormalizeTrainVehInDepot(v);
792 }
793
794 CheckConsistencyOfArticulatedVehicle(v);
795 }
796
797 return CommandCost();
798 }
799
FindGoodVehiclePos(const Train * src)800 static Train *FindGoodVehiclePos(const Train *src)
801 {
802 EngineID eng = src->engine_type;
803 TileIndex tile = src->tile;
804
805 for (Train *dst : Train::Iterate()) {
806 if (dst->IsFreeWagon() && dst->tile == tile && !(dst->vehstatus & VS_CRASHED)) {
807 /* check so all vehicles in the line have the same engine. */
808 Train *t = dst;
809 while (t->engine_type == eng) {
810 t = t->Next();
811 if (t == nullptr) return dst;
812 }
813 }
814 }
815
816 return nullptr;
817 }
818
819 /** Helper type for lists/vectors of trains */
820 typedef std::vector<Train *> TrainList;
821
822 /**
823 * Make a backup of a train into a train list.
824 * @param list to make the backup in
825 * @param t the train to make the backup of
826 */
MakeTrainBackup(TrainList & list,Train * t)827 static void MakeTrainBackup(TrainList &list, Train *t)
828 {
829 for (; t != nullptr; t = t->Next()) list.push_back(t);
830 }
831
832 /**
833 * Restore the train from the backup list.
834 * @param list the train to restore.
835 */
RestoreTrainBackup(TrainList & list)836 static void RestoreTrainBackup(TrainList &list)
837 {
838 /* No train, nothing to do. */
839 if (list.size() == 0) return;
840
841 Train *prev = nullptr;
842 /* Iterate over the list and rebuild it. */
843 for (Train *t : list) {
844 if (prev != nullptr) {
845 prev->SetNext(t);
846 } else if (t->Previous() != nullptr) {
847 /* Make sure the head of the train is always the first in the chain. */
848 t->Previous()->SetNext(nullptr);
849 }
850 prev = t;
851 }
852 }
853
854 /**
855 * Remove the given wagon from its consist.
856 * @param part the part of the train to remove.
857 * @param chain whether to remove the whole chain.
858 */
RemoveFromConsist(Train * part,bool chain=false)859 static void RemoveFromConsist(Train *part, bool chain = false)
860 {
861 Train *tail = chain ? part->Last() : part->GetLastEnginePart();
862
863 /* Unlink at the front, but make it point to the next
864 * vehicle after the to be remove part. */
865 if (part->Previous() != nullptr) part->Previous()->SetNext(tail->Next());
866
867 /* Unlink at the back */
868 tail->SetNext(nullptr);
869 }
870
871 /**
872 * Inserts a chain into the train at dst.
873 * @param dst the place where to append after.
874 * @param chain the chain to actually add.
875 */
InsertInConsist(Train * dst,Train * chain)876 static void InsertInConsist(Train *dst, Train *chain)
877 {
878 /* We do not want to add something in the middle of an articulated part. */
879 assert(dst != nullptr && (dst->Next() == nullptr || !dst->Next()->IsArticulatedPart()));
880
881 chain->Last()->SetNext(dst->Next());
882 dst->SetNext(chain);
883 }
884
885 /**
886 * Normalise the dual heads in the train, i.e. if one is
887 * missing move that one to this train.
888 * @param t the train to normalise.
889 */
NormaliseDualHeads(Train * t)890 static void NormaliseDualHeads(Train *t)
891 {
892 for (; t != nullptr; t = t->GetNextVehicle()) {
893 if (!t->IsMultiheaded() || !t->IsEngine()) continue;
894
895 /* Make sure that there are no free cars before next engine */
896 Train *u;
897 for (u = t; u->Next() != nullptr && !u->Next()->IsEngine(); u = u->Next()) {}
898
899 if (u == t->other_multiheaded_part) continue;
900
901 /* Remove the part from the 'wrong' train */
902 RemoveFromConsist(t->other_multiheaded_part);
903 /* And add it to the 'right' train */
904 InsertInConsist(u, t->other_multiheaded_part);
905 }
906 }
907
908 /**
909 * Normalise the sub types of the parts in this chain.
910 * @param chain the chain to normalise.
911 */
NormaliseSubtypes(Train * chain)912 static void NormaliseSubtypes(Train *chain)
913 {
914 /* Nothing to do */
915 if (chain == nullptr) return;
916
917 /* We must be the first in the chain. */
918 assert(chain->Previous() == nullptr);
919
920 /* Set the appropriate bits for the first in the chain. */
921 if (chain->IsWagon()) {
922 chain->SetFreeWagon();
923 } else {
924 assert(chain->IsEngine());
925 chain->SetFrontEngine();
926 }
927
928 /* Now clear the bits for the rest of the chain */
929 for (Train *t = chain->Next(); t != nullptr; t = t->Next()) {
930 t->ClearFreeWagon();
931 t->ClearFrontEngine();
932 }
933 }
934
935 /**
936 * Check/validate whether we may actually build a new train.
937 * @note All vehicles are/were 'heads' of their chains.
938 * @param original_dst The original destination chain.
939 * @param dst The destination chain after constructing the train.
940 * @param original_src The original source chain.
941 * @param src The source chain after constructing the train.
942 * @return possible error of this command.
943 */
CheckNewTrain(Train * original_dst,Train * dst,Train * original_src,Train * src)944 static CommandCost CheckNewTrain(Train *original_dst, Train *dst, Train *original_src, Train *src)
945 {
946 /* Just add 'new' engines and subtract the original ones.
947 * If that's less than or equal to 0 we can be sure we did
948 * not add any engines (read: trains) along the way. */
949 if ((src != nullptr && src->IsEngine() ? 1 : 0) +
950 (dst != nullptr && dst->IsEngine() ? 1 : 0) -
951 (original_src != nullptr && original_src->IsEngine() ? 1 : 0) -
952 (original_dst != nullptr && original_dst->IsEngine() ? 1 : 0) <= 0) {
953 return CommandCost();
954 }
955
956 /* Get a free unit number and check whether it's within the bounds.
957 * There will always be a maximum of one new train. */
958 if (GetFreeUnitNumber(VEH_TRAIN) <= _settings_game.vehicle.max_trains) return CommandCost();
959
960 return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
961 }
962
963 /**
964 * Check whether the train parts can be attached.
965 * @param t the train to check
966 * @return possible error of this command.
967 */
CheckTrainAttachment(Train * t)968 static CommandCost CheckTrainAttachment(Train *t)
969 {
970 /* No multi-part train, no need to check. */
971 if (t == nullptr || t->Next() == nullptr) return CommandCost();
972
973 /* The maximum length for a train. For each part we decrease this by one
974 * and if the result is negative the train is simply too long. */
975 int allowed_len = _settings_game.vehicle.max_train_length * TILE_SIZE - t->gcache.cached_veh_length;
976
977 /* For free-wagon chains, check if they are within the max_train_length limit. */
978 if (!t->IsEngine()) {
979 t = t->Next();
980 while (t != nullptr) {
981 allowed_len -= t->gcache.cached_veh_length;
982
983 t = t->Next();
984 }
985
986 if (allowed_len < 0) return_cmd_error(STR_ERROR_TRAIN_TOO_LONG);
987 return CommandCost();
988 }
989
990 Train *head = t;
991 Train *prev = t;
992
993 /* Break the prev -> t link so it always holds within the loop. */
994 t = t->Next();
995 prev->SetNext(nullptr);
996
997 /* Make sure the cache is cleared. */
998 head->InvalidateNewGRFCache();
999
1000 while (t != nullptr) {
1001 allowed_len -= t->gcache.cached_veh_length;
1002
1003 Train *next = t->Next();
1004
1005 /* Unlink the to-be-added piece; it is already unlinked from the previous
1006 * part due to the fact that the prev -> t link is broken. */
1007 t->SetNext(nullptr);
1008
1009 /* Don't check callback for articulated or rear dual headed parts */
1010 if (!t->IsArticulatedPart() && !t->IsRearDualheaded()) {
1011 /* Back up and clear the first_engine data to avoid using wagon override group */
1012 EngineID first_engine = t->gcache.first_engine;
1013 t->gcache.first_engine = INVALID_ENGINE;
1014
1015 /* We don't want the cache to interfere. head's cache is cleared before
1016 * the loop and after each callback does not need to be cleared here. */
1017 t->InvalidateNewGRFCache();
1018
1019 uint16 callback = GetVehicleCallbackParent(CBID_TRAIN_ALLOW_WAGON_ATTACH, 0, 0, head->engine_type, t, head);
1020
1021 /* Restore original first_engine data */
1022 t->gcache.first_engine = first_engine;
1023
1024 /* We do not want to remember any cached variables from the test run */
1025 t->InvalidateNewGRFCache();
1026 head->InvalidateNewGRFCache();
1027
1028 if (callback != CALLBACK_FAILED) {
1029 /* A failing callback means everything is okay */
1030 StringID error = STR_NULL;
1031
1032 if (head->GetGRF()->grf_version < 8) {
1033 if (callback == 0xFD) error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1034 if (callback < 0xFD) error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
1035 if (callback >= 0x100) ErrorUnknownCallbackResult(head->GetGRFID(), CBID_TRAIN_ALLOW_WAGON_ATTACH, callback);
1036 } else {
1037 if (callback < 0x400) {
1038 error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
1039 } else {
1040 switch (callback) {
1041 case 0x400: // allow if railtypes match (always the case for OpenTTD)
1042 case 0x401: // allow
1043 break;
1044
1045 default: // unknown reason -> disallow
1046 case 0x402: // disallow attaching
1047 error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1048 break;
1049 }
1050 }
1051 }
1052
1053 if (error != STR_NULL) return_cmd_error(error);
1054 }
1055 }
1056
1057 /* And link it to the new part. */
1058 prev->SetNext(t);
1059 prev = t;
1060 t = next;
1061 }
1062
1063 if (allowed_len < 0) return_cmd_error(STR_ERROR_TRAIN_TOO_LONG);
1064 return CommandCost();
1065 }
1066
1067 /**
1068 * Validate whether we are going to create valid trains.
1069 * @note All vehicles are/were 'heads' of their chains.
1070 * @param original_dst The original destination chain.
1071 * @param dst The destination chain after constructing the train.
1072 * @param original_src The original source chain.
1073 * @param src The source chain after constructing the train.
1074 * @param check_limit Whether to check the vehicle limit.
1075 * @return possible error of this command.
1076 */
ValidateTrains(Train * original_dst,Train * dst,Train * original_src,Train * src,bool check_limit)1077 static CommandCost ValidateTrains(Train *original_dst, Train *dst, Train *original_src, Train *src, bool check_limit)
1078 {
1079 /* Check whether we may actually construct the trains. */
1080 CommandCost ret = CheckTrainAttachment(src);
1081 if (ret.Failed()) return ret;
1082 ret = CheckTrainAttachment(dst);
1083 if (ret.Failed()) return ret;
1084
1085 /* Check whether we need to build a new train. */
1086 return check_limit ? CheckNewTrain(original_dst, dst, original_src, src) : CommandCost();
1087 }
1088
1089 /**
1090 * Arrange the trains in the wanted way.
1091 * @param dst_head The destination chain of the to be moved vehicle.
1092 * @param dst The destination for the to be moved vehicle.
1093 * @param src_head The source chain of the to be moved vehicle.
1094 * @param src The to be moved vehicle.
1095 * @param move_chain Whether to move all vehicles after src or not.
1096 */
ArrangeTrains(Train ** dst_head,Train * dst,Train ** src_head,Train * src,bool move_chain)1097 static void ArrangeTrains(Train **dst_head, Train *dst, Train **src_head, Train *src, bool move_chain)
1098 {
1099 /* First determine the front of the two resulting trains */
1100 if (*src_head == *dst_head) {
1101 /* If we aren't moving part(s) to a new train, we are just moving the
1102 * front back and there is not destination head. */
1103 *dst_head = nullptr;
1104 } else if (*dst_head == nullptr) {
1105 /* If we are moving to a new train the head of the move train would become
1106 * the head of the new vehicle. */
1107 *dst_head = src;
1108 }
1109
1110 if (src == *src_head) {
1111 /* If we are moving the front of a train then we are, in effect, creating
1112 * a new head for the train. Point to that. Unless we are moving the whole
1113 * train in which case there is not 'source' train anymore.
1114 * In case we are a multiheaded part we want the complete thing to come
1115 * with us, so src->GetNextUnit(), however... when we are e.g. a wagon
1116 * that is followed by a rear multihead we do not want to include that. */
1117 *src_head = move_chain ? nullptr :
1118 (src->IsMultiheaded() ? src->GetNextUnit() : src->GetNextVehicle());
1119 }
1120
1121 /* Now it's just simply removing the part that we are going to move from the
1122 * source train and *if* the destination is a not a new train add the chain
1123 * at the destination location. */
1124 RemoveFromConsist(src, move_chain);
1125 if (*dst_head != src) InsertInConsist(dst, src);
1126
1127 /* Now normalise the dual heads, that is move the dual heads around in such
1128 * a way that the head and rear of a dual head are in the same train */
1129 NormaliseDualHeads(*src_head);
1130 NormaliseDualHeads(*dst_head);
1131 }
1132
1133 /**
1134 * Normalise the head of the train again, i.e. that is tell the world that
1135 * we have changed and update all kinds of variables.
1136 * @param head the train to update.
1137 */
NormaliseTrainHead(Train * head)1138 static void NormaliseTrainHead(Train *head)
1139 {
1140 /* Not much to do! */
1141 if (head == nullptr) return;
1142
1143 /* Tell the 'world' the train changed. */
1144 head->ConsistChanged(CCF_ARRANGE);
1145 UpdateTrainGroupID(head);
1146
1147 /* Not a front engine, i.e. a free wagon chain. No need to do more. */
1148 if (!head->IsFrontEngine()) return;
1149
1150 /* Update the refit button and window */
1151 InvalidateWindowData(WC_VEHICLE_REFIT, head->index, VIWD_CONSIST_CHANGED);
1152 SetWindowWidgetDirty(WC_VEHICLE_VIEW, head->index, WID_VV_REFIT);
1153
1154 /* If we don't have a unit number yet, set one. */
1155 if (head->unitnumber != 0) return;
1156 head->unitnumber = GetFreeUnitNumber(VEH_TRAIN);
1157 }
1158
1159 /**
1160 * Move a rail vehicle around inside the depot.
1161 * @param tile unused
1162 * @param flags type of operation
1163 * Note: DC_AUTOREPLACE is set when autoreplace tries to undo its modifications or moves vehicles to temporary locations inside the depot.
1164 * @param p1 various bitstuffed elements
1165 * - p1 (bit 0 - 19) source vehicle index
1166 * - p1 (bit 20) move all vehicles following the source vehicle
1167 * @param p2 what wagon to put the source wagon AFTER, XXX - INVALID_VEHICLE to make a new line
1168 * @param text unused
1169 * @return the cost of this operation or an error
1170 */
CmdMoveRailVehicle(TileIndex tile,DoCommandFlag flags,uint32 p1,uint32 p2,const std::string & text)1171 CommandCost CmdMoveRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text)
1172 {
1173 VehicleID s = GB(p1, 0, 20);
1174 VehicleID d = GB(p2, 0, 20);
1175 bool move_chain = HasBit(p1, 20);
1176
1177 Train *src = Train::GetIfValid(s);
1178 if (src == nullptr) return CMD_ERROR;
1179
1180 CommandCost ret = CheckOwnership(src->owner);
1181 if (ret.Failed()) return ret;
1182
1183 /* Do not allow moving crashed vehicles inside the depot, it is likely to cause asserts later */
1184 if (src->vehstatus & VS_CRASHED) return CMD_ERROR;
1185
1186 /* if nothing is selected as destination, try and find a matching vehicle to drag to. */
1187 Train *dst;
1188 if (d == INVALID_VEHICLE) {
1189 dst = (src->IsEngine() || (flags & DC_AUTOREPLACE)) ? nullptr : FindGoodVehiclePos(src);
1190 } else {
1191 dst = Train::GetIfValid(d);
1192 if (dst == nullptr) return CMD_ERROR;
1193
1194 CommandCost ret = CheckOwnership(dst->owner);
1195 if (ret.Failed()) return ret;
1196
1197 /* Do not allow appending to crashed vehicles, too */
1198 if (dst->vehstatus & VS_CRASHED) return CMD_ERROR;
1199 }
1200
1201 /* if an articulated part is being handled, deal with its parent vehicle */
1202 src = src->GetFirstEnginePart();
1203 if (dst != nullptr) {
1204 dst = dst->GetFirstEnginePart();
1205 }
1206
1207 /* don't move the same vehicle.. */
1208 if (src == dst) return CommandCost();
1209
1210 /* locate the head of the two chains */
1211 Train *src_head = src->First();
1212 Train *dst_head;
1213 if (dst != nullptr) {
1214 dst_head = dst->First();
1215 if (dst_head->tile != src_head->tile) return CMD_ERROR;
1216 /* Now deal with articulated part of destination wagon */
1217 dst = dst->GetLastEnginePart();
1218 } else {
1219 dst_head = nullptr;
1220 }
1221
1222 if (src->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
1223
1224 /* When moving all wagons, we can't have the same src_head and dst_head */
1225 if (move_chain && src_head == dst_head) return CommandCost();
1226
1227 /* When moving a multiheaded part to be place after itself, bail out. */
1228 if (!move_chain && dst != nullptr && dst->IsRearDualheaded() && src == dst->other_multiheaded_part) return CommandCost();
1229
1230 /* Check if all vehicles in the source train are stopped inside a depot. */
1231 if (!src_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1232
1233 /* Check if all vehicles in the destination train are stopped inside a depot. */
1234 if (dst_head != nullptr && !dst_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1235
1236 /* First make a backup of the order of the trains. That way we can do
1237 * whatever we want with the order and later on easily revert. */
1238 TrainList original_src;
1239 TrainList original_dst;
1240
1241 MakeTrainBackup(original_src, src_head);
1242 MakeTrainBackup(original_dst, dst_head);
1243
1244 /* Also make backup of the original heads as ArrangeTrains can change them.
1245 * For the destination head we do not care if it is the same as the source
1246 * head because in that case it's just a copy. */
1247 Train *original_src_head = src_head;
1248 Train *original_dst_head = (dst_head == src_head ? nullptr : dst_head);
1249
1250 /* We want this information from before the rearrangement, but execute this after the validation.
1251 * original_src_head can't be nullptr; src is by definition != nullptr, so src_head can't be nullptr as
1252 * src->GetFirst() always yields non-nullptr, so eventually original_src_head != nullptr as well. */
1253 bool original_src_head_front_engine = original_src_head->IsFrontEngine();
1254 bool original_dst_head_front_engine = original_dst_head != nullptr && original_dst_head->IsFrontEngine();
1255
1256 /* (Re)arrange the trains in the wanted arrangement. */
1257 ArrangeTrains(&dst_head, dst, &src_head, src, move_chain);
1258
1259 if ((flags & DC_AUTOREPLACE) == 0) {
1260 /* If the autoreplace flag is set we do not need to test for the validity
1261 * because we are going to revert the train to its original state. As we
1262 * assume the original state was correct autoreplace can skip this. */
1263 CommandCost ret = ValidateTrains(original_dst_head, dst_head, original_src_head, src_head, true);
1264 if (ret.Failed()) {
1265 /* Restore the train we had. */
1266 RestoreTrainBackup(original_src);
1267 RestoreTrainBackup(original_dst);
1268 return ret;
1269 }
1270 }
1271
1272 /* do it? */
1273 if (flags & DC_EXEC) {
1274 /* Remove old heads from the statistics */
1275 if (original_src_head_front_engine) GroupStatistics::CountVehicle(original_src_head, -1);
1276 if (original_dst_head_front_engine) GroupStatistics::CountVehicle(original_dst_head, -1);
1277
1278 /* First normalise the sub types of the chains. */
1279 NormaliseSubtypes(src_head);
1280 NormaliseSubtypes(dst_head);
1281
1282 /* There are 14 different cases:
1283 * 1) front engine gets moved to a new train, it stays a front engine.
1284 * a) the 'next' part is a wagon that becomes a free wagon chain.
1285 * b) the 'next' part is an engine that becomes a front engine.
1286 * c) there is no 'next' part, nothing else happens
1287 * 2) front engine gets moved to another train, it is not a front engine anymore
1288 * a) the 'next' part is a wagon that becomes a free wagon chain.
1289 * b) the 'next' part is an engine that becomes a front engine.
1290 * c) there is no 'next' part, nothing else happens
1291 * 3) front engine gets moved to later in the current train, it is not a front engine anymore.
1292 * a) the 'next' part is a wagon that becomes a free wagon chain.
1293 * b) the 'next' part is an engine that becomes a front engine.
1294 * 4) free wagon gets moved
1295 * a) the 'next' part is a wagon that becomes a free wagon chain.
1296 * b) the 'next' part is an engine that becomes a front engine.
1297 * c) there is no 'next' part, nothing else happens
1298 * 5) non front engine gets moved and becomes a new train, nothing else happens
1299 * 6) non front engine gets moved within a train / to another train, nothing happens
1300 * 7) wagon gets moved, nothing happens
1301 */
1302 if (src == original_src_head && src->IsEngine() && !src->IsFrontEngine()) {
1303 /* Cases #2 and #3: the front engine gets trashed. */
1304 CloseWindowById(WC_VEHICLE_VIEW, src->index);
1305 CloseWindowById(WC_VEHICLE_ORDERS, src->index);
1306 CloseWindowById(WC_VEHICLE_REFIT, src->index);
1307 CloseWindowById(WC_VEHICLE_DETAILS, src->index);
1308 CloseWindowById(WC_VEHICLE_TIMETABLE, src->index);
1309 DeleteNewGRFInspectWindow(GSF_TRAINS, src->index);
1310 SetWindowDirty(WC_COMPANY, _current_company);
1311
1312 /* Delete orders, group stuff and the unit number as we're not the
1313 * front of any vehicle anymore. */
1314 DeleteVehicleOrders(src);
1315 RemoveVehicleFromGroup(src);
1316 src->unitnumber = 0;
1317 }
1318
1319 /* We weren't a front engine but are becoming one. So
1320 * we should be put in the default group. */
1321 if (original_src_head != src && dst_head == src) {
1322 SetTrainGroupID(src, DEFAULT_GROUP);
1323 SetWindowDirty(WC_COMPANY, _current_company);
1324 }
1325
1326 /* Add new heads to statistics */
1327 if (src_head != nullptr && src_head->IsFrontEngine()) GroupStatistics::CountVehicle(src_head, 1);
1328 if (dst_head != nullptr && dst_head->IsFrontEngine()) GroupStatistics::CountVehicle(dst_head, 1);
1329
1330 /* Handle 'new engine' part of cases #1b, #2b, #3b, #4b and #5 in NormaliseTrainHead. */
1331 NormaliseTrainHead(src_head);
1332 NormaliseTrainHead(dst_head);
1333
1334 if ((flags & DC_NO_CARGO_CAP_CHECK) == 0) {
1335 CheckCargoCapacity(src_head);
1336 CheckCargoCapacity(dst_head);
1337 }
1338
1339 if (src_head != nullptr) src_head->First()->MarkDirty();
1340 if (dst_head != nullptr) dst_head->First()->MarkDirty();
1341
1342 /* We are undoubtedly changing something in the depot and train list. */
1343 InvalidateWindowData(WC_VEHICLE_DEPOT, src->tile);
1344 InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
1345 } else {
1346 /* We don't want to execute what we're just tried. */
1347 RestoreTrainBackup(original_src);
1348 RestoreTrainBackup(original_dst);
1349 }
1350
1351 return CommandCost();
1352 }
1353
1354 /**
1355 * Sell a (single) train wagon/engine.
1356 * @param flags type of operation
1357 * @param t the train wagon to sell
1358 * @param data the selling mode
1359 * - data = 0: only sell the single dragged wagon/engine (and any belonging rear-engines)
1360 * - data = 1: sell the vehicle and all vehicles following it in the chain
1361 * if the wagon is dragged, don't delete the possibly belonging rear-engine to some front
1362 * @param user the user for the order backup.
1363 * @return the cost of this operation or an error
1364 */
CmdSellRailWagon(DoCommandFlag flags,Vehicle * t,uint16 data,uint32 user)1365 CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *t, uint16 data, uint32 user)
1366 {
1367 /* Sell a chain of vehicles or not? */
1368 bool sell_chain = HasBit(data, 0);
1369
1370 Train *v = Train::From(t)->GetFirstEnginePart();
1371 Train *first = v->First();
1372
1373 if (v->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
1374
1375 /* First make a backup of the order of the train. That way we can do
1376 * whatever we want with the order and later on easily revert. */
1377 TrainList original;
1378 MakeTrainBackup(original, first);
1379
1380 /* We need to keep track of the new head and the head of what we're going to sell. */
1381 Train *new_head = first;
1382 Train *sell_head = nullptr;
1383
1384 /* Split the train in the wanted way. */
1385 ArrangeTrains(&sell_head, nullptr, &new_head, v, sell_chain);
1386
1387 /* We don't need to validate the second train; it's going to be sold. */
1388 CommandCost ret = ValidateTrains(nullptr, nullptr, first, new_head, (flags & DC_AUTOREPLACE) == 0);
1389 if (ret.Failed()) {
1390 /* Restore the train we had. */
1391 RestoreTrainBackup(original);
1392 return ret;
1393 }
1394
1395 if (first->orders.list == nullptr && !OrderList::CanAllocateItem()) {
1396 /* Restore the train we had. */
1397 RestoreTrainBackup(original);
1398 return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
1399 }
1400
1401 CommandCost cost(EXPENSES_NEW_VEHICLES);
1402 for (Train *part = sell_head; part != nullptr; part = part->Next()) cost.AddCost(-part->value);
1403
1404 /* do it? */
1405 if (flags & DC_EXEC) {
1406 /* First normalise the sub types of the chain. */
1407 NormaliseSubtypes(new_head);
1408
1409 if (v == first && v->IsEngine() && !sell_chain && new_head != nullptr && new_head->IsFrontEngine()) {
1410 /* We are selling the front engine. In this case we want to
1411 * 'give' the order, unit number and such to the new head. */
1412 new_head->orders.list = first->orders.list;
1413 new_head->AddToShared(first);
1414 DeleteVehicleOrders(first);
1415
1416 /* Copy other important data from the front engine */
1417 new_head->CopyVehicleConfigAndStatistics(first);
1418 GroupStatistics::CountVehicle(new_head, 1); // after copying over the profit
1419 } else if (v->IsPrimaryVehicle() && data & (MAKE_ORDER_BACKUP_FLAG >> 20)) {
1420 OrderBackup::Backup(v, user);
1421 }
1422
1423 /* We need to update the information about the train. */
1424 NormaliseTrainHead(new_head);
1425
1426 /* We are undoubtedly changing something in the depot and train list. */
1427 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1428 InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
1429
1430 /* Actually delete the sold 'goods' */
1431 delete sell_head;
1432 } else {
1433 /* We don't want to execute what we're just tried. */
1434 RestoreTrainBackup(original);
1435 }
1436
1437 return cost;
1438 }
1439
UpdateDeltaXY()1440 void Train::UpdateDeltaXY()
1441 {
1442 /* Set common defaults. */
1443 this->x_offs = -1;
1444 this->y_offs = -1;
1445 this->x_extent = 3;
1446 this->y_extent = 3;
1447 this->z_extent = 6;
1448 this->x_bb_offs = 0;
1449 this->y_bb_offs = 0;
1450
1451 if (!IsDiagonalDirection(this->direction)) {
1452 static const int _sign_table[] =
1453 {
1454 /* x, y */
1455 -1, -1, // DIR_N
1456 -1, 1, // DIR_E
1457 1, 1, // DIR_S
1458 1, -1, // DIR_W
1459 };
1460
1461 int half_shorten = (VEHICLE_LENGTH - this->gcache.cached_veh_length) / 2;
1462
1463 /* For all straight directions, move the bound box to the centre of the vehicle, but keep the size. */
1464 this->x_offs -= half_shorten * _sign_table[this->direction];
1465 this->y_offs -= half_shorten * _sign_table[this->direction + 1];
1466 this->x_extent += this->x_bb_offs = half_shorten * _sign_table[direction];
1467 this->y_extent += this->y_bb_offs = half_shorten * _sign_table[direction + 1];
1468 } else {
1469 switch (this->direction) {
1470 /* Shorten southern corner of the bounding box according the vehicle length
1471 * and center the bounding box on the vehicle. */
1472 case DIR_NE:
1473 this->x_offs = 1 - (this->gcache.cached_veh_length + 1) / 2;
1474 this->x_extent = this->gcache.cached_veh_length - 1;
1475 this->x_bb_offs = -1;
1476 break;
1477
1478 case DIR_NW:
1479 this->y_offs = 1 - (this->gcache.cached_veh_length + 1) / 2;
1480 this->y_extent = this->gcache.cached_veh_length - 1;
1481 this->y_bb_offs = -1;
1482 break;
1483
1484 /* Move northern corner of the bounding box down according to vehicle length
1485 * and center the bounding box on the vehicle. */
1486 case DIR_SW:
1487 this->x_offs = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH;
1488 this->x_extent = VEHICLE_LENGTH - 1;
1489 this->x_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
1490 break;
1491
1492 case DIR_SE:
1493 this->y_offs = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH;
1494 this->y_extent = VEHICLE_LENGTH - 1;
1495 this->y_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
1496 break;
1497
1498 default:
1499 NOT_REACHED();
1500 }
1501 }
1502 }
1503
1504 /**
1505 * Mark a train as stuck and stop it if it isn't stopped right now.
1506 * @param v %Train to mark as being stuck.
1507 */
MarkTrainAsStuck(Train * v)1508 static void MarkTrainAsStuck(Train *v)
1509 {
1510 if (!HasBit(v->flags, VRF_TRAIN_STUCK)) {
1511 /* It is the first time the problem occurred, set the "train stuck" flag. */
1512 SetBit(v->flags, VRF_TRAIN_STUCK);
1513
1514 v->wait_counter = 0;
1515
1516 /* Stop train */
1517 v->cur_speed = 0;
1518 v->subspeed = 0;
1519 v->SetLastSpeed();
1520
1521 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
1522 }
1523 }
1524
1525 /**
1526 * Swap the two up/down flags in two ways:
1527 * - Swap values of \a swap_flag1 and \a swap_flag2, and
1528 * - If going up previously (#GVF_GOINGUP_BIT set), the #GVF_GOINGDOWN_BIT is set, and vice versa.
1529 * @param[in,out] swap_flag1 First train flag.
1530 * @param[in,out] swap_flag2 Second train flag.
1531 */
SwapTrainFlags(uint16 * swap_flag1,uint16 * swap_flag2)1532 static void SwapTrainFlags(uint16 *swap_flag1, uint16 *swap_flag2)
1533 {
1534 uint16 flag1 = *swap_flag1;
1535 uint16 flag2 = *swap_flag2;
1536
1537 /* Clear the flags */
1538 ClrBit(*swap_flag1, GVF_GOINGUP_BIT);
1539 ClrBit(*swap_flag1, GVF_GOINGDOWN_BIT);
1540 ClrBit(*swap_flag2, GVF_GOINGUP_BIT);
1541 ClrBit(*swap_flag2, GVF_GOINGDOWN_BIT);
1542
1543 /* Reverse the rail-flags (if needed) */
1544 if (HasBit(flag1, GVF_GOINGUP_BIT)) {
1545 SetBit(*swap_flag2, GVF_GOINGDOWN_BIT);
1546 } else if (HasBit(flag1, GVF_GOINGDOWN_BIT)) {
1547 SetBit(*swap_flag2, GVF_GOINGUP_BIT);
1548 }
1549 if (HasBit(flag2, GVF_GOINGUP_BIT)) {
1550 SetBit(*swap_flag1, GVF_GOINGDOWN_BIT);
1551 } else if (HasBit(flag2, GVF_GOINGDOWN_BIT)) {
1552 SetBit(*swap_flag1, GVF_GOINGUP_BIT);
1553 }
1554 }
1555
1556 /**
1557 * Updates some variables after swapping the vehicle.
1558 * @param v swapped vehicle
1559 */
UpdateStatusAfterSwap(Train * v)1560 static void UpdateStatusAfterSwap(Train *v)
1561 {
1562 /* Reverse the direction. */
1563 if (v->track != TRACK_BIT_DEPOT) v->direction = ReverseDir(v->direction);
1564
1565 /* Call the proper EnterTile function unless we are in a wormhole. */
1566 if (v->track != TRACK_BIT_WORMHOLE) {
1567 VehicleEnterTile(v, v->tile, v->x_pos, v->y_pos);
1568 } else {
1569 /* VehicleEnter_TunnelBridge() sets TRACK_BIT_WORMHOLE when the vehicle
1570 * is on the last bit of the bridge head (frame == TILE_SIZE - 1).
1571 * If we were swapped with such a vehicle, we have set TRACK_BIT_WORMHOLE,
1572 * when we shouldn't have. Check if this is the case. */
1573 TileIndex vt = TileVirtXY(v->x_pos, v->y_pos);
1574 if (IsTileType(vt, MP_TUNNELBRIDGE)) {
1575 VehicleEnterTile(v, vt, v->x_pos, v->y_pos);
1576 if (v->track != TRACK_BIT_WORMHOLE && IsBridgeTile(v->tile)) {
1577 /* We have just left the wormhole, possibly set the
1578 * "goingdown" bit. UpdateInclination() can be used
1579 * because we are at the border of the tile. */
1580 v->UpdatePosition();
1581 v->UpdateInclination(true, true);
1582 return;
1583 }
1584 }
1585 }
1586
1587 v->UpdatePosition();
1588 v->UpdateViewport(true, true);
1589 }
1590
1591 /**
1592 * Swap vehicles \a l and \a r in consist \a v, and reverse their direction.
1593 * @param v Consist to change.
1594 * @param l %Vehicle index in the consist of the first vehicle.
1595 * @param r %Vehicle index in the consist of the second vehicle.
1596 */
ReverseTrainSwapVeh(Train * v,int l,int r)1597 void ReverseTrainSwapVeh(Train *v, int l, int r)
1598 {
1599 Train *a, *b;
1600
1601 /* locate vehicles to swap */
1602 for (a = v; l != 0; l--) a = a->Next();
1603 for (b = v; r != 0; r--) b = b->Next();
1604
1605 if (a != b) {
1606 /* swap the hidden bits */
1607 {
1608 uint16 tmp = (a->vehstatus & ~VS_HIDDEN) | (b->vehstatus & VS_HIDDEN);
1609 b->vehstatus = (b->vehstatus & ~VS_HIDDEN) | (a->vehstatus & VS_HIDDEN);
1610 a->vehstatus = tmp;
1611 }
1612
1613 Swap(a->track, b->track);
1614 Swap(a->direction, b->direction);
1615 Swap(a->x_pos, b->x_pos);
1616 Swap(a->y_pos, b->y_pos);
1617 Swap(a->tile, b->tile);
1618 Swap(a->z_pos, b->z_pos);
1619
1620 SwapTrainFlags(&a->gv_flags, &b->gv_flags);
1621
1622 UpdateStatusAfterSwap(a);
1623 UpdateStatusAfterSwap(b);
1624 } else {
1625 /* Swap GVF_GOINGUP_BIT/GVF_GOINGDOWN_BIT.
1626 * This is a little bit redundant way, a->gv_flags will
1627 * be (re)set twice, but it reduces code duplication */
1628 SwapTrainFlags(&a->gv_flags, &a->gv_flags);
1629 UpdateStatusAfterSwap(a);
1630 }
1631 }
1632
1633
1634 /**
1635 * Check if the vehicle is a train
1636 * @param v vehicle on tile
1637 * @return v if it is a train, nullptr otherwise
1638 */
TrainOnTileEnum(Vehicle * v,void *)1639 static Vehicle *TrainOnTileEnum(Vehicle *v, void *)
1640 {
1641 return (v->type == VEH_TRAIN) ? v : nullptr;
1642 }
1643
1644
1645 /**
1646 * Checks if a train is approaching a rail-road crossing
1647 * @param v vehicle on tile
1648 * @param data tile with crossing we are testing
1649 * @return v if it is approaching a crossing, nullptr otherwise
1650 */
TrainApproachingCrossingEnum(Vehicle * v,void * data)1651 static Vehicle *TrainApproachingCrossingEnum(Vehicle *v, void *data)
1652 {
1653 if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return nullptr;
1654
1655 Train *t = Train::From(v);
1656 if (!t->IsFrontEngine()) return nullptr;
1657
1658 TileIndex tile = *(TileIndex *)data;
1659
1660 if (TrainApproachingCrossingTile(t) != tile) return nullptr;
1661
1662 return t;
1663 }
1664
1665
1666 /**
1667 * Finds a vehicle approaching rail-road crossing
1668 * @param tile tile to test
1669 * @return true if a vehicle is approaching the crossing
1670 * @pre tile is a rail-road crossing
1671 */
TrainApproachingCrossing(TileIndex tile)1672 static bool TrainApproachingCrossing(TileIndex tile)
1673 {
1674 assert(IsLevelCrossingTile(tile));
1675
1676 DiagDirection dir = AxisToDiagDir(GetCrossingRailAxis(tile));
1677 TileIndex tile_from = tile + TileOffsByDiagDir(dir);
1678
1679 if (HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum)) return true;
1680
1681 dir = ReverseDiagDir(dir);
1682 tile_from = tile + TileOffsByDiagDir(dir);
1683
1684 return HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum);
1685 }
1686
1687
1688 /**
1689 * Sets correct crossing state
1690 * @param tile tile to update
1691 * @param sound should we play sound?
1692 * @pre tile is a rail-road crossing
1693 */
UpdateLevelCrossing(TileIndex tile,bool sound)1694 void UpdateLevelCrossing(TileIndex tile, bool sound)
1695 {
1696 assert(IsLevelCrossingTile(tile));
1697
1698 /* reserved || train on crossing || train approaching crossing */
1699 bool new_state = HasCrossingReservation(tile) || HasVehicleOnPos(tile, nullptr, &TrainOnTileEnum) || TrainApproachingCrossing(tile);
1700
1701 if (new_state != IsCrossingBarred(tile)) {
1702 if (new_state && sound) {
1703 if (_settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
1704 }
1705 SetCrossingBarred(tile, new_state);
1706 MarkTileDirtyByTile(tile);
1707 }
1708 }
1709
1710
1711 /**
1712 * Bars crossing and plays ding-ding sound if not barred already
1713 * @param tile tile with crossing
1714 * @pre tile is a rail-road crossing
1715 */
MaybeBarCrossingWithSound(TileIndex tile)1716 static inline void MaybeBarCrossingWithSound(TileIndex tile)
1717 {
1718 if (!IsCrossingBarred(tile)) {
1719 BarCrossing(tile);
1720 if (_settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
1721 MarkTileDirtyByTile(tile);
1722 }
1723 }
1724
1725
1726 /**
1727 * Advances wagons for train reversing, needed for variable length wagons.
1728 * This one is called before the train is reversed.
1729 * @param v First vehicle in chain
1730 */
AdvanceWagonsBeforeSwap(Train * v)1731 static void AdvanceWagonsBeforeSwap(Train *v)
1732 {
1733 Train *base = v;
1734 Train *first = base; // first vehicle to move
1735 Train *last = v->Last(); // last vehicle to move
1736 uint length = CountVehiclesInChain(v);
1737
1738 while (length > 2) {
1739 last = last->Previous();
1740 first = first->Next();
1741
1742 int differential = base->CalcNextVehicleOffset() - last->CalcNextVehicleOffset();
1743
1744 /* do not update images now
1745 * negative differential will be handled in AdvanceWagonsAfterSwap() */
1746 for (int i = 0; i < differential; i++) TrainController(first, last->Next());
1747
1748 base = first; // == base->Next()
1749 length -= 2;
1750 }
1751 }
1752
1753
1754 /**
1755 * Advances wagons for train reversing, needed for variable length wagons.
1756 * This one is called after the train is reversed.
1757 * @param v First vehicle in chain
1758 */
AdvanceWagonsAfterSwap(Train * v)1759 static void AdvanceWagonsAfterSwap(Train *v)
1760 {
1761 /* first of all, fix the situation when the train was entering a depot */
1762 Train *dep = v; // last vehicle in front of just left depot
1763 while (dep->Next() != nullptr && (dep->track == TRACK_BIT_DEPOT || dep->Next()->track != TRACK_BIT_DEPOT)) {
1764 dep = dep->Next(); // find first vehicle outside of a depot, with next vehicle inside a depot
1765 }
1766
1767 Train *leave = dep->Next(); // first vehicle in a depot we are leaving now
1768
1769 if (leave != nullptr) {
1770 /* 'pull' next wagon out of the depot, so we won't miss it (it could stay in depot forever) */
1771 int d = TicksToLeaveDepot(dep);
1772
1773 if (d <= 0) {
1774 leave->vehstatus &= ~VS_HIDDEN; // move it out of the depot
1775 leave->track = TrackToTrackBits(GetRailDepotTrack(leave->tile));
1776 for (int i = 0; i >= d; i--) TrainController(leave, nullptr); // maybe move it, and maybe let another wagon leave
1777 }
1778 } else {
1779 dep = nullptr; // no vehicle in a depot, so no vehicle leaving a depot
1780 }
1781
1782 Train *base = v;
1783 Train *first = base; // first vehicle to move
1784 Train *last = v->Last(); // last vehicle to move
1785 uint length = CountVehiclesInChain(v);
1786
1787 /* We have to make sure all wagons that leave a depot because of train reversing are moved correctly
1788 * they have already correct spacing, so we have to make sure they are moved how they should */
1789 bool nomove = (dep == nullptr); // If there is no vehicle leaving a depot, limit the number of wagons moved immediately.
1790
1791 while (length > 2) {
1792 /* we reached vehicle (originally) in front of a depot, stop now
1793 * (we would move wagons that are already moved with new wagon length). */
1794 if (base == dep) break;
1795
1796 /* the last wagon was that one leaving a depot, so do not move it anymore */
1797 if (last == dep) nomove = true;
1798
1799 last = last->Previous();
1800 first = first->Next();
1801
1802 int differential = last->CalcNextVehicleOffset() - base->CalcNextVehicleOffset();
1803
1804 /* do not update images now */
1805 for (int i = 0; i < differential; i++) TrainController(first, (nomove ? last->Next() : nullptr));
1806
1807 base = first; // == base->Next()
1808 length -= 2;
1809 }
1810 }
1811
IsWholeTrainInsideDepot(const Train * v)1812 static bool IsWholeTrainInsideDepot(const Train *v)
1813 {
1814 for (const Train *u = v; u != nullptr; u = u->Next()) {
1815 if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return false;
1816 }
1817 return true;
1818 }
1819
1820 /**
1821 * Turn a train around.
1822 * @param v %Train to turn around.
1823 */
ReverseTrainDirection(Train * v)1824 void ReverseTrainDirection(Train *v)
1825 {
1826 if (IsRailDepotTile(v->tile)) {
1827 if (IsWholeTrainInsideDepot(v)) return;
1828 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1829 }
1830
1831 /* Clear path reservation in front if train is not stuck. */
1832 if (!HasBit(v->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(v);
1833
1834 /* Check if we were approaching a rail/road-crossing */
1835 TileIndex crossing = TrainApproachingCrossingTile(v);
1836
1837 /* count number of vehicles */
1838 int r = CountVehiclesInChain(v) - 1; // number of vehicles - 1
1839
1840 AdvanceWagonsBeforeSwap(v);
1841
1842 /* swap start<>end, start+1<>end-1, ... */
1843 int l = 0;
1844 do {
1845 ReverseTrainSwapVeh(v, l++, r--);
1846 } while (l <= r);
1847
1848 AdvanceWagonsAfterSwap(v);
1849
1850 if (IsRailDepotTile(v->tile)) {
1851 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1852 }
1853
1854 ToggleBit(v->flags, VRF_TOGGLE_REVERSE);
1855
1856 ClrBit(v->flags, VRF_REVERSING);
1857
1858 /* recalculate cached data */
1859 v->ConsistChanged(CCF_TRACK);
1860
1861 /* update all images */
1862 for (Train *u = v; u != nullptr; u = u->Next()) u->UpdateViewport(false, false);
1863
1864 /* update crossing we were approaching */
1865 if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
1866
1867 /* maybe we are approaching crossing now, after reversal */
1868 crossing = TrainApproachingCrossingTile(v);
1869 if (crossing != INVALID_TILE) MaybeBarCrossingWithSound(crossing);
1870
1871 /* If we are inside a depot after reversing, don't bother with path reserving. */
1872 if (v->track == TRACK_BIT_DEPOT) {
1873 /* Can't be stuck here as inside a depot is always a safe tile. */
1874 if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
1875 ClrBit(v->flags, VRF_TRAIN_STUCK);
1876 return;
1877 }
1878
1879 /* VehicleExitDir does not always produce the desired dir for depots and
1880 * tunnels/bridges that is needed for UpdateSignalsOnSegment. */
1881 DiagDirection dir = VehicleExitDir(v->direction, v->track);
1882 if (IsRailDepotTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE)) dir = INVALID_DIAGDIR;
1883
1884 if (UpdateSignalsOnSegment(v->tile, dir, v->owner) == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
1885 /* If we are currently on a tile with conventional signals, we can't treat the
1886 * current tile as a safe tile or we would enter a PBS block without a reservation. */
1887 bool first_tile_okay = !(IsTileType(v->tile, MP_RAILWAY) &&
1888 HasSignalOnTrackdir(v->tile, v->GetVehicleTrackdir()) &&
1889 !IsPbsSignal(GetSignalType(v->tile, FindFirstTrack(v->track))));
1890
1891 /* If we are on a depot tile facing outwards, do not treat the current tile as safe. */
1892 if (IsRailDepotTile(v->tile) && TrackdirToExitdir(v->GetVehicleTrackdir()) == GetRailDepotDirection(v->tile)) first_tile_okay = false;
1893
1894 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
1895 if (TryPathReserve(v, false, first_tile_okay)) {
1896 /* Do a look-ahead now in case our current tile was already a safe tile. */
1897 CheckNextTrainTile(v);
1898 } else if (v->current_order.GetType() != OT_LOADING) {
1899 /* Do not wait for a way out when we're still loading */
1900 MarkTrainAsStuck(v);
1901 }
1902 } else if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
1903 /* A train not inside a PBS block can't be stuck. */
1904 ClrBit(v->flags, VRF_TRAIN_STUCK);
1905 v->wait_counter = 0;
1906 }
1907 }
1908
1909 /**
1910 * Reverse train.
1911 * @param tile unused
1912 * @param flags type of operation
1913 * @param p1 train to reverse
1914 * @param p2 if true, reverse a unit in a train (needs to be in a depot)
1915 * @param text unused
1916 * @return the cost of this operation or an error
1917 */
CmdReverseTrainDirection(TileIndex tile,DoCommandFlag flags,uint32 p1,uint32 p2,const std::string & text)1918 CommandCost CmdReverseTrainDirection(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text)
1919 {
1920 Train *v = Train::GetIfValid(p1);
1921 if (v == nullptr) return CMD_ERROR;
1922
1923 CommandCost ret = CheckOwnership(v->owner);
1924 if (ret.Failed()) return ret;
1925
1926 if (p2 != 0) {
1927 /* turn a single unit around */
1928
1929 if (v->IsMultiheaded() || HasBit(EngInfo(v->engine_type)->callback_mask, CBM_VEHICLE_ARTIC_ENGINE)) {
1930 return_cmd_error(STR_ERROR_CAN_T_REVERSE_DIRECTION_RAIL_VEHICLE_MULTIPLE_UNITS);
1931 }
1932 if (!HasBit(EngInfo(v->engine_type)->misc_flags, EF_RAIL_FLIPS)) return CMD_ERROR;
1933
1934 Train *front = v->First();
1935 /* make sure the vehicle is stopped in the depot */
1936 if (!front->IsStoppedInDepot()) {
1937 return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1938 }
1939
1940 if (flags & DC_EXEC) {
1941 ToggleBit(v->flags, VRF_REVERSE_DIRECTION);
1942
1943 front->ConsistChanged(CCF_ARRANGE);
1944 SetWindowDirty(WC_VEHICLE_DEPOT, front->tile);
1945 SetWindowDirty(WC_VEHICLE_DETAILS, front->index);
1946 SetWindowDirty(WC_VEHICLE_VIEW, front->index);
1947 SetWindowClassesDirty(WC_TRAINS_LIST);
1948 }
1949 } else {
1950 /* turn the whole train around */
1951 if ((v->vehstatus & VS_CRASHED) || v->breakdown_ctr != 0) return CMD_ERROR;
1952
1953 if (flags & DC_EXEC) {
1954 /* Properly leave the station if we are loading and won't be loading anymore */
1955 if (v->current_order.IsType(OT_LOADING)) {
1956 const Vehicle *last = v;
1957 while (last->Next() != nullptr) last = last->Next();
1958
1959 /* not a station || different station --> leave the station */
1960 if (!IsTileType(last->tile, MP_STATION) || GetStationIndex(last->tile) != GetStationIndex(v->tile)) {
1961 v->LeaveStation();
1962 }
1963 }
1964
1965 /* We cancel any 'skip signal at dangers' here */
1966 v->force_proceed = TFP_NONE;
1967 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
1968
1969 if (_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL && v->cur_speed != 0) {
1970 ToggleBit(v->flags, VRF_REVERSING);
1971 } else {
1972 v->cur_speed = 0;
1973 v->SetLastSpeed();
1974 HideFillingPercent(&v->fill_percent_te_id);
1975 ReverseTrainDirection(v);
1976 }
1977 }
1978 }
1979 return CommandCost();
1980 }
1981
1982 /**
1983 * Force a train through a red signal
1984 * @param tile unused
1985 * @param flags type of operation
1986 * @param p1 train to ignore the red signal
1987 * @param p2 unused
1988 * @param text unused
1989 * @return the cost of this operation or an error
1990 */
CmdForceTrainProceed(TileIndex tile,DoCommandFlag flags,uint32 p1,uint32 p2,const std::string & text)1991 CommandCost CmdForceTrainProceed(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text)
1992 {
1993 Train *t = Train::GetIfValid(p1);
1994 if (t == nullptr) return CMD_ERROR;
1995
1996 if (!t->IsPrimaryVehicle()) return CMD_ERROR;
1997
1998 CommandCost ret = CheckOwnership(t->owner);
1999 if (ret.Failed()) return ret;
2000
2001
2002 if (flags & DC_EXEC) {
2003 /* If we are forced to proceed, cancel that order.
2004 * If we are marked stuck we would want to force the train
2005 * to proceed to the next signal. In the other cases we
2006 * would like to pass the signal at danger and run till the
2007 * next signal we encounter. */
2008 t->force_proceed = t->force_proceed == TFP_SIGNAL ? TFP_NONE : HasBit(t->flags, VRF_TRAIN_STUCK) || t->IsChainInDepot() ? TFP_STUCK : TFP_SIGNAL;
2009 SetWindowDirty(WC_VEHICLE_VIEW, t->index);
2010 }
2011
2012 return CommandCost();
2013 }
2014
2015 /**
2016 * Try to find a depot nearby.
2017 * @param v %Train that wants a depot.
2018 * @param max_distance Maximal search distance.
2019 * @return Information where the closest train depot is located.
2020 * @pre The given vehicle must not be crashed!
2021 */
FindClosestTrainDepot(Train * v,int max_distance)2022 static FindDepotData FindClosestTrainDepot(Train *v, int max_distance)
2023 {
2024 assert(!(v->vehstatus & VS_CRASHED));
2025
2026 if (IsRailDepotTile(v->tile)) return FindDepotData(v->tile, 0);
2027
2028 PBSTileInfo origin = FollowTrainReservation(v);
2029 if (IsRailDepotTile(origin.tile)) return FindDepotData(origin.tile, 0);
2030
2031 switch (_settings_game.pf.pathfinder_for_trains) {
2032 case VPF_NPF: return NPFTrainFindNearestDepot(v, max_distance);
2033 case VPF_YAPF: return YapfTrainFindNearestDepot(v, max_distance);
2034
2035 default: NOT_REACHED();
2036 }
2037 }
2038
2039 /**
2040 * Locate the closest depot for this consist, and return the information to the caller.
2041 * @param[out] location If not \c nullptr and a depot is found, store its location in the given address.
2042 * @param[out] destination If not \c nullptr and a depot is found, store its index in the given address.
2043 * @param[out] reverse If not \c nullptr and a depot is found, store reversal information in the given address.
2044 * @return A depot has been found.
2045 */
FindClosestDepot(TileIndex * location,DestinationID * destination,bool * reverse)2046 bool Train::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
2047 {
2048 FindDepotData tfdd = FindClosestTrainDepot(this, 0);
2049 if (tfdd.best_length == UINT_MAX) return false;
2050
2051 if (location != nullptr) *location = tfdd.tile;
2052 if (destination != nullptr) *destination = GetDepotIndex(tfdd.tile);
2053 if (reverse != nullptr) *reverse = tfdd.reverse;
2054
2055 return true;
2056 }
2057
2058 /** Play a sound for a train leaving the station. */
PlayLeaveStationSound() const2059 void Train::PlayLeaveStationSound() const
2060 {
2061 static const SoundFx sfx[] = {
2062 SND_04_DEPARTURE_STEAM,
2063 SND_0A_DEPARTURE_TRAIN,
2064 SND_0A_DEPARTURE_TRAIN,
2065 SND_47_DEPARTURE_MONORAIL,
2066 SND_41_DEPARTURE_MAGLEV
2067 };
2068
2069 if (PlayVehicleSound(this, VSE_START)) return;
2070
2071 EngineID engtype = this->engine_type;
2072 SndPlayVehicleFx(sfx[RailVehInfo(engtype)->engclass], this);
2073 }
2074
2075 /**
2076 * Check if the train is on the last reserved tile and try to extend the path then.
2077 * @param v %Train that needs its path extended.
2078 */
CheckNextTrainTile(Train * v)2079 static void CheckNextTrainTile(Train *v)
2080 {
2081 /* Don't do any look-ahead if path_backoff_interval is 255. */
2082 if (_settings_game.pf.path_backoff_interval == 255) return;
2083
2084 /* Exit if we are inside a depot. */
2085 if (v->track == TRACK_BIT_DEPOT) return;
2086
2087 switch (v->current_order.GetType()) {
2088 /* Exit if we reached our destination depot. */
2089 case OT_GOTO_DEPOT:
2090 if (v->tile == v->dest_tile) return;
2091 break;
2092
2093 case OT_GOTO_WAYPOINT:
2094 /* If we reached our waypoint, make sure we see that. */
2095 if (IsRailWaypointTile(v->tile) && GetStationIndex(v->tile) == v->current_order.GetDestination()) ProcessOrders(v);
2096 break;
2097
2098 case OT_NOTHING:
2099 case OT_LEAVESTATION:
2100 case OT_LOADING:
2101 /* Exit if the current order doesn't have a destination, but the train has orders. */
2102 if (v->GetNumOrders() > 0) return;
2103 break;
2104
2105 default:
2106 break;
2107 }
2108 /* Exit if we are on a station tile and are going to stop. */
2109 if (IsRailStationTile(v->tile) && v->current_order.ShouldStopAtStation(v, GetStationIndex(v->tile))) return;
2110
2111 Trackdir td = v->GetVehicleTrackdir();
2112
2113 /* On a tile with a red non-pbs signal, don't look ahead. */
2114 if (IsTileType(v->tile, MP_RAILWAY) && HasSignalOnTrackdir(v->tile, td) &&
2115 !IsPbsSignal(GetSignalType(v->tile, TrackdirToTrack(td))) &&
2116 GetSignalStateByTrackdir(v->tile, td) == SIGNAL_STATE_RED) return;
2117
2118 CFollowTrackRail ft(v);
2119 if (!ft.Follow(v->tile, td)) return;
2120
2121 if (!HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(ft.m_new_td_bits))) {
2122 /* Next tile is not reserved. */
2123 if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
2124 if (HasPbsSignalOnTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) {
2125 /* If the next tile is a PBS signal, try to make a reservation. */
2126 TrackBits tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
2127 if (Rail90DegTurnDisallowed(GetTileRailType(ft.m_old_tile), GetTileRailType(ft.m_new_tile))) {
2128 tracks &= ~TrackCrossesTracks(TrackdirToTrack(ft.m_old_td));
2129 }
2130 ChooseTrainTrack(v, ft.m_new_tile, ft.m_exitdir, tracks, false, nullptr, false);
2131 }
2132 }
2133 }
2134 }
2135
2136 /**
2137 * Will the train stay in the depot the next tick?
2138 * @param v %Train to check.
2139 * @return True if it stays in the depot, false otherwise.
2140 */
CheckTrainStayInDepot(Train * v)2141 static bool CheckTrainStayInDepot(Train *v)
2142 {
2143 /* bail out if not all wagons are in the same depot or not in a depot at all */
2144 for (const Train *u = v; u != nullptr; u = u->Next()) {
2145 if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return false;
2146 }
2147
2148 /* if the train got no power, then keep it in the depot */
2149 if (v->gcache.cached_power == 0) {
2150 v->vehstatus |= VS_STOPPED;
2151 SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
2152 return true;
2153 }
2154
2155 SigSegState seg_state;
2156
2157 if (v->force_proceed == TFP_NONE) {
2158 /* force proceed was not pressed */
2159 if (++v->wait_counter < 37) {
2160 SetWindowClassesDirty(WC_TRAINS_LIST);
2161 return true;
2162 }
2163
2164 v->wait_counter = 0;
2165
2166 seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
2167 if (seg_state == SIGSEG_FULL || HasDepotReservation(v->tile)) {
2168 /* Full and no PBS signal in block or depot reserved, can't exit. */
2169 SetWindowClassesDirty(WC_TRAINS_LIST);
2170 return true;
2171 }
2172 } else {
2173 seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
2174 }
2175
2176 /* We are leaving a depot, but have to go to the exact same one; re-enter. */
2177 if (v->current_order.IsType(OT_GOTO_DEPOT) && v->tile == v->dest_tile) {
2178 /* Service when depot has no reservation. */
2179 if (!HasDepotReservation(v->tile)) VehicleEnterDepot(v);
2180 return true;
2181 }
2182
2183 /* Only leave when we can reserve a path to our destination. */
2184 if (seg_state == SIGSEG_PBS && !TryPathReserve(v) && v->force_proceed == TFP_NONE) {
2185 /* No path and no force proceed. */
2186 SetWindowClassesDirty(WC_TRAINS_LIST);
2187 MarkTrainAsStuck(v);
2188 return true;
2189 }
2190
2191 SetDepotReservation(v->tile, true);
2192 if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
2193
2194 VehicleServiceInDepot(v);
2195 SetWindowClassesDirty(WC_TRAINS_LIST);
2196 v->PlayLeaveStationSound();
2197
2198 v->track = TRACK_BIT_X;
2199 if (v->direction & 2) v->track = TRACK_BIT_Y;
2200
2201 v->vehstatus &= ~VS_HIDDEN;
2202 v->cur_speed = 0;
2203
2204 v->UpdateViewport(true, true);
2205 v->UpdatePosition();
2206 UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
2207 v->UpdateAcceleration();
2208 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
2209
2210 return false;
2211 }
2212
2213 /**
2214 * Clear the reservation of \a tile that was just left by a wagon on \a track_dir.
2215 * @param v %Train owning the reservation.
2216 * @param tile Tile with reservation to clear.
2217 * @param track_dir Track direction to clear.
2218 */
ClearPathReservation(const Train * v,TileIndex tile,Trackdir track_dir)2219 static void ClearPathReservation(const Train *v, TileIndex tile, Trackdir track_dir)
2220 {
2221 DiagDirection dir = TrackdirToExitdir(track_dir);
2222
2223 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
2224 /* Are we just leaving a tunnel/bridge? */
2225 if (GetTunnelBridgeDirection(tile) == ReverseDiagDir(dir)) {
2226 TileIndex end = GetOtherTunnelBridgeEnd(tile);
2227
2228 if (TunnelBridgeIsFree(tile, end, v).Succeeded()) {
2229 /* Free the reservation only if no other train is on the tiles. */
2230 SetTunnelBridgeReservation(tile, false);
2231 SetTunnelBridgeReservation(end, false);
2232
2233 if (_settings_client.gui.show_track_reservation) {
2234 if (IsBridge(tile)) {
2235 MarkBridgeDirty(tile);
2236 } else {
2237 MarkTileDirtyByTile(tile);
2238 MarkTileDirtyByTile(end);
2239 }
2240 }
2241 }
2242 }
2243 } else if (IsRailStationTile(tile)) {
2244 TileIndex new_tile = TileAddByDiagDir(tile, dir);
2245 /* If the new tile is not a further tile of the same station, we
2246 * clear the reservation for the whole platform. */
2247 if (!IsCompatibleTrainStationTile(new_tile, tile)) {
2248 SetRailStationPlatformReservation(tile, ReverseDiagDir(dir), false);
2249 }
2250 } else {
2251 /* Any other tile */
2252 UnreserveRailTrack(tile, TrackdirToTrack(track_dir));
2253 }
2254 }
2255
2256 /**
2257 * Free the reserved path in front of a vehicle.
2258 * @param v %Train owning the reserved path.
2259 */
FreeTrainTrackReservation(const Train * v)2260 void FreeTrainTrackReservation(const Train *v)
2261 {
2262 assert(v->IsFrontEngine());
2263
2264 TileIndex tile = v->tile;
2265 Trackdir td = v->GetVehicleTrackdir();
2266 bool free_tile = !(IsRailStationTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE));
2267 StationID station_id = IsRailStationTile(v->tile) ? GetStationIndex(v->tile) : INVALID_STATION;
2268
2269 /* Can't be holding a reservation if we enter a depot. */
2270 if (IsRailDepotTile(tile) && TrackdirToExitdir(td) != GetRailDepotDirection(tile)) return;
2271 if (v->track == TRACK_BIT_DEPOT) {
2272 /* Front engine is in a depot. We enter if some part is not in the depot. */
2273 for (const Train *u = v; u != nullptr; u = u->Next()) {
2274 if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return;
2275 }
2276 }
2277 /* Don't free reservation if it's not ours. */
2278 if (TracksOverlap(GetReservedTrackbits(tile) | TrackToTrackBits(TrackdirToTrack(td)))) return;
2279
2280 CFollowTrackRail ft(v, GetRailTypeInfo(v->railtype)->compatible_railtypes);
2281 while (ft.Follow(tile, td)) {
2282 tile = ft.m_new_tile;
2283 TrackdirBits bits = ft.m_new_td_bits & TrackBitsToTrackdirBits(GetReservedTrackbits(tile));
2284 td = RemoveFirstTrackdir(&bits);
2285 assert(bits == TRACKDIR_BIT_NONE);
2286
2287 if (!IsValidTrackdir(td)) break;
2288
2289 if (IsTileType(tile, MP_RAILWAY)) {
2290 if (HasSignalOnTrackdir(tile, td) && !IsPbsSignal(GetSignalType(tile, TrackdirToTrack(td)))) {
2291 /* Conventional signal along trackdir: remove reservation and stop. */
2292 UnreserveRailTrack(tile, TrackdirToTrack(td));
2293 break;
2294 }
2295 if (HasPbsSignalOnTrackdir(tile, td)) {
2296 if (GetSignalStateByTrackdir(tile, td) == SIGNAL_STATE_RED) {
2297 /* Red PBS signal? Can't be our reservation, would be green then. */
2298 break;
2299 } else {
2300 /* Turn the signal back to red. */
2301 SetSignalStateByTrackdir(tile, td, SIGNAL_STATE_RED);
2302 MarkTileDirtyByTile(tile);
2303 }
2304 } else if (HasSignalOnTrackdir(tile, ReverseTrackdir(td)) && IsOnewaySignal(tile, TrackdirToTrack(td))) {
2305 break;
2306 }
2307 }
2308
2309 /* Don't free first station/bridge/tunnel if we are on it. */
2310 if (free_tile || (!(ft.m_is_station && GetStationIndex(ft.m_new_tile) == station_id) && !ft.m_is_tunnel && !ft.m_is_bridge)) ClearPathReservation(v, tile, td);
2311
2312 free_tile = true;
2313 }
2314 }
2315
2316 static const byte _initial_tile_subcoord[6][4][3] = {
2317 {{ 15, 8, 1 }, { 0, 0, 0 }, { 0, 8, 5 }, { 0, 0, 0 }},
2318 {{ 0, 0, 0 }, { 8, 0, 3 }, { 0, 0, 0 }, { 8, 15, 7 }},
2319 {{ 0, 0, 0 }, { 7, 0, 2 }, { 0, 7, 6 }, { 0, 0, 0 }},
2320 {{ 15, 8, 2 }, { 0, 0, 0 }, { 0, 0, 0 }, { 8, 15, 6 }},
2321 {{ 15, 7, 0 }, { 8, 0, 4 }, { 0, 0, 0 }, { 0, 0, 0 }},
2322 {{ 0, 0, 0 }, { 0, 0, 0 }, { 0, 8, 4 }, { 7, 15, 0 }},
2323 };
2324
2325 /**
2326 * Perform pathfinding for a train.
2327 *
2328 * @param v The train
2329 * @param tile The tile the train is about to enter
2330 * @param enterdir Diagonal direction the train is coming from
2331 * @param tracks Usable tracks on the new tile
2332 * @param[out] path_found Whether a path has been found or not.
2333 * @param do_track_reservation Path reservation is requested
2334 * @param[out] dest State and destination of the requested path
2335 * @return The best track the train should follow
2336 */
DoTrainPathfind(const Train * v,TileIndex tile,DiagDirection enterdir,TrackBits tracks,bool & path_found,bool do_track_reservation,PBSTileInfo * dest)2337 static Track DoTrainPathfind(const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found, bool do_track_reservation, PBSTileInfo *dest)
2338 {
2339 switch (_settings_game.pf.pathfinder_for_trains) {
2340 case VPF_NPF: return NPFTrainChooseTrack(v, path_found, do_track_reservation, dest);
2341 case VPF_YAPF: return YapfTrainChooseTrack(v, tile, enterdir, tracks, path_found, do_track_reservation, dest);
2342
2343 default: NOT_REACHED();
2344 }
2345 }
2346
2347 /**
2348 * Extend a train path as far as possible. Stops on encountering a safe tile,
2349 * another reservation or a track choice.
2350 * @return INVALID_TILE indicates that the reservation failed.
2351 */
ExtendTrainReservation(const Train * v,TrackBits * new_tracks,DiagDirection * enterdir)2352 static PBSTileInfo ExtendTrainReservation(const Train *v, TrackBits *new_tracks, DiagDirection *enterdir)
2353 {
2354 PBSTileInfo origin = FollowTrainReservation(v);
2355
2356 CFollowTrackRail ft(v);
2357
2358 TileIndex tile = origin.tile;
2359 Trackdir cur_td = origin.trackdir;
2360 while (ft.Follow(tile, cur_td)) {
2361 if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
2362 /* Possible signal tile. */
2363 if (HasOnewaySignalBlockingTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) break;
2364 }
2365
2366 if (Rail90DegTurnDisallowed(GetTileRailType(ft.m_old_tile), GetTileRailType(ft.m_new_tile))) {
2367 ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
2368 if (ft.m_new_td_bits == TRACKDIR_BIT_NONE) break;
2369 }
2370
2371 /* Station, depot or waypoint are a possible target. */
2372 bool target_seen = ft.m_is_station || (IsTileType(ft.m_new_tile, MP_RAILWAY) && !IsPlainRail(ft.m_new_tile));
2373 if (target_seen || KillFirstBit(ft.m_new_td_bits) != TRACKDIR_BIT_NONE) {
2374 /* Choice found or possible target encountered.
2375 * On finding a possible target, we need to stop and let the pathfinder handle the
2376 * remaining path. This is because we don't know if this target is in one of our
2377 * orders, so we might cause pathfinding to fail later on if we find a choice.
2378 * This failure would cause a bogous call to TryReserveSafePath which might reserve
2379 * a wrong path not leading to our next destination. */
2380 if (HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(TrackdirReachesTrackdirs(ft.m_old_td)))) break;
2381
2382 /* If we did skip some tiles, backtrack to the first skipped tile so the pathfinder
2383 * actually starts its search at the first unreserved tile. */
2384 if (ft.m_tiles_skipped != 0) ft.m_new_tile -= TileOffsByDiagDir(ft.m_exitdir) * ft.m_tiles_skipped;
2385
2386 /* Choice found, path valid but not okay. Save info about the choice tile as well. */
2387 if (new_tracks != nullptr) *new_tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
2388 if (enterdir != nullptr) *enterdir = ft.m_exitdir;
2389 return PBSTileInfo(ft.m_new_tile, ft.m_old_td, false);
2390 }
2391
2392 tile = ft.m_new_tile;
2393 cur_td = FindFirstTrackdir(ft.m_new_td_bits);
2394
2395 if (IsSafeWaitingPosition(v, tile, cur_td, true, _settings_game.pf.forbid_90_deg)) {
2396 bool wp_free = IsWaitingPositionFree(v, tile, cur_td, _settings_game.pf.forbid_90_deg);
2397 if (!(wp_free && TryReserveRailTrack(tile, TrackdirToTrack(cur_td)))) break;
2398 /* Safe position is all good, path valid and okay. */
2399 return PBSTileInfo(tile, cur_td, true);
2400 }
2401
2402 if (!TryReserveRailTrack(tile, TrackdirToTrack(cur_td))) break;
2403 }
2404
2405 if (ft.m_err == CFollowTrackRail::EC_OWNER || ft.m_err == CFollowTrackRail::EC_NO_WAY) {
2406 /* End of line, path valid and okay. */
2407 return PBSTileInfo(ft.m_old_tile, ft.m_old_td, true);
2408 }
2409
2410 /* Sorry, can't reserve path, back out. */
2411 tile = origin.tile;
2412 cur_td = origin.trackdir;
2413 TileIndex stopped = ft.m_old_tile;
2414 Trackdir stopped_td = ft.m_old_td;
2415 while (tile != stopped || cur_td != stopped_td) {
2416 if (!ft.Follow(tile, cur_td)) break;
2417
2418 if (Rail90DegTurnDisallowed(GetTileRailType(ft.m_old_tile), GetTileRailType(ft.m_new_tile))) {
2419 ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
2420 assert(ft.m_new_td_bits != TRACKDIR_BIT_NONE);
2421 }
2422 assert(KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE);
2423
2424 tile = ft.m_new_tile;
2425 cur_td = FindFirstTrackdir(ft.m_new_td_bits);
2426
2427 UnreserveRailTrack(tile, TrackdirToTrack(cur_td));
2428 }
2429
2430 /* Path invalid. */
2431 return PBSTileInfo();
2432 }
2433
2434 /**
2435 * Try to reserve any path to a safe tile, ignoring the vehicle's destination.
2436 * Safe tiles are tiles in front of a signal, depots and station tiles at end of line.
2437 *
2438 * @param v The vehicle.
2439 * @param tile The tile the search should start from.
2440 * @param td The trackdir the search should start from.
2441 * @param override_railtype Whether all physically compatible railtypes should be followed.
2442 * @return True if a path to a safe stopping tile could be reserved.
2443 */
TryReserveSafeTrack(const Train * v,TileIndex tile,Trackdir td,bool override_railtype)2444 static bool TryReserveSafeTrack(const Train *v, TileIndex tile, Trackdir td, bool override_railtype)
2445 {
2446 switch (_settings_game.pf.pathfinder_for_trains) {
2447 case VPF_NPF: return NPFTrainFindNearestSafeTile(v, tile, td, override_railtype);
2448 case VPF_YAPF: return YapfTrainFindNearestSafeTile(v, tile, td, override_railtype);
2449
2450 default: NOT_REACHED();
2451 }
2452 }
2453
2454 /** This class will save the current order of a vehicle and restore it on destruction. */
2455 class VehicleOrderSaver {
2456 private:
2457 Train *v;
2458 Order old_order;
2459 TileIndex old_dest_tile;
2460 StationID old_last_station_visited;
2461 VehicleOrderID index;
2462 bool suppress_implicit_orders;
2463
2464 public:
VehicleOrderSaver(Train * _v)2465 VehicleOrderSaver(Train *_v) :
2466 v(_v),
2467 old_order(_v->current_order),
2468 old_dest_tile(_v->dest_tile),
2469 old_last_station_visited(_v->last_station_visited),
2470 index(_v->cur_real_order_index),
2471 suppress_implicit_orders(HasBit(_v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS))
2472 {
2473 }
2474
~VehicleOrderSaver()2475 ~VehicleOrderSaver()
2476 {
2477 this->v->current_order = this->old_order;
2478 this->v->dest_tile = this->old_dest_tile;
2479 this->v->last_station_visited = this->old_last_station_visited;
2480 SB(this->v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS, 1, suppress_implicit_orders ? 1: 0);
2481 }
2482
2483 /**
2484 * Set the current vehicle order to the next order in the order list.
2485 * @param skip_first Shall the first (i.e. active) order be skipped?
2486 * @return True if a suitable next order could be found.
2487 */
SwitchToNextOrder(bool skip_first)2488 bool SwitchToNextOrder(bool skip_first)
2489 {
2490 if (this->v->GetNumOrders() == 0) return false;
2491
2492 if (skip_first) ++this->index;
2493
2494 int depth = 0;
2495
2496 do {
2497 /* Wrap around. */
2498 if (this->index >= this->v->GetNumOrders()) this->index = 0;
2499
2500 Order *order = this->v->GetOrder(this->index);
2501 assert(order != nullptr);
2502
2503 switch (order->GetType()) {
2504 case OT_GOTO_DEPOT:
2505 /* Skip service in depot orders when the train doesn't need service. */
2506 if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !this->v->NeedsServicing()) break;
2507 FALLTHROUGH;
2508 case OT_GOTO_STATION:
2509 case OT_GOTO_WAYPOINT:
2510 this->v->current_order = *order;
2511 return UpdateOrderDest(this->v, order, 0, true);
2512 case OT_CONDITIONAL: {
2513 VehicleOrderID next = ProcessConditionalOrder(order, this->v);
2514 if (next != INVALID_VEH_ORDER_ID) {
2515 depth++;
2516 this->index = next;
2517 /* Don't increment next, so no break here. */
2518 continue;
2519 }
2520 break;
2521 }
2522 default:
2523 break;
2524 }
2525 /* Don't increment inside the while because otherwise conditional
2526 * orders can lead to an infinite loop. */
2527 ++this->index;
2528 depth++;
2529 } while (this->index != this->v->cur_real_order_index && depth < this->v->GetNumOrders());
2530
2531 return false;
2532 }
2533 };
2534
2535 /* choose a track */
ChooseTrainTrack(Train * v,TileIndex tile,DiagDirection enterdir,TrackBits tracks,bool force_res,bool * got_reservation,bool mark_stuck)2536 static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck)
2537 {
2538 Track best_track = INVALID_TRACK;
2539 bool do_track_reservation = _settings_game.pf.reserve_paths || force_res;
2540 bool changed_signal = false;
2541
2542 assert((tracks & ~TRACK_BIT_MASK) == 0);
2543
2544 if (got_reservation != nullptr) *got_reservation = false;
2545
2546 /* Don't use tracks here as the setting to forbid 90 deg turns might have been switched between reservation and now. */
2547 TrackBits res_tracks = (TrackBits)(GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir));
2548 /* Do we have a suitable reserved track? */
2549 if (res_tracks != TRACK_BIT_NONE) return FindFirstTrack(res_tracks);
2550
2551 /* Quick return in case only one possible track is available */
2552 if (KillFirstBit(tracks) == TRACK_BIT_NONE) {
2553 Track track = FindFirstTrack(tracks);
2554 /* We need to check for signals only here, as a junction tile can't have signals. */
2555 if (track != INVALID_TRACK && HasPbsSignalOnTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir))) {
2556 do_track_reservation = true;
2557 changed_signal = true;
2558 SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir), SIGNAL_STATE_GREEN);
2559 } else if (!do_track_reservation) {
2560 return track;
2561 }
2562 best_track = track;
2563 }
2564
2565 PBSTileInfo res_dest(tile, INVALID_TRACKDIR, false);
2566 DiagDirection dest_enterdir = enterdir;
2567 if (do_track_reservation) {
2568 res_dest = ExtendTrainReservation(v, &tracks, &dest_enterdir);
2569 if (res_dest.tile == INVALID_TILE) {
2570 /* Reservation failed? */
2571 if (mark_stuck) MarkTrainAsStuck(v);
2572 if (changed_signal) SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(best_track, enterdir), SIGNAL_STATE_RED);
2573 return FindFirstTrack(tracks);
2574 }
2575 if (res_dest.okay) {
2576 /* Got a valid reservation that ends at a safe target, quick exit. */
2577 if (got_reservation != nullptr) *got_reservation = true;
2578 if (changed_signal) MarkTileDirtyByTile(tile);
2579 TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
2580 return best_track;
2581 }
2582
2583 /* Check if the train needs service here, so it has a chance to always find a depot.
2584 * Also check if the current order is a service order so we don't reserve a path to
2585 * the destination but instead to the next one if service isn't needed. */
2586 CheckIfTrainNeedsService(v);
2587 if (v->current_order.IsType(OT_DUMMY) || v->current_order.IsType(OT_CONDITIONAL) || v->current_order.IsType(OT_GOTO_DEPOT)) ProcessOrders(v);
2588 }
2589
2590 /* Save the current train order. The destructor will restore the old order on function exit. */
2591 VehicleOrderSaver orders(v);
2592
2593 /* If the current tile is the destination of the current order and
2594 * a reservation was requested, advance to the next order.
2595 * Don't advance on a depot order as depots are always safe end points
2596 * for a path and no look-ahead is necessary. This also avoids a
2597 * problem with depot orders not part of the order list when the
2598 * order list itself is empty. */
2599 if (v->current_order.IsType(OT_LEAVESTATION)) {
2600 orders.SwitchToNextOrder(false);
2601 } else if (v->current_order.IsType(OT_LOADING) || (!v->current_order.IsType(OT_GOTO_DEPOT) && (
2602 v->current_order.IsType(OT_GOTO_STATION) ?
2603 IsRailStationTile(v->tile) && v->current_order.GetDestination() == GetStationIndex(v->tile) :
2604 v->tile == v->dest_tile))) {
2605 orders.SwitchToNextOrder(true);
2606 }
2607
2608 if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
2609 /* Pathfinders are able to tell that route was only 'guessed'. */
2610 bool path_found = true;
2611 TileIndex new_tile = res_dest.tile;
2612
2613 Track next_track = DoTrainPathfind(v, new_tile, dest_enterdir, tracks, path_found, do_track_reservation, &res_dest);
2614 if (new_tile == tile) best_track = next_track;
2615 v->HandlePathfindingResult(path_found);
2616 }
2617
2618 /* No track reservation requested -> finished. */
2619 if (!do_track_reservation) return best_track;
2620
2621 /* A path was found, but could not be reserved. */
2622 if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
2623 if (mark_stuck) MarkTrainAsStuck(v);
2624 FreeTrainTrackReservation(v);
2625 return best_track;
2626 }
2627
2628 /* No possible reservation target found, we are probably lost. */
2629 if (res_dest.tile == INVALID_TILE) {
2630 /* Try to find any safe destination. */
2631 PBSTileInfo origin = FollowTrainReservation(v);
2632 if (TryReserveSafeTrack(v, origin.tile, origin.trackdir, false)) {
2633 TrackBits res = GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir);
2634 best_track = FindFirstTrack(res);
2635 TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
2636 if (got_reservation != nullptr) *got_reservation = true;
2637 if (changed_signal) MarkTileDirtyByTile(tile);
2638 } else {
2639 FreeTrainTrackReservation(v);
2640 if (mark_stuck) MarkTrainAsStuck(v);
2641 }
2642 return best_track;
2643 }
2644
2645 if (got_reservation != nullptr) *got_reservation = true;
2646
2647 /* Reservation target found and free, check if it is safe. */
2648 while (!IsSafeWaitingPosition(v, res_dest.tile, res_dest.trackdir, true, _settings_game.pf.forbid_90_deg)) {
2649 /* Extend reservation until we have found a safe position. */
2650 DiagDirection exitdir = TrackdirToExitdir(res_dest.trackdir);
2651 TileIndex next_tile = TileAddByDiagDir(res_dest.tile, exitdir);
2652 TrackBits reachable = TrackdirBitsToTrackBits((TrackdirBits)(GetTileTrackStatus(next_tile, TRANSPORT_RAIL, 0))) & DiagdirReachesTracks(exitdir);
2653 if (Rail90DegTurnDisallowed(GetTileRailType(res_dest.tile), GetTileRailType(next_tile))) {
2654 reachable &= ~TrackCrossesTracks(TrackdirToTrack(res_dest.trackdir));
2655 }
2656
2657 /* Get next order with destination. */
2658 if (orders.SwitchToNextOrder(true)) {
2659 PBSTileInfo cur_dest;
2660 bool path_found;
2661 DoTrainPathfind(v, next_tile, exitdir, reachable, path_found, true, &cur_dest);
2662 if (cur_dest.tile != INVALID_TILE) {
2663 res_dest = cur_dest;
2664 if (res_dest.okay) continue;
2665 /* Path found, but could not be reserved. */
2666 FreeTrainTrackReservation(v);
2667 if (mark_stuck) MarkTrainAsStuck(v);
2668 if (got_reservation != nullptr) *got_reservation = false;
2669 changed_signal = false;
2670 break;
2671 }
2672 }
2673 /* No order or no safe position found, try any position. */
2674 if (!TryReserveSafeTrack(v, res_dest.tile, res_dest.trackdir, true)) {
2675 FreeTrainTrackReservation(v);
2676 if (mark_stuck) MarkTrainAsStuck(v);
2677 if (got_reservation != nullptr) *got_reservation = false;
2678 changed_signal = false;
2679 }
2680 break;
2681 }
2682
2683 TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
2684
2685 if (changed_signal) MarkTileDirtyByTile(tile);
2686
2687 return best_track;
2688 }
2689
2690 /**
2691 * Try to reserve a path to a safe position.
2692 *
2693 * @param v The vehicle
2694 * @param mark_as_stuck Should the train be marked as stuck on a failed reservation?
2695 * @param first_tile_okay True if no path should be reserved if the current tile is a safe position.
2696 * @return True if a path could be reserved.
2697 */
TryPathReserve(Train * v,bool mark_as_stuck,bool first_tile_okay)2698 bool TryPathReserve(Train *v, bool mark_as_stuck, bool first_tile_okay)
2699 {
2700 assert(v->IsFrontEngine());
2701
2702 /* We have to handle depots specially as the track follower won't look
2703 * at the depot tile itself but starts from the next tile. If we are still
2704 * inside the depot, a depot reservation can never be ours. */
2705 if (v->track == TRACK_BIT_DEPOT) {
2706 if (HasDepotReservation(v->tile)) {
2707 if (mark_as_stuck) MarkTrainAsStuck(v);
2708 return false;
2709 } else {
2710 /* Depot not reserved, but the next tile might be. */
2711 TileIndex next_tile = TileAddByDiagDir(v->tile, GetRailDepotDirection(v->tile));
2712 if (HasReservedTracks(next_tile, DiagdirReachesTracks(GetRailDepotDirection(v->tile)))) return false;
2713 }
2714 }
2715
2716 Vehicle *other_train = nullptr;
2717 PBSTileInfo origin = FollowTrainReservation(v, &other_train);
2718 /* The path we are driving on is already blocked by some other train.
2719 * This can only happen in certain situations when mixing path and
2720 * block signals or when changing tracks and/or signals.
2721 * Exit here as doing any further reservations will probably just
2722 * make matters worse. */
2723 if (other_train != nullptr && other_train->index != v->index) {
2724 if (mark_as_stuck) MarkTrainAsStuck(v);
2725 return false;
2726 }
2727 /* If we have a reserved path and the path ends at a safe tile, we are finished already. */
2728 if (origin.okay && (v->tile != origin.tile || first_tile_okay)) {
2729 /* Can't be stuck then. */
2730 if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2731 ClrBit(v->flags, VRF_TRAIN_STUCK);
2732 return true;
2733 }
2734
2735 /* If we are in a depot, tentatively reserve the depot. */
2736 if (v->track == TRACK_BIT_DEPOT) {
2737 SetDepotReservation(v->tile, true);
2738 if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
2739 }
2740
2741 DiagDirection exitdir = TrackdirToExitdir(origin.trackdir);
2742 TileIndex new_tile = TileAddByDiagDir(origin.tile, exitdir);
2743 TrackBits reachable = TrackdirBitsToTrackBits(TrackStatusToTrackdirBits(GetTileTrackStatus(new_tile, TRANSPORT_RAIL, 0)) & DiagdirReachesTrackdirs(exitdir));
2744
2745 if (Rail90DegTurnDisallowed(GetTileRailType(origin.tile), GetTileRailType(new_tile))) reachable &= ~TrackCrossesTracks(TrackdirToTrack(origin.trackdir));
2746
2747 bool res_made = false;
2748 ChooseTrainTrack(v, new_tile, exitdir, reachable, true, &res_made, mark_as_stuck);
2749
2750 if (!res_made) {
2751 /* Free the depot reservation as well. */
2752 if (v->track == TRACK_BIT_DEPOT) SetDepotReservation(v->tile, false);
2753 return false;
2754 }
2755
2756 if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
2757 v->wait_counter = 0;
2758 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2759 }
2760 ClrBit(v->flags, VRF_TRAIN_STUCK);
2761 return true;
2762 }
2763
2764
CheckReverseTrain(const Train * v)2765 static bool CheckReverseTrain(const Train *v)
2766 {
2767 if (_settings_game.difficulty.line_reverse_mode != 0 ||
2768 v->track == TRACK_BIT_DEPOT || v->track == TRACK_BIT_WORMHOLE ||
2769 !(v->direction & 1)) {
2770 return false;
2771 }
2772
2773 assert(v->track != TRACK_BIT_NONE);
2774
2775 switch (_settings_game.pf.pathfinder_for_trains) {
2776 case VPF_NPF: return NPFTrainCheckReverse(v);
2777 case VPF_YAPF: return YapfTrainCheckReverse(v);
2778
2779 default: NOT_REACHED();
2780 }
2781 }
2782
2783 /**
2784 * Get the location of the next station to visit.
2785 * @param station Next station to visit.
2786 * @return Location of the new station.
2787 */
GetOrderStationLocation(StationID station)2788 TileIndex Train::GetOrderStationLocation(StationID station)
2789 {
2790 if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
2791
2792 const Station *st = Station::Get(station);
2793 if (!(st->facilities & FACIL_TRAIN)) {
2794 /* The destination station has no trainstation tiles. */
2795 this->IncrementRealOrderIndex();
2796 return 0;
2797 }
2798
2799 return st->xy;
2800 }
2801
2802 /** Goods at the consist have changed, update the graphics, cargo, and acceleration. */
MarkDirty()2803 void Train::MarkDirty()
2804 {
2805 Train *v = this;
2806 do {
2807 v->colourmap = PAL_NONE;
2808 v->UpdateViewport(true, false);
2809 } while ((v = v->Next()) != nullptr);
2810
2811 /* need to update acceleration and cached values since the goods on the train changed. */
2812 this->CargoChanged();
2813 this->UpdateAcceleration();
2814 }
2815
2816 /**
2817 * This function looks at the vehicle and updates its speed (cur_speed
2818 * and subspeed) variables. Furthermore, it returns the distance that
2819 * the train can drive this tick. #Vehicle::GetAdvanceDistance() determines
2820 * the distance to drive before moving a step on the map.
2821 * @return distance to drive.
2822 */
UpdateSpeed()2823 int Train::UpdateSpeed()
2824 {
2825 switch (_settings_game.vehicle.train_acceleration_model) {
2826 default: NOT_REACHED();
2827 case AM_ORIGINAL:
2828 return this->DoUpdateSpeed(this->acceleration * (this->GetAccelerationStatus() == AS_BRAKE ? -4 : 2), 0, this->GetCurrentMaxSpeed());
2829
2830 case AM_REALISTIC:
2831 return this->DoUpdateSpeed(this->GetAcceleration(), this->GetAccelerationStatus() == AS_BRAKE ? 0 : 2, this->GetCurrentMaxSpeed());
2832 }
2833 }
2834
2835 /**
2836 * Trains enters a station, send out a news item if it is the first train, and start loading.
2837 * @param v Train that entered the station.
2838 * @param station Station visited.
2839 */
TrainEnterStation(Train * v,StationID station)2840 static void TrainEnterStation(Train *v, StationID station)
2841 {
2842 v->last_station_visited = station;
2843
2844 /* check if a train ever visited this station before */
2845 Station *st = Station::Get(station);
2846 if (!(st->had_vehicle_of_type & HVOT_TRAIN)) {
2847 st->had_vehicle_of_type |= HVOT_TRAIN;
2848 SetDParam(0, st->index);
2849 AddVehicleNewsItem(
2850 STR_NEWS_FIRST_TRAIN_ARRIVAL,
2851 v->owner == _local_company ? NT_ARRIVAL_COMPANY : NT_ARRIVAL_OTHER,
2852 v->index,
2853 st->index
2854 );
2855 AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
2856 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
2857 }
2858
2859 v->force_proceed = TFP_NONE;
2860 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
2861
2862 v->BeginLoading();
2863
2864 TriggerStationRandomisation(st, v->tile, SRT_TRAIN_ARRIVES);
2865 TriggerStationAnimation(st, v->tile, SAT_TRAIN_ARRIVES);
2866 }
2867
2868 /* Check if the vehicle is compatible with the specified tile */
CheckCompatibleRail(const Train * v,TileIndex tile)2869 static inline bool CheckCompatibleRail(const Train *v, TileIndex tile)
2870 {
2871 return IsTileOwner(tile, v->owner) &&
2872 (!v->IsFrontEngine() || HasBit(v->compatible_railtypes, GetRailType(tile)));
2873 }
2874
2875 /** Data structure for storing engine speed changes of an acceleration type. */
2876 struct AccelerationSlowdownParams {
2877 byte small_turn; ///< Speed change due to a small turn.
2878 byte large_turn; ///< Speed change due to a large turn.
2879 byte z_up; ///< Fraction to remove when moving up.
2880 byte z_down; ///< Fraction to add when moving down.
2881 };
2882
2883 /** Speed update fractions for each acceleration type. */
2884 static const AccelerationSlowdownParams _accel_slowdown[] = {
2885 /* normal accel */
2886 {256 / 4, 256 / 2, 256 / 4, 2}, ///< normal
2887 {256 / 4, 256 / 2, 256 / 4, 2}, ///< monorail
2888 {0, 256 / 2, 256 / 4, 2}, ///< maglev
2889 };
2890
2891 /**
2892 * Modify the speed of the vehicle due to a change in altitude.
2893 * @param v %Train to update.
2894 * @param old_z Previous height.
2895 */
AffectSpeedByZChange(Train * v,int old_z)2896 static inline void AffectSpeedByZChange(Train *v, int old_z)
2897 {
2898 if (old_z == v->z_pos || _settings_game.vehicle.train_acceleration_model != AM_ORIGINAL) return;
2899
2900 const AccelerationSlowdownParams *asp = &_accel_slowdown[GetRailTypeInfo(v->railtype)->acceleration_type];
2901
2902 if (old_z < v->z_pos) {
2903 v->cur_speed -= (v->cur_speed * asp->z_up >> 8);
2904 } else {
2905 uint16 spd = v->cur_speed + asp->z_down;
2906 if (spd <= v->gcache.cached_max_track_speed) v->cur_speed = spd;
2907 }
2908 }
2909
TrainMovedChangeSignals(TileIndex tile,DiagDirection dir)2910 static bool TrainMovedChangeSignals(TileIndex tile, DiagDirection dir)
2911 {
2912 if (IsTileType(tile, MP_RAILWAY) &&
2913 GetRailTileType(tile) == RAIL_TILE_SIGNALS) {
2914 TrackdirBits tracks = TrackBitsToTrackdirBits(GetTrackBits(tile)) & DiagdirReachesTrackdirs(dir);
2915 Trackdir trackdir = FindFirstTrackdir(tracks);
2916 if (UpdateSignalsOnSegment(tile, TrackdirToExitdir(trackdir), GetTileOwner(tile)) == SIGSEG_PBS && HasSignalOnTrackdir(tile, trackdir)) {
2917 /* A PBS block with a non-PBS signal facing us? */
2918 if (!IsPbsSignal(GetSignalType(tile, TrackdirToTrack(trackdir)))) return true;
2919 }
2920 }
2921 return false;
2922 }
2923
2924 /** Tries to reserve track under whole train consist. */
ReserveTrackUnderConsist() const2925 void Train::ReserveTrackUnderConsist() const
2926 {
2927 for (const Train *u = this; u != nullptr; u = u->Next()) {
2928 switch (u->track) {
2929 case TRACK_BIT_WORMHOLE:
2930 TryReserveRailTrack(u->tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(u->tile)));
2931 break;
2932 case TRACK_BIT_DEPOT:
2933 break;
2934 default:
2935 TryReserveRailTrack(u->tile, TrackBitsToTrack(u->track));
2936 break;
2937 }
2938 }
2939 }
2940
2941 /**
2942 * The train vehicle crashed!
2943 * Update its status and other parts around it.
2944 * @param flooded Crash was caused by flooding.
2945 * @return Number of people killed.
2946 */
Crash(bool flooded)2947 uint Train::Crash(bool flooded)
2948 {
2949 uint pass = 0;
2950 if (this->IsFrontEngine()) {
2951 pass += 2; // driver
2952
2953 /* Remove the reserved path in front of the train if it is not stuck.
2954 * Also clear all reserved tracks the train is currently on. */
2955 if (!HasBit(this->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(this);
2956 for (const Train *v = this; v != nullptr; v = v->Next()) {
2957 ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
2958 if (IsTileType(v->tile, MP_TUNNELBRIDGE)) {
2959 /* ClearPathReservation will not free the wormhole exit
2960 * if the train has just entered the wormhole. */
2961 SetTunnelBridgeReservation(GetOtherTunnelBridgeEnd(v->tile), false);
2962 }
2963 }
2964
2965 /* we may need to update crossing we were approaching,
2966 * but must be updated after the train has been marked crashed */
2967 TileIndex crossing = TrainApproachingCrossingTile(this);
2968 if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
2969
2970 /* Remove the loading indicators (if any) */
2971 HideFillingPercent(&this->fill_percent_te_id);
2972 }
2973
2974 pass += this->GroundVehicleBase::Crash(flooded);
2975
2976 this->crash_anim_pos = flooded ? 4000 : 1; // max 4440, disappear pretty fast when flooded
2977 return pass;
2978 }
2979
2980 /**
2981 * Marks train as crashed and creates an AI event.
2982 * Doesn't do anything if the train is crashed already.
2983 * @param v first vehicle of chain
2984 * @return number of victims (including 2 drivers; zero if train was already crashed)
2985 */
TrainCrashed(Train * v)2986 static uint TrainCrashed(Train *v)
2987 {
2988 uint num = 0;
2989
2990 /* do not crash train twice */
2991 if (!(v->vehstatus & VS_CRASHED)) {
2992 num = v->Crash();
2993 AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
2994 Game::NewEvent(new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
2995 }
2996
2997 /* Try to re-reserve track under already crashed train too.
2998 * Crash() clears the reservation! */
2999 v->ReserveTrackUnderConsist();
3000
3001 return num;
3002 }
3003
3004 /** Temporary data storage for testing collisions. */
3005 struct TrainCollideChecker {
3006 Train *v; ///< %Vehicle we are testing for collision.
3007 uint num; ///< Total number of victims if train collided.
3008 };
3009
3010 /**
3011 * Collision test function.
3012 * @param v %Train vehicle to test collision with.
3013 * @param data %Train being examined.
3014 * @return \c nullptr (always continue search)
3015 */
FindTrainCollideEnum(Vehicle * v,void * data)3016 static Vehicle *FindTrainCollideEnum(Vehicle *v, void *data)
3017 {
3018 TrainCollideChecker *tcc = (TrainCollideChecker*)data;
3019
3020 /* not a train or in depot */
3021 if (v->type != VEH_TRAIN || Train::From(v)->track == TRACK_BIT_DEPOT) return nullptr;
3022
3023 /* do not crash into trains of another company. */
3024 if (v->owner != tcc->v->owner) return nullptr;
3025
3026 /* get first vehicle now to make most usual checks faster */
3027 Train *coll = Train::From(v)->First();
3028
3029 /* can't collide with own wagons */
3030 if (coll == tcc->v) return nullptr;
3031
3032 int x_diff = v->x_pos - tcc->v->x_pos;
3033 int y_diff = v->y_pos - tcc->v->y_pos;
3034
3035 /* Do fast calculation to check whether trains are not in close vicinity
3036 * and quickly reject trains distant enough for any collision.
3037 * Differences are shifted by 7, mapping range [-7 .. 8] into [0 .. 15]
3038 * Differences are then ORed and then we check for any higher bits */
3039 uint hash = (y_diff + 7) | (x_diff + 7);
3040 if (hash & ~15) return nullptr;
3041
3042 /* Slower check using multiplication */
3043 int min_diff = (Train::From(v)->gcache.cached_veh_length + 1) / 2 + (tcc->v->gcache.cached_veh_length + 1) / 2 - 1;
3044 if (x_diff * x_diff + y_diff * y_diff > min_diff * min_diff) return nullptr;
3045
3046 /* Happens when there is a train under bridge next to bridge head */
3047 if (abs(v->z_pos - tcc->v->z_pos) > 5) return nullptr;
3048
3049 /* crash both trains */
3050 tcc->num += TrainCrashed(tcc->v);
3051 tcc->num += TrainCrashed(coll);
3052
3053 return nullptr; // continue searching
3054 }
3055
3056 /**
3057 * Checks whether the specified train has a collision with another vehicle. If
3058 * so, destroys this vehicle, and the other vehicle if its subtype has TS_Front.
3059 * Reports the incident in a flashy news item, modifies station ratings and
3060 * plays a sound.
3061 * @param v %Train to test.
3062 */
CheckTrainCollision(Train * v)3063 static bool CheckTrainCollision(Train *v)
3064 {
3065 /* can't collide in depot */
3066 if (v->track == TRACK_BIT_DEPOT) return false;
3067
3068 assert(v->track == TRACK_BIT_WORMHOLE || TileVirtXY(v->x_pos, v->y_pos) == v->tile);
3069
3070 TrainCollideChecker tcc;
3071 tcc.v = v;
3072 tcc.num = 0;
3073
3074 /* find colliding vehicles */
3075 if (v->track == TRACK_BIT_WORMHOLE) {
3076 FindVehicleOnPos(v->tile, &tcc, FindTrainCollideEnum);
3077 FindVehicleOnPos(GetOtherTunnelBridgeEnd(v->tile), &tcc, FindTrainCollideEnum);
3078 } else {
3079 FindVehicleOnPosXY(v->x_pos, v->y_pos, &tcc, FindTrainCollideEnum);
3080 }
3081
3082 /* any dead -> no crash */
3083 if (tcc.num == 0) return false;
3084
3085 SetDParam(0, tcc.num);
3086 AddTileNewsItem(STR_NEWS_TRAIN_CRASH, NT_ACCIDENT, v->tile);
3087
3088 ModifyStationRatingAround(v->tile, v->owner, -160, 30);
3089 if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_13_TRAIN_COLLISION, v);
3090 return true;
3091 }
3092
CheckTrainAtSignal(Vehicle * v,void * data)3093 static Vehicle *CheckTrainAtSignal(Vehicle *v, void *data)
3094 {
3095 if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return nullptr;
3096
3097 Train *t = Train::From(v);
3098 DiagDirection exitdir = *(DiagDirection *)data;
3099
3100 /* not front engine of a train, inside wormhole or depot, crashed */
3101 if (!t->IsFrontEngine() || !(t->track & TRACK_BIT_MASK)) return nullptr;
3102
3103 if (t->cur_speed > 5 || VehicleExitDir(t->direction, t->track) != exitdir) return nullptr;
3104
3105 return t;
3106 }
3107
3108 /**
3109 * Move a vehicle chain one movement stop forwards.
3110 * @param v First vehicle to move.
3111 * @param nomove Stop moving this and all following vehicles.
3112 * @param reverse Set to false to not execute the vehicle reversing. This does not change any other logic.
3113 * @return True if the vehicle could be moved forward, false otherwise.
3114 */
TrainController(Train * v,Vehicle * nomove,bool reverse)3115 bool TrainController(Train *v, Vehicle *nomove, bool reverse)
3116 {
3117 Train *first = v->First();
3118 Train *prev;
3119 bool direction_changed = false; // has direction of any part changed?
3120
3121 /* For every vehicle after and including the given vehicle */
3122 for (prev = v->Previous(); v != nomove; prev = v, v = v->Next()) {
3123 DiagDirection enterdir = DIAGDIR_BEGIN;
3124 bool update_signals_crossing = false; // will we update signals or crossing state?
3125
3126 GetNewVehiclePosResult gp = GetNewVehiclePos(v);
3127 if (v->track != TRACK_BIT_WORMHOLE) {
3128 /* Not inside tunnel */
3129 if (gp.old_tile == gp.new_tile) {
3130 /* Staying in the old tile */
3131 if (v->track == TRACK_BIT_DEPOT) {
3132 /* Inside depot */
3133 gp.x = v->x_pos;
3134 gp.y = v->y_pos;
3135 } else {
3136 /* Not inside depot */
3137
3138 /* Reverse when we are at the end of the track already, do not move to the new position */
3139 if (v->IsFrontEngine() && !TrainCheckIfLineEnds(v, reverse)) return false;
3140
3141 uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
3142 if (HasBit(r, VETS_CANNOT_ENTER)) {
3143 goto invalid_rail;
3144 }
3145 if (HasBit(r, VETS_ENTERED_STATION)) {
3146 /* The new position is the end of the platform */
3147 TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
3148 }
3149 }
3150 } else {
3151 /* A new tile is about to be entered. */
3152
3153 /* Determine what direction we're entering the new tile from */
3154 enterdir = DiagdirBetweenTiles(gp.old_tile, gp.new_tile);
3155 assert(IsValidDiagDirection(enterdir));
3156
3157 /* Get the status of the tracks in the new tile and mask
3158 * away the bits that aren't reachable. */
3159 TrackStatus ts = GetTileTrackStatus(gp.new_tile, TRANSPORT_RAIL, 0, ReverseDiagDir(enterdir));
3160 TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(enterdir);
3161
3162 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
3163 TrackBits red_signals = TrackdirBitsToTrackBits(TrackStatusToRedSignals(ts) & reachable_trackdirs);
3164
3165 TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
3166 if (Rail90DegTurnDisallowed(GetTileRailType(gp.old_tile), GetTileRailType(gp.new_tile)) && prev == nullptr) {
3167 /* We allow wagons to make 90 deg turns, because forbid_90_deg
3168 * can be switched on halfway a turn */
3169 bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
3170 }
3171
3172 if (bits == TRACK_BIT_NONE) goto invalid_rail;
3173
3174 /* Check if the new tile constrains tracks that are compatible
3175 * with the current train, if not, bail out. */
3176 if (!CheckCompatibleRail(v, gp.new_tile)) goto invalid_rail;
3177
3178 TrackBits chosen_track;
3179 if (prev == nullptr) {
3180 /* Currently the locomotive is active. Determine which one of the
3181 * available tracks to choose */
3182 chosen_track = TrackToTrackBits(ChooseTrainTrack(v, gp.new_tile, enterdir, bits, false, nullptr, true));
3183 assert(chosen_track & (bits | GetReservedTrackbits(gp.new_tile)));
3184
3185 if (v->force_proceed != TFP_NONE && IsPlainRailTile(gp.new_tile) && HasSignals(gp.new_tile)) {
3186 /* For each signal we find decrease the counter by one.
3187 * We start at two, so the first signal we pass decreases
3188 * this to one, then if we reach the next signal it is
3189 * decreased to zero and we won't pass that new signal. */
3190 Trackdir dir = FindFirstTrackdir(trackdirbits);
3191 if (HasSignalOnTrackdir(gp.new_tile, dir) ||
3192 (HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(dir)) &&
3193 GetSignalType(gp.new_tile, TrackdirToTrack(dir)) != SIGTYPE_PBS)) {
3194 /* However, we do not want to be stopped by PBS signals
3195 * entered via the back. */
3196 v->force_proceed = (v->force_proceed == TFP_SIGNAL) ? TFP_STUCK : TFP_NONE;
3197 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
3198 }
3199 }
3200
3201 /* Check if it's a red signal and that force proceed is not clicked. */
3202 if ((red_signals & chosen_track) && v->force_proceed == TFP_NONE) {
3203 /* In front of a red signal */
3204 Trackdir i = FindFirstTrackdir(trackdirbits);
3205
3206 /* Don't handle stuck trains here. */
3207 if (HasBit(v->flags, VRF_TRAIN_STUCK)) return false;
3208
3209 if (!HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(i))) {
3210 v->cur_speed = 0;
3211 v->subspeed = 0;
3212 v->progress = 255; // make sure that every bit of acceleration will hit the signal again, so speed stays 0.
3213 if (!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_oneway_signal * DAY_TICKS * 2) return false;
3214 } else if (HasSignalOnTrackdir(gp.new_tile, i)) {
3215 v->cur_speed = 0;
3216 v->subspeed = 0;
3217 v->progress = 255; // make sure that every bit of acceleration will hit the signal again, so speed stays 0.
3218 if (!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_twoway_signal * DAY_TICKS * 2) {
3219 DiagDirection exitdir = TrackdirToExitdir(i);
3220 TileIndex o_tile = TileAddByDiagDir(gp.new_tile, exitdir);
3221
3222 exitdir = ReverseDiagDir(exitdir);
3223
3224 /* check if a train is waiting on the other side */
3225 if (!HasVehicleOnPos(o_tile, &exitdir, &CheckTrainAtSignal)) return false;
3226 }
3227 }
3228
3229 /* If we would reverse but are currently in a PBS block and
3230 * reversing of stuck trains is disabled, don't reverse.
3231 * This does not apply if the reason for reversing is a one-way
3232 * signal blocking us, because a train would then be stuck forever. */
3233 if (!_settings_game.pf.reverse_at_signals && !HasOnewaySignalBlockingTrackdir(gp.new_tile, i) &&
3234 UpdateSignalsOnSegment(v->tile, enterdir, v->owner) == SIGSEG_PBS) {
3235 v->wait_counter = 0;
3236 return false;
3237 }
3238 goto reverse_train_direction;
3239 } else {
3240 TryReserveRailTrack(gp.new_tile, TrackBitsToTrack(chosen_track), false);
3241 }
3242 } else {
3243 /* The wagon is active, simply follow the prev vehicle. */
3244 if (prev->tile == gp.new_tile) {
3245 /* Choose the same track as prev */
3246 if (prev->track == TRACK_BIT_WORMHOLE) {
3247 /* Vehicles entering tunnels enter the wormhole earlier than for bridges.
3248 * However, just choose the track into the wormhole. */
3249 assert(IsTunnel(prev->tile));
3250 chosen_track = bits;
3251 } else {
3252 chosen_track = prev->track;
3253 }
3254 } else {
3255 /* Choose the track that leads to the tile where prev is.
3256 * This case is active if 'prev' is already on the second next tile, when 'v' just enters the next tile.
3257 * I.e. when the tile between them has only space for a single vehicle like
3258 * 1) horizontal/vertical track tiles and
3259 * 2) some orientations of tunnel entries, where the vehicle is already inside the wormhole at 8/16 from the tile edge.
3260 * Is also the train just reversing, the wagon inside the tunnel is 'on' the tile of the opposite tunnel entry.
3261 */
3262 static const TrackBits _connecting_track[DIAGDIR_END][DIAGDIR_END] = {
3263 {TRACK_BIT_X, TRACK_BIT_LOWER, TRACK_BIT_NONE, TRACK_BIT_LEFT },
3264 {TRACK_BIT_UPPER, TRACK_BIT_Y, TRACK_BIT_LEFT, TRACK_BIT_NONE },
3265 {TRACK_BIT_NONE, TRACK_BIT_RIGHT, TRACK_BIT_X, TRACK_BIT_UPPER},
3266 {TRACK_BIT_RIGHT, TRACK_BIT_NONE, TRACK_BIT_LOWER, TRACK_BIT_Y }
3267 };
3268 DiagDirection exitdir = DiagdirBetweenTiles(gp.new_tile, prev->tile);
3269 assert(IsValidDiagDirection(exitdir));
3270 chosen_track = _connecting_track[enterdir][exitdir];
3271 }
3272 chosen_track &= bits;
3273 }
3274
3275 /* Make sure chosen track is a valid track */
3276 assert(
3277 chosen_track == TRACK_BIT_X || chosen_track == TRACK_BIT_Y ||
3278 chosen_track == TRACK_BIT_UPPER || chosen_track == TRACK_BIT_LOWER ||
3279 chosen_track == TRACK_BIT_LEFT || chosen_track == TRACK_BIT_RIGHT);
3280
3281 /* Update XY to reflect the entrance to the new tile, and select the direction to use */
3282 const byte *b = _initial_tile_subcoord[FIND_FIRST_BIT(chosen_track)][enterdir];
3283 gp.x = (gp.x & ~0xF) | b[0];
3284 gp.y = (gp.y & ~0xF) | b[1];
3285 Direction chosen_dir = (Direction)b[2];
3286
3287 /* Call the landscape function and tell it that the vehicle entered the tile */
3288 uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
3289 if (HasBit(r, VETS_CANNOT_ENTER)) {
3290 goto invalid_rail;
3291 }
3292
3293 if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
3294 Track track = FindFirstTrack(chosen_track);
3295 Trackdir tdir = TrackDirectionToTrackdir(track, chosen_dir);
3296 if (v->IsFrontEngine() && HasPbsSignalOnTrackdir(gp.new_tile, tdir)) {
3297 SetSignalStateByTrackdir(gp.new_tile, tdir, SIGNAL_STATE_RED);
3298 MarkTileDirtyByTile(gp.new_tile);
3299 }
3300
3301 /* Clear any track reservation when the last vehicle leaves the tile */
3302 if (v->Next() == nullptr) ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
3303
3304 v->tile = gp.new_tile;
3305
3306 if (GetTileRailType(gp.new_tile) != GetTileRailType(gp.old_tile)) {
3307 v->First()->ConsistChanged(CCF_TRACK);
3308 }
3309
3310 v->track = chosen_track;
3311 assert(v->track);
3312 }
3313
3314 /* We need to update signal status, but after the vehicle position hash
3315 * has been updated by UpdateInclination() */
3316 update_signals_crossing = true;
3317
3318 if (chosen_dir != v->direction) {
3319 if (prev == nullptr && _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) {
3320 const AccelerationSlowdownParams *asp = &_accel_slowdown[GetRailTypeInfo(v->railtype)->acceleration_type];
3321 DirDiff diff = DirDifference(v->direction, chosen_dir);
3322 v->cur_speed -= (diff == DIRDIFF_45RIGHT || diff == DIRDIFF_45LEFT ? asp->small_turn : asp->large_turn) * v->cur_speed >> 8;
3323 }
3324 direction_changed = true;
3325 v->direction = chosen_dir;
3326 }
3327
3328 if (v->IsFrontEngine()) {
3329 v->wait_counter = 0;
3330
3331 /* If we are approaching a crossing that is reserved, play the sound now. */
3332 TileIndex crossing = TrainApproachingCrossingTile(v);
3333 if (crossing != INVALID_TILE && HasCrossingReservation(crossing) && _settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, crossing);
3334
3335 /* Always try to extend the reservation when entering a tile. */
3336 CheckNextTrainTile(v);
3337 }
3338
3339 if (HasBit(r, VETS_ENTERED_STATION)) {
3340 /* The new position is the location where we want to stop */
3341 TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
3342 }
3343 }
3344 } else {
3345 if (IsTileType(gp.new_tile, MP_TUNNELBRIDGE) && HasBit(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y), VETS_ENTERED_WORMHOLE)) {
3346 /* Perform look-ahead on tunnel exit. */
3347 if (v->IsFrontEngine()) {
3348 TryReserveRailTrack(gp.new_tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(gp.new_tile)));
3349 CheckNextTrainTile(v);
3350 }
3351 /* Prevent v->UpdateInclination() being called with wrong parameters.
3352 * This could happen if the train was reversed inside the tunnel/bridge. */
3353 if (gp.old_tile == gp.new_tile) {
3354 gp.old_tile = GetOtherTunnelBridgeEnd(gp.old_tile);
3355 }
3356 } else {
3357 v->x_pos = gp.x;
3358 v->y_pos = gp.y;
3359 v->UpdatePosition();
3360 if ((v->vehstatus & VS_HIDDEN) == 0) v->Vehicle::UpdateViewport(true);
3361 continue;
3362 }
3363 }
3364
3365 /* update image of train, as well as delta XY */
3366 v->UpdateDeltaXY();
3367
3368 v->x_pos = gp.x;
3369 v->y_pos = gp.y;
3370 v->UpdatePosition();
3371
3372 /* update the Z position of the vehicle */
3373 int old_z = v->UpdateInclination(gp.new_tile != gp.old_tile, false);
3374
3375 if (prev == nullptr) {
3376 /* This is the first vehicle in the train */
3377 AffectSpeedByZChange(v, old_z);
3378 }
3379
3380 if (update_signals_crossing) {
3381 if (v->IsFrontEngine()) {
3382 if (TrainMovedChangeSignals(gp.new_tile, enterdir)) {
3383 /* We are entering a block with PBS signals right now, but
3384 * not through a PBS signal. This means we don't have a
3385 * reservation right now. As a conventional signal will only
3386 * ever be green if no other train is in the block, getting
3387 * a path should always be possible. If the player built
3388 * such a strange network that it is not possible, the train
3389 * will be marked as stuck and the player has to deal with
3390 * the problem. */
3391 if ((!HasReservedTracks(gp.new_tile, v->track) &&
3392 !TryReserveRailTrack(gp.new_tile, FindFirstTrack(v->track))) ||
3393 !TryPathReserve(v)) {
3394 MarkTrainAsStuck(v);
3395 }
3396 }
3397 }
3398
3399 /* Signals can only change when the first
3400 * (above) or the last vehicle moves. */
3401 if (v->Next() == nullptr) {
3402 TrainMovedChangeSignals(gp.old_tile, ReverseDiagDir(enterdir));
3403 if (IsLevelCrossingTile(gp.old_tile)) UpdateLevelCrossing(gp.old_tile);
3404 }
3405 }
3406
3407 /* Do not check on every tick to save some computing time. */
3408 if (v->IsFrontEngine() && v->tick_counter % _settings_game.pf.path_backoff_interval == 0) CheckNextTrainTile(v);
3409 }
3410
3411 if (direction_changed) first->tcache.cached_max_curve_speed = first->GetCurveSpeedLimit();
3412
3413 return true;
3414
3415 invalid_rail:
3416 /* We've reached end of line?? */
3417 if (prev != nullptr) error("Disconnecting train");
3418
3419 reverse_train_direction:
3420 if (reverse) {
3421 v->wait_counter = 0;
3422 v->cur_speed = 0;
3423 v->subspeed = 0;
3424 ReverseTrainDirection(v);
3425 }
3426
3427 return false;
3428 }
3429
3430 /**
3431 * Collect trackbits of all crashed train vehicles on a tile
3432 * @param v Vehicle passed from Find/HasVehicleOnPos()
3433 * @param data trackdirbits for the result
3434 * @return nullptr to iterate over all vehicles on the tile.
3435 */
CollectTrackbitsFromCrashedVehiclesEnum(Vehicle * v,void * data)3436 static Vehicle *CollectTrackbitsFromCrashedVehiclesEnum(Vehicle *v, void *data)
3437 {
3438 TrackBits *trackbits = (TrackBits *)data;
3439
3440 if (v->type == VEH_TRAIN && (v->vehstatus & VS_CRASHED) != 0) {
3441 TrackBits train_tbits = Train::From(v)->track;
3442 if (train_tbits == TRACK_BIT_WORMHOLE) {
3443 /* Vehicle is inside a wormhole, v->track contains no useful value then. */
3444 *trackbits |= DiagDirToDiagTrackBits(GetTunnelBridgeDirection(v->tile));
3445 } else if (train_tbits != TRACK_BIT_DEPOT) {
3446 *trackbits |= train_tbits;
3447 }
3448 }
3449
3450 return nullptr;
3451 }
3452
3453 /**
3454 * Deletes/Clears the last wagon of a crashed train. It takes the engine of the
3455 * train, then goes to the last wagon and deletes that. Each call to this function
3456 * will remove the last wagon of a crashed train. If this wagon was on a crossing,
3457 * or inside a tunnel/bridge, recalculate the signals as they might need updating
3458 * @param v the Vehicle of which last wagon is to be removed
3459 */
DeleteLastWagon(Train * v)3460 static void DeleteLastWagon(Train *v)
3461 {
3462 Train *first = v->First();
3463
3464 /* Go to the last wagon and delete the link pointing there
3465 * *u is then the one-before-last wagon, and *v the last
3466 * one which will physically be removed */
3467 Train *u = v;
3468 for (; v->Next() != nullptr; v = v->Next()) u = v;
3469 u->SetNext(nullptr);
3470
3471 if (first != v) {
3472 /* Recalculate cached train properties */
3473 first->ConsistChanged(CCF_ARRANGE);
3474 /* Update the depot window if the first vehicle is in depot -
3475 * if v == first, then it is updated in PreDestructor() */
3476 if (first->track == TRACK_BIT_DEPOT) {
3477 SetWindowDirty(WC_VEHICLE_DEPOT, first->tile);
3478 }
3479 v->last_station_visited = first->last_station_visited; // for PreDestructor
3480 }
3481
3482 /* 'v' shouldn't be accessed after it has been deleted */
3483 TrackBits trackbits = v->track;
3484 TileIndex tile = v->tile;
3485 Owner owner = v->owner;
3486
3487 delete v;
3488 v = nullptr; // make sure nobody will try to read 'v' anymore
3489
3490 if (trackbits == TRACK_BIT_WORMHOLE) {
3491 /* Vehicle is inside a wormhole, v->track contains no useful value then. */
3492 trackbits = DiagDirToDiagTrackBits(GetTunnelBridgeDirection(tile));
3493 }
3494
3495 Track track = TrackBitsToTrack(trackbits);
3496 if (HasReservedTracks(tile, trackbits)) {
3497 UnreserveRailTrack(tile, track);
3498
3499 /* If there are still crashed vehicles on the tile, give the track reservation to them */
3500 TrackBits remaining_trackbits = TRACK_BIT_NONE;
3501 FindVehicleOnPos(tile, &remaining_trackbits, CollectTrackbitsFromCrashedVehiclesEnum);
3502
3503 /* It is important that these two are the first in the loop, as reservation cannot deal with every trackbit combination */
3504 assert(TRACK_BEGIN == TRACK_X && TRACK_Y == TRACK_BEGIN + 1);
3505 for (Track t : SetTrackBitIterator(remaining_trackbits)) TryReserveRailTrack(tile, t);
3506 }
3507
3508 /* check if the wagon was on a road/rail-crossing */
3509 if (IsLevelCrossingTile(tile)) UpdateLevelCrossing(tile);
3510
3511 /* Update signals */
3512 if (IsTileType(tile, MP_TUNNELBRIDGE) || IsRailDepotTile(tile)) {
3513 UpdateSignalsOnSegment(tile, INVALID_DIAGDIR, owner);
3514 } else {
3515 SetSignalsOnBothDir(tile, track, owner);
3516 }
3517 }
3518
3519 /**
3520 * Rotate all vehicles of a (crashed) train chain randomly to animate the crash.
3521 * @param v First crashed vehicle.
3522 */
ChangeTrainDirRandomly(Train * v)3523 static void ChangeTrainDirRandomly(Train *v)
3524 {
3525 static const DirDiff delta[] = {
3526 DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT
3527 };
3528
3529 do {
3530 /* We don't need to twist around vehicles if they're not visible */
3531 if (!(v->vehstatus & VS_HIDDEN)) {
3532 v->direction = ChangeDir(v->direction, delta[GB(Random(), 0, 2)]);
3533 /* Refrain from updating the z position of the vehicle when on
3534 * a bridge, because UpdateInclination() will put the vehicle under
3535 * the bridge in that case */
3536 if (v->track != TRACK_BIT_WORMHOLE) {
3537 v->UpdatePosition();
3538 v->UpdateInclination(false, true);
3539 } else {
3540 v->UpdateViewport(false, true);
3541 }
3542 }
3543 } while ((v = v->Next()) != nullptr);
3544 }
3545
3546 /**
3547 * Handle a crashed train.
3548 * @param v First train vehicle.
3549 * @return %Vehicle chain still exists.
3550 */
HandleCrashedTrain(Train * v)3551 static bool HandleCrashedTrain(Train *v)
3552 {
3553 int state = ++v->crash_anim_pos;
3554
3555 if (state == 4 && !(v->vehstatus & VS_HIDDEN)) {
3556 CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE);
3557 }
3558
3559 uint32 r;
3560 if (state <= 200 && Chance16R(1, 7, r)) {
3561 int index = (r * 10 >> 16);
3562
3563 Vehicle *u = v;
3564 do {
3565 if (--index < 0) {
3566 r = Random();
3567
3568 CreateEffectVehicleRel(u,
3569 GB(r, 8, 3) + 2,
3570 GB(r, 16, 3) + 2,
3571 GB(r, 0, 3) + 5,
3572 EV_EXPLOSION_SMALL);
3573 break;
3574 }
3575 } while ((u = u->Next()) != nullptr);
3576 }
3577
3578 if (state <= 240 && !(v->tick_counter & 3)) ChangeTrainDirRandomly(v);
3579
3580 if (state >= 4440 && !(v->tick_counter & 0x1F)) {
3581 bool ret = v->Next() != nullptr;
3582 DeleteLastWagon(v);
3583 return ret;
3584 }
3585
3586 return true;
3587 }
3588
3589 /** Maximum speeds for train that is broken down or approaching line end */
3590 static const uint16 _breakdown_speeds[16] = {
3591 225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
3592 };
3593
3594
3595 /**
3596 * Train is approaching line end, slow down and possibly reverse
3597 *
3598 * @param v front train engine
3599 * @param signal not line end, just a red signal
3600 * @param reverse Set to false to not execute the vehicle reversing. This does not change any other logic.
3601 * @return true iff we did NOT have to reverse
3602 */
TrainApproachingLineEnd(Train * v,bool signal,bool reverse)3603 static bool TrainApproachingLineEnd(Train *v, bool signal, bool reverse)
3604 {
3605 /* Calc position within the current tile */
3606 uint x = v->x_pos & 0xF;
3607 uint y = v->y_pos & 0xF;
3608
3609 /* for diagonal directions, 'x' will be 0..15 -
3610 * for other directions, it will be 1, 3, 5, ..., 15 */
3611 switch (v->direction) {
3612 case DIR_N : x = ~x + ~y + 25; break;
3613 case DIR_NW: x = y; FALLTHROUGH;
3614 case DIR_NE: x = ~x + 16; break;
3615 case DIR_E : x = ~x + y + 9; break;
3616 case DIR_SE: x = y; break;
3617 case DIR_S : x = x + y - 7; break;
3618 case DIR_W : x = ~y + x + 9; break;
3619 default: break;
3620 }
3621
3622 /* Do not reverse when approaching red signal. Make sure the vehicle's front
3623 * does not cross the tile boundary when we do reverse, but as the vehicle's
3624 * location is based on their center, use half a vehicle's length as offset.
3625 * Multiply the half-length by two for straight directions to compensate that
3626 * we only get odd x offsets there. */
3627 if (!signal && x + (v->gcache.cached_veh_length + 1) / 2 * (IsDiagonalDirection(v->direction) ? 1 : 2) >= TILE_SIZE) {
3628 /* we are too near the tile end, reverse now */
3629 v->cur_speed = 0;
3630 if (reverse) ReverseTrainDirection(v);
3631 return false;
3632 }
3633
3634 /* slow down */
3635 v->vehstatus |= VS_TRAIN_SLOWING;
3636 uint16 break_speed = _breakdown_speeds[x & 0xF];
3637 if (break_speed < v->cur_speed) v->cur_speed = break_speed;
3638
3639 return true;
3640 }
3641
3642
3643 /**
3644 * Determines whether train would like to leave the tile
3645 * @param v train to test
3646 * @return true iff vehicle is NOT entering or inside a depot or tunnel/bridge
3647 */
TrainCanLeaveTile(const Train * v)3648 static bool TrainCanLeaveTile(const Train *v)
3649 {
3650 /* Exit if inside a tunnel/bridge or a depot */
3651 if (v->track == TRACK_BIT_WORMHOLE || v->track == TRACK_BIT_DEPOT) return false;
3652
3653 TileIndex tile = v->tile;
3654
3655 /* entering a tunnel/bridge? */
3656 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
3657 DiagDirection dir = GetTunnelBridgeDirection(tile);
3658 if (DiagDirToDir(dir) == v->direction) return false;
3659 }
3660
3661 /* entering a depot? */
3662 if (IsRailDepotTile(tile)) {
3663 DiagDirection dir = ReverseDiagDir(GetRailDepotDirection(tile));
3664 if (DiagDirToDir(dir) == v->direction) return false;
3665 }
3666
3667 return true;
3668 }
3669
3670
3671 /**
3672 * Determines whether train is approaching a rail-road crossing
3673 * (thus making it barred)
3674 * @param v front engine of train
3675 * @return TileIndex of crossing the train is approaching, else INVALID_TILE
3676 * @pre v in non-crashed front engine
3677 */
TrainApproachingCrossingTile(const Train * v)3678 static TileIndex TrainApproachingCrossingTile(const Train *v)
3679 {
3680 assert(v->IsFrontEngine());
3681 assert(!(v->vehstatus & VS_CRASHED));
3682
3683 if (!TrainCanLeaveTile(v)) return INVALID_TILE;
3684
3685 DiagDirection dir = VehicleExitDir(v->direction, v->track);
3686 TileIndex tile = v->tile + TileOffsByDiagDir(dir);
3687
3688 /* not a crossing || wrong axis || unusable rail (wrong type or owner) */
3689 if (!IsLevelCrossingTile(tile) || DiagDirToAxis(dir) == GetCrossingRoadAxis(tile) ||
3690 !CheckCompatibleRail(v, tile)) {
3691 return INVALID_TILE;
3692 }
3693
3694 return tile;
3695 }
3696
3697
3698 /**
3699 * Checks for line end. Also, bars crossing at next tile if needed
3700 *
3701 * @param v vehicle we are checking
3702 * @param reverse Set to false to not execute the vehicle reversing. This does not change any other logic.
3703 * @return true iff we did NOT have to reverse
3704 */
TrainCheckIfLineEnds(Train * v,bool reverse)3705 static bool TrainCheckIfLineEnds(Train *v, bool reverse)
3706 {
3707 /* First, handle broken down train */
3708
3709 int t = v->breakdown_ctr;
3710 if (t > 1) {
3711 v->vehstatus |= VS_TRAIN_SLOWING;
3712
3713 uint16 break_speed = _breakdown_speeds[GB(~t, 4, 4)];
3714 if (break_speed < v->cur_speed) v->cur_speed = break_speed;
3715 } else {
3716 v->vehstatus &= ~VS_TRAIN_SLOWING;
3717 }
3718
3719 if (!TrainCanLeaveTile(v)) return true;
3720
3721 /* Determine the non-diagonal direction in which we will exit this tile */
3722 DiagDirection dir = VehicleExitDir(v->direction, v->track);
3723 /* Calculate next tile */
3724 TileIndex tile = v->tile + TileOffsByDiagDir(dir);
3725
3726 /* Determine the track status on the next tile */
3727 TrackStatus ts = GetTileTrackStatus(tile, TRANSPORT_RAIL, 0, ReverseDiagDir(dir));
3728 TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(dir);
3729
3730 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
3731 TrackdirBits red_signals = TrackStatusToRedSignals(ts) & reachable_trackdirs;
3732
3733 /* We are sure the train is not entering a depot, it is detected above */
3734
3735 /* mask unreachable track bits if we are forbidden to do 90deg turns */
3736 TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
3737 if (Rail90DegTurnDisallowed(GetTileRailType(v->tile), GetTileRailType(tile))) {
3738 bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
3739 }
3740
3741 /* no suitable trackbits at all || unusable rail (wrong type or owner) */
3742 if (bits == TRACK_BIT_NONE || !CheckCompatibleRail(v, tile)) {
3743 return TrainApproachingLineEnd(v, false, reverse);
3744 }
3745
3746 /* approaching red signal */
3747 if ((trackdirbits & red_signals) != 0) return TrainApproachingLineEnd(v, true, reverse);
3748
3749 /* approaching a rail/road crossing? then make it red */
3750 if (IsLevelCrossingTile(tile)) MaybeBarCrossingWithSound(tile);
3751
3752 return true;
3753 }
3754
3755
TrainLocoHandler(Train * v,bool mode)3756 static bool TrainLocoHandler(Train *v, bool mode)
3757 {
3758 /* train has crashed? */
3759 if (v->vehstatus & VS_CRASHED) {
3760 return mode ? true : HandleCrashedTrain(v); // 'this' can be deleted here
3761 }
3762
3763 if (v->force_proceed != TFP_NONE) {
3764 ClrBit(v->flags, VRF_TRAIN_STUCK);
3765 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
3766 }
3767
3768 /* train is broken down? */
3769 if (v->HandleBreakdown()) return true;
3770
3771 if (HasBit(v->flags, VRF_REVERSING) && v->cur_speed == 0) {
3772 ReverseTrainDirection(v);
3773 }
3774
3775 /* exit if train is stopped */
3776 if ((v->vehstatus & VS_STOPPED) && v->cur_speed == 0) return true;
3777
3778 bool valid_order = !v->current_order.IsType(OT_NOTHING) && v->current_order.GetType() != OT_CONDITIONAL;
3779 if (ProcessOrders(v) && CheckReverseTrain(v)) {
3780 v->wait_counter = 0;
3781 v->cur_speed = 0;
3782 v->subspeed = 0;
3783 ClrBit(v->flags, VRF_LEAVING_STATION);
3784 ReverseTrainDirection(v);
3785 return true;
3786 } else if (HasBit(v->flags, VRF_LEAVING_STATION)) {
3787 /* Try to reserve a path when leaving the station as we
3788 * might not be marked as wanting a reservation, e.g.
3789 * when an overlength train gets turned around in a station. */
3790 DiagDirection dir = VehicleExitDir(v->direction, v->track);
3791 if (IsRailDepotTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE)) dir = INVALID_DIAGDIR;
3792
3793 if (UpdateSignalsOnSegment(v->tile, dir, v->owner) == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
3794 TryPathReserve(v, true, true);
3795 }
3796 ClrBit(v->flags, VRF_LEAVING_STATION);
3797 }
3798
3799 v->HandleLoading(mode);
3800
3801 if (v->current_order.IsType(OT_LOADING)) return true;
3802
3803 if (CheckTrainStayInDepot(v)) return true;
3804
3805 if (!mode) v->ShowVisualEffect();
3806
3807 /* We had no order but have an order now, do look ahead. */
3808 if (!valid_order && !v->current_order.IsType(OT_NOTHING)) {
3809 CheckNextTrainTile(v);
3810 }
3811
3812 /* Handle stuck trains. */
3813 if (!mode && HasBit(v->flags, VRF_TRAIN_STUCK)) {
3814 ++v->wait_counter;
3815
3816 /* Should we try reversing this tick if still stuck? */
3817 bool turn_around = v->wait_counter % (_settings_game.pf.wait_for_pbs_path * DAY_TICKS) == 0 && _settings_game.pf.reverse_at_signals;
3818
3819 if (!turn_around && v->wait_counter % _settings_game.pf.path_backoff_interval != 0 && v->force_proceed == TFP_NONE) return true;
3820 if (!TryPathReserve(v)) {
3821 /* Still stuck. */
3822 if (turn_around) ReverseTrainDirection(v);
3823
3824 if (HasBit(v->flags, VRF_TRAIN_STUCK) && v->wait_counter > 2 * _settings_game.pf.wait_for_pbs_path * DAY_TICKS) {
3825 /* Show message to player. */
3826 if (_settings_client.gui.lost_vehicle_warn && v->owner == _local_company) {
3827 SetDParam(0, v->index);
3828 AddVehicleAdviceNewsItem(STR_NEWS_TRAIN_IS_STUCK, v->index);
3829 }
3830 v->wait_counter = 0;
3831 }
3832 /* Exit if force proceed not pressed, else reset stuck flag anyway. */
3833 if (v->force_proceed == TFP_NONE) return true;
3834 ClrBit(v->flags, VRF_TRAIN_STUCK);
3835 v->wait_counter = 0;
3836 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
3837 }
3838 }
3839
3840 if (v->current_order.IsType(OT_LEAVESTATION)) {
3841 v->current_order.Free();
3842 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
3843 return true;
3844 }
3845
3846 int j = v->UpdateSpeed();
3847
3848 /* we need to invalidate the widget if we are stopping from 'Stopping 0 km/h' to 'Stopped' */
3849 if (v->cur_speed == 0 && (v->vehstatus & VS_STOPPED)) {
3850 /* If we manually stopped, we're not force-proceeding anymore. */
3851 v->force_proceed = TFP_NONE;
3852 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
3853 }
3854
3855 int adv_spd = v->GetAdvanceDistance();
3856 if (j < adv_spd) {
3857 /* if the vehicle has speed 0, update the last_speed field. */
3858 if (v->cur_speed == 0) v->SetLastSpeed();
3859 } else {
3860 TrainCheckIfLineEnds(v);
3861 /* Loop until the train has finished moving. */
3862 for (;;) {
3863 j -= adv_spd;
3864 TrainController(v, nullptr);
3865 /* Don't continue to move if the train crashed. */
3866 if (CheckTrainCollision(v)) break;
3867 /* Determine distance to next map position */
3868 adv_spd = v->GetAdvanceDistance();
3869
3870 /* No more moving this tick */
3871 if (j < adv_spd || v->cur_speed == 0) break;
3872
3873 OrderType order_type = v->current_order.GetType();
3874 /* Do not skip waypoints (incl. 'via' stations) when passing through at full speed. */
3875 if ((order_type == OT_GOTO_WAYPOINT || order_type == OT_GOTO_STATION) &&
3876 (v->current_order.GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) &&
3877 IsTileType(v->tile, MP_STATION) &&
3878 v->current_order.GetDestination() == GetStationIndex(v->tile)) {
3879 ProcessOrders(v);
3880 }
3881 }
3882 v->SetLastSpeed();
3883 }
3884
3885 for (Train *u = v; u != nullptr; u = u->Next()) {
3886 if ((u->vehstatus & VS_HIDDEN) != 0) continue;
3887
3888 u->UpdateViewport(false, false);
3889 }
3890
3891 if (v->progress == 0) v->progress = j; // Save unused spd for next time, if TrainController didn't set progress
3892
3893 return true;
3894 }
3895
3896 /**
3897 * Get running cost for the train consist.
3898 * @return Yearly running costs.
3899 */
GetRunningCost() const3900 Money Train::GetRunningCost() const
3901 {
3902 Money cost = 0;
3903 const Train *v = this;
3904
3905 do {
3906 const Engine *e = v->GetEngine();
3907 if (e->u.rail.running_cost_class == INVALID_PRICE) continue;
3908
3909 uint cost_factor = GetVehicleProperty(v, PROP_TRAIN_RUNNING_COST_FACTOR, e->u.rail.running_cost);
3910 if (cost_factor == 0) continue;
3911
3912 /* Halve running cost for multiheaded parts */
3913 if (v->IsMultiheaded()) cost_factor /= 2;
3914
3915 cost += GetPrice(e->u.rail.running_cost_class, cost_factor, e->GetGRF());
3916 } while ((v = v->GetNextVehicle()) != nullptr);
3917
3918 return cost;
3919 }
3920
3921 /**
3922 * Update train vehicle data for a tick.
3923 * @return True if the vehicle still exists, false if it has ceased to exist (front of consists only).
3924 */
Tick()3925 bool Train::Tick()
3926 {
3927 PerformanceAccumulator framerate(PFE_GL_TRAINS);
3928
3929 this->tick_counter++;
3930
3931 if (this->IsFrontEngine()) {
3932 if (!(this->vehstatus & VS_STOPPED) || this->cur_speed > 0) this->running_ticks++;
3933
3934 this->current_order_time++;
3935
3936 if (!TrainLocoHandler(this, false)) return false;
3937
3938 return TrainLocoHandler(this, true);
3939 } else if (this->IsFreeWagon() && (this->vehstatus & VS_CRASHED)) {
3940 /* Delete flooded standalone wagon chain */
3941 if (++this->crash_anim_pos >= 4400) {
3942 delete this;
3943 return false;
3944 }
3945 }
3946
3947 return true;
3948 }
3949
3950 /**
3951 * Check whether a train needs service, and if so, find a depot or service it.
3952 * @return v %Train to check.
3953 */
CheckIfTrainNeedsService(Train * v)3954 static void CheckIfTrainNeedsService(Train *v)
3955 {
3956 if (Company::Get(v->owner)->settings.vehicle.servint_trains == 0 || !v->NeedsAutomaticServicing()) return;
3957 if (v->IsChainInDepot()) {
3958 VehicleServiceInDepot(v);
3959 return;
3960 }
3961
3962 uint max_penalty;
3963 switch (_settings_game.pf.pathfinder_for_trains) {
3964 case VPF_NPF: max_penalty = _settings_game.pf.npf.maximum_go_to_depot_penalty; break;
3965 case VPF_YAPF: max_penalty = _settings_game.pf.yapf.maximum_go_to_depot_penalty; break;
3966 default: NOT_REACHED();
3967 }
3968
3969 FindDepotData tfdd = FindClosestTrainDepot(v, max_penalty);
3970 /* Only go to the depot if it is not too far out of our way. */
3971 if (tfdd.best_length == UINT_MAX || tfdd.best_length > max_penalty) {
3972 if (v->current_order.IsType(OT_GOTO_DEPOT)) {
3973 /* If we were already heading for a depot but it has
3974 * suddenly moved farther away, we continue our normal
3975 * schedule? */
3976 v->current_order.MakeDummy();
3977 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
3978 }
3979 return;
3980 }
3981
3982 DepotID depot = GetDepotIndex(tfdd.tile);
3983
3984 if (v->current_order.IsType(OT_GOTO_DEPOT) &&
3985 v->current_order.GetDestination() != depot &&
3986 !Chance16(3, 16)) {
3987 return;
3988 }
3989
3990 SetBit(v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
3991 v->current_order.MakeGoToDepot(depot, ODTFB_SERVICE);
3992 v->dest_tile = tfdd.tile;
3993 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
3994 }
3995
3996 /** Update day counters of the train vehicle. */
OnNewDay()3997 void Train::OnNewDay()
3998 {
3999 AgeVehicle(this);
4000
4001 if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
4002
4003 if (this->IsFrontEngine()) {
4004 CheckVehicleBreakdown(this);
4005
4006 CheckIfTrainNeedsService(this);
4007
4008 CheckOrders(this);
4009
4010 /* update destination */
4011 if (this->current_order.IsType(OT_GOTO_STATION)) {
4012 TileIndex tile = Station::Get(this->current_order.GetDestination())->train_station.tile;
4013 if (tile != INVALID_TILE) this->dest_tile = tile;
4014 }
4015
4016 if (this->running_ticks != 0) {
4017 /* running costs */
4018 CommandCost cost(EXPENSES_TRAIN_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR * DAY_TICKS));
4019
4020 this->profit_this_year -= cost.GetCost();
4021 this->running_ticks = 0;
4022
4023 SubtractMoneyFromCompanyFract(this->owner, cost);
4024
4025 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
4026 SetWindowClassesDirty(WC_TRAINS_LIST);
4027 }
4028 }
4029 }
4030
4031 /**
4032 * Get the tracks of the train vehicle.
4033 * @return Current tracks of the vehicle.
4034 */
GetVehicleTrackdir() const4035 Trackdir Train::GetVehicleTrackdir() const
4036 {
4037 if (this->vehstatus & VS_CRASHED) return INVALID_TRACKDIR;
4038
4039 if (this->track == TRACK_BIT_DEPOT) {
4040 /* We'll assume the train is facing outwards */
4041 return DiagDirToDiagTrackdir(GetRailDepotDirection(this->tile)); // Train in depot
4042 }
4043
4044 if (this->track == TRACK_BIT_WORMHOLE) {
4045 /* train in tunnel or on bridge, so just use its direction and assume a diagonal track */
4046 return DiagDirToDiagTrackdir(DirToDiagDir(this->direction));
4047 }
4048
4049 return TrackDirectionToTrackdir(FindFirstTrack(this->track), this->direction);
4050 }
4051