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