Update readme and changelog for v1.26.0
[openttd-joker.git] / src / train_cmd.cpp
blob5a61c97bc47f9df4de717b4361ff58d0a17f2ee6
1 /* $Id$ */
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 */
10 /** @file train_cmd.cpp Handling of trains. */
12 #include "stdafx.h"
13 #include "error.h"
14 #include "articulated_vehicles.h"
15 #include "command_func.h"
16 #include "pathfinder/npf/npf_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 #include "tracerestrict.h"
39 #include "logic_signals.h"
40 #include "tbtr_template_vehicle_func.h"
41 #include "autoreplace_func.h"
42 #include "bridge_signal_map.h"
43 #include "tunnelbridge.h"
45 #include "table/strings.h"
46 #include "table/train_cmd.h"
48 #include "engine_func.h"
50 #include "safeguards.h"
52 static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck);
53 static bool TrainApproachingLineEnd(Train *v, bool signal, bool reverse);
54 static bool TrainCheckIfLineEnds(Train *v, bool reverse = true);
55 bool TrainController(Train *v, Vehicle *nomove, bool reverse = true); // Also used in vehicle_sl.cpp.
56 static TileIndex TrainApproachingCrossingTile(const Train *v);
57 static void CheckIfTrainNeedsService(Train *v);
58 static void CheckNextTrainTile(Train *v);
60 static const byte _vehicle_initial_x_fract[4] = {10, 8, 4, 8};
61 static const byte _vehicle_initial_y_fract[4] = { 8, 4, 8, 10};
63 template <>
64 bool IsValidImageIndex<VEH_TRAIN>(uint8 image_index)
66 return image_index < lengthof(_engine_sprite_base);
69 /**
70 * Determine the side in which the train will leave the tile
72 * @param direction vehicle direction
73 * @param track vehicle track bits
74 * @return side of tile the train will leave
76 static inline DiagDirection TrainExitDir(Direction direction, TrackBits track)
78 static const TrackBits state_dir_table[DIAGDIR_END] = { TRACK_BIT_RIGHT, TRACK_BIT_LOWER, TRACK_BIT_LEFT, TRACK_BIT_UPPER };
80 DiagDirection diagdir = DirToDiagDir(direction);
82 /* Determine the diagonal direction in which we will exit this tile */
83 if (!HasBit(direction, 0) && track != state_dir_table[diagdir]) {
84 diagdir = ChangeDiagDir(diagdir, DIAGDIRDIFF_90LEFT);
87 return diagdir;
91 /**
92 * Return the cargo weight multiplier to use for a rail vehicle
93 * @param cargo Cargo type to get multiplier for
94 * @return Cargo weight multiplier
96 byte FreightWagonMult(CargoID cargo)
98 if (!CargoSpec::Get(cargo)->is_freight) return 1;
99 return _settings_game.vehicle.freight_trains;
102 /** Checks if lengths of all rail vehicles are valid. If not, shows an error message. */
103 void CheckTrainsLengths()
105 const Train *v;
106 bool first = true;
108 FOR_ALL_TRAINS(v) {
109 if (v->First() == v && !(v->vehstatus & VS_CRASHED)) {
110 for (const Train *u = v, *w = v->Next(); w != nullptr; u = w, w = w->Next()) {
111 if (u->track != TRACK_BIT_DEPOT) {
112 if ((w->track != TRACK_BIT_DEPOT &&
113 max(abs(u->x_pos - w->x_pos), abs(u->y_pos - w->y_pos)) != u->CalcNextVehicleOffset()) ||
114 (w->track == TRACK_BIT_DEPOT && TicksToLeaveDepot(u) <= 0)) {
115 SetDParam(0, v->index);
116 SetDParam(1, v->owner);
117 ShowErrorMessage(STR_BROKEN_VEHICLE_LENGTH, INVALID_STRING_ID, WL_CRITICAL);
119 if (!_networking && first) {
120 first = false;
121 DoCommandP(0, PM_PAUSED_ERROR, 1, CMD_PAUSE);
123 /* Break so we warn only once for each train. */
124 break;
133 * Recalculates the cached stuff of a train. Should be called each time a vehicle is added
134 * to/removed from the chain, and when the game is loaded.
135 * Note: this needs to be called too for 'wagon chains' (in the depot, without an engine)
136 * @param allowed_changes Stuff that is allowed to change.
138 void Train::ConsistChanged(ConsistChangeFlags allowed_changes)
140 uint16 max_speed = UINT16_MAX;
142 assert(this->IsFrontEngine() || this->IsFreeWagon());
144 const RailVehicleInfo *rvi_v = RailVehInfo(this->engine_type);
145 EngineID first_engine = this->IsFrontEngine() ? this->engine_type : INVALID_ENGINE;
146 this->gcache.cached_total_length = 0;
147 this->compatible_railtypes = RAILTYPES_NONE;
149 bool train_can_tilt = true;
151 for (Train *u = this; u != nullptr; u = u->Next()) {
152 const RailVehicleInfo *rvi_u = RailVehInfo(u->engine_type);
154 /* Check the this->first cache. */
155 assert(u->First() == this);
157 /* update the 'first engine' */
158 u->gcache.first_engine = this == u ? INVALID_ENGINE : first_engine;
159 u->railtype = rvi_u->railtype;
161 if (u->IsEngine()) first_engine = u->engine_type;
163 /* Set user defined data to its default value */
164 u->tcache.user_def_data = rvi_u->user_def_data;
165 this->InvalidateNewGRFCache();
166 u->InvalidateNewGRFCache();
169 for (Train *u = this; u != nullptr; u = u->Next()) {
170 /* Update user defined data (must be done before other properties) */
171 u->tcache.user_def_data = GetVehicleProperty(u, PROP_TRAIN_USER_DATA, u->tcache.user_def_data);
172 this->InvalidateNewGRFCache();
173 u->InvalidateNewGRFCache();
176 for (Train *u = this; u != nullptr; u = u->Next()) {
177 const Engine *e_u = u->GetEngine();
178 const RailVehicleInfo *rvi_u = &e_u->u.rail;
180 if (!HasBit(e_u->info.misc_flags, EF_RAIL_TILTS)) train_can_tilt = false;
182 /* Cache wagon override sprite group. nullptr is returned if there is none */
183 u->tcache.cached_override = GetWagonOverrideSpriteSet(u->engine_type, u->cargo_type, u->gcache.first_engine);
185 /* Reset colour map */
186 u->colourmap = PAL_NONE;
188 RailType rt = u->railtype;
190 /* Update powered-wagon-status and visual effect */
191 u->UpdateVisualEffect(true);
193 if (rvi_v->pow_wag_power != 0 && rvi_u->railveh_type == RAILVEH_WAGON &&
194 UsesWagonOverride(u) && !HasBit(u->vcache.cached_vis_effect, VE_DISABLE_WAGON_POWER)) {
195 /* wagon is powered */
196 SetBit(u->flags, VRF_POWEREDWAGON); // cache 'powered' status
197 } else {
198 ClrBit(u->flags, VRF_POWEREDWAGON);
201 if (!u->IsArticulatedPart()) {
202 /* Do not count powered wagons for the compatible railtypes, as wagons always
203 have railtype normal */
204 if (rvi_u->power > 0) {
205 this->compatible_railtypes |= GetRailTypeInfo(u->railtype)->powered_railtypes;
208 /* Some electric engines can be allowed to run on normal rail. It happens to all
209 * existing electric engines when elrails are disabled and then re-enabled */
210 if (HasBit(u->flags, VRF_EL_ENGINE_ALLOWED_NORMAL_RAIL)) {
211 u->railtype = RAILTYPE_RAIL;
212 u->compatible_railtypes |= RAILTYPES_RAIL;
215 /* max speed is the minimum of the speed limits of all vehicles in the consist */
216 if ((rvi_u->railveh_type != RAILVEH_WAGON || _settings_game.vehicle.wagon_speed_limits) && !UsesWagonOverride(u)) {
217 uint16 speed = GetVehicleProperty(u, PROP_TRAIN_SPEED, rvi_u->max_speed);
218 if (speed != 0) max_speed = min(speed, max_speed);
222 uint16 new_cap = e_u->DetermineCapacity(u);
223 if (allowed_changes & CCF_CAPACITY) {
224 /* Update vehicle capacity. */
225 if (u->cargo_cap > new_cap) u->cargo.Truncate(new_cap);
226 u->refit_cap = min(new_cap, u->refit_cap);
227 u->cargo_cap = new_cap;
228 } else {
229 /* Verify capacity hasn't changed. */
230 if (new_cap != u->cargo_cap) ShowNewGrfVehicleError(u->engine_type, STR_NEWGRF_BROKEN, STR_NEWGRF_BROKEN_CAPACITY, GBUG_VEH_CAPACITY, true);
232 u->vcache.cached_cargo_age_period = GetVehicleProperty(u, PROP_TRAIN_CARGO_AGE_PERIOD, e_u->info.cargo_age_period);
234 /* check the vehicle length (callback) */
235 uint16 veh_len = CALLBACK_FAILED;
236 if (e_u->GetGRF() != nullptr && e_u->GetGRF()->grf_version >= 8) {
237 /* Use callback 36 */
238 veh_len = GetVehicleProperty(u, PROP_TRAIN_SHORTEN_FACTOR, CALLBACK_FAILED);
240 if (veh_len != CALLBACK_FAILED && veh_len >= VEHICLE_LENGTH) {
241 ErrorUnknownCallbackResult(e_u->GetGRFID(), CBID_VEHICLE_LENGTH, veh_len);
243 } else if (HasBit(e_u->info.callback_mask, CBM_VEHICLE_LENGTH)) {
244 /* Use callback 11 */
245 veh_len = GetVehicleCallback(CBID_VEHICLE_LENGTH, 0, 0, u->engine_type, u);
247 if (veh_len == CALLBACK_FAILED) veh_len = rvi_u->shorten_factor;
248 veh_len = VEHICLE_LENGTH - Clamp(veh_len, 0, VEHICLE_LENGTH - 1);
250 if (allowed_changes & CCF_LENGTH) {
251 /* Update vehicle length. */
252 u->gcache.cached_veh_length = veh_len;
253 } else {
254 /* Verify length hasn't changed. */
255 if (veh_len != u->gcache.cached_veh_length) VehicleLengthChanged(u);
258 this->gcache.cached_total_length += u->gcache.cached_veh_length;
259 this->InvalidateNewGRFCache();
260 u->InvalidateNewGRFCache();
263 /* store consist weight/max speed in cache */
264 this->vcache.cached_max_speed = max_speed;
265 this->tcache.cached_tilt = train_can_tilt;
266 this->tcache.cached_max_curve_speed = this->GetCurveSpeedLimit();
268 /* 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) */
269 this->CargoChanged();
271 if (this->IsFrontEngine()) {
272 this->UpdateAcceleration();
273 if ( !HasBit(this->subtype, GVSF_VIRTUAL) ) SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
274 InvalidateWindowData(WC_VEHICLE_REFIT, this->index, VIWD_CONSIST_CHANGED);
275 InvalidateWindowData(WC_VEHICLE_ORDERS, this->index, VIWD_CONSIST_CHANGED);
276 InvalidateNewGRFInspectWindow(GSF_TRAINS, this->index);
281 * Get the stop location of (the center) of the front vehicle of a train at
282 * a platform of a station.
283 * @param station_id the ID of the station where we're stopping
284 * @param tile the tile where the vehicle currently is
285 * @param v the vehicle to get the stop location of
286 * @param station_ahead 'return' the amount of 1/16th tiles in front of the train
287 * @param station_length 'return' the station length in 1/16th tiles
288 * @return the location, calculated from the begin of the station to stop at.
290 int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *v, int *station_ahead, int *station_length)
292 const Station *st = Station::Get(station_id);
293 *station_ahead = st->GetPlatformLength(tile, DirToDiagDir(v->direction)) * TILE_SIZE;
294 *station_length = st->GetPlatformLength(tile) * TILE_SIZE;
296 /* Default to the middle of the station for stations stops that are not in
297 * the order list like intermediate stations when non-stop is disabled */
298 OrderStopLocation osl = OSL_PLATFORM_MIDDLE;
299 if (v->gcache.cached_total_length >= *station_length) {
300 /* The train is longer than the station, make it stop at the far end of the platform */
301 osl = OSL_PLATFORM_FAR_END;
302 } else if (v->current_order.IsType(OT_GOTO_STATION) && v->current_order.GetDestination() == station_id) {
303 osl = v->current_order.GetStopLocation();
306 /* The stop location of the FRONT! of the train */
307 int stop;
308 switch (osl) {
309 default: NOT_REACHED();
311 case OSL_PLATFORM_NEAR_END:
312 stop = v->gcache.cached_total_length;
313 break;
315 case OSL_PLATFORM_MIDDLE:
316 stop = *station_length - (*station_length - v->gcache.cached_total_length) / 2;
317 break;
319 case OSL_PLATFORM_FAR_END:
320 stop = *station_length;
321 break;
324 /* Subtract half the front vehicle length of the train so we get the real
325 * stop location of the train. */
326 return stop - (v->gcache.cached_veh_length + 1) / 2;
331 * Computes train speed limit caused by curves
332 * @return imposed speed limit
334 int Train::GetCurveSpeedLimit() const
336 assert(this->First() == this);
338 static const int absolute_max_speed = UINT16_MAX;
339 int max_speed = absolute_max_speed;
341 if (_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) return max_speed;
343 int curvecount[2] = {0, 0};
345 /* first find the curve speed limit */
346 int numcurve = 0;
347 int sum = 0;
348 int pos = 0;
349 int lastpos = -1;
350 for (const Vehicle *u = this; u->Next() != nullptr; u = u->Next(), pos++) {
351 Direction this_dir = u->direction;
352 Direction next_dir = u->Next()->direction;
354 DirDiff dirdiff = DirDifference(this_dir, next_dir);
355 if (dirdiff == DIRDIFF_SAME) continue;
357 if (dirdiff == DIRDIFF_45LEFT) curvecount[0]++;
358 if (dirdiff == DIRDIFF_45RIGHT) curvecount[1]++;
359 if (dirdiff == DIRDIFF_45LEFT || dirdiff == DIRDIFF_45RIGHT) {
360 if (lastpos != -1) {
361 numcurve++;
362 sum += pos - lastpos;
363 if (pos - lastpos == 1 && max_speed > 88) {
364 max_speed = 88;
367 lastpos = pos;
370 /* if we have a 90 degree turn, fix the speed limit to 60 */
371 if (dirdiff == DIRDIFF_90LEFT || dirdiff == DIRDIFF_90RIGHT) {
372 max_speed = 61;
376 if (numcurve > 0 && max_speed > 88) {
377 if (curvecount[0] == 1 && curvecount[1] == 1) {
378 max_speed = absolute_max_speed;
379 } else {
380 sum /= numcurve;
381 max_speed = 232 - (13 - Clamp(sum, 1, 12)) * (13 - Clamp(sum, 1, 12));
385 if (max_speed != absolute_max_speed) {
386 /* Apply the engine's rail type curve speed advantage, if it slowed by curves */
387 const RailtypeInfo *rti = GetRailTypeInfo(this->railtype);
388 max_speed += (max_speed / 2) * rti->curve_speed;
390 if (this->tcache.cached_tilt) {
391 /* Apply max_speed bonus of 20% for a tilting train */
392 max_speed += max_speed / 5;
396 return max_speed;
399 enum TrackBits;
402 * Calculates the maximum speed of the vehicle under its current conditions.
403 * @return Maximum speed of the vehicle.
405 int Train::GetCurrentMaxSpeed() const
407 int max_speed = _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL ?
408 this->gcache.cached_max_track_speed :
409 this->tcache.cached_max_curve_speed;
411 if (!(this->vehstatus & VS_CRASHED) && _settings_game.vehicle.train_speed_adaption) {
412 int atc_speed = max_speed;
414 CFollowTrackRail ft(this);
415 Trackdir old_td = this->GetVehicleTrackdir();
417 if (ft.Follow(this->tile, this->GetVehicleTrackdir())) {
418 /* Basic idea: Follow the track for 20 tiles or 3 signals (i.e. at most two signal blocks) looking for other trains. */
419 /* If we find one (that meets certain restrictions), we limit the max speed to the speed of that train. */
420 int num_tiles = 0;
421 int num_signals = 0;
423 do {
424 old_td = ft.m_old_td;
426 /* If we are on a depot or rail station tile stop searching */
427 if (IsDepotTile(ft.m_new_tile) || IsRailStationTile(ft.m_new_tile))
428 break;
430 /* Increment signal counter if we're on a signal */
431 if (IsTileType(ft.m_new_tile, MP_RAILWAY) && ///< Tile has rails
432 KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE && ///< Tile has exactly *one* track
433 HasSignalOnTrack(ft.m_new_tile, TrackBitsToTrack(TrackdirBitsToTrackBits(ft.m_new_td_bits)))) { ///< Tile has signal
434 num_signals++;
437 /* Check if tile has train/is reserved */
438 if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE && ///< Tile has exactly *one* track
439 HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(ft.m_new_td_bits))) { ///< Tile is reserved
440 Train* other_train = GetTrainForReservation(ft.m_new_tile, TrackBitsToTrack(TrackdirBitsToTrackBits(ft.m_new_td_bits)));
443 if (other_train != nullptr &&
444 other_train != this && ///< Other train is not this train
445 other_train->GetAccelerationStatus() != AS_BRAKE) { ///< Other train is not braking
446 atc_speed = other_train->GetCurrentSpeed();
447 break;
451 /* Decide what in direction to continue: reservation, straight or "first/only" direction. */
452 /* Abort if there's no reservation even though the tile contains multiple tracks. */
453 TrackdirBits reserved = ft.m_new_td_bits & TrackBitsToTrackdirBits(GetReservedTrackbits(ft.m_new_tile));
455 if (reserved != TRACKDIR_BIT_NONE) {
456 // There is a reservation to follow.
457 old_td = FindFirstTrackdir(reserved);
459 else if (KillFirstBit(ft.m_new_td_bits) != TRACKDIR_BIT_NONE) {
460 // Tile has more than one track and we have no reservation. Bail out.
461 break;
463 else {
464 // There was no reservation but there is only one direction to follow, so follow it.
465 old_td = FindFirstTrackdir(ft.m_new_td_bits);
468 num_tiles++;
469 } while (num_tiles < 20 && num_signals < 3 && ft.Follow(ft.m_new_tile, old_td));
472 /* Check that the ATC speed is sufficiently large.
473 Avoids assertion error in UpdateSpeed(). */
474 max_speed = max(25, min(max_speed, atc_speed));
477 if (_settings_game.vehicle.train_acceleration_model == AM_REALISTIC && IsRailStationTile(this->tile)) {
478 StationID sid = GetStationIndex(this->tile);
479 if (this->current_order.ShouldStopAtStation(this, sid)) {
480 int station_ahead;
481 int station_length;
482 int stop_at = GetTrainStopLocation(sid, this->tile, this, &station_ahead, &station_length);
484 /* The distance to go is whatever is still ahead of the train minus the
485 * distance from the train's stop location to the end of the platform */
486 int distance_to_go = station_ahead / TILE_SIZE - (station_length - stop_at) / TILE_SIZE;
488 if (distance_to_go > 0) {
489 int st_max_speed = 120;
491 int delta_v = this->cur_speed / (distance_to_go + 1);
492 if (max_speed > (this->cur_speed - delta_v)) {
493 st_max_speed = this->cur_speed - (delta_v / 10);
496 st_max_speed = max(st_max_speed, 25 * distance_to_go);
497 max_speed = min(max_speed, st_max_speed);
502 for (const Train *u = this; u != nullptr; u = u->Next()) {
503 if (_settings_game.vehicle.train_acceleration_model == AM_REALISTIC && u->track == TRACK_BIT_DEPOT) {
504 max_speed = min(max_speed, 61);
505 break;
508 /* Vehicle is on the middle part of a bridge. */
509 if (u->track == TRACK_BIT_WORMHOLE && !(u->vehstatus & VS_HIDDEN)) {
510 max_speed = min(max_speed, GetBridgeSpec(GetBridgeType(u->tile))->speed);
514 max_speed = min(max_speed, this->current_order.GetMaxSpeed());
515 return min(max_speed, this->gcache.cached_max_track_speed);
518 /** Update acceleration of the train from the cached power and weight. */
519 void Train::UpdateAcceleration()
521 assert(this->IsFrontEngine() || this->IsFreeWagon());
523 uint power = this->gcache.cached_power;
524 uint weight = this->gcache.cached_weight;
525 assert(weight != 0);
526 this->acceleration = Clamp(power / weight * 4, 1, 255);
530 * Get the width of a train vehicle image in the GUI.
531 * @param offset Additional offset for positioning the sprite; set to nullptr if not needed
532 * @return Width in pixels
534 int Train::GetDisplayImageWidth(Point *offset) const
536 int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
537 int vehicle_pitch = 0;
539 const Engine *e = this->GetEngine();
540 if (e->GetGRF() != nullptr && is_custom_sprite(e->u.rail.image_index)) {
541 reference_width = e->GetGRF()->traininfo_vehicle_width;
542 vehicle_pitch = e->GetGRF()->traininfo_vehicle_pitch;
545 if (offset != nullptr) {
546 offset->x = ScaleGUITrad(reference_width) / 2;
547 offset->y = ScaleGUITrad(vehicle_pitch);
549 return ScaleGUITrad(this->gcache.cached_veh_length * reference_width / VEHICLE_LENGTH);
552 static SpriteID GetDefaultTrainSprite(uint8 spritenum, Direction direction)
554 assert(IsValidImageIndex<VEH_TRAIN>(spritenum));
555 return ((direction + _engine_sprite_add[spritenum]) & _engine_sprite_and[spritenum]) + _engine_sprite_base[spritenum];
559 * Get the sprite to display the train.
560 * @param direction Direction of view/travel.
561 * @param image_type Visualisation context.
562 * @return Sprite to display.
564 void Train::GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const
566 uint8 spritenum = this->spritenum;
568 if (HasBit(this->flags, VRF_REVERSE_DIRECTION)) direction = ReverseDir(direction);
570 if (is_custom_sprite(spritenum)) {
571 GetCustomVehicleSprite(this, (Direction)(direction + 4 * IS_CUSTOM_SECONDHEAD_SPRITE(spritenum)), image_type, result);
572 if (result->IsValid()) return;
574 spritenum = this->GetEngine()->original_image_index;
577 assert(IsValidImageIndex<VEH_TRAIN>(spritenum));
578 SpriteID sprite = GetDefaultTrainSprite(spritenum, direction);
580 if (this->cargo.StoredCount() >= this->cargo_cap / 2U) sprite += _wagon_full_adder[spritenum];
582 result->Set(sprite);
585 static void GetRailIcon(EngineID engine, bool rear_head, int &y, EngineImageType image_type, VehicleSpriteSeq *result)
587 const Engine *e = Engine::Get(engine);
588 Direction dir = rear_head ? DIR_E : DIR_W;
589 uint8 spritenum = e->u.rail.image_index;
591 if (is_custom_sprite(spritenum)) {
592 GetCustomVehicleIcon(engine, dir, image_type, result);
593 if (result->IsValid()) {
594 if (e->GetGRF() != nullptr) {
595 y += ScaleGUITrad(e->GetGRF()->traininfo_vehicle_pitch);
597 return;
600 spritenum = Engine::Get(engine)->original_image_index;
603 if (rear_head) spritenum++;
605 result->Set(GetDefaultTrainSprite(spritenum, DIR_W));
608 void DrawTrainEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
610 if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
611 int yf = y;
612 int yr = y;
614 VehicleSpriteSeq seqf, seqr;
615 GetRailIcon(engine, false, yf, image_type, &seqf);
616 GetRailIcon(engine, true, yr, image_type, &seqr);
618 Rect16 rectf = seqf.GetBounds();
619 Rect16 rectr = seqr.GetBounds();
621 preferred_x = SoftClamp(preferred_x,
622 left - UnScaleGUI(rectf.left) + ScaleGUITrad(14),
623 right - UnScaleGUI(rectr.right) - ScaleGUITrad(15));
625 seqf.Draw(preferred_x - ScaleGUITrad(14), yf, pal, pal == PALETTE_CRASH);
626 seqr.Draw(preferred_x + ScaleGUITrad(15), yr, pal, pal == PALETTE_CRASH);
627 } else {
628 VehicleSpriteSeq seq;
629 GetRailIcon(engine, false, y, image_type, &seq);
631 Rect16 rect = seq.GetBounds();
632 preferred_x = Clamp(preferred_x,
633 left - UnScaleGUI(rect.left),
634 right - UnScaleGUI(rect.right));
636 seq.Draw(preferred_x, y, pal, pal == PALETTE_CRASH);
641 * Get the size of the sprite of a train sprite heading west, or both heads (used for lists).
642 * @param engine The engine to get the sprite from.
643 * @param[out] width The width of the sprite.
644 * @param[out] height The height of the sprite.
645 * @param[out] xoffs Number of pixels to shift the sprite to the right.
646 * @param[out] yoffs Number of pixels to shift the sprite downwards.
647 * @param image_type Context the sprite is used in.
649 void GetTrainSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
651 int y = 0;
653 VehicleSpriteSeq seq;
654 GetRailIcon(engine, false, y, image_type, &seq);
656 Rect16 rect = seq.GetBounds();
658 width = UnScaleGUI(rect.right - rect.left + 1);
659 height = UnScaleGUI(rect.bottom - rect.top + 1);
660 xoffs = UnScaleGUI(rect.left);
661 yoffs = UnScaleGUI(rect.top);
663 if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
664 GetRailIcon(engine, true, y, image_type, &seq);
665 rect = seq.GetBounds();
667 /* Calculate values relative to an imaginary center between the two sprites. */
668 width = ScaleGUITrad(TRAININFO_DEFAULT_VEHICLE_WIDTH) + UnScaleGUI(rect.right) - xoffs;
669 height = max<uint>(height, UnScaleGUI(rect.bottom - rect.top + 1));
670 xoffs = xoffs - ScaleGUITrad(TRAININFO_DEFAULT_VEHICLE_WIDTH) / 2;
671 yoffs = min(yoffs, UnScaleGUI(rect.top));
676 * Build a railroad wagon.
677 * @param tile tile of the depot where rail-vehicle is built.
678 * @param flags type of operation.
679 * @param e the engine to build.
680 * @param ret[out] the vehicle that has been built.
681 * @return the cost of this operation or an error.
683 static CommandCost CmdBuildRailWagon(TileIndex tile, DoCommandFlag flags, const Engine *e, Vehicle **ret)
685 const RailVehicleInfo *rvi = &e->u.rail;
687 /* Check that the wagon can drive on the track in question */
688 if (!IsCompatibleRail(rvi->railtype, GetRailType(tile))) return CommandError();
690 if (flags & DC_EXEC) {
691 Train *v = new Train();
692 *ret = v;
693 v->spritenum = rvi->image_index;
695 v->engine_type = e->index;
696 v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
698 DiagDirection dir = GetRailDepotDirection(tile);
700 v->direction = DiagDirToDir(dir);
701 v->tile = tile;
703 int x = TileX(tile) * TILE_SIZE | _vehicle_initial_x_fract[dir];
704 int y = TileY(tile) * TILE_SIZE | _vehicle_initial_y_fract[dir];
706 v->x_pos = x;
707 v->y_pos = y;
708 v->z_pos = GetSlopePixelZ(x, y);
709 v->owner = _current_company;
710 v->track = TRACK_BIT_DEPOT;
711 v->vehstatus = VS_HIDDEN | VS_DEFPAL;
712 v->reverse_distance = 0;
714 v->SetWagon();
716 v->SetFreeWagon();
717 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
719 v->cargo_type = e->GetDefaultCargoType();
720 v->cargo_cap = rvi->capacity;
721 v->refit_cap = 0;
723 v->railtype = rvi->railtype;
725 v->date_of_last_service = _date;
726 v->build_year = _cur_year;
727 v->sprite_seq.Set(SPR_IMG_QUERY);
728 v->random_bits = VehicleRandomBits();
730 v->group_id = DEFAULT_GROUP;
732 AddArticulatedParts(v);
734 _new_vehicle_id = v->index;
736 v->UpdatePosition();
737 v->First()->ConsistChanged(CCF_ARRANGE);
738 UpdateTrainGroupID(v->First());
740 CheckConsistencyOfArticulatedVehicle(v);
742 /* Try to connect the vehicle to one of free chains of wagons. */
743 Train *w;
744 FOR_ALL_TRAINS(w) {
745 if (w->tile == tile && ///< Same depot
746 w->IsFreeWagon() && ///< A free wagon chain
747 w->engine_type == e->index && ///< Same type
748 w->First() != v && ///< Don't connect to ourself
749 !(w->vehstatus & VS_CRASHED)) { ///< Not crashed/flooded
750 DoCommand(0, v->index | 1 << 20, w->Last()->index, DC_EXEC, CMD_MOVE_RAIL_VEHICLE);
751 break;
756 return CommandCost();
759 /** Move all free vehicles in the depot to the train */
760 static void NormalizeTrainVehInDepot(const Train *u)
762 const Train *v;
763 FOR_ALL_TRAINS(v) {
764 if (v->IsFreeWagon() && v->tile == u->tile &&
765 v->track == TRACK_BIT_DEPOT) {
766 if (DoCommand(0, v->index | 1 << 20, u->index, DC_EXEC,
767 CMD_MOVE_RAIL_VEHICLE).Failed())
768 break;
773 static void AddRearEngineToMultiheadedTrain(Train *v)
775 Train *u = new Train();
776 v->value >>= 1;
777 u->value = v->value;
778 u->direction = v->direction;
779 u->owner = v->owner;
780 u->tile = v->tile;
781 u->x_pos = v->x_pos;
782 u->y_pos = v->y_pos;
783 u->z_pos = v->z_pos;
784 u->track = TRACK_BIT_DEPOT;
785 u->vehstatus = v->vehstatus & ~VS_STOPPED;
786 u->spritenum = v->spritenum + 1;
787 u->cargo_type = v->cargo_type;
788 u->cargo_subtype = v->cargo_subtype;
789 u->cargo_cap = v->cargo_cap;
790 u->refit_cap = v->refit_cap;
791 u->railtype = v->railtype;
792 u->engine_type = v->engine_type;
793 u->date_of_last_service = v->date_of_last_service;
794 u->build_year = v->build_year;
795 u->sprite_seq.Set(SPR_IMG_QUERY);
796 u->random_bits = VehicleRandomBits();
797 v->SetMultiheaded();
798 u->SetMultiheaded();
799 v->SetNext(u);
800 u->UpdatePosition();
802 /* Now we need to link the front and rear engines together */
803 v->other_multiheaded_part = u;
804 u->other_multiheaded_part = v;
808 * Build a railroad vehicle.
809 * @param tile tile of the depot where rail-vehicle is built.
810 * @param flags type of operation.
811 * @param e the engine to build.
812 * @param data bit 0 prevents any free cars from being added to the train.
813 * @param ret[out] the vehicle that has been built.
814 * @return the cost of this operation or an error.
816 CommandCost CmdBuildRailVehicle(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **ret)
818 const RailVehicleInfo *rvi = &e->u.rail;
820 if (rvi->railveh_type == RAILVEH_WAGON) return CmdBuildRailWagon(tile, flags, e, ret);
822 /* Check if depot and new engine uses the same kind of tracks *
823 * We need to see if the engine got power on the tile to avoid electric engines in non-electric depots */
824 if (!HasPowerOnRail(rvi->railtype, GetRailType(tile))) return CommandError();
826 if (flags & DC_EXEC) {
827 DiagDirection dir = GetRailDepotDirection(tile);
828 int x = TileX(tile) * TILE_SIZE + _vehicle_initial_x_fract[dir];
829 int y = TileY(tile) * TILE_SIZE + _vehicle_initial_y_fract[dir];
831 Train *v = new Train();
832 *ret = v;
833 v->direction = DiagDirToDir(dir);
834 v->tile = tile;
835 v->owner = _current_company;
836 v->x_pos = x;
837 v->y_pos = y;
838 v->z_pos = GetSlopePixelZ(x, y);
839 v->track = TRACK_BIT_DEPOT;
840 v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
841 v->spritenum = rvi->image_index;
842 v->cargo_type = e->GetDefaultCargoType();
843 v->cargo_cap = rvi->capacity;
844 v->refit_cap = 0;
845 v->last_station_visited = INVALID_STATION;
846 v->last_loading_station = INVALID_STATION;
847 v->reverse_distance = 0;
849 v->engine_type = e->index;
850 v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
852 v->reliability = e->reliability;
853 v->reliability_spd_dec = e->reliability_spd_dec;
854 v->max_age = e->GetLifeLengthInDays();
856 v->railtype = rvi->railtype;
857 _new_vehicle_id = v->index;
859 v->SetServiceInterval(Company::Get(_current_company)->settings.vehicle.servint_trains);
860 v->date_of_last_service = _date;
861 v->build_year = _cur_year;
862 v->sprite_seq.Set(SPR_IMG_QUERY);
863 v->random_bits = VehicleRandomBits();
865 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
866 v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
868 v->group_id = DEFAULT_GROUP;
870 v->SetFrontEngine();
871 v->SetEngine();
873 v->UpdatePosition();
875 if (rvi->railveh_type == RAILVEH_MULTIHEAD) {
876 AddRearEngineToMultiheadedTrain(v);
877 } else {
878 AddArticulatedParts(v);
881 v->ConsistChanged(CCF_ARRANGE);
882 UpdateTrainGroupID(v);
884 if (!HasBit(data, 0) && !(flags & DC_AUTOREPLACE)) { // check if the cars should be added to the new vehicle
885 NormalizeTrainVehInDepot(v);
888 CheckConsistencyOfArticulatedVehicle(v);
891 return CommandCost();
894 static Train *FindGoodVehiclePos(const Train *src)
896 EngineID eng = src->engine_type;
897 TileIndex tile = src->tile;
899 Train *dst;
900 FOR_ALL_TRAINS(dst) {
901 if (dst->IsFreeWagon() && dst->tile == tile && !(dst->vehstatus & VS_CRASHED)) {
902 /* check so all vehicles in the line have the same engine. */
903 Train *t = dst;
904 while (t->engine_type == eng) {
905 t = t->Next();
906 if (t == nullptr) return dst;
911 return nullptr;
914 /** Helper type for lists/vectors of trains */
915 typedef SmallVector<Train *, 16> TrainList;
918 * Make a backup of a train into a train list.
919 * @param list to make the backup in
920 * @param t the train to make the backup of
922 static void MakeTrainBackup(TrainList &list, Train *t)
924 for (; t != nullptr; t = t->Next()) *list.Append() = t;
928 * Restore the train from the backup list.
929 * @param list the train to restore.
931 static void RestoreTrainBackup(TrainList &list)
933 /* No train, nothing to do. */
934 if (list.Length() == 0) return;
936 Train *prev = nullptr;
937 /* Iterate over the list and rebuild it. */
938 for (Train **iter = list.Begin(); iter != list.End(); iter++) {
939 Train *t = *iter;
940 if (prev != nullptr) {
941 prev->SetNext(t);
942 } else if (t->Previous() != nullptr) {
943 /* Make sure the head of the train is always the first in the chain. */
944 t->Previous()->SetNext(nullptr);
946 prev = t;
951 * Remove the given wagon from its consist.
952 * @param part the part of the train to remove.
953 * @param chain whether to remove the whole chain.
955 static void RemoveFromConsist(Train *part, bool chain = false)
957 Train *tail = chain ? part->Last() : part->GetLastEnginePart();
959 /* Unlink at the front, but make it point to the next
960 * vehicle after the to be remove part. */
961 if (part->Previous() != nullptr) part->Previous()->SetNext(tail->Next());
963 /* Unlink at the back */
964 tail->SetNext(nullptr);
968 * Inserts a chain into the train at dst.
969 * @param dst the place where to append after.
970 * @param chain the chain to actually add.
972 static void InsertInConsist(Train *dst, Train *chain)
974 /* We do not want to add something in the middle of an articulated part. */
975 assert(dst->Next() == nullptr || !dst->Next()->IsArticulatedPart());
977 chain->Last()->SetNext(dst->Next());
978 dst->SetNext(chain);
982 * Normalise the dual heads in the train, i.e. if one is
983 * missing move that one to this train.
984 * @param t the train to normalise.
986 static void NormaliseDualHeads(Train *t)
988 for (; t != nullptr; t = t->GetNextVehicle()) {
989 if (!t->IsMultiheaded() || !t->IsEngine()) continue;
991 /* Make sure that there are no free cars before next engine */
992 Train *u;
993 for (u = t; u->Next() != nullptr && !u->Next()->IsEngine(); u = u->Next()) {}
995 if (u == t->other_multiheaded_part) continue;
997 /* Remove the part from the 'wrong' train */
998 RemoveFromConsist(t->other_multiheaded_part);
999 /* And add it to the 'right' train */
1000 InsertInConsist(u, t->other_multiheaded_part);
1005 * Normalise the sub types of the parts in this chain.
1006 * @param chain the chain to normalise.
1008 static void NormaliseSubtypes(Train *chain)
1010 /* Nothing to do */
1011 if (chain == nullptr) return;
1013 /* We must be the first in the chain. */
1014 assert(chain->Previous() == nullptr);
1016 /* Set the appropriate bits for the first in the chain. */
1017 if (chain->IsWagon()) {
1018 chain->SetFreeWagon();
1019 } else {
1020 assert(chain->IsEngine());
1021 chain->SetFrontEngine();
1024 /* Now clear the bits for the rest of the chain */
1025 for (Train *t = chain->Next(); t != nullptr; t = t->Next()) {
1026 t->ClearFreeWagon();
1027 t->ClearFrontEngine();
1032 * Check/validate whether we may actually build a new train.
1033 * @note All vehicles are/were 'heads' of their chains.
1034 * @param original_dst The original destination chain.
1035 * @param dst The destination chain after constructing the train.
1036 * @param original_dst The original source chain.
1037 * @param dst The source chain after constructing the train.
1038 * @return possible error of this command.
1040 static CommandCost CheckNewTrain(Train *original_dst, Train *dst, Train *original_src, Train *src)
1042 /* Just add 'new' engines and subtract the original ones.
1043 * If that's less than or equal to 0 we can be sure we did
1044 * not add any engines (read: trains) along the way. */
1045 if ((src != nullptr && src->IsEngine() ? 1 : 0) +
1046 (dst != nullptr && dst->IsEngine() ? 1 : 0) -
1047 (original_src != nullptr && original_src->IsEngine() ? 1 : 0) -
1048 (original_dst != nullptr && original_dst->IsEngine() ? 1 : 0) <= 0) {
1049 return CommandCost();
1052 /* Get a free unit number and check whether it's within the bounds.
1053 * There will always be a maximum of one new train. */
1054 if (GetFreeUnitNumber(VEH_TRAIN) <= _settings_game.vehicle.max_trains) return CommandCost();
1056 return CommandError(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
1060 * Check whether the train parts can be attached.
1061 * @param t the train to check
1062 * @return possible error of this command.
1064 static CommandCost CheckTrainAttachment(Train *t)
1066 /* No multi-part train, no need to check. */
1067 if (t == nullptr || t->Next() == nullptr || !t->IsEngine()) return CommandCost();
1069 /* The maximum length for a train. For each part we decrease this by one
1070 * and if the result is negative the train is simply too long. */
1071 int allowed_len = _settings_game.vehicle.max_train_length * TILE_SIZE - t->gcache.cached_veh_length;
1073 Train *head = t;
1074 Train *prev = t;
1076 /* Break the prev -> t link so it always holds within the loop. */
1077 t = t->Next();
1078 prev->SetNext(nullptr);
1080 /* Make sure the cache is cleared. */
1081 head->InvalidateNewGRFCache();
1083 while (t != nullptr) {
1084 allowed_len -= t->gcache.cached_veh_length;
1086 Train *next = t->Next();
1088 /* Unlink the to-be-added piece; it is already unlinked from the previous
1089 * part due to the fact that the prev -> t link is broken. */
1090 t->SetNext(nullptr);
1092 /* Don't check callback for articulated or rear dual headed parts */
1093 if (!t->IsArticulatedPart() && !t->IsRearDualheaded()) {
1094 /* Back up and clear the first_engine data to avoid using wagon override group */
1095 EngineID first_engine = t->gcache.first_engine;
1096 t->gcache.first_engine = INVALID_ENGINE;
1098 /* We don't want the cache to interfere. head's cache is cleared before
1099 * the loop and after each callback does not need to be cleared here. */
1100 t->InvalidateNewGRFCache();
1102 uint16 callback = GetVehicleCallbackParent(CBID_TRAIN_ALLOW_WAGON_ATTACH, 0, 0, head->engine_type, t, head);
1104 /* Restore original first_engine data */
1105 t->gcache.first_engine = first_engine;
1107 /* We do not want to remember any cached variables from the test run */
1108 t->InvalidateNewGRFCache();
1109 head->InvalidateNewGRFCache();
1111 if (callback != CALLBACK_FAILED) {
1112 /* A failing callback means everything is okay */
1113 StringID error = STR_NULL;
1115 if (head->GetGRF()->grf_version < 8) {
1116 if (callback == 0xFD) error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1117 if (callback < 0xFD) error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
1118 if (callback >= 0x100) ErrorUnknownCallbackResult(head->GetGRFID(), CBID_TRAIN_ALLOW_WAGON_ATTACH, callback);
1119 } else {
1120 if (callback < 0x400) {
1121 error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
1122 } else {
1123 switch (callback) {
1124 case 0x400: // allow if railtypes match (always the case for OpenTTD)
1125 case 0x401: // allow
1126 break;
1128 default: // unknown reason -> disallow
1129 case 0x402: // disallow attaching
1130 error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1131 break;
1136 if (error != STR_NULL) return CommandError(error);
1140 /* And link it to the new part. */
1141 prev->SetNext(t);
1142 prev = t;
1143 t = next;
1146 if (allowed_len < 0) return CommandError(STR_ERROR_TRAIN_TOO_LONG);
1147 return CommandCost();
1151 * Validate whether we are going to create valid trains.
1152 * @note All vehicles are/were 'heads' of their chains.
1153 * @param original_dst The original destination chain.
1154 * @param dst The destination chain after constructing the train.
1155 * @param original_dst The original source chain.
1156 * @param dst The source chain after constructing the train.
1157 * @param check_limit Whether to check the vehicle limit.
1158 * @return possible error of this command.
1160 static CommandCost ValidateTrains(Train *original_dst, Train *dst, Train *original_src, Train *src, bool check_limit)
1162 /* Check whether we may actually construct the trains. */
1163 CommandCost ret = CheckTrainAttachment(src);
1164 if (ret.Failed()) return ret;
1165 ret = CheckTrainAttachment(dst);
1166 if (ret.Failed()) return ret;
1168 /* Check whether we need to build a new train. */
1169 return check_limit ? CheckNewTrain(original_dst, dst, original_src, src) : CommandCost();
1173 * Arrange the trains in the wanted way.
1174 * @param dst_head The destination chain of the to be moved vehicle.
1175 * @param dst The destination for the to be moved vehicle.
1176 * @param src_head The source chain of the to be moved vehicle.
1177 * @param src The to be moved vehicle.
1178 * @param move_chain Whether to move all vehicles after src or not.
1180 static void ArrangeTrains(Train **dst_head, Train *dst, Train **src_head, Train *src, bool move_chain)
1182 /* First determine the front of the two resulting trains */
1183 if (*src_head == *dst_head) {
1184 /* If we aren't moving part(s) to a new train, we are just moving the
1185 * front back and there is not destination head. */
1186 *dst_head = nullptr;
1187 } else if (*dst_head == nullptr) {
1188 /* If we are moving to a new train the head of the move train would become
1189 * the head of the new vehicle. */
1190 *dst_head = src;
1193 if (src == *src_head) {
1194 /* If we are moving the front of a train then we are, in effect, creating
1195 * a new head for the train. Point to that. Unless we are moving the whole
1196 * train in which case there is not 'source' train anymore.
1197 * In case we are a multiheaded part we want the complete thing to come
1198 * with us, so src->GetNextUnit(), however... when we are e.g. a wagon
1199 * that is followed by a rear multihead we do not want to include that. */
1200 *src_head = move_chain ? nullptr :
1201 (src->IsMultiheaded() ? src->GetNextUnit() : src->GetNextVehicle());
1204 /* Now it's just simply removing the part that we are going to move from the
1205 * source train and *if* the destination is a not a new train add the chain
1206 * at the destination location. */
1207 RemoveFromConsist(src, move_chain);
1208 if (*dst_head != src) InsertInConsist(dst, src);
1210 /* Now normalise the dual heads, that is move the dual heads around in such
1211 * a way that the head and rear of a dual head are in the same train */
1212 NormaliseDualHeads(*src_head);
1213 NormaliseDualHeads(*dst_head);
1217 * Normalise the head of the train again, i.e. that is tell the world that
1218 * we have changed and update all kinds of variables.
1219 * @param head the train to update.
1221 static void NormaliseTrainHead(Train *head)
1223 /* Not much to do! */
1224 if (head == nullptr) return;
1226 /* Tell the 'world' the train changed. */
1227 head->ConsistChanged(CCF_ARRANGE);
1228 UpdateTrainGroupID(head);
1230 /* Not a front engine, i.e. a free wagon chain. No need to do more. */
1231 if (!head->IsFrontEngine()) return;
1233 /* Update the refit button and window */
1234 InvalidateWindowData(WC_VEHICLE_REFIT, head->index, VIWD_CONSIST_CHANGED);
1235 SetWindowWidgetDirty(WC_VEHICLE_VIEW, head->index, WID_VV_REFIT);
1237 /* If we don't have a unit number yet, set one. */
1238 if (head->unitnumber != 0) return;
1239 head->unitnumber = GetFreeUnitNumber(VEH_TRAIN);
1243 * Move a rail vehicle around inside the depot.
1244 * @param tile unused
1245 * @param flags type of operation
1246 * Note: DC_AUTOREPLACE is set when autoreplace tries to undo its modifications or moves vehicles to temporary locations inside the depot.
1247 * @param p1 various bitstuffed elements
1248 * - p1 (bit 0 - 19) source vehicle index
1249 * - p1 (bit 20) move all vehicles following the source vehicle
1250 * - p1 (bit 21) this is a virtual vehicle (for creating TemplateVehicles)
1251 * @param p2 what wagon to put the source wagon AFTER, XXX - INVALID_VEHICLE to make a new line
1252 * @param text unused
1253 * @return the cost of this operation or an error
1255 CommandCost CmdMoveRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1257 VehicleID s = GB(p1, 0, 20);
1258 VehicleID d = GB(p2, 0, 20);
1259 bool move_chain = HasBit(p1, 20);
1261 Train *src = Train::GetIfValid(s);
1262 if (src == nullptr) return CommandError();
1264 CommandCost ret = CheckOwnership(src->owner);
1265 if (ret.Failed()) return ret;
1267 /* Do not allow moving crashed vehicles inside the depot, it is likely to cause asserts later */
1268 if (src->vehstatus & VS_CRASHED) return CommandError();
1270 /* if nothing is selected as destination, try and find a matching vehicle to drag to. */
1271 Train *dst;
1272 if (d == INVALID_VEHICLE) {
1273 dst = src->IsEngine() ? nullptr : FindGoodVehiclePos(src);
1274 } else {
1275 dst = Train::GetIfValid(d);
1276 if (dst == nullptr) return CommandError();
1278 CommandCost ret = CheckOwnership(dst->owner);
1279 if (ret.Failed()) return ret;
1281 /* Do not allow appending to crashed vehicles, too */
1282 if (dst->vehstatus & VS_CRASHED) return CommandError();
1285 /* if an articulated part is being handled, deal with its parent vehicle */
1286 src = src->GetFirstEnginePart();
1287 if (dst != nullptr) {
1288 dst = dst->GetFirstEnginePart();
1289 assert(HasBit(dst->subtype, GVSF_VIRTUAL) == HasBit(src->subtype, GVSF_VIRTUAL));
1292 /* don't move the same vehicle.. */
1293 if (src == dst) return CommandCost();
1295 /* locate the head of the two chains */
1296 Train *src_head = src->First();
1297 assert(HasBit(src_head->subtype, GVSF_VIRTUAL) == HasBit(src->subtype, GVSF_VIRTUAL));
1298 Train *dst_head;
1299 if (dst != nullptr) {
1300 dst_head = dst->First();
1301 assert(HasBit(dst_head->subtype, GVSF_VIRTUAL) == HasBit(dst->subtype, GVSF_VIRTUAL));
1302 if (dst_head->tile != src_head->tile) return CommandError();
1303 /* Now deal with articulated part of destination wagon */
1304 dst = dst->GetLastEnginePart();
1305 } else {
1306 dst_head = nullptr;
1309 if (src->IsRearDualheaded()) return CommandError(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
1311 /* When moving all wagons, we can't have the same src_head and dst_head */
1312 if (move_chain && src_head == dst_head) return CommandCost();
1314 /* When moving a multiheaded part to be place after itself, bail out. */
1315 if (!move_chain && dst != nullptr && dst->IsRearDualheaded() && src == dst->other_multiheaded_part) return CommandCost();
1317 /* Check if all vehicles in the source train are stopped inside a depot. */
1318 /* Do this check only if the vehicle to be moved is non-virtual */
1319 if ( !HasBit(p1, 21) )
1320 if (!src_head->IsStoppedInDepot()) return CommandError(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1322 /* Check if all vehicles in the destination train are stopped inside a depot. */
1323 /* Do this check only if the destination vehicle is non-virtual */
1324 if ( !HasBit(p1, 21) )
1325 if (dst_head != nullptr && !dst_head->IsStoppedInDepot()) return CommandError(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1327 /* First make a backup of the order of the trains. That way we can do
1328 * whatever we want with the order and later on easily revert. */
1329 TrainList original_src;
1330 TrainList original_dst;
1332 MakeTrainBackup(original_src, src_head);
1333 MakeTrainBackup(original_dst, dst_head);
1335 /* Also make backup of the original heads as ArrangeTrains can change them.
1336 * For the destination head we do not care if it is the same as the source
1337 * head because in that case it's just a copy. */
1338 Train *original_src_head = src_head;
1339 Train *original_dst_head = (dst_head == src_head ? nullptr : dst_head);
1341 /* We want this information from before the rearrangement, but execute this after the validation.
1342 * original_src_head can't be nullptr; src is by definition != nullptr, so src_head can't be nullptr as
1343 * src->GetFirst() always yields non-nullptr, so eventually original_src_head != nullptr as well. */
1344 bool original_src_head_front_engine = original_src_head->IsFrontEngine();
1345 bool original_dst_head_front_engine = original_dst_head != nullptr && original_dst_head->IsFrontEngine();
1347 /* (Re)arrange the trains in the wanted arrangement. */
1348 ArrangeTrains(&dst_head, dst, &src_head, src, move_chain);
1350 if ((flags & DC_AUTOREPLACE) == 0) {
1351 /* If the autoreplace flag is set we do not need to test for the validity
1352 * because we are going to revert the train to its original state. As we
1353 * assume the original state was correct autoreplace can skip this. */
1354 CommandCost ret = ValidateTrains(original_dst_head, dst_head, original_src_head, src_head, true);
1355 if (ret.Failed()) {
1356 /* Restore the train we had. */
1357 RestoreTrainBackup(original_src);
1358 RestoreTrainBackup(original_dst);
1359 return ret;
1363 /* do it? */
1364 if (flags & DC_EXEC) {
1365 /* Remove old heads from the statistics */
1366 if (original_src_head_front_engine) GroupStatistics::CountVehicle(original_src_head, -1);
1367 if (original_dst_head_front_engine) GroupStatistics::CountVehicle(original_dst_head, -1);
1369 /* First normalise the sub types of the chains. */
1370 NormaliseSubtypes(src_head);
1371 NormaliseSubtypes(dst_head);
1373 /* There are 14 different cases:
1374 * 1) front engine gets moved to a new train, it stays a front engine.
1375 * a) the 'next' part is a wagon that becomes a free wagon chain.
1376 * b) the 'next' part is an engine that becomes a front engine.
1377 * c) there is no 'next' part, nothing else happens
1378 * 2) front engine gets moved to another train, it is not a front engine anymore
1379 * a) the 'next' part is a wagon that becomes a free wagon chain.
1380 * b) the 'next' part is an engine that becomes a front engine.
1381 * c) there is no 'next' part, nothing else happens
1382 * 3) front engine gets moved to later in the current train, it is not a front engine anymore.
1383 * a) the 'next' part is a wagon that becomes a free wagon chain.
1384 * b) the 'next' part is an engine that becomes a front engine.
1385 * 4) free wagon gets moved
1386 * a) the 'next' part is a wagon that becomes a free wagon chain.
1387 * b) the 'next' part is an engine that becomes a front engine.
1388 * c) there is no 'next' part, nothing else happens
1389 * 5) non front engine gets moved and becomes a new train, nothing else happens
1390 * 6) non front engine gets moved within a train / to another train, nothing hapens
1391 * 7) wagon gets moved, nothing happens
1393 if (src == original_src_head && src->IsEngine() && !src->IsFrontEngine()) {
1394 /* Cases #2 and #3: the front engine gets trashed. */
1395 DeleteWindowById(WC_VEHICLE_VIEW, src->index);
1396 DeleteWindowById(WC_VEHICLE_ORDERS, src->index);
1397 DeleteWindowById(WC_VEHICLE_REFIT, src->index);
1398 DeleteWindowById(WC_VEHICLE_DETAILS, src->index);
1399 DeleteWindowById(WC_VEHICLE_TIMETABLE, src->index);
1400 DeleteNewGRFInspectWindow(GSF_TRAINS, src->index);
1401 SetWindowDirty(WC_COMPANY, _current_company);
1403 /* Delete orders, group stuff and the unit number as we're not the
1404 * front of any vehicle anymore. */
1405 src->DeleteVehicleOrders();
1406 RemoveVehicleFromGroup(src);
1407 src->unitnumber = 0;
1408 if (HasBit(src->flags, VRF_HAVE_SLOT)) {
1409 TraceRestrictRemoveVehicleFromAllSlots(src->index);
1410 ClrBit(src->flags, VRF_HAVE_SLOT);
1414 /* We weren't a front engine but are becoming one. So
1415 * we should be put in the default group. */
1416 if (original_src_head != src && dst_head == src) {
1417 SetTrainGroupID(src, DEFAULT_GROUP);
1418 SetWindowDirty(WC_COMPANY, _current_company);
1421 /* Add new heads to statistics */
1422 if (src_head != nullptr && src_head->IsFrontEngine()) GroupStatistics::CountVehicle(src_head, 1);
1423 if (dst_head != nullptr && dst_head->IsFrontEngine()) GroupStatistics::CountVehicle(dst_head, 1);
1425 /* Handle 'new engine' part of cases #1b, #2b, #3b, #4b and #5 in NormaliseTrainHead. */
1426 NormaliseTrainHead(src_head);
1427 NormaliseTrainHead(dst_head);
1429 if ((flags & DC_NO_CARGO_CAP_CHECK) == 0) {
1430 CheckCargoCapacity(src_head);
1431 CheckCargoCapacity(dst_head);
1434 if (src_head != nullptr) {
1435 src_head->last_loading_station = INVALID_STATION;
1436 ClrBit(src_head->vehicle_flags, VF_LAST_LOAD_ST_SEP);
1438 if (dst_head != nullptr) {
1439 dst_head->last_loading_station = INVALID_STATION;
1440 ClrBit(dst_head->vehicle_flags, VF_LAST_LOAD_ST_SEP);
1443 if (src_head != nullptr) src_head->First()->MarkDirty();
1444 if (dst_head != nullptr) dst_head->First()->MarkDirty();
1446 /* We are undoubtedly changing something in the depot and train list. */
1447 /* But only if the moved vehicle is not virtual */
1448 if ( !HasBit(src->subtype, GVSF_VIRTUAL) ) {
1449 InvalidateWindowData(WC_VEHICLE_DEPOT, src->tile);
1450 InvalidateWindowClassesData(WC_TRAINS_LIST);
1451 InvalidateWindowClassesData(WC_TRACE_RESTRICT_SLOTS);
1452 } else {
1453 InvalidateWindowClassesData(WC_CREATE_TEMPLATE);
1455 } else {
1456 /* We don't want to execute what we're just tried. */
1457 RestoreTrainBackup(original_src);
1458 RestoreTrainBackup(original_dst);
1461 return CommandCost();
1465 * Sell a (single) train wagon/engine.
1466 * @param flags type of operation
1467 * @param t the train wagon to sell
1468 * @param data the selling mode
1469 * - data = 0: only sell the single dragged wagon/engine (and any belonging rear-engines)
1470 * - data = 1: sell the vehicle and all vehicles following it in the chain
1471 * if the wagon is dragged, don't delete the possibly belonging rear-engine to some front
1472 * @param user the user for the order backup.
1473 * @return the cost of this operation or an error
1475 CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *t, uint16 data, uint32 user)
1477 /* Sell a chain of vehicles or not? */
1478 bool sell_chain = HasBit(data, 0);
1480 Train *v = Train::From(t)->GetFirstEnginePart();
1481 Train *first = v->First();
1483 if (v->IsRearDualheaded()) return CommandError(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
1485 /* First make a backup of the order of the train. That way we can do
1486 * whatever we want with the order and later on easily revert. */
1487 TrainList original;
1488 MakeTrainBackup(original, first);
1490 /* We need to keep track of the new head and the head of what we're going to sell. */
1491 Train *new_head = first;
1492 Train *sell_head = nullptr;
1494 /* Split the train in the wanted way. */
1495 ArrangeTrains(&sell_head, nullptr, &new_head, v, sell_chain);
1497 /* We don't need to validate the second train; it's going to be sold. */
1498 CommandCost ret = ValidateTrains(nullptr, nullptr, first, new_head, (flags & DC_AUTOREPLACE) == 0);
1499 if (ret.Failed()) {
1500 /* Restore the train we had. */
1501 RestoreTrainBackup(original);
1502 return ret;
1505 if (!first->HasOrdersList() && !OrderList::CanAllocateItem()) {
1506 /* Restore the train we had. */
1507 RestoreTrainBackup(original);
1508 return CommandError(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
1511 CommandCost cost(EXPENSES_NEW_VEHICLES);
1512 for (Train *t = sell_head; t != nullptr; t = t->Next()) cost.AddCost(-t->value);
1514 /* do it? */
1515 if (flags & DC_EXEC) {
1516 /* First normalise the sub types of the chain. */
1517 NormaliseSubtypes(new_head);
1519 if (v == first && v->IsEngine() && !sell_chain && new_head != nullptr && new_head->IsFrontEngine()) {
1520 /* We are selling the front engine. In this case we want to
1521 * 'give' the order, unit number and such to the new head. */
1522 new_head->ShareOrdersWith(first);
1523 new_head->AddToShared(first);
1524 first->DeleteVehicleOrders();
1526 /* Copy other important data from the front engine */
1527 new_head->CopyVehicleConfigAndStatistics(first);
1528 GroupStatistics::CountVehicle(new_head, 1); // after copying over the profit
1529 } else if (v->IsPrimaryVehicle() && data & (MAKE_ORDER_BACKUP_FLAG >> 20)) {
1530 OrderBackup::Backup(v, user);
1533 /* We need to update the information about the train. */
1534 NormaliseTrainHead(new_head);
1536 /* We are undoubtedly changing something in the depot and train list. */
1537 /* Unless its a virtual train */
1538 if ( !HasBit(v->subtype, GVSF_VIRTUAL) ) {
1539 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1540 InvalidateWindowClassesData(WC_TRAINS_LIST);
1541 InvalidateWindowClassesData(WC_TRACE_RESTRICT_SLOTS);
1542 } else {
1543 InvalidateWindowClassesData(WC_CREATE_TEMPLATE);
1546 /* Actually delete the sold 'goods' */
1547 delete sell_head;
1548 } else {
1549 /* We don't want to execute what we're just tried. */
1550 RestoreTrainBackup(original);
1553 return cost;
1556 void Train::UpdateDeltaXY(Direction direction)
1558 /* Set common defaults. */
1559 this->x_offs = -1;
1560 this->y_offs = -1;
1561 this->x_extent = 3;
1562 this->y_extent = 3;
1563 this->z_extent = 6;
1564 this->x_bb_offs = 0;
1565 this->y_bb_offs = 0;
1567 if (!IsDiagonalDirection(direction)) {
1568 static const int _sign_table[] =
1570 /* x, y */
1571 -1, -1, // DIR_N
1572 -1, 1, // DIR_E
1573 1, 1, // DIR_S
1574 1, -1, // DIR_W
1577 int half_shorten = (VEHICLE_LENGTH - this->gcache.cached_veh_length) / 2;
1579 /* For all straight directions, move the bound box to the centre of the vehicle, but keep the size. */
1580 this->x_offs -= half_shorten * _sign_table[direction];
1581 this->y_offs -= half_shorten * _sign_table[direction + 1];
1582 this->x_extent += this->x_bb_offs = half_shorten * _sign_table[direction];
1583 this->y_extent += this->y_bb_offs = half_shorten * _sign_table[direction + 1];
1584 } else {
1585 switch (direction) {
1586 /* Shorten southern corner of the bounding box according the vehicle length
1587 * and center the bounding box on the vehicle. */
1588 case DIR_NE:
1589 this->x_offs = 1 - (this->gcache.cached_veh_length + 1) / 2;
1590 this->x_extent = this->gcache.cached_veh_length - 1;
1591 this->x_bb_offs = -1;
1592 break;
1594 case DIR_NW:
1595 this->y_offs = 1 - (this->gcache.cached_veh_length + 1) / 2;
1596 this->y_extent = this->gcache.cached_veh_length - 1;
1597 this->y_bb_offs = -1;
1598 break;
1600 /* Move northern corner of the bounding box down according to vehicle length
1601 * and center the bounding box on the vehicle. */
1602 case DIR_SW:
1603 this->x_offs = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH;
1604 this->x_extent = VEHICLE_LENGTH - 1;
1605 this->x_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
1606 break;
1608 case DIR_SE:
1609 this->y_offs = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH;
1610 this->y_extent = VEHICLE_LENGTH - 1;
1611 this->y_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
1612 break;
1614 default:
1615 NOT_REACHED();
1621 * Mark a train as stuck and stop it if it isn't stopped right now.
1622 * @param v %Train to mark as being stuck.
1624 static void MarkTrainAsStuck(Train *v, bool waiting_restriction = false)
1626 if (!HasBit(v->flags, VRF_TRAIN_STUCK)) {
1627 /* It is the first time the problem occurred, set the "train stuck" flag. */
1628 SetBit(v->flags, VRF_TRAIN_STUCK);
1629 SB(v->flags, VRF_WAITING_RESTRICTION, 1, waiting_restriction ? 1 : 0);
1631 v->wait_counter = 0;
1633 /* Stop train */
1634 v->cur_speed = 0;
1635 v->subspeed = 0;
1636 v->SetLastSpeed();
1638 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
1639 } else if (waiting_restriction != HasBit(v->flags, VRF_WAITING_RESTRICTION)) {
1640 ToggleBit(v->flags, VRF_WAITING_RESTRICTION);
1641 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
1646 * Swap the two up/down flags in two ways:
1647 * - Swap values of \a swap_flag1 and \a swap_flag2, and
1648 * - If going up previously (#GVF_GOINGUP_BIT set), the #GVF_GOINGDOWN_BIT is set, and vice versa.
1649 * @param swap_flag1 [inout] First train flag.
1650 * @param swap_flag2 [inout] Second train flag.
1652 static void SwapTrainFlags(uint16 *swap_flag1, uint16 *swap_flag2)
1654 uint16 flag1 = *swap_flag1;
1655 uint16 flag2 = *swap_flag2;
1657 /* Clear the flags */
1658 ClrBit(*swap_flag1, GVF_GOINGUP_BIT);
1659 ClrBit(*swap_flag1, GVF_GOINGDOWN_BIT);
1660 ClrBit(*swap_flag1, GVF_CHUNNEL_BIT);
1661 ClrBit(*swap_flag2, GVF_GOINGUP_BIT);
1662 ClrBit(*swap_flag2, GVF_GOINGDOWN_BIT);
1663 ClrBit(*swap_flag2, GVF_CHUNNEL_BIT);
1665 /* Reverse the rail-flags (if needed) */
1666 if (HasBit(flag1, GVF_GOINGUP_BIT)) {
1667 SetBit(*swap_flag2, GVF_GOINGDOWN_BIT);
1668 } else if (HasBit(flag1, GVF_GOINGDOWN_BIT)) {
1669 SetBit(*swap_flag2, GVF_GOINGUP_BIT);
1672 if (HasBit(flag2, GVF_GOINGUP_BIT)) {
1673 SetBit(*swap_flag1, GVF_GOINGDOWN_BIT);
1674 } else if (HasBit(flag2, GVF_GOINGDOWN_BIT)) {
1675 SetBit(*swap_flag1, GVF_GOINGUP_BIT);
1678 if (HasBit(flag1, GVF_CHUNNEL_BIT)) {
1679 SetBit(*swap_flag2, GVF_CHUNNEL_BIT);
1682 if (HasBit(flag2, GVF_CHUNNEL_BIT)) {
1683 SetBit(*swap_flag1, GVF_CHUNNEL_BIT);
1688 * Updates some variables after swapping the vehicle.
1689 * @param v swapped vehicle
1691 static void UpdateStatusAfterSwap(Train *v)
1693 /* Reverse the direction. */
1694 if (v->track != TRACK_BIT_DEPOT) v->direction = ReverseDir(v->direction);
1696 /* Call the proper EnterTile function unless we are in a wormhole. */
1697 if (v->track != TRACK_BIT_WORMHOLE) {
1698 VehicleEnterTile(v, v->tile, v->x_pos, v->y_pos);
1699 } else {
1700 /* VehicleEnter_TunnelBridge() sets TRACK_BIT_WORMHOLE when the vehicle
1701 * is on the last bit of the bridge head (frame == TILE_SIZE - 1).
1702 * If we were swapped with such a vehicle, we have set TRACK_BIT_WORMHOLE,
1703 * when we shouldn't have. Check if this is the case. */
1704 TileIndex vt = TileVirtXY(v->x_pos, v->y_pos);
1705 if (IsTileType(vt, MP_TUNNELBRIDGE)) {
1706 VehicleEnterTile(v, vt, v->x_pos, v->y_pos);
1707 if (v->track != TRACK_BIT_WORMHOLE && IsBridgeTile(v->tile)) {
1708 /* We have just left the wormhole, possibly set the
1709 * "goingdown" bit. UpdateInclination() can be used
1710 * because we are at the border of the tile. */
1711 v->UpdatePosition();
1712 v->UpdateInclination(true, true);
1713 return;
1718 v->UpdatePosition();
1719 if (v->track == TRACK_BIT_WORMHOLE) v->UpdateInclination(false, false, true);
1720 v->UpdateViewport(true, true);
1724 * Swap vehicles \a l and \a r in consist \a v, and reverse their direction.
1725 * @param v Consist to change.
1726 * @param l %Vehicle index in the consist of the first vehicle.
1727 * @param r %Vehicle index in the consist of the second vehicle.
1729 void ReverseTrainSwapVeh(Train *v, int l, int r)
1731 Train *a, *b;
1733 /* locate vehicles to swap */
1734 for (a = v; l != 0; l--) a = a->Next();
1735 for (b = v; r != 0; r--) b = b->Next();
1737 if (a != b) {
1738 /* swap the hidden bits */
1740 uint16 tmp = (a->vehstatus & ~VS_HIDDEN) | (b->vehstatus & VS_HIDDEN);
1741 b->vehstatus = (b->vehstatus & ~VS_HIDDEN) | (a->vehstatus & VS_HIDDEN);
1742 a->vehstatus = tmp;
1745 Swap(a->track, b->track);
1746 Swap(a->direction, b->direction);
1747 Swap(a->x_pos, b->x_pos);
1748 Swap(a->y_pos, b->y_pos);
1749 Swap(a->tile, b->tile);
1750 Swap(a->z_pos, b->z_pos);
1752 SwapTrainFlags(&a->gv_flags, &b->gv_flags);
1754 UpdateStatusAfterSwap(a);
1755 UpdateStatusAfterSwap(b);
1756 } else {
1757 /* Swap GVF_GOINGUP_BIT/GVF_GOINGDOWN_BIT.
1758 * This is a little bit redundant way, a->gv_flags will
1759 * be (re)set twice, but it reduces code duplication */
1760 SwapTrainFlags(&a->gv_flags, &a->gv_flags);
1761 UpdateStatusAfterSwap(a);
1767 * Check if the vehicle is a train
1768 * @param v vehicle on tile
1769 * @return v if it is a train, nullptr otherwise
1771 static Vehicle *TrainOnTileEnum(Vehicle *v, void *)
1773 return (v->type == VEH_TRAIN) ? v : nullptr;
1778 * Checks if a train is approaching a rail-road crossing
1779 * @param v vehicle on tile
1780 * @param data tile with crossing we are testing
1781 * @return v if it is approaching a crossing, nullptr otherwise
1783 static Vehicle *TrainApproachingCrossingEnum(Vehicle *v, void *data)
1785 if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return nullptr;
1787 Train *t = Train::From(v);
1788 if (!t->IsFrontEngine()) return nullptr;
1790 TileIndex tile = *(TileIndex *)data;
1792 if (TrainApproachingCrossingTile(t) != tile) return nullptr;
1794 return t;
1799 * Finds a vehicle approaching rail-road crossing
1800 * @param tile tile to test
1801 * @return true if a vehicle is approaching the crossing
1802 * @pre tile is a rail-road crossing
1804 static bool TrainApproachingCrossing(TileIndex tile)
1806 assert(IsLevelCrossingTile(tile));
1808 DiagDirection dir = AxisToDiagDir(GetCrossingRailAxis(tile));
1809 TileIndex tile_from = tile + TileOffsByDiagDir(dir);
1811 if (HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum)) return true;
1813 dir = ReverseDiagDir(dir);
1814 tile_from = tile + TileOffsByDiagDir(dir);
1816 return HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum);
1819 /** Check if the crossing should be closed
1820 * @return train on crossing || train approaching crossing || reserved
1822 static inline bool CheckLevelCrossing(TileIndex tile)
1824 return HasCrossingReservation(tile) || HasVehicleOnPos(tile, nullptr, &TrainOnTileEnum) || TrainApproachingCrossing(tile);
1828 * Sets correct crossing state
1829 * @param tile tile to update
1830 * @param sound should we play sound?
1831 * @param is_forced force set the crossing state to that of forced_state
1832 * @param forced_state the crossing state to set when using is_forced
1833 * @pre tile is a rail-road crossing
1835 static void UpdateLevelCrossingTile(TileIndex tile, bool sound, bool is_forced, bool forced_state)
1837 assert(IsLevelCrossingTile(tile));
1839 // Ignore level crossings for types where it doesn't matter.
1840 RailTypeLabel railTypeLabel = GetRailTypeInfo(GetTileRailType(tile))->label;
1842 if (railTypeLabel == _planning_tracks_label ||
1843 railTypeLabel == _pipeline_tracks_label ||
1844 railTypeLabel == _wires_tracks_label) {
1846 if (IsCrossingBarred(tile)) {
1847 MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
1850 SetCrossingBarred(tile, false);
1851 return;
1854 bool new_state;
1856 if (is_forced) {
1857 new_state = forced_state;
1858 } else {
1859 new_state = CheckLevelCrossing(tile);
1862 if (new_state != IsCrossingBarred(tile)) {
1863 if (new_state && sound) {
1865 if (_settings_client.sound.ambient) {
1866 SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
1869 SetCrossingBarred(tile, new_state);
1870 MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
1875 * Cycles the adjacent crossings and sets their state
1876 * @param tile tile to update
1877 * @param sound should we play sound?
1878 * @param force_close force close the crossing
1880 void UpdateLevelCrossing(TileIndex tile, bool sound, bool force_close)
1882 bool forced_state = force_close;
1883 if (!IsLevelCrossingTile(tile)) return;
1885 const Axis axis = GetCrossingRoadAxis(tile);
1886 const DiagDirection dir = AxisToDiagDir(axis);
1887 const DiagDirection reverse_dir = ReverseDiagDir(dir);
1889 for (TileIndex t = tile; !forced_state && IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == axis; t = TileAddByDiagDir(t, dir)) {
1890 forced_state |= CheckLevelCrossing(t);
1892 for (TileIndex t = TileAddByDiagDir(tile, reverse_dir); !forced_state && IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == axis; t = TileAddByDiagDir(t, reverse_dir)) {
1893 forced_state |= CheckLevelCrossing(t);
1896 UpdateLevelCrossingTile(tile, sound, force_close, forced_state);
1897 for (TileIndex t = TileAddByDiagDir(tile, dir); IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == axis; t = TileAddByDiagDir(t, dir)) {
1898 UpdateLevelCrossingTile(t, sound, true, forced_state);
1900 for (TileIndex t = TileAddByDiagDir(tile, reverse_dir); IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == axis; t = TileAddByDiagDir(t, reverse_dir)) {
1901 UpdateLevelCrossingTile(t, sound, true, forced_state);
1907 * Bars crossing and plays ding-ding sound if not barred already
1908 * @param tile tile with crossing
1909 * @pre tile is a rail-road crossing
1911 static inline void MaybeBarCrossingWithSound(TileIndex tile)
1913 if (!IsCrossingBarred(tile)) {
1914 UpdateLevelCrossing(tile, true, true);
1920 * Advances wagons for train reversing, needed for variable length wagons.
1921 * This one is called before the train is reversed.
1922 * @param v First vehicle in chain
1924 static void AdvanceWagonsBeforeSwap(Train *v)
1926 Train *base = v;
1927 Train *first = base; // first vehicle to move
1928 Train *last = v->Last(); // last vehicle to move
1929 uint length = CountVehiclesInChain(v);
1931 while (length > 2) {
1932 last = last->Previous();
1933 first = first->Next();
1935 int differential = base->CalcNextVehicleOffset() - last->CalcNextVehicleOffset();
1937 /* do not update images now
1938 * negative differential will be handled in AdvanceWagonsAfterSwap() */
1939 for (int i = 0; i < differential; i++) TrainController(first, last->Next());
1941 base = first; // == base->Next()
1942 length -= 2;
1948 * Advances wagons for train reversing, needed for variable length wagons.
1949 * This one is called after the train is reversed.
1950 * @param v First vehicle in chain
1952 static void AdvanceWagonsAfterSwap(Train *v)
1954 /* first of all, fix the situation when the train was entering a depot */
1955 Train *dep = v; // last vehicle in front of just left depot
1956 while (dep->Next() != nullptr && (dep->track == TRACK_BIT_DEPOT || dep->Next()->track != TRACK_BIT_DEPOT)) {
1957 dep = dep->Next(); // find first vehicle outside of a depot, with next vehicle inside a depot
1960 Train *leave = dep->Next(); // first vehicle in a depot we are leaving now
1962 if (leave != nullptr) {
1963 /* 'pull' next wagon out of the depot, so we won't miss it (it could stay in depot forever) */
1964 int d = TicksToLeaveDepot(dep);
1966 if (d <= 0) {
1967 leave->vehstatus &= ~VS_HIDDEN; // move it out of the depot
1968 leave->track = TrackToTrackBits(GetRailDepotTrack(leave->tile));
1969 for (int i = 0; i >= d; i--) TrainController(leave, nullptr); // maybe move it, and maybe let another wagon leave
1971 } else {
1972 dep = nullptr; // no vehicle in a depot, so no vehicle leaving a depot
1975 Train *base = v;
1976 Train *first = base; // first vehicle to move
1977 Train *last = v->Last(); // last vehicle to move
1978 uint length = CountVehiclesInChain(v);
1980 /* We have to make sure all wagons that leave a depot because of train reversing are moved correctly
1981 * they have already correct spacing, so we have to make sure they are moved how they should */
1982 bool nomove = (dep == nullptr); // If there is no vehicle leaving a depot, limit the number of wagons moved immediately.
1984 while (length > 2) {
1985 /* we reached vehicle (originally) in front of a depot, stop now
1986 * (we would move wagons that are already moved with new wagon length). */
1987 if (base == dep) break;
1989 /* the last wagon was that one leaving a depot, so do not move it anymore */
1990 if (last == dep) nomove = true;
1992 last = last->Previous();
1993 first = first->Next();
1995 int differential = last->CalcNextVehicleOffset() - base->CalcNextVehicleOffset();
1997 /* do not update images now */
1998 for (int i = 0; i < differential; i++) TrainController(first, (nomove ? last->Next() : nullptr));
2000 base = first; // == base->Next()
2001 length -= 2;
2006 * Turn a train around.
2007 * @param v %Train to turn around.
2009 void ReverseTrainDirection(Train *v)
2011 if (IsRailDepotTile(v->tile)) {
2012 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
2015 v->reverse_distance = 0;
2017 /* Clear path reservation in front if train is not stuck. */
2018 if (!HasBit(v->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(v);
2020 /* Check if we were approaching a rail/road-crossing */
2021 TileIndex crossing = TrainApproachingCrossingTile(v);
2023 /* count number of vehicles */
2024 int r = CountVehiclesInChain(v) - 1; // number of vehicles - 1
2026 AdvanceWagonsBeforeSwap(v);
2028 /* swap start<>end, start+1<>end-1, ... */
2029 int l = 0;
2030 do {
2031 ReverseTrainSwapVeh(v, l++, r--);
2032 } while (l <= r);
2034 AdvanceWagonsAfterSwap(v);
2036 if (IsRailDepotTile(v->tile)) {
2037 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
2040 ToggleBit(v->flags, VRF_TOGGLE_REVERSE);
2042 ClrBit(v->flags, VRF_REVERSING);
2044 /* recalculate cached data */
2045 v->ConsistChanged(CCF_TRACK);
2047 /* update all images */
2048 for (Train *u = v; u != nullptr; u = u->Next()) u->UpdateViewport(false, false);
2050 /* update crossing we were approaching */
2051 if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
2053 /* maybe we are approaching crossing now, after reversal */
2054 crossing = TrainApproachingCrossingTile(v);
2055 if (crossing != INVALID_TILE) MaybeBarCrossingWithSound(crossing);
2057 /* If we are inside a depot after reversing, don't bother with path reserving. */
2058 if (v->track == TRACK_BIT_DEPOT) {
2059 /* Can't be stuck here as inside a depot is always a safe tile. */
2060 if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2061 ClrBit(v->flags, VRF_TRAIN_STUCK);
2062 return;
2065 /* We are inside tunnel/bidge with signals, reversing will close the entrance. */
2066 if (IsTunnelBridgeWithSignalSimulation(v->tile)) {
2067 /* Flip signal on tunnel entrance tile red. */
2068 SetTunnelBridgeSignalState(v->tile, SIGNAL_STATE_RED);
2069 MarkTileDirtyByTile(v->tile);
2070 /* Clear counters. */
2071 v->wait_counter = 0;
2072 v->tunnel_bridge_signal_num = 0;
2073 return;
2076 /* TrainExitDir does not always produce the desired dir for depots and
2077 * tunnels/bridges that is needed for UpdateSignalsOnSegment. */
2078 DiagDirection dir = TrainExitDir(v->direction, v->track);
2079 if (IsRailDepotTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE)) dir = INVALID_DIAGDIR;
2081 if (UpdateSignalsOnSegment(v->tile, dir, v->owner) == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
2082 /* If we are currently on a tile with conventional signals, we can't treat the
2083 * current tile as a safe tile or we would enter a PBS block without a reservation. */
2084 bool first_tile_okay = !(IsTileType(v->tile, MP_RAILWAY) &&
2085 HasSignalOnTrackdir(v->tile, v->GetVehicleTrackdir()) &&
2086 !IsPbsSignal(GetSignalType(v->tile, FindFirstTrack(v->track))));
2088 /* If we are on a depot tile facing outwards, do not treat the current tile as safe. */
2089 if (IsRailDepotTile(v->tile) && TrackdirToExitdir(v->GetVehicleTrackdir()) == GetRailDepotDirection(v->tile)) first_tile_okay = false;
2091 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
2092 if (TryPathReserve(v, false, first_tile_okay)) {
2093 /* Do a look-ahead now in case our current tile was already a safe tile. */
2094 CheckNextTrainTile(v);
2095 } else if (v->current_order.GetType() != OT_LOADING) {
2096 /* Do not wait for a way out when we're still loading */
2097 MarkTrainAsStuck(v);
2099 } else if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
2100 /* A train not inside a PBS block can't be stuck. */
2101 ClrBit(v->flags, VRF_TRAIN_STUCK);
2102 v->wait_counter = 0;
2107 * Reverse train.
2108 * @param tile unused
2109 * @param flags type of operation
2110 * @param p1 train to reverse
2111 * @param p2 if true, reverse a unit in a train (needs to be in a depot)
2112 * @param text unused
2113 * @return the cost of this operation or an error
2115 CommandCost CmdReverseTrainDirection(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2117 Train *v = Train::GetIfValid(p1);
2118 if (v == nullptr) return CommandError();
2120 CommandCost ret = CheckOwnership(v->owner);
2121 if (ret.Failed()) return ret;
2123 if (p2 != 0) {
2124 /* turn a single unit around */
2126 if (v->IsMultiheaded() || HasBit(EngInfo(v->engine_type)->callback_mask, CBM_VEHICLE_ARTIC_ENGINE)) {
2127 return CommandError(STR_ERROR_CAN_T_REVERSE_DIRECTION_RAIL_VEHICLE_MULTIPLE_UNITS);
2129 if (!HasBit(EngInfo(v->engine_type)->misc_flags, EF_RAIL_FLIPS)) return CommandError();
2131 Train *front = v->First();
2132 /* make sure the vehicle is stopped in the depot */
2133 if (!front->IsStoppedInDepot()) {
2134 return CommandError(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
2137 if (flags & DC_EXEC) {
2138 ToggleBit(v->flags, VRF_REVERSE_DIRECTION);
2140 front->ConsistChanged(CCF_ARRANGE);
2141 SetWindowDirty(WC_VEHICLE_DEPOT, front->tile);
2142 SetWindowDirty(WC_VEHICLE_DETAILS, front->index);
2143 SetWindowDirty(WC_VEHICLE_VIEW, front->index);
2144 SetWindowClassesDirty(WC_TRAINS_LIST);
2145 SetWindowClassesDirty(WC_TRACE_RESTRICT_SLOTS);
2147 } else {
2148 /* turn the whole train around */
2149 if ((v->vehstatus & VS_CRASHED) || v->breakdown_ctr != 0) return CommandError();
2151 if (flags & DC_EXEC) {
2152 /* Properly leave the station if we are loading and won't be loading anymore */
2153 if (v->current_order.IsType(OT_LOADING)) {
2154 const Vehicle *last = v;
2155 while (last->Next() != nullptr) last = last->Next();
2157 /* not a station || different station --> leave the station */
2158 if (!IsTileType(last->tile, MP_STATION) || GetStationIndex(last->tile) != GetStationIndex(v->tile)) {
2159 v->LeaveStation();
2163 /* We cancel any 'skip signal at dangers' here */
2164 v->force_proceed = TFP_NONE;
2165 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
2167 if (_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL && v->cur_speed != 0) {
2168 ToggleBit(v->flags, VRF_REVERSING);
2169 } else {
2170 v->cur_speed = 0;
2171 v->SetLastSpeed();
2172 HideFillingPercent(&v->fill_percent_te_id);
2173 ReverseTrainDirection(v);
2177 return CommandCost();
2181 * Force a train through a red signal
2182 * @param tile unused
2183 * @param flags type of operation
2184 * @param p1 train to ignore the red signal
2185 * @param p2 unused
2186 * @param text unused
2187 * @return the cost of this operation or an error
2189 CommandCost CmdForceTrainProceed(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2191 Train *t = Train::GetIfValid(p1);
2192 if (t == nullptr) return CommandError();
2194 if (!t->IsPrimaryVehicle()) return CommandError();
2196 CommandCost ret = CheckOwnership(t->owner);
2197 if (ret.Failed()) return ret;
2200 if (flags & DC_EXEC) {
2201 /* If we are forced to proceed, cancel that order.
2202 * If we are marked stuck we would want to force the train
2203 * to proceed to the next signal. In the other cases we
2204 * would like to pass the signal at danger and run till the
2205 * next signal we encounter. */
2206 t->force_proceed = t->force_proceed == TFP_SIGNAL ? TFP_NONE : HasBit(t->flags, VRF_TRAIN_STUCK) || t->IsChainInDepot() ? TFP_STUCK : TFP_SIGNAL;
2207 SetWindowDirty(WC_VEHICLE_VIEW, t->index);
2210 return CommandCost();
2214 * Try to find a depot nearby.
2215 * @param v %Train that wants a depot.
2216 * @param max_distance Maximal search distance.
2217 * @return Information where the closest train depot is located.
2218 * @pre The given vehicle must not be crashed!
2220 static FindDepotData FindClosestTrainDepot(Train *v, int max_distance)
2222 assert(!(v->vehstatus & VS_CRASHED));
2224 if (IsRailDepotTile(v->tile)) return FindDepotData(v->tile, 0);
2226 PBSTileInfo origin = FollowTrainReservation(v);
2227 if (IsRailDepotTile(origin.tile)) return FindDepotData(origin.tile, 0);
2229 switch (_settings_game.pf.pathfinder_for_trains) {
2230 case VPF_NPF: return NPFTrainFindNearestDepot(v, max_distance);
2231 case VPF_YAPF: return YapfTrainFindNearestDepot(v, max_distance);
2233 default: NOT_REACHED();
2238 * Locate the closest depot for this consist, and return the information to the caller.
2239 * @param location [out] If not \c nullptr and a depot is found, store its location in the given address.
2240 * @param destination [out] If not \c nullptr and a depot is found, store its index in the given address.
2241 * @param reverse [out] If not \c nullptr and a depot is found, store reversal information in the given address.
2242 * @return A depot has been found.
2244 bool Train::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
2246 FindDepotData tfdd = FindClosestTrainDepot(this, 0);
2247 if (tfdd.best_length == UINT_MAX) return false;
2249 if (location != nullptr) *location = tfdd.tile;
2250 if (destination != nullptr) *destination = GetDepotIndex(tfdd.tile);
2251 if (reverse != nullptr) *reverse = tfdd.reverse;
2253 return true;
2256 /** Play a sound for a train leaving the station. */
2257 void Train::PlayLeaveStationSound() const
2259 static const SoundFx sfx[] = {
2260 SND_04_TRAIN,
2261 SND_0A_TRAIN_HORN,
2262 SND_0A_TRAIN_HORN,
2263 SND_47_MAGLEV_2,
2264 SND_41_MAGLEV
2267 if (PlayVehicleSound(this, VSE_START)) return;
2269 EngineID engtype = this->engine_type;
2270 SndPlayVehicleFx(sfx[RailVehInfo(engtype)->engclass], this);
2274 * Check if the train is on the last reserved tile and try to extend the path then.
2275 * @param v %Train that needs its path extended.
2277 static void CheckNextTrainTile(Train *v)
2279 /* Don't do any look-ahead if path_backoff_interval is 255. */
2280 if (_settings_game.pf.path_backoff_interval == 255) return;
2282 /* Exit if we are inside a depot. */
2283 if (v->track == TRACK_BIT_DEPOT) return;
2285 switch (v->current_order.GetType()) {
2286 /* Exit if we reached our destination depot. */
2287 case OT_GOTO_DEPOT:
2288 if (v->tile == v->dest_tile) return;
2289 break;
2291 case OT_GOTO_WAYPOINT:
2292 /* If we reached our waypoint, make sure we see that. */
2293 if (IsRailWaypointTile(v->tile) && GetStationIndex(v->tile) == v->current_order.GetDestination()) ProcessOrders(v);
2294 break;
2296 case OT_NOTHING:
2297 case OT_LEAVESTATION:
2298 case OT_LOADING:
2299 /* Exit if the current order doesn't have a destination, but the train has orders. */
2300 if (v->GetNumOrders() > 0) return;
2301 break;
2303 default:
2304 break;
2306 /* Exit if we are on a station tile and are going to stop. */
2307 if (IsRailStationTile(v->tile) && v->current_order.ShouldStopAtStation(v, GetStationIndex(v->tile))) return;
2309 Trackdir td = v->GetVehicleTrackdir();
2311 /* On a tile with a red non-pbs signal, don't look ahead. */
2312 if (IsTileType(v->tile, MP_RAILWAY) && HasSignalOnTrackdir(v->tile, td) &&
2313 !IsPbsSignal(GetSignalType(v->tile, TrackdirToTrack(td))) &&
2314 GetSignalStateByTrackdir(v->tile, td) == SIGNAL_STATE_RED) return;
2316 CFollowTrackRail ft(v);
2317 if (!ft.Follow(v->tile, td)) return;
2319 if (!HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(ft.m_new_td_bits))) {
2320 /* Next tile is not reserved. */
2321 if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
2322 if (HasPbsSignalOnTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) {
2323 /* If the next tile is a PBS signal, try to make a reservation. */
2324 TrackBits tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
2325 if (_settings_game.pf.forbid_90_deg) {
2326 tracks &= ~TrackCrossesTracks(TrackdirToTrack(ft.m_old_td));
2328 ChooseTrainTrack(v, ft.m_new_tile, ft.m_exitdir, tracks, false, nullptr, false);
2335 * Will the train stay in the depot the next tick?
2336 * @param v %Train to check.
2337 * @return True if it stays in the depot, false otherwise.
2339 static bool CheckTrainStayInDepot(Train *v)
2341 /* bail out if not all wagons are in the same depot or not in a depot at all */
2342 for (const Train *u = v; u != nullptr; u = u->Next()) {
2343 if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return false;
2346 /* if the train got no power, then keep it in the depot */
2347 if (v->gcache.cached_power == 0) {
2348 v->vehstatus |= VS_STOPPED;
2349 SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
2350 return true;
2353 if (v->current_order.IsWaitTimetabled())
2354 v->HandleWaiting(false);
2355 if (v->current_order.IsType(OT_WAITING))
2356 return true;
2358 SigSegState seg_state;
2360 if (v->force_proceed == TFP_NONE) {
2361 /* force proceed was not pressed */
2362 if (++v->wait_counter < 37) {
2363 SetWindowClassesDirty(WC_TRAINS_LIST);
2364 SetWindowClassesDirty(WC_TRACE_RESTRICT_SLOTS);
2365 return true;
2368 v->wait_counter = 0;
2370 seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
2371 if (seg_state == SIGSEG_FULL || HasDepotReservation(v->tile)) {
2372 /* Full and no PBS signal in block or depot reserved, can't exit. */
2373 SetWindowClassesDirty(WC_TRAINS_LIST);
2374 SetWindowClassesDirty(WC_TRACE_RESTRICT_SLOTS);
2375 return true;
2377 } else {
2378 seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
2381 /* We are leaving a depot, but have to go to the exact same one; re-enter */
2382 if (v->current_order.IsType(OT_GOTO_DEPOT) && v->tile == v->dest_tile) {
2383 /* We need to have a reservation for this to work. */
2384 if (HasDepotReservation(v->tile)) return true;
2385 SetDepotReservation(v->tile, true);
2386 VehicleEnterDepot(v);
2387 return true;
2390 /* Only leave when we can reserve a path to our destination. */
2391 if (seg_state == SIGSEG_PBS && !TryPathReserve(v) && v->force_proceed == TFP_NONE) {
2392 /* No path and no force proceed. */
2393 SetWindowClassesDirty(WC_TRAINS_LIST);
2394 SetWindowClassesDirty(WC_TRACE_RESTRICT_SLOTS);
2395 MarkTrainAsStuck(v);
2396 return true;
2399 SetDepotReservation(v->tile, true);
2400 if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile, ZOOM_LVL_DRAW_MAP);
2402 VehicleServiceInDepot(v);
2403 SetWindowClassesDirty(WC_TRAINS_LIST);
2404 SetWindowClassesDirty(WC_TRACE_RESTRICT_SLOTS);
2405 v->PlayLeaveStationSound();
2407 v->track = TRACK_BIT_X;
2408 if (v->direction & 2) v->track = TRACK_BIT_Y;
2410 v->vehstatus &= ~VS_HIDDEN;
2411 v->cur_speed = 0;
2413 v->UpdateViewport(true, true);
2414 v->UpdatePosition();
2415 UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
2416 v->UpdateAcceleration();
2417 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
2419 return false;
2422 static int GetAndClearLastBridgeEntranceSetSignalIndex(TileIndex bridge_entrance)
2424 uint16 m = _m[bridge_entrance].m2;
2425 if (m & 0x8000) {
2426 auto it = _long_bridge_signal_sim_map.find(bridge_entrance);
2427 if (it != _long_bridge_signal_sim_map.end()) {
2428 LongBridgeSignalStorage &lbss = it->second;
2429 size_t slot = lbss.signal_red_bits.size();
2430 while (slot > 0) {
2431 slot--;
2432 uint64 &slot_bits = lbss.signal_red_bits[slot];
2433 if (slot_bits) {
2434 uint8 i = FindLastBit(slot_bits);
2435 ClrBit(slot_bits, i);
2436 return (int)(1 + 15 + (64 * slot) + i);
2441 if (m & 0x7FFF) {
2442 uint8 i = FindLastBit(m & 0x7FFF);
2443 ClrBit(_m[bridge_entrance].m2, i);
2444 return 1 + i;
2447 return 0;
2450 static void HandleLastTunnelBridgeSignals(TileIndex tile, TileIndex end, DiagDirection dir, bool free)
2452 if (IsBridge(end) && _m[end].m2 != 0) {
2453 /* Clearing last bridge signal. */
2454 int signal_offset = GetAndClearLastBridgeEntranceSetSignalIndex(end);
2455 if (signal_offset) {
2456 TileIndex last_signal_tile = end + (TileOffsByDiagDir(dir) * _settings_game.construction.simulated_wormhole_signals * signal_offset);
2457 MarkTileDirtyByTile(last_signal_tile);
2459 MarkTileDirtyByTile(tile);
2461 if (free) {
2462 /* Open up the wormhole and clear m2. */
2463 if (IsBridge(end)) {
2464 SetAllBridgeEntranceSimulatedSignalsGreen(end);
2467 if (IsTunnelBridgeSignalSimulationEntrance(end) && GetTunnelBridgeSignalState(end) == SIGNAL_STATE_RED) {
2468 SetTunnelBridgeSignalState(end, SIGNAL_STATE_GREEN);
2469 MarkTileDirtyByTile(end);
2470 } else if (IsTunnelBridgeSignalSimulationEntrance(tile) && GetTunnelBridgeSignalState(tile) == SIGNAL_STATE_RED) {
2471 SetTunnelBridgeSignalState(tile, SIGNAL_STATE_GREEN);
2472 MarkTileDirtyByTile(tile);
2477 static void UnreserveBridgeTunnelTile(TileIndex tile)
2479 SetTunnelBridgeReservation(tile, false);
2480 if (IsTunnelBridgeSignalSimulationExit(tile) && IsTunnelBridgePBS(tile)) SetTunnelBridgeSignalState(tile, SIGNAL_STATE_RED);
2484 * Clear the reservation of \a tile that was just left by a wagon on \a track_dir.
2485 * @param v %Train owning the reservation.
2486 * @param tile Tile with reservation to clear.
2487 * @param track_dir Track direction to clear.
2489 static void ClearPathReservation(const Train *v, TileIndex tile, Trackdir track_dir, bool clear_unsignaled_other_end = false)
2491 DiagDirection dir = TrackdirToExitdir(track_dir);
2493 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
2494 TileIndex end = GetOtherTunnelBridgeEnd(tile);
2495 bool free = TunnelBridgeIsFree(tile, end, v).Succeeded();
2496 UnreserveBridgeTunnelTile(tile);
2498 if (IsTunnelBridgeWithSignalSimulation(tile)) {
2499 if (GetTunnelBridgeDirection(tile) == ReverseDiagDir(dir)) {
2500 HandleLastTunnelBridgeSignals(tile, end, dir, free);
2503 else if (clear_unsignaled_other_end)
2505 UnreserveBridgeTunnelTile(end);
2508 if (_settings_client.gui.show_track_reservation) {
2509 MarkTileDirtyByTile(tile);
2510 MarkTileDirtyByTile(end);
2512 } else if (IsRailStationTile(tile)) {
2513 TileIndex new_tile = TileAddByDiagDir(tile, dir);
2514 /* If the new tile is not a further tile of the same station, we
2515 * clear the reservation for the whole platform. */
2516 if (!IsCompatibleTrainStationTile(new_tile, tile)) {
2517 SetRailStationPlatformReservation(tile, ReverseDiagDir(dir), false);
2519 } else {
2520 /* Any other tile */
2521 UnreserveRailTrack(tile, TrackdirToTrack(track_dir));
2526 * Free the reserved path in front of a vehicle.
2527 * @param v %Train owning the reserved path.
2528 * @param origin %Tile to start clearing (if #INVALID_TILE, use the current tile of \a v).
2529 * @param orig_td Track direction (if #INVALID_TRACKDIR, use the track direction of \a v).
2531 void FreeTrainTrackReservation(const Train *v, TileIndex origin, Trackdir orig_td)
2533 assert(v->IsFrontEngine());
2535 TileIndex tile = origin != INVALID_TILE ? origin : v->tile;
2536 Trackdir td = orig_td != INVALID_TRACKDIR ? orig_td : v->GetVehicleTrackdir();
2537 bool free_tile = tile != v->tile || !(IsRailStationTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE));
2538 StationID station_id = IsRailStationTile(v->tile) ? GetStationIndex(v->tile) : INVALID_STATION;
2540 /* Can't be holding a reservation if we enter a depot. */
2541 if (IsRailDepotTile(tile) && TrackdirToExitdir(td) != GetRailDepotDirection(tile)) return;
2542 if (v->track == TRACK_BIT_DEPOT) {
2543 /* Front engine is in a depot. We enter if some part is not in the depot. */
2544 for (const Train *u = v; u != nullptr; u = u->Next()) {
2545 if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return;
2548 /* Don't free reservation if it's not ours. */
2549 if (TracksOverlap(GetReservedTrackbits(tile) | TrackToTrackBits(TrackdirToTrack(td)))) return;
2551 CFollowTrackRail ft(v, GetRailTypeInfo(v->railtype)->compatible_railtypes);
2552 while (ft.Follow(tile, td)) {
2553 tile = ft.m_new_tile;
2554 TrackdirBits bits = ft.m_new_td_bits & TrackBitsToTrackdirBits(GetReservedTrackbits(tile));
2555 td = RemoveFirstTrackdir(&bits);
2556 assert(bits == TRACKDIR_BIT_NONE);
2558 if (!IsValidTrackdir(td)) break;
2560 if (IsTileType(tile, MP_RAILWAY)) {
2561 if (HasSignalOnTrackdir(tile, td) && !IsPbsSignal(GetSignalType(tile, TrackdirToTrack(td)))) {
2562 /* Conventional signal along trackdir: remove reservation and stop. */
2563 UnreserveRailTrack(tile, TrackdirToTrack(td));
2564 break;
2566 if (HasPbsSignalOnTrackdir(tile, td)) {
2567 if (GetSignalStateByTrackdir(tile, td) == SIGNAL_STATE_RED) {
2568 /* Red PBS signal? Can't be our reservation, would be green then. */
2569 break;
2570 } else {
2571 /* Turn the signal back to red. */
2572 SetSignalStateByTrackdir(tile, td, SIGNAL_STATE_RED);
2573 MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
2575 /* notify logic signals of the state change */
2576 SignalStateChanged(tile, TrackdirToTrack(td), 1);
2578 } else if (HasSignalOnTrackdir(tile, ReverseTrackdir(td)) && IsOnewaySignal(tile, TrackdirToTrack(td))) {
2579 break;
2582 else if (IsTunnelBridgeWithSignalSimulation(tile)) {
2583 TileIndex end = GetOtherTunnelBridgeEnd(tile);
2584 bool free = TunnelBridgeIsFree(tile, end, v).Succeeded();
2586 if (!free && GetTunnelBridgeDirection(tile) == ReverseDiagDir(TrackdirToExitdir(td))) break;
2589 /* Don't free first station/bridge/tunnel if we are on it. */
2590 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);
2592 free_tile = true;
2596 static const byte _initial_tile_subcoord[6][4][3] = {
2597 {{ 15, 8, 1 }, { 0, 0, 0 }, { 0, 8, 5 }, { 0, 0, 0 }},
2598 {{ 0, 0, 0 }, { 8, 0, 3 }, { 0, 0, 0 }, { 8, 15, 7 }},
2599 {{ 0, 0, 0 }, { 7, 0, 2 }, { 0, 7, 6 }, { 0, 0, 0 }},
2600 {{ 15, 8, 2 }, { 0, 0, 0 }, { 0, 0, 0 }, { 8, 15, 6 }},
2601 {{ 15, 7, 0 }, { 8, 0, 4 }, { 0, 0, 0 }, { 0, 0, 0 }},
2602 {{ 0, 0, 0 }, { 0, 0, 0 }, { 0, 8, 4 }, { 7, 15, 0 }},
2606 * Perform pathfinding for a train.
2608 * @param v The train
2609 * @param tile The tile the train is about to enter
2610 * @param enterdir Diagonal direction the train is coming from
2611 * @param tracks Usable tracks on the new tile
2612 * @param path_found [out] Whether a path has been found or not.
2613 * @param do_track_reservation Path reservation is requested
2614 * @param dest [out] State and destination of the requested path
2615 * @return The best track the train should follow
2617 static Track DoTrainPathfind(const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found, bool do_track_reservation, PBSTileInfo *dest)
2619 switch (_settings_game.pf.pathfinder_for_trains) {
2620 case VPF_NPF: return NPFTrainChooseTrack(v, tile, enterdir, tracks, path_found, do_track_reservation, dest);
2621 case VPF_YAPF: return YapfTrainChooseTrack(v, tile, enterdir, tracks, path_found, do_track_reservation, dest);
2623 default: NOT_REACHED();
2628 * Extend a train path as far as possible. Stops on encountering a safe tile,
2629 * another reservation or a track choice.
2630 * @param v The train.
2631 * @param origin The tile from which the reservation have to be extended
2632 * @param new_tracks [out] Tracks to choose from when encountering a choice
2633 * @param enterdir [out] The direction from which the choice tile is to be entered
2634 * @return INVALID_TILE indicates that the reservation failed.
2636 static PBSTileInfo ExtendTrainReservation(const Train *v, const PBSTileInfo &origin, TrackBits *new_tracks, DiagDirection *enterdir)
2638 CFollowTrackRail ft(v);
2640 TileIndex tile = origin.tile;
2641 Trackdir cur_td = origin.trackdir;
2642 while (ft.Follow(tile, cur_td)) {
2643 if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
2644 /* Possible signal tile. */
2645 if (HasOnewaySignalBlockingTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) break;
2648 if (_settings_game.pf.forbid_90_deg) {
2649 ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
2650 if (ft.m_new_td_bits == TRACKDIR_BIT_NONE) break;
2653 /* Station, depot or waypoint are a possible target. */
2654 bool target_seen = ft.m_is_station || (IsTileType(ft.m_new_tile, MP_RAILWAY) && !IsPlainRail(ft.m_new_tile));
2655 if (target_seen || KillFirstBit(ft.m_new_td_bits) != TRACKDIR_BIT_NONE) {
2656 /* Choice found or possible target encountered.
2657 * On finding a possible target, we need to stop and let the pathfinder handle the
2658 * remaining path. This is because we don't know if this target is in one of our
2659 * orders, so we might cause pathfinding to fail later on if we find a choice.
2660 * This failure would cause a bogous call to TryReserveSafePath which might reserve
2661 * a wrong path not leading to our next destination. */
2662 if (HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(TrackdirReachesTrackdirs(ft.m_old_td)))) break;
2664 /* If we did skip some tiles, backtrack to the first skipped tile so the pathfinder
2665 * actually starts its search at the first unreserved tile. */
2666 if (ft.m_tiles_skipped != 0) ft.m_new_tile -= TileOffsByDiagDir(ft.m_exitdir) * ft.m_tiles_skipped;
2668 /* Choice found, path valid but not okay. Save info about the choice tile as well. */
2669 if (new_tracks != nullptr) *new_tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
2670 if (enterdir != nullptr) *enterdir = ft.m_exitdir;
2671 return PBSTileInfo(ft.m_new_tile, ft.m_old_td, false);
2674 tile = ft.m_new_tile;
2675 cur_td = FindFirstTrackdir(ft.m_new_td_bits);
2677 if (IsSafeWaitingPosition(v, tile, cur_td, true, _settings_game.pf.forbid_90_deg)) {
2678 bool wp_free = IsWaitingPositionFree(v, tile, cur_td, _settings_game.pf.forbid_90_deg);
2679 if (!(wp_free && TryReserveRailTrack(tile, TrackdirToTrack(cur_td)))) break;
2680 /* Safe position is all good, path valid and okay. */
2681 return PBSTileInfo(tile, cur_td, true);
2684 if (!TryReserveRailTrackdir(tile, cur_td)) break;
2687 if (ft.m_err == CFollowTrackRail::EC_OWNER || ft.m_err == CFollowTrackRail::EC_NO_WAY) {
2688 /* End of line, path valid and okay. */
2689 return PBSTileInfo(ft.m_old_tile, ft.m_old_td, true);
2692 /* Sorry, can't reserve path, back out. */
2693 tile = origin.tile;
2694 cur_td = origin.trackdir;
2695 TileIndex stopped = ft.m_old_tile;
2696 Trackdir stopped_td = ft.m_old_td;
2697 while (tile != stopped || cur_td != stopped_td) {
2698 if (!ft.Follow(tile, cur_td)) break;
2700 if (_settings_game.pf.forbid_90_deg) {
2701 ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
2702 assert(ft.m_new_td_bits != TRACKDIR_BIT_NONE);
2704 assert(KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE);
2706 tile = ft.m_new_tile;
2707 cur_td = FindFirstTrackdir(ft.m_new_td_bits);
2709 UnreserveRailTrackdir(tile, cur_td);
2712 /* Path invalid. */
2713 return PBSTileInfo();
2717 * Try to reserve any path to a safe tile, ignoring the vehicle's destination.
2718 * Safe tiles are tiles in front of a signal, depots and station tiles at end of line.
2720 * @param v The vehicle.
2721 * @param tile The tile the search should start from.
2722 * @param td The trackdir the search should start from.
2723 * @param override_railtype Whether all physically compatible railtypes should be followed.
2724 * @return True if a path to a safe stopping tile could be reserved.
2726 static bool TryReserveSafeTrack(const Train *v, TileIndex tile, Trackdir td, bool override_tailtype)
2728 switch (_settings_game.pf.pathfinder_for_trains) {
2729 case VPF_NPF: return NPFTrainFindNearestSafeTile(v, tile, td, override_tailtype);
2730 case VPF_YAPF: return YapfTrainFindNearestSafeTile(v, tile, td, override_tailtype);
2732 default: NOT_REACHED();
2736 /** This class will save the current order of a vehicle and restore it on destruction. */
2737 class VehicleOrderSaver {
2738 private:
2739 Train *v;
2740 Order old_order;
2741 TileIndex old_dest_tile;
2742 StationID old_last_station_visited;
2743 VehicleOrderID index;
2744 bool suppress_implicit_orders;
2746 public:
2747 VehicleOrderSaver(Train *_v) :
2748 v(_v),
2749 old_order(_v->current_order),
2750 old_dest_tile(_v->dest_tile),
2751 old_last_station_visited(_v->last_station_visited),
2752 index(_v->cur_real_order_index),
2753 suppress_implicit_orders(HasBit(_v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS))
2757 ~VehicleOrderSaver()
2759 this->v->current_order = this->old_order;
2760 this->v->dest_tile = this->old_dest_tile;
2761 this->v->last_station_visited = this->old_last_station_visited;
2762 SB(this->v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS, 1, suppress_implicit_orders ? 1: 0);
2766 * Set the current vehicle order to the next order in the order list.
2767 * @param skip_first Shall the first (i.e. active) order be skipped?
2768 * @return True if a suitable next order could be found.
2770 bool SwitchToNextOrder(bool skip_first)
2772 if (this->v->GetNumOrders() == 0) return false;
2774 if (skip_first) ++this->index;
2776 int depth = 0;
2777 bool has_manual_depot_order = (HasBit(v->vehicle_flags, VF_SHOULD_GOTO_DEPOT) || HasBit(v->vehicle_flags, VF_SHOULD_SERVICE_AT_DEPOT));
2779 do {
2780 /* Wrap around. */
2781 if (this->index >= this->v->GetNumOrders()) this->index = 0;
2783 Order *order = this->v->GetOrder(this->index);
2784 assert(order != nullptr);
2786 switch (order->GetType()) {
2787 case OT_GOTO_DEPOT:
2788 /* Skip service in depot orders when the train doesn't need service. */
2789 if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !(this->v->NeedsServicing() || has_manual_depot_order)) break;
2790 FALLTHROUGH;
2791 case OT_GOTO_STATION:
2792 case OT_GOTO_WAYPOINT:
2793 this->v->current_order = *order;
2794 return UpdateOrderDest(this->v, order, 0, true);
2795 case OT_CONDITIONAL: {
2796 VehicleOrderID next = ProcessConditionalOrder(order, this->v);
2797 if (next != INVALID_VEH_ORDER_ID) {
2798 depth++;
2799 this->index = next;
2800 /* Don't increment next, so no break here. */
2801 continue;
2803 break;
2805 default:
2806 break;
2808 /* Don't increment inside the while because otherwise conditional
2809 * orders can lead to an infinite loop. */
2810 ++this->index;
2811 depth++;
2812 } while (this->index != this->v->cur_real_order_index && depth < this->v->GetNumOrders());
2814 return false;
2819 * This is called to retrieve the previous signal, as required
2820 * This is not run all the time as it is somewhat expensive and most restrictions will not test for the previous signal
2822 static TileIndex ChooseTrainTrackTraceRestrictPreviousSignalCallback(const Train *v, const void *)
2824 // scan forwards from vehicle position, for the case that train is waiting at/approaching PBS signal
2826 TileIndex tile = v->tile;
2827 Trackdir trackdir = v->GetVehicleTrackdir();
2829 CFollowTrackRail ft(v);
2831 for (;;) {
2832 if (IsTileType(tile, MP_RAILWAY) && HasSignalOnTrackdir(tile, trackdir)) {
2833 if (HasPbsSignalOnTrackdir(tile, trackdir)) {
2834 // found PBS signal
2835 return tile;
2836 } else {
2837 // wrong type of signal
2838 return INVALID_TILE;
2842 // advance to next tile
2843 if (!ft.Follow(tile, trackdir)) {
2844 // ran out of track
2845 return INVALID_TILE;
2848 if (KillFirstBit(ft.m_new_td_bits) != TRACKDIR_BIT_NONE) {
2849 // reached a junction tile
2850 return INVALID_TILE;
2853 tile = ft.m_new_tile;
2854 trackdir = FindFirstTrackdir(ft.m_new_td_bits);
2858 static bool HasLongReservePbsSignalOnTrackdir(Train* v, TileIndex tile, Trackdir trackdir)
2860 if (HasPbsSignalOnTrackdir(tile, trackdir)) {
2861 if (IsRestrictedSignal(tile)) {
2862 const TraceRestrictProgram *prog = GetExistingTraceRestrictProgram(tile, TrackdirToTrack(trackdir));
2863 if (prog && prog->actions_used_flags & TRPAUF_LONG_RESERVE) {
2864 TraceRestrictProgramResult out;
2865 prog->Execute(v, TraceRestrictProgramInput(tile, trackdir, &ChooseTrainTrackTraceRestrictPreviousSignalCallback, nullptr), out);
2866 if (out.flags & TRPRF_LONG_RESERVE) {
2867 return true;
2873 return false;
2877 * Choose a track and reserve if necessary
2879 * @param v The vehicle
2880 * @param tile The tile from which to start
2881 * @param enterdir
2882 * @param tracks
2883 * @param force_res Force a reservation to be made
2884 * @param p_got_reservation [out] If the train has a reservation
2885 * @param mark_stuck The train has to be marked as stuck when needed
2886 * @return The track the train should take.
2888 static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *p_got_reservation, bool mark_stuck)
2890 Track best_track = INVALID_TRACK;
2891 bool do_track_reservation = _settings_game.pf.reserve_paths || force_res;
2892 bool changed_signal = false;
2893 bool got_reservation = false;
2894 if (p_got_reservation != nullptr) *p_got_reservation = got_reservation;
2896 assert((tracks & ~TRACK_BIT_MASK) == 0);
2898 /* Don't use tracks here as the setting to forbid 90 deg turns might have been switched between reservation and now. */
2899 TrackBits res_tracks = (TrackBits)(GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir));
2900 /* Do we have a suitable reserved track? */
2901 if (res_tracks != TRACK_BIT_NONE) return FindFirstTrack(res_tracks);
2903 /* Quick return in case only one possible track is available */
2904 if (KillFirstBit(tracks) == TRACK_BIT_NONE) {
2905 Track track = FindFirstTrack(tracks);
2906 /* We need to check for signals only here, as a junction tile can't have signals. */
2907 if (track != INVALID_TRACK && HasPbsSignalOnTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir))) {
2908 if (IsRestrictedSignal(tile) && v->force_proceed != TFP_SIGNAL) {
2909 const TraceRestrictProgram *prog = GetExistingTraceRestrictProgram(tile, track);
2910 if (prog && prog->actions_used_flags & (TRPAUF_WAIT_AT_PBS | TRPAUF_SLOT_ACQUIRE)) {
2911 TraceRestrictProgramResult out;
2912 TraceRestrictProgramInput input(tile, TrackEnterdirToTrackdir(track, enterdir), nullptr, nullptr);
2913 input.permitted_slot_operations = TRPISP_ACQUIRE;
2914 prog->Execute(v, input, out);
2915 if (out.flags & TRPRF_WAIT_AT_PBS) {
2916 if (mark_stuck) MarkTrainAsStuck(v, true);
2917 return track;
2921 ClrBit(v->flags, VRF_WAITING_RESTRICTION);
2923 do_track_reservation = true;
2924 changed_signal = true;
2925 SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir), SIGNAL_STATE_GREEN);
2927 /* notify logic signals of the state change */
2928 SignalStateChanged(tile, TrackdirToTrack(TrackEnterdirToTrackdir(track, enterdir)), 1);
2929 } else if (!do_track_reservation) {
2930 return track;
2932 best_track = track;
2935 PBSTileInfo origin = FollowTrainReservation(v);
2936 PBSTileInfo res_dest(tile, INVALID_TRACKDIR, false);
2937 DiagDirection dest_enterdir = enterdir;
2938 if (do_track_reservation) {
2939 res_dest = ExtendTrainReservation(v, origin, &tracks, &dest_enterdir);
2940 if (res_dest.tile == INVALID_TILE) {
2941 /* Reservation failed? */
2942 if (mark_stuck) MarkTrainAsStuck(v);
2943 if (changed_signal) {
2944 SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(best_track, enterdir), SIGNAL_STATE_RED);
2946 /* notify logic signals of the state change */
2947 SignalStateChanged(tile, TrackdirToTrack(TrackEnterdirToTrackdir(best_track, enterdir)), 1);
2949 return FindFirstTrack(tracks);
2952 if (res_dest.okay) {
2953 CFollowTrackRail ft(v);
2954 if (ft.Follow(res_dest.tile, res_dest.trackdir)) {
2955 Trackdir new_td = FindFirstTrackdir(ft.m_new_td_bits);
2957 if (!HasLongReservePbsSignalOnTrackdir(v, ft.m_new_tile, new_td)) {
2958 /* Got a valid reservation that ends at a safe target, quick exit. */
2959 if (p_got_reservation != nullptr) *p_got_reservation = true;
2960 if (changed_signal) MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
2961 TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
2962 return best_track;
2967 /* Check if the train needs service here, so it has a chance to always find a depot.
2968 * Also check if the current order is a service order so we don't reserve a path to
2969 * the destination but instead to the next one if service isn't needed. */
2970 CheckIfTrainNeedsService(v);
2971 if (v->current_order.IsType(OT_DUMMY) || v->current_order.IsType(OT_CONDITIONAL) || v->current_order.IsType(OT_GOTO_DEPOT)) ProcessOrders(v);
2974 /* Save the current train order. The destructor will restore the old order on function exit. */
2975 VehicleOrderSaver orders(v);
2977 /* If the current tile is the destination of the current order and
2978 * a reservation was requested, advance to the next order.
2979 * Don't advance on a depot order as depots are always safe end points
2980 * for a path and no look-ahead is necessary. This also avoids a
2981 * problem with depot orders not part of the order list when the
2982 * order list itself is empty. */
2983 if (v->current_order.IsType(OT_LEAVESTATION)) {
2984 orders.SwitchToNextOrder(false);
2985 } else if (v->current_order.IsType(OT_LOADING) || (!v->current_order.IsType(OT_GOTO_DEPOT) && (
2986 v->current_order.IsType(OT_GOTO_STATION) ?
2987 IsRailStationTile(v->tile) && v->current_order.GetDestination() == GetStationIndex(v->tile) :
2988 v->tile == v->dest_tile))) {
2989 orders.SwitchToNextOrder(true);
2992 if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
2993 /* Pathfinders are able to tell that route was only 'guessed'. */
2994 bool path_found = true;
2995 TileIndex new_tile = res_dest.tile;
2997 Track next_track = DoTrainPathfind(v, new_tile, dest_enterdir, tracks, path_found, do_track_reservation, &res_dest);
2998 if (new_tile == tile) best_track = next_track;
2999 v->HandlePathfindingResult(path_found);
3002 /* No track reservation requested -> finished. */
3003 if (!do_track_reservation) return best_track;
3005 /* A path was found, but could not be reserved. */
3006 if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
3007 if (mark_stuck) MarkTrainAsStuck(v);
3008 FreeTrainTrackReservation(v, origin.tile, origin.trackdir);
3009 return best_track;
3012 /* No possible reservation target found, we are probably lost. */
3013 if (res_dest.tile == INVALID_TILE) {
3014 /* Try to find any safe destination. */
3015 PBSTileInfo path_end = FollowTrainReservation(v);
3016 if (TryReserveSafeTrack(v, path_end.tile, path_end.trackdir, false)) {
3017 TrackBits res = GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir);
3018 best_track = FindFirstTrack(res);
3019 TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
3020 // Use p_got_reservation because were going to return
3021 if (p_got_reservation != nullptr) *p_got_reservation = true;
3022 if (changed_signal) MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
3023 } else {
3024 FreeTrainTrackReservation(v, origin.tile, origin.trackdir);
3025 if (mark_stuck) MarkTrainAsStuck(v);
3027 return best_track;
3030 got_reservation = true;
3032 /* Reservation target found and free, check if it is safe. */
3033 while (!IsSafeWaitingPosition(v, res_dest.tile, res_dest.trackdir, true, _settings_game.pf.forbid_90_deg)) {
3034 /* Extend reservation until we have found a safe position. */
3035 DiagDirection exitdir = TrackdirToExitdir(res_dest.trackdir);
3036 TileIndex next_tile = TileAddByDiagDir(res_dest.tile, exitdir);
3037 TrackBits reachable = TrackdirBitsToTrackBits((TrackdirBits)(GetTileTrackStatus(next_tile, TRANSPORT_RAIL, 0))) & DiagdirReachesTracks(exitdir);
3038 if (_settings_game.pf.forbid_90_deg) {
3039 reachable &= ~TrackCrossesTracks(TrackdirToTrack(res_dest.trackdir));
3042 /* Get next order with destination. */
3043 if (orders.SwitchToNextOrder(true)) {
3044 PBSTileInfo cur_dest;
3045 bool path_found;
3046 DoTrainPathfind(v, next_tile, exitdir, reachable, path_found, true, &cur_dest);
3047 if (cur_dest.tile != INVALID_TILE) {
3048 res_dest = cur_dest;
3049 if (res_dest.okay) continue;
3050 /* Path found, but could not be reserved. */
3051 FreeTrainTrackReservation(v, origin.tile, origin.trackdir);
3052 if (mark_stuck) MarkTrainAsStuck(v);
3053 got_reservation = false;
3054 changed_signal = false;
3055 break;
3058 /* No order or no safe position found, try any position. */
3059 if (!TryReserveSafeTrack(v, res_dest.tile, res_dest.trackdir, true)) {
3060 FreeTrainTrackReservation(v, origin.tile, origin.trackdir);
3061 if (mark_stuck) MarkTrainAsStuck(v);
3062 got_reservation = false;
3063 changed_signal = false;
3065 break;
3068 if (got_reservation) {
3069 CFollowTrackRail ft(v);
3070 if (ft.Follow(res_dest.tile, res_dest.trackdir)) {
3071 Trackdir new_td = FindFirstTrackdir(ft.m_new_td_bits);
3073 if (HasLongReservePbsSignalOnTrackdir(v, ft.m_new_tile, new_td)) {
3074 // We reserved up to a LR signal, reserve past it as well. recursion
3075 ChooseTrainTrack(v, ft.m_new_tile, ft.m_exitdir, TrackdirBitsToTrackBits(ft.m_new_td_bits), force_res, nullptr, mark_stuck);
3080 TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
3082 if (changed_signal) MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
3083 if (p_got_reservation != nullptr) *p_got_reservation = got_reservation;
3085 return best_track;
3089 * Try to reserve a path to a safe position.
3091 * @param v The vehicle
3092 * @param mark_as_stuck Should the train be marked as stuck on a failed reservation?
3093 * @param first_tile_okay True if no path should be reserved if the current tile is a safe position.
3094 * @return True if a path could be reserved.
3096 bool TryPathReserve(Train *v, bool mark_as_stuck, bool first_tile_okay)
3098 assert(v->IsFrontEngine());
3100 /* We have to handle depots specially as the track follower won't look
3101 * at the depot tile itself but starts from the next tile. If we are still
3102 * inside the depot, a depot reservation can never be ours. */
3103 if (v->track == TRACK_BIT_DEPOT) {
3104 if (HasDepotReservation(v->tile)) {
3105 if (mark_as_stuck) MarkTrainAsStuck(v);
3106 return false;
3107 } else {
3108 /* Depot not reserved, but the next tile might be. */
3109 TileIndex next_tile = TileAddByDiagDir(v->tile, GetRailDepotDirection(v->tile));
3110 if (HasReservedTracks(next_tile, DiagdirReachesTracks(GetRailDepotDirection(v->tile)))) return false;
3114 if (IsTileType(v->tile, MP_TUNNELBRIDGE) && IsTunnelBridgeSignalSimulationExit(v->tile) &&
3115 DiagDirToDiagTrackBits(GetTunnelBridgeDirection(v->tile)) == v->track) {
3116 // prevent any attempt to reserve the wrong way onto a tunnel/bridge exit
3117 return false;
3120 Vehicle *other_train = nullptr;
3121 PBSTileInfo origin = FollowTrainReservation(v, &other_train);
3122 /* The path we are driving on is already blocked by some other train.
3123 * This can only happen in certain situations when mixing path and
3124 * block signals or when changing tracks and/or signals.
3125 * Exit here as doing any further reservations will probably just
3126 * make matters worse. */
3127 if (other_train != nullptr && other_train->index != v->index) {
3128 if (mark_as_stuck) MarkTrainAsStuck(v);
3129 return false;
3131 /* If we have a reserved path and the path ends at a safe tile, we are finished already. */
3132 if (origin.okay && (v->tile != origin.tile || first_tile_okay)) {
3133 /* Can't be stuck then. */
3134 if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
3135 ClrBit(v->flags, VRF_TRAIN_STUCK);
3136 return true;
3139 /* If we are in a depot, tentatively reserve the depot. */
3140 if (v->track == TRACK_BIT_DEPOT && v->tile == origin.tile) {
3141 SetDepotReservation(v->tile, true);
3142 if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile, ZOOM_LVL_DRAW_MAP);
3145 DiagDirection exitdir = TrackdirToExitdir(origin.trackdir);
3146 TileIndex new_tile = TileAddByDiagDir(origin.tile, exitdir);
3147 TrackBits reachable = TrackdirBitsToTrackBits(TrackStatusToTrackdirBits(GetTileTrackStatus(new_tile, TRANSPORT_RAIL, 0)) & DiagdirReachesTrackdirs(exitdir));
3149 if (_settings_game.pf.forbid_90_deg) reachable &= ~TrackCrossesTracks(TrackdirToTrack(origin.trackdir));
3151 bool res_made = false;
3152 ChooseTrainTrack(v, new_tile, exitdir, reachable, true, &res_made, mark_as_stuck);
3154 if (!res_made) {
3155 /* Free the depot reservation as well. */
3156 if (v->track == TRACK_BIT_DEPOT && v->tile == origin.tile) SetDepotReservation(v->tile, false);
3157 return false;
3160 if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
3161 v->wait_counter = 0;
3162 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
3164 ClrBit(v->flags, VRF_TRAIN_STUCK);
3165 return true;
3169 static bool CheckReverseTrain(const Train *v)
3171 if (_settings_game.difficulty.line_reverse_mode != 0 ||
3172 v->track == TRACK_BIT_DEPOT || v->track == TRACK_BIT_WORMHOLE ||
3173 !(v->direction & 1)) {
3174 return false;
3177 assert(v->track != TRACK_BIT_NONE);
3179 switch (_settings_game.pf.pathfinder_for_trains) {
3180 case VPF_NPF: return NPFTrainCheckReverse(v);
3181 case VPF_YAPF: return YapfTrainCheckReverse(v);
3183 default: NOT_REACHED();
3188 * Get the location of the next station to visit.
3189 * @param station Next station to visit.
3190 * @return Location of the new station.
3192 TileIndex Train::GetOrderStationLocation(StationID station)
3194 if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
3196 const Station *st = Station::Get(station);
3197 if (!(st->facilities & FACIL_TRAIN)) {
3198 /* The destination station has no trainstation tiles. */
3199 this->IncrementRealOrderIndex();
3200 return 0;
3203 return st->xy;
3206 /** Goods at the consist have changed, update the graphics, cargo, and acceleration. */
3207 void Train::MarkDirty()
3209 Train *v = this;
3210 do {
3211 v->colourmap = PAL_NONE;
3212 v->UpdateViewport(true, false);
3213 } while ((v = v->Next()) != nullptr);
3215 /* need to update acceleration and cached values since the goods on the train changed. */
3216 this->CargoChanged();
3217 this->UpdateAcceleration();
3221 * This function looks at the vehicle and updates its speed (cur_speed
3222 * and subspeed) variables. Furthermore, it returns the distance that
3223 * the train can drive this tick. #Vehicle::GetAdvanceDistance() determines
3224 * the distance to drive before moving a step on the map.
3225 * @return distance to drive.
3227 int Train::UpdateSpeed()
3229 switch (_settings_game.vehicle.train_acceleration_model) {
3230 default: NOT_REACHED();
3231 case AM_ORIGINAL:
3232 return this->DoUpdateSpeed(this->acceleration * (this->GetAccelerationStatus() == AS_BRAKE ? -4 : 2), 0, this->GetCurrentMaxSpeed());
3234 case AM_REALISTIC:
3235 return this->DoUpdateSpeed(this->GetAcceleration(), this->GetAccelerationStatus() == AS_BRAKE ? 0 : 2, this->GetCurrentMaxSpeed());
3240 * Trains enters a station, send out a news item if it is the first train, and start loading.
3241 * @param v Train that entered the station.
3242 * @param station Station visited.
3244 static void TrainEnterStation(Train *v, StationID station)
3246 v->last_station_visited = station;
3248 /* check if a train ever visited this station before */
3249 Station *st = Station::Get(station);
3250 if (!(st->had_vehicle_of_type & HVOT_TRAIN)) {
3251 st->had_vehicle_of_type |= HVOT_TRAIN;
3252 SetDParam(0, st->index);
3253 AddVehicleNewsItem(
3254 STR_NEWS_FIRST_TRAIN_ARRIVAL,
3255 v->owner == _local_company ? NT_ARRIVAL_COMPANY : NT_ARRIVAL_OTHER,
3256 v->index,
3257 st->index
3259 AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
3260 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
3263 v->force_proceed = TFP_NONE;
3264 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
3266 v->BeginLoading();
3268 TriggerStationRandomisation(st, v->tile, SRT_TRAIN_ARRIVES);
3269 TriggerStationAnimation(st, v->tile, SAT_TRAIN_ARRIVES);
3272 /* Check if the vehicle is compatible with the specified tile */
3273 static inline bool CheckCompatibleRail(const Train *v, TileIndex tile)
3275 return IsTileOwner(tile, v->owner) &&
3276 (!v->IsFrontEngine() || HasBit(v->compatible_railtypes, GetRailType(tile)));
3279 /** Data structure for storing engine speed changes of an acceleration type. */
3280 struct AccelerationSlowdownParams {
3281 byte small_turn; ///< Speed change due to a small turn.
3282 byte large_turn; ///< Speed change due to a large turn.
3283 byte z_up; ///< Fraction to remove when moving up.
3284 byte z_down; ///< Fraction to add when moving down.
3287 /** Speed update fractions for each acceleration type. */
3288 static const AccelerationSlowdownParams _accel_slowdown[] = {
3289 /* normal accel */
3290 {256 / 4, 256 / 2, 256 / 4, 2}, ///< normal
3291 {256 / 4, 256 / 2, 256 / 4, 2}, ///< monorail
3292 {0, 256 / 2, 256 / 4, 2}, ///< maglev
3296 * Modify the speed of the vehicle due to a change in altitude.
3297 * @param v %Train to update.
3298 * @param old_z Previous height.
3300 static inline void AffectSpeedByZChange(Train *v, int old_z)
3302 if (old_z == v->z_pos || _settings_game.vehicle.train_acceleration_model != AM_ORIGINAL) return;
3304 const AccelerationSlowdownParams *asp = &_accel_slowdown[GetRailTypeInfo(v->railtype)->acceleration_type];
3306 if (old_z < v->z_pos) {
3307 v->cur_speed -= (v->cur_speed * asp->z_up >> 8);
3308 } else {
3309 uint16 spd = v->cur_speed + asp->z_down;
3310 if (spd <= v->gcache.cached_max_track_speed) v->cur_speed = spd;
3314 enum TrainMovedChangeSignalEnum {
3315 CHANGED_NOTHING, ///< No special signals were changed
3316 CHANGED_NORMAL_TO_PBS_BLOCK, ///< A PBS block with a non-PBS signal facing us
3317 CHANGED_LR_PBS ///< A long reserve PBS signal
3320 static TrainMovedChangeSignalEnum TrainMovedChangeSignal(Train* v, TileIndex tile, DiagDirection dir)
3322 if (IsTileType(tile, MP_RAILWAY) &&
3323 GetRailTileType(tile) == RAIL_TILE_SIGNALS) {
3324 TrackdirBits tracks = TrackBitsToTrackdirBits(GetTrackBits(tile)) & DiagdirReachesTrackdirs(dir);
3325 Trackdir trackdir = FindFirstTrackdir(tracks);
3326 if (UpdateSignalsOnSegment(tile, TrackdirToExitdir(trackdir), GetTileOwner(tile)) == SIGSEG_PBS && HasSignalOnTrackdir(tile, trackdir)) {
3327 /* A PBS block with a non-PBS signal facing us? */
3328 if (!IsPbsSignal(GetSignalType(tile, TrackdirToTrack(trackdir)))) return CHANGED_NORMAL_TO_PBS_BLOCK;
3330 if (HasLongReservePbsSignalOnTrackdir(v, tile, trackdir)) return CHANGED_LR_PBS;
3334 if (IsTileType(tile, MP_TUNNELBRIDGE) && IsTunnelBridgeSignalSimulationExit(tile) && GetTunnelBridgeDirection(tile) == ReverseDiagDir(dir)) {
3335 if (UpdateSignalsOnSegment(tile, dir, GetTileOwner(tile)) == SIGSEG_PBS) {
3336 return CHANGED_NORMAL_TO_PBS_BLOCK;
3340 return CHANGED_NOTHING;
3343 /** Tries to reserve track under whole train consist. */
3344 void Train::ReserveTrackUnderConsist() const
3346 for (const Train *u = this; u != nullptr; u = u->Next()) {
3347 switch (u->track) {
3348 case TRACK_BIT_WORMHOLE:
3349 TryReserveRailTrack(u->tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(u->tile)));
3350 break;
3351 case TRACK_BIT_DEPOT:
3352 break;
3353 default:
3354 TryReserveRailTrack(u->tile, TrackBitsToTrack(u->track));
3355 break;
3361 * The train vehicle crashed!
3362 * Update its status and other parts around it.
3363 * @param flooded Crash was caused by flooding.
3364 * @return Number of people killed.
3366 uint Train::Crash(bool flooded)
3368 uint pass = 0;
3369 if (this->IsFrontEngine()) {
3370 pass += 2; // driver
3372 /* Remove the reserved path in front of the train if it is not stuck.
3373 * Also clear all reserved tracks the train is currently on. */
3374 if (!HasBit(this->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(this);
3375 for (const Train *v = this; v != nullptr; v = v->Next()) {
3376 ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
3377 if (IsTileType(v->tile, MP_TUNNELBRIDGE)) {
3378 /* ClearPathReservation will not free the wormhole exit
3379 * if the train has just entered the wormhole. */
3380 UnreserveBridgeTunnelTile(GetOtherTunnelBridgeEnd(v->tile));
3384 /* we may need to update crossing we were approaching,
3385 * but must be updated after the train has been marked crashed */
3386 TileIndex crossing = TrainApproachingCrossingTile(this);
3387 if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
3389 /* Remove the loading indicators (if any) */
3390 HideFillingPercent(&this->fill_percent_te_id);
3393 pass += this->GroundVehicleBase::Crash(flooded);
3395 this->crash_anim_pos = flooded ? 4000 : 1; // max 4440, disappear pretty fast when flooded
3396 return pass;
3400 * Marks train as crashed and creates an AI event.
3401 * Doesn't do anything if the train is crashed already.
3402 * @param v first vehicle of chain
3403 * @return number of victims (including 2 drivers; zero if train was already crashed)
3405 static uint TrainCrashed(Train *v)
3407 uint num = 0;
3409 /* do not crash train twice */
3410 if (!(v->vehstatus & VS_CRASHED)) {
3411 num = v->Crash();
3412 AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
3413 Game::NewEvent(new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
3416 /* Try to re-reserve track under already crashed train too.
3417 * Crash() clears the reservation! */
3418 v->ReserveTrackUnderConsist();
3420 return num;
3423 /** Temporary data storage for testing collisions. */
3424 struct TrainCollideChecker {
3425 Train *v; ///< %Vehicle we are testing for collision.
3426 uint num; ///< Total number of victims if train collided.
3430 * Collision test function.
3431 * @param v %Train vehicle to test collision with.
3432 * @param data %Train being examined.
3433 * @return \c nullptr (always continue search)
3435 static Vehicle *FindTrainCollideEnum(Vehicle *v, void *data)
3437 TrainCollideChecker *tcc = (TrainCollideChecker*)data;
3439 /* not a train or in depot */
3440 if (v->type != VEH_TRAIN || Train::From(v)->track == TRACK_BIT_DEPOT) return nullptr;
3442 /* do not crash into trains of another company. */
3443 if (v->owner != tcc->v->owner) return nullptr;
3445 /* get first vehicle now to make most usual checks faster */
3446 Train *coll = Train::From(v)->First();
3448 /* can't collide with own wagons */
3449 if (coll == tcc->v) return nullptr;
3451 int x_diff = v->x_pos - tcc->v->x_pos;
3452 int y_diff = v->y_pos - tcc->v->y_pos;
3454 /* Do fast calculation to check whether trains are not in close vicinity
3455 * and quickly reject trains distant enough for any collision.
3456 * Differences are shifted by 7, mapping range [-7 .. 8] into [0 .. 15]
3457 * Differences are then ORed and then we check for any higher bits */
3458 uint hash = (y_diff + 7) | (x_diff + 7);
3459 if (hash & ~15) return nullptr;
3461 /* Slower check using multiplication */
3462 int min_diff = (Train::From(v)->gcache.cached_veh_length + 1) / 2 + (tcc->v->gcache.cached_veh_length + 1) / 2 - 1;
3463 if (x_diff * x_diff + y_diff * y_diff >= min_diff * min_diff) return nullptr;
3465 /* Happens when there is a train under bridge next to bridge head */
3466 if (abs(v->z_pos - tcc->v->z_pos) > 5) return nullptr;
3468 /* crash both trains */
3469 tcc->num += TrainCrashed(tcc->v);
3470 tcc->num += TrainCrashed(coll);
3472 return nullptr; // continue searching
3476 * Checks whether the specified train has a collision with another vehicle. If
3477 * so, destroys this vehicle, and the other vehicle if its subtype has TS_Front.
3478 * Reports the incident in a flashy news item, modifies station ratings and
3479 * plays a sound.
3480 * @param v %Train to test.
3482 static bool CheckTrainCollision(Train *v)
3484 /* can't collide in depot */
3485 if (v->track == TRACK_BIT_DEPOT) return false;
3487 assert(v->track == TRACK_BIT_WORMHOLE || TileVirtXY(v->x_pos, v->y_pos) == v->tile);
3489 TrainCollideChecker tcc;
3490 tcc.v = v;
3491 tcc.num = 0;
3493 /* find colliding vehicles */
3494 if (v->track == TRACK_BIT_WORMHOLE) {
3495 FindVehicleOnPos(v->tile, &tcc, FindTrainCollideEnum);
3496 FindVehicleOnPos(GetOtherTunnelBridgeEnd(v->tile), &tcc, FindTrainCollideEnum);
3497 } else {
3498 FindVehicleOnPosXY(v->x_pos, v->y_pos, &tcc, FindTrainCollideEnum);
3501 /* any dead -> no crash */
3502 if (tcc.num == 0) return false;
3504 SetDParam(0, tcc.num);
3505 AddVehicleNewsItem(STR_NEWS_TRAIN_CRASH, NT_ACCIDENT, v->index);
3507 ModifyStationRatingAround(v->tile, v->owner, -160, 30);
3508 if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_13_BIG_CRASH, v);
3509 return true;
3512 static Vehicle *CheckTrainAtSignal(Vehicle *v, void *data)
3514 if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return nullptr;
3516 Train *t = Train::From(v);
3517 DiagDirection exitdir = *(DiagDirection *)data;
3519 /* not front engine of a train, inside wormhole or depot, crashed */
3520 if (!t->IsFrontEngine() || !(t->track & TRACK_BIT_MASK)) return nullptr;
3522 if (t->cur_speed > 5 || TrainExitDir(t->direction, t->track) != exitdir) return nullptr;
3524 return t;
3527 struct FindSpaceBetweenTrainsChecker {
3528 int32 pos;
3529 uint16 distance;
3530 DirectionByte direction;
3533 /** Find train in front and keep distance between trains in tunnel/bridge. */
3534 static Vehicle *FindSpaceBetweenTrainsEnum(Vehicle *v, void *data)
3536 /* Don't look at wagons between front and back of train. */
3537 if (v->type != VEH_TRAIN || (v->Previous() != nullptr && v->Next() != nullptr)) return nullptr;
3539 const FindSpaceBetweenTrainsChecker *checker = (FindSpaceBetweenTrainsChecker*)data;
3540 int32 a, b = 0;
3542 switch (checker->direction) {
3543 default: NOT_REACHED();
3544 case DIR_NE: a = checker->pos; b = v->x_pos; break;
3545 case DIR_SE: a = v->y_pos; b = checker->pos; break;
3546 case DIR_SW: a = v->x_pos; b = checker->pos; break;
3547 case DIR_NW: a = checker->pos; b = v->y_pos; break;
3550 if (a > b && a <= (b + (int)(checker->distance)) + (int)(TILE_SIZE)-1) return v;
3551 return nullptr;
3554 static bool IsTooCloseBehindTrain(Vehicle *v, TileIndex tile, uint16 distance, bool check_endtile)
3556 Train *t = Train::From(v);
3558 if (t->force_proceed != 0) return false;
3560 FindSpaceBetweenTrainsChecker checker;
3561 checker.distance = distance;
3562 checker.direction = t->direction;
3563 switch (checker.direction) {
3564 default: NOT_REACHED();
3565 case DIR_NE: checker.pos = (TileX(tile) * TILE_SIZE) + TILE_UNIT_MASK; break;
3566 case DIR_SE: checker.pos = (TileY(tile) * TILE_SIZE); break;
3567 case DIR_SW: checker.pos = (TileX(tile) * TILE_SIZE); break;
3568 case DIR_NW: checker.pos = (TileY(tile) * TILE_SIZE) + TILE_UNIT_MASK; break;
3571 if (HasVehicleOnPos(t->tile, &checker, &FindSpaceBetweenTrainsEnum)) {
3572 /* Revert train if not going with tunnel direction. */
3573 if (DirToDiagDir(t->direction) != GetTunnelBridgeDirection(t->tile)) {
3574 SetBit(t->flags, VRF_REVERSING);
3576 return true;
3578 /* Cover blind spot at end of tunnel bridge. */
3579 if (check_endtile){
3580 if (HasVehicleOnPos(GetOtherTunnelBridgeEnd(t->tile), &checker, &FindSpaceBetweenTrainsEnum)) {
3581 /* Revert train if not going with tunnel direction. */
3582 if (DirToDiagDir(t->direction) != GetTunnelBridgeDirection(t->tile)) {
3583 SetBit(t->flags, VRF_REVERSING);
3585 return true;
3589 return false;
3592 static bool CheckTrainStayInWormHolePathReserve(Train *t, TileIndex tile)
3594 TileIndex veh_orig = t->tile;
3595 t->tile = tile;
3596 CFollowTrackRail ft(GetTileOwner(tile), GetRailTypeInfo(t->railtype)->compatible_railtypes);
3597 if (ft.Follow(tile, DiagDirToDiagTrackdir(ReverseDiagDir(GetTunnelBridgeDirection(tile))))) {
3598 TrackdirBits reserved = ft.m_new_td_bits & TrackBitsToTrackdirBits(GetReservedTrackbits(ft.m_new_tile));
3599 if (reserved == TRACKDIR_BIT_NONE) {
3600 /* next tile is not reserved, so reserve the exit tile */
3601 SetTunnelBridgeReservation(tile, true);
3604 bool ok = TryPathReserve(t);
3605 t->tile = veh_orig;
3606 if (ok && IsTunnelBridgePBS(tile)) SetTunnelBridgeSignalState(tile, SIGNAL_STATE_GREEN);
3607 return ok;
3610 /** Simulate signals in tunnel - bridge. */
3611 static bool CheckTrainStayInWormHole(Train *t, TileIndex tile)
3613 if (t->force_proceed != 0) return false;
3615 /* When not exit reverse train. */
3616 if (!IsTunnelBridgeSignalSimulationExit(tile)) {
3617 SetBit(t->flags, VRF_REVERSING);
3618 return true;
3620 SigSegState seg_state = (_settings_game.pf.reserve_paths || IsTunnelBridgePBS(tile)) ? SIGSEG_PBS : UpdateSignalsOnSegment(tile, INVALID_DIAGDIR, t->owner);
3621 if (seg_state != SIGSEG_PBS) {
3622 CFollowTrackRail ft(GetTileOwner(tile), GetRailTypeInfo(t->railtype)->compatible_railtypes);
3623 if (ft.Follow(tile, DiagDirToDiagTrackdir(ReverseDiagDir(GetTunnelBridgeDirection(tile))))) {
3624 if (ft.m_new_td_bits != TRACKDIR_BIT_NONE && KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
3625 Trackdir td = FindFirstTrackdir(ft.m_new_td_bits);
3626 if (HasPbsSignalOnTrackdir(ft.m_new_tile, td)) {
3627 /* immediately after the exit, there is a PBS signal, switch to PBS mode */
3628 seg_state = SIGSEG_PBS;
3633 if (seg_state == SIGSEG_FULL || (seg_state == SIGSEG_PBS && !CheckTrainStayInWormHolePathReserve(t, tile))) {
3634 t->vehstatus |= VS_TRAIN_SLOWING;
3635 return true;
3638 return false;
3641 static void HandleSignalBehindTrain(Train *v, int signal_number)
3643 TileIndex tile;
3644 switch (v->direction) {
3645 default: NOT_REACHED();
3646 case DIR_NE: tile = TileVirtXY(v->x_pos + (TILE_SIZE * _settings_game.construction.simulated_wormhole_signals), v->y_pos); break;
3647 case DIR_SE: tile = TileVirtXY(v->x_pos, v->y_pos - (TILE_SIZE * _settings_game.construction.simulated_wormhole_signals) ); break;
3648 case DIR_SW: tile = TileVirtXY(v->x_pos - (TILE_SIZE * _settings_game.construction.simulated_wormhole_signals), v->y_pos); break;
3649 case DIR_NW: tile = TileVirtXY(v->x_pos, v->y_pos + (TILE_SIZE * _settings_game.construction.simulated_wormhole_signals)); break;
3652 if(tile == v->tile) {
3653 /* Flip signal on ramp. */
3654 if (IsTunnelBridgeSignalSimulationEntrance(tile) && GetTunnelBridgeSignalState(tile) == SIGNAL_STATE_RED) {
3655 SetTunnelBridgeSignalState(tile, SIGNAL_STATE_GREEN);
3656 MarkTileDirtyByTile(tile);
3658 } else if (IsBridge(v->tile) && signal_number >= 0) {
3659 SetBridgeEntranceSimulatedSignalState(v->tile, signal_number, SIGNAL_STATE_GREEN);
3660 MarkTileDirtyByTile(tile);
3664 static inline void IncreaseTrackUsage(TileIndex ti, Track track_piece)
3666 if (!IsTileType(ti, MP_RAILWAY))
3667 return;
3668 if (!IsPlainRailTile(ti))
3669 return;
3671 /* ignore track_piece, 1 state per tile */
3672 byte age = GetRailAge(ti);
3674 static byte train_clean_strength = 32;
3676 if (age <= train_clean_strength)
3677 age = 0;
3678 else
3679 age -= train_clean_strength;
3681 byte old_growth = GetTrackGrowthPhase(ti);
3683 SetRailAge(ti, age);
3685 /* If rounded growth amount changes, redraw */
3686 if (GetTrackGrowthPhase(ti) != old_growth)
3687 MarkTileDirtyByTile(ti);
3690 uint16 ReversingDistanceTargetSpeed(const Train *v)
3692 int target_speed;
3693 if (_settings_game.vehicle.train_acceleration_model == AM_REALISTIC) {
3694 target_speed = ((v->reverse_distance - 1) * 5) / 2;
3696 else {
3697 target_speed = (v->reverse_distance - 1) * 10 - 5;
3699 return max(0, target_speed);
3703 * Move a vehicle chain one movement stop forwards.
3704 * @param v First vehicle to move.
3705 * @param nomove Stop moving this and all following vehicles.
3706 * @param reverse Set to false to not execute the vehicle reversing. This does not change any other logic.
3707 * @return True if the vehicle could be moved forward, false otherwise.
3709 bool TrainController(Train *v, Vehicle *nomove, bool reverse)
3711 Train *first = v->First();
3712 Train *prev;
3713 bool direction_changed = false; // has direction of any part changed?
3715 if (reverse && v->reverse_distance == 1) {
3716 goto reverse_train_direction;
3719 if (v->reverse_distance > 1) {
3720 uint16 spd = ReversingDistanceTargetSpeed(v);
3721 if (spd < v->cur_speed) v->cur_speed = spd;
3724 /* For every vehicle after and including the given vehicle */
3725 for (prev = v->Previous(); v != nomove; prev = v, v = v->Next()) {
3726 DiagDirection enterdir = DIAGDIR_BEGIN;
3727 bool update_signals_crossing = false; // will we update signals or crossing state?
3729 GetNewVehiclePosResult gp = GetNewVehiclePos(v);
3730 if (v->track != TRACK_BIT_WORMHOLE) {
3731 /* Not inside tunnel */
3732 if (gp.old_tile == gp.new_tile) {
3733 /* Staying in the old tile */
3734 if (v->track == TRACK_BIT_DEPOT) {
3735 /* Inside depot */
3736 gp.x = v->x_pos;
3737 gp.y = v->y_pos;
3738 v->reverse_distance = 0;
3739 } else {
3740 /* Not inside depot */
3742 /* Reverse when we are at the end of the track already, do not move to the new position */
3743 if (v->IsFrontEngine() && !TrainCheckIfLineEnds(v, reverse)) return false;
3745 uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
3746 if (HasBit(r, VETS_CANNOT_ENTER)) {
3747 goto invalid_rail;
3749 if (HasBit(r, VETS_ENTERED_STATION)) {
3750 /* The new position is the end of the platform */
3751 TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
3754 } else {
3755 /* A new tile is about to be entered. */
3757 /* Determine what direction we're entering the new tile from */
3758 enterdir = DiagdirBetweenTiles(gp.old_tile, gp.new_tile);
3759 assert(IsValidDiagDirection(enterdir));
3761 /* Get the status of the tracks in the new tile and mask
3762 * away the bits that aren't reachable. */
3763 TrackStatus ts = GetTileTrackStatus(gp.new_tile, TRANSPORT_RAIL, 0, ReverseDiagDir(enterdir));
3764 TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(enterdir);
3766 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
3767 TrackBits red_signals = TrackdirBitsToTrackBits(TrackStatusToRedSignals(ts) & reachable_trackdirs);
3769 TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
3770 if (_settings_game.pf.forbid_90_deg && prev == nullptr) {
3771 /* We allow wagons to make 90 deg turns, because forbid_90_deg
3772 * can be switched on halfway a turn */
3773 bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
3776 if (bits == TRACK_BIT_NONE)
3777 goto invalid_rail;
3779 /* Check if the new tile constrains tracks that are compatible
3780 * with the current train, if not, bail out. */
3781 if (!CheckCompatibleRail(v, gp.new_tile))
3782 goto invalid_rail;
3784 TrackBits chosen_track;
3785 if (prev == nullptr) {
3786 /* Currently the locomotive is active. Determine which one of the
3787 * available tracks to choos/// e */
3788 Track chosen_track_num = ChooseTrainTrack(v, gp.new_tile, enterdir, bits, false, nullptr, true);
3789 chosen_track = TrackToTrackBits(chosen_track_num);
3790 assert(chosen_track & (bits | GetReservedTrackbits(gp.new_tile)));
3792 if (v->force_proceed != TFP_NONE && IsPlainRailTile(gp.new_tile) && HasSignals(gp.new_tile)) {
3793 /* For each signal we find decrease the counter by one.
3794 * We start at two, so the first signal we pass decreases
3795 * this to one, then if we reach the next signal it is
3796 * decreased to zero and we won't pass that new signal. */
3797 Trackdir dir = FindFirstTrackdir(trackdirbits);
3798 if (HasSignalOnTrackdir(gp.new_tile, dir) ||
3799 (HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(dir)) &&
3800 GetSignalType(gp.new_tile, TrackdirToTrack(dir)) != SIGTYPE_PBS)) {
3801 /* However, we do not want to be stopped by PBS signals
3802 * entered via the back. */
3803 v->force_proceed = (v->force_proceed == TFP_SIGNAL) ? TFP_STUCK : TFP_NONE;
3804 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
3808 /* Check if it's a red signal and that force proceed is not clicked. */
3809 if ((red_signals & chosen_track) && v->force_proceed == TFP_NONE) {
3810 /* In front of a red signal */
3811 Trackdir i = FindFirstTrackdir(trackdirbits);
3813 /* Don't handle stuck trains here. */
3814 if (HasBit(v->flags, VRF_TRAIN_STUCK)) return false;
3816 if (!HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(i))) {
3817 v->cur_speed = 0;
3818 v->subspeed = 0;
3819 v->progress = 255 - 100;
3820 if (!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_oneway_signal * 20) return false;
3821 } else if (HasSignalOnTrackdir(gp.new_tile, i)) {
3822 v->cur_speed = 0;
3823 v->subspeed = 0;
3824 v->progress = 255 - 10;
3825 if (!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_twoway_signal * 73) {
3826 DiagDirection exitdir = TrackdirToExitdir(i);
3827 TileIndex o_tile = TileAddByDiagDir(gp.new_tile, exitdir);
3829 exitdir = ReverseDiagDir(exitdir);
3831 /* check if a train is waiting on the other side */
3832 if (!HasVehicleOnPos(o_tile, &exitdir, &CheckTrainAtSignal)) return false;
3836 /* If we would reverse but are currently in a PBS block and
3837 * reversing of stuck trains is disabled, don't reverse.
3838 * This does not apply if the reason for reversing is a one-way
3839 * signal blocking us, because a train would then be stuck forever. */
3840 if (!_settings_game.pf.reverse_at_signals && !HasOnewaySignalBlockingTrackdir(gp.new_tile, i) &&
3841 UpdateSignalsOnSegment(v->tile, enterdir, v->owner) == SIGSEG_PBS) {
3842 v->wait_counter = 0;
3843 return false;
3845 goto reverse_train_direction;
3846 } else {
3847 TryReserveRailTrack(gp.new_tile, TrackBitsToTrack(chosen_track), false);
3849 if (IsPlainRailTile(gp.new_tile) && HasSignals(gp.new_tile) && IsRestrictedSignal(gp.new_tile)) {
3850 const Trackdir dir = FindFirstTrackdir(trackdirbits);
3851 if (HasSignalOnTrack(gp.new_tile, TrackdirToTrack(dir))) {
3852 const TraceRestrictProgram *prog = GetExistingTraceRestrictProgram(gp.new_tile, TrackdirToTrack(dir));
3853 if (prog && prog->actions_used_flags & (TRPAUF_SLOT_ACQUIRE | TRPAUF_SLOT_RELEASE_FRONT)) {
3854 TraceRestrictProgramResult out;
3855 TraceRestrictProgramInput input(gp.new_tile, dir, nullptr, nullptr);
3856 input.permitted_slot_operations = TRPISP_ACQUIRE | TRPISP_RELEASE_FRONT;
3857 prog->Execute(v, input, out);
3862 IncreaseTrackUsage(gp.new_tile, chosen_track_num);
3863 } else {
3864 /* The wagon is active, simply follow the prev vehicle. */
3865 if (prev->tile == gp.new_tile) {
3866 /* Choose the same track as prev */
3867 if (prev->track == TRACK_BIT_WORMHOLE) {
3868 /* Vehicles entering tunnels enter the wormhole earlier than for bridges.
3869 * However, just choose the track into the wormhole. */
3870 assert(IsTunnel(prev->tile));
3871 chosen_track = bits;
3872 } else {
3873 chosen_track = prev->track;
3875 } else {
3876 /* Choose the track that leads to the tile where prev is.
3877 * This case is active if 'prev' is already on the second next tile, when 'v' just enters the next tile.
3878 * I.e. when the tile between them has only space for a single vehicle like
3879 * 1) horizontal/vertical track tiles and
3880 * 2) some orientations of tunnel entries, where the vehicle is already inside the wormhole at 8/16 from the tile edge.
3881 * Is also the train just reversing, the wagon inside the tunnel is 'on' the tile of the opposite tunnel entry.
3883 static const TrackBits _connecting_track[DIAGDIR_END][DIAGDIR_END] = {
3884 {TRACK_BIT_X, TRACK_BIT_LOWER, TRACK_BIT_NONE, TRACK_BIT_LEFT },
3885 {TRACK_BIT_UPPER, TRACK_BIT_Y, TRACK_BIT_LEFT, TRACK_BIT_NONE },
3886 {TRACK_BIT_NONE, TRACK_BIT_RIGHT, TRACK_BIT_X, TRACK_BIT_UPPER},
3887 {TRACK_BIT_RIGHT, TRACK_BIT_NONE, TRACK_BIT_LOWER, TRACK_BIT_Y }
3889 DiagDirection exitdir = DiagdirBetweenTiles(gp.new_tile, prev->tile);
3890 assert(IsValidDiagDirection(exitdir));
3891 chosen_track = _connecting_track[enterdir][exitdir];
3893 chosen_track &= bits;
3896 /* Make sure chosen track is a valid track */
3897 assert(
3898 chosen_track == TRACK_BIT_X || chosen_track == TRACK_BIT_Y ||
3899 chosen_track == TRACK_BIT_UPPER || chosen_track == TRACK_BIT_LOWER ||
3900 chosen_track == TRACK_BIT_LEFT || chosen_track == TRACK_BIT_RIGHT);
3902 /* Update XY to reflect the entrance to the new tile, and select the direction to use */
3903 const byte *b = _initial_tile_subcoord[FIND_FIRST_BIT(chosen_track)][enterdir];
3904 gp.x = (gp.x & ~0xF) | b[0];
3905 gp.y = (gp.y & ~0xF) | b[1];
3906 Direction chosen_dir = (Direction)b[2];
3908 /* Call the landscape function and tell it that the vehicle entered the tile */
3909 uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
3910 if (HasBit(r, VETS_CANNOT_ENTER)) {
3911 goto invalid_rail;
3914 if (IsTunnelBridgeWithSignalSimulation(gp.new_tile)) {
3915 /* If red signal stop. */
3916 if (v->IsFrontEngine() && v->force_proceed == 0) {
3917 if (IsTunnelBridgeSignalSimulationEntrance(gp.new_tile) && GetTunnelBridgeSignalState(gp.new_tile) == SIGNAL_STATE_RED) {
3918 v->cur_speed = 0;
3919 v->vehstatus |= VS_TRAIN_SLOWING;
3920 return false;
3922 if (IsTunnelBridgeSignalSimulationExit(gp.new_tile)) {
3923 v->cur_speed = 0;
3924 goto invalid_rail;
3926 /* Flip signal on tunnel entrance tile red. */
3927 SetTunnelBridgeSignalState(gp.new_tile, SIGNAL_STATE_RED);
3928 MarkTileDirtyByTile(gp.new_tile);
3932 if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
3933 Track track = FindFirstTrack(chosen_track);
3934 Trackdir tdir = TrackDirectionToTrackdir(track, chosen_dir);
3935 if (v->IsFrontEngine() && HasPbsSignalOnTrackdir(gp.new_tile, tdir)) {
3936 SetSignalStateByTrackdir(gp.new_tile, tdir, SIGNAL_STATE_RED);
3937 MarkTileDirtyByTile(gp.new_tile);
3939 /* notify logic signals of the state change */
3940 SignalStateChanged(gp.new_tile, TrackdirToTrack(tdir), 1);
3943 /* Clear any track reservation when the last vehicle leaves the tile */
3944 if (v->Next() == nullptr) ClearPathReservation(v, v->tile, v->GetVehicleTrackdir(), true);
3946 v->tile = gp.new_tile;
3948 if (GetTileRailType(gp.new_tile) != GetTileRailType(gp.old_tile)) {
3949 v->First()->ConsistChanged(CCF_TRACK);
3952 v->track = chosen_track;
3953 assert(v->track);
3956 /* We need to update signal status, but after the vehicle position hash
3957 * has been updated by UpdateInclination() */
3958 update_signals_crossing = true;
3960 if (chosen_dir != v->direction) {
3961 if (prev == nullptr && _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) {
3962 const AccelerationSlowdownParams *asp = &_accel_slowdown[GetRailTypeInfo(v->railtype)->acceleration_type];
3963 DirDiff diff = DirDifference(v->direction, chosen_dir);
3964 v->cur_speed -= (diff == DIRDIFF_45RIGHT || diff == DIRDIFF_45LEFT ? asp->small_turn : asp->large_turn) * v->cur_speed >> 8;
3966 direction_changed = true;
3967 v->direction = chosen_dir;
3970 if (v->IsFrontEngine()) {
3971 v->wait_counter = 0;
3973 /* If we are approaching a crossing that is reserved, play the sound now. */
3974 TileIndex crossing = TrainApproachingCrossingTile(v);
3976 if (crossing != INVALID_TILE)
3978 RailTypeLabel railTypeLabel = GetRailTypeInfo(GetTileRailType(crossing))->label;
3979 bool is_no_sound_rail_type = (railTypeLabel == _planning_tracks_label || railTypeLabel == _pipeline_tracks_label || railTypeLabel == _wires_tracks_label);
3981 if (HasCrossingReservation(crossing) && _settings_client.sound.ambient && !is_no_sound_rail_type)
3982 SndPlayTileFx(SND_0E_LEVEL_CROSSING, crossing);
3985 /* Always try to extend the reservation when entering a tile. */
3986 CheckNextTrainTile(v);
3989 if (HasBit(r, VETS_ENTERED_STATION)) {
3990 /* The new position is the location where we want to stop */
3991 TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
3994 } else {
3995 /* Handle signal simulation on tunnel/bridge. */
3996 TileIndex old_tile = TileVirtXY(v->x_pos, v->y_pos);
3997 if (old_tile != gp.new_tile && IsTunnelBridgeWithSignalSimulation(v->tile) && (v->IsFrontEngine() || v->Next() == nullptr)) {
3998 if (old_tile == v->tile) {
3999 if (v->IsFrontEngine() && v->force_proceed == 0 && IsTunnelBridgeSignalSimulationExit(v->tile))
4000 goto invalid_rail;
4001 /* Entered wormhole set counters. */
4002 v->wait_counter = (TILE_SIZE * _settings_game.construction.simulated_wormhole_signals) - TILE_SIZE;
4003 v->tunnel_bridge_signal_num = 0;
4006 uint distance = v->wait_counter;
4007 bool leaving = false;
4008 if (distance == 0) v->wait_counter = (TILE_SIZE * _settings_game.construction.simulated_wormhole_signals);
4010 if (v->IsFrontEngine()) {
4011 /* Check if track in front is free and see if we can leave wormhole. */
4012 int z = GetSlopePixelZ(gp.x, gp.y) - v->z_pos;
4013 if (IsTileType(gp.new_tile, MP_TUNNELBRIDGE) && !(abs(z) > 2)) {
4014 if (CheckTrainStayInWormHole(v, gp.new_tile)) {
4015 v->cur_speed = 0;
4016 return false;
4018 leaving = true;
4019 } else {
4020 if (IsTooCloseBehindTrain(v, gp.new_tile, v->wait_counter, distance == 0)) {
4021 if (distance == 0) v->wait_counter = 0;
4022 v->cur_speed = 0;
4023 v->vehstatus |= VS_TRAIN_SLOWING;
4024 return false;
4026 /* flip signal in front to red on bridges*/
4027 if (distance == 0 && IsBridge(v->tile)) {
4028 SetBridgeEntranceSimulatedSignalState(v->tile, v->tunnel_bridge_signal_num, SIGNAL_STATE_RED);
4029 MarkTileDirtyByTile(gp.new_tile);
4033 if (v->Next() == nullptr) {
4034 if (v->tunnel_bridge_signal_num > 0 && distance == (TILE_SIZE * _settings_game.construction.simulated_wormhole_signals) - TILE_SIZE) HandleSignalBehindTrain(v, v->load_unload_ticks - 2);
4035 if (old_tile == v->tile) {
4036 /* We left ramp into wormhole. */
4037 v->x_pos = gp.x;
4038 v->y_pos = gp.y;
4039 UpdateSignalsOnSegment(old_tile, INVALID_DIAGDIR, v->owner);
4040 UnreserveBridgeTunnelTile(old_tile);
4041 if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(old_tile);
4044 if (distance == 0) v->tunnel_bridge_signal_num++;
4045 v->wait_counter -= TILE_SIZE;
4047 if (leaving) { // Reset counters.
4048 v->force_proceed = 0;
4049 v->wait_counter = 0;
4050 v->tunnel_bridge_signal_num = 0;
4051 v->x_pos = gp.x;
4052 v->y_pos = gp.y;
4053 v->UpdatePosition();
4054 v->UpdateViewport(false, false);
4055 UpdateSignalsOnSegment(gp.new_tile, INVALID_DIAGDIR, v->owner);
4056 continue;
4060 if (old_tile == gp.new_tile && IsTunnelBridgeWithSignalSimulation(v->tile) && v->IsFrontEngine()) {
4061 TileIndex next_tile = old_tile + TileOffsByDir(v->direction);
4062 bool is_exit = false;
4063 if (IsTileType(next_tile, MP_TUNNELBRIDGE) && IsTunnelBridgeWithSignalSimulation(next_tile) &&
4064 ReverseDiagDir(GetTunnelBridgeDirection(next_tile)) == DirToDiagDir(v->direction)) {
4065 if (IsBridge(next_tile) && IsBridge(v->tile)) {
4066 // bridge ramp facing towards us
4067 is_exit = true;
4068 } else if (IsTunnel(next_tile) && IsTunnel(v->tile)) {
4069 // tunnel exit at same height
4070 is_exit = (GetTileZ(next_tile) == GetTileZ(v->tile));
4073 if (is_exit) {
4074 if (CheckTrainStayInWormHole(v, next_tile)) {
4075 TrainApproachingLineEnd(v, true, false);
4077 } else if (v->wait_counter == 0) {
4078 if (IsTooCloseBehindTrain(v, next_tile, TILE_SIZE * _settings_game.construction.simulated_wormhole_signals, true)) {
4079 TrainApproachingLineEnd(v, true, false);
4084 if (IsTileType(gp.new_tile, MP_TUNNELBRIDGE) && HasBit(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y), VETS_ENTERED_WORMHOLE)) {
4085 /* Perform look-ahead on tunnel exit. */
4086 if (v->IsFrontEngine()) {
4087 TryReserveRailTrack(gp.new_tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(gp.new_tile)));
4088 CheckNextTrainTile(v);
4090 /* Prevent v->UpdateInclination() being called with wrong parameters.
4091 * This could happen if the train was reversed inside the tunnel/bridge. */
4092 if (gp.old_tile == gp.new_tile) {
4093 gp.old_tile = GetOtherTunnelBridgeEnd(gp.old_tile);
4095 } else {
4096 v->x_pos = gp.x;
4097 v->y_pos = gp.y;
4098 v->UpdatePosition();
4099 if (HasBit(v->gv_flags, GVF_CHUNNEL_BIT)) {
4100 /* update the Z position of the vehicle */
4101 int old_z = v->UpdateInclination(false, false, true);
4103 if (prev == nullptr) {
4104 /* This is the first vehicle in the train */
4105 AffectSpeedByZChange(v, old_z);
4108 if (v->IsDrawn()) v->Vehicle::UpdateViewport(true);
4109 continue;
4113 /* update image of train, as well as delta XY */
4114 v->UpdateDeltaXY(v->direction);
4116 v->x_pos = gp.x;
4117 v->y_pos = gp.y;
4118 v->UpdatePosition();
4119 if (v->reverse_distance > 1) {
4120 v->reverse_distance--;
4123 /* update the Z position of the vehicle */
4124 int old_z = v->UpdateInclination(gp.new_tile != gp.old_tile, false, v->track == TRACK_BIT_WORMHOLE);
4126 if (prev == nullptr) {
4127 /* This is the first vehicle in the train */
4128 AffectSpeedByZChange(v, old_z);
4131 if (update_signals_crossing) {
4132 if (v->IsFrontEngine()) {
4133 switch(TrainMovedChangeSignal(v, gp.new_tile, enterdir)) {
4134 case CHANGED_NORMAL_TO_PBS_BLOCK:
4135 /* We are entering a block with PBS signals right now, but
4136 * not through a PBS signal. This means we don't have a
4137 * reservation right now. As a conventional signal will only
4138 * ever be green if no other train is in the block, getting
4139 * a path should always be possible. If the player built
4140 * such a strange network that it is not possible, the train
4141 * will be marked as stuck and the player has to deal with
4142 * the problem. */
4143 if ((!HasReservedTracks(gp.new_tile, v->track) &&
4144 !TryReserveRailTrack(gp.new_tile, FindFirstTrack(v->track))) ||
4145 !TryPathReserve(v)) {
4146 MarkTrainAsStuck(v);
4149 break;
4150 case CHANGED_LR_PBS:
4152 /* We went past a long reserve PBS signal. Try to extend the
4153 * reservation if reserving failed at another LR signal. */
4154 PBSTileInfo origin = FollowTrainReservation(v);
4155 CFollowTrackRail ft(v);
4157 if (ft.Follow(origin.tile, origin.trackdir)) {
4158 Trackdir new_td = FindFirstTrackdir(ft.m_new_td_bits);
4160 if (HasLongReservePbsSignalOnTrackdir(v, ft.m_new_tile, new_td)) {
4161 ChooseTrainTrack(v, ft.m_new_tile, ft.m_exitdir, TrackdirBitsToTrackBits(ft.m_new_td_bits), true, nullptr, false);
4165 break;
4167 default: break;
4171 /* Signals can only change when the first
4172 * (above) or the last vehicle moves. */
4173 if (v->Next() == nullptr) {
4174 TrainMovedChangeSignal(v, gp.old_tile, ReverseDiagDir(enterdir));
4175 if (IsLevelCrossingTile(gp.old_tile)) UpdateLevelCrossing(gp.old_tile);
4177 if (IsTileType(gp.old_tile, MP_RAILWAY) && HasSignals(gp.old_tile) && IsRestrictedSignal(gp.old_tile)) {
4178 const TrackdirBits rev_tracks = TrackBitsToTrackdirBits(GetTrackBits(gp.old_tile)) & DiagdirReachesTrackdirs(ReverseDiagDir(enterdir));
4179 const Trackdir rev_trackdir = FindFirstTrackdir(rev_tracks);
4180 const Track track = TrackdirToTrack(rev_trackdir);
4181 if (HasSignalOnTrack(gp.old_tile, track)) {
4182 const TraceRestrictProgram *prog = GetExistingTraceRestrictProgram(gp.old_tile, track);
4183 if (prog && prog->actions_used_flags & TRPAUF_SLOT_RELEASE_BACK) {
4184 TraceRestrictProgramResult out;
4185 TraceRestrictProgramInput input(gp.old_tile, ReverseTrackdir(rev_trackdir), nullptr, nullptr);
4186 input.permitted_slot_operations = TRPISP_RELEASE_BACK;
4187 prog->Execute(first, input, out);
4194 /* Do not check on every tick to save some computing time. */
4195 if (v->IsFrontEngine() && v->tick_counter % _settings_game.pf.path_backoff_interval == 0) CheckNextTrainTile(v);
4198 if (direction_changed) first->tcache.cached_max_curve_speed = first->GetCurveSpeedLimit();
4200 return true;
4202 invalid_rail:
4203 /* We've reached end of line?? */
4204 if (prev != nullptr) error("Disconnecting train");
4206 reverse_train_direction:
4207 if (reverse) {
4208 v->wait_counter = 0;
4209 v->cur_speed = 0;
4210 v->subspeed = 0;
4211 ReverseTrainDirection(v);
4214 return false;
4218 * Collect trackbits of all crashed train vehicles on a tile
4219 * @param v Vehicle passed from Find/HasVehicleOnPos()
4220 * @param data trackdirbits for the result
4221 * @return nullptr to iterate over all vehicles on the tile.
4223 static Vehicle *CollectTrackbitsFromCrashedVehiclesEnum(Vehicle *v, void *data)
4225 TrackBits *trackbits = (TrackBits *)data;
4227 if (v->type == VEH_TRAIN && (v->vehstatus & VS_CRASHED) != 0) {
4228 TrackBits train_tbits = Train::From(v)->track;
4229 if (train_tbits == TRACK_BIT_WORMHOLE) {
4230 /* Vehicle is inside a wormhole, v->track contains no useful value then. */
4231 *trackbits |= DiagDirToDiagTrackBits(GetTunnelBridgeDirection(v->tile));
4232 } else if (train_tbits != TRACK_BIT_DEPOT) {
4233 *trackbits |= train_tbits;
4237 return nullptr;
4241 * Deletes/Clears the last wagon of a crashed train. It takes the engine of the
4242 * train, then goes to the last wagon and deletes that. Each call to this function
4243 * will remove the last wagon of a crashed train. If this wagon was on a crossing,
4244 * or inside a tunnel/bridge, recalculate the signals as they might need updating
4245 * @param v the Vehicle of which last wagon is to be removed
4247 static void DeleteLastWagon(Train *v)
4249 Train *first = v->First();
4251 /* Go to the last wagon and delete the link pointing there
4252 * *u is then the one-before-last wagon, and *v the last
4253 * one which will physically be removed */
4254 Train *u = v;
4255 for (; v->Next() != nullptr; v = v->Next()) u = v;
4256 u->SetNext(nullptr);
4258 if (first != v) {
4259 /* Recalculate cached train properties */
4260 first->ConsistChanged(CCF_ARRANGE);
4261 /* Update the depot window if the first vehicle is in depot -
4262 * if v == first, then it is updated in PreDestructor() */
4263 if (first->track == TRACK_BIT_DEPOT) {
4264 SetWindowDirty(WC_VEHICLE_DEPOT, first->tile);
4266 v->last_station_visited = first->last_station_visited; // for PreDestructor
4269 /* 'v' shouldn't be accessed after it has been deleted */
4270 TrackBits trackbits = v->track;
4271 TileIndex tile = v->tile;
4272 Owner owner = v->owner;
4274 delete v;
4275 v = nullptr; // make sure nobody will try to read 'v' anymore
4277 if (trackbits == TRACK_BIT_WORMHOLE) {
4278 /* Vehicle is inside a wormhole, v->track contains no useful value then. */
4279 trackbits = DiagDirToDiagTrackBits(GetTunnelBridgeDirection(tile));
4282 Track track = TrackBitsToTrack(trackbits);
4283 if (HasReservedTracks(tile, trackbits)) {
4284 UnreserveRailTrack(tile, track);
4286 /* If there are still crashed vehicles on the tile, give the track reservation to them */
4287 TrackBits remaining_trackbits = TRACK_BIT_NONE;
4288 FindVehicleOnPos(tile, &remaining_trackbits, CollectTrackbitsFromCrashedVehiclesEnum);
4290 /* It is important that these two are the first in the loop, as reservation cannot deal with every trackbit combination */
4291 assert(TRACK_BEGIN == TRACK_X && TRACK_Y == TRACK_BEGIN + 1);
4292 Track t;
4293 FOR_EACH_SET_TRACK(t, remaining_trackbits) TryReserveRailTrack(tile, t);
4296 /* check if the wagon was on a road/rail-crossing */
4297 if (IsLevelCrossingTile(tile)) UpdateLevelCrossing(tile);
4299 /* Update signals */
4300 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
4301 UpdateSignalsOnSegment(tile, INVALID_DIAGDIR, owner);
4302 if (IsTunnelBridgeWithSignalSimulation(tile)) {
4303 TileIndex end = GetOtherTunnelBridgeEnd(tile);
4304 UpdateSignalsOnSegment(end, INVALID_DIAGDIR, owner);
4305 bool is_entrance = IsTunnelBridgeSignalSimulationEntrance(tile);
4306 TileIndex entrance = is_entrance ? tile : end;
4307 if (TunnelBridgeIsFree(tile, end, nullptr).Succeeded()) {
4308 if (IsBridge(entrance)) {
4309 SetAllBridgeEntranceSimulatedSignalsGreen(entrance);
4310 MarkBridgeDirty(entrance, ZOOM_LVL_DRAW_MAP);
4312 if (IsTunnelBridgeSignalSimulationEntrance(entrance) && GetTunnelBridgeSignalState(entrance) == SIGNAL_STATE_RED) {
4313 SetTunnelBridgeSignalState(entrance, SIGNAL_STATE_GREEN);
4314 MarkTileDirtyByTile(entrance);
4318 } else if (IsRailDepotTile(tile)) {
4319 UpdateSignalsOnSegment(tile, INVALID_DIAGDIR, owner);
4320 } else {
4321 SetSignalsOnBothDir(tile, track, owner);
4326 * Rotate all vehicles of a (crashed) train chain randomly to animate the crash.
4327 * @param v First crashed vehicle.
4329 static void ChangeTrainDirRandomly(Train *v)
4331 static const DirDiff delta[] = {
4332 DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT
4335 do {
4336 /* We don't need to twist around vehicles if they're not visible */
4337 if (!(v->vehstatus & VS_HIDDEN)) {
4338 v->direction = ChangeDir(v->direction, delta[GB(Random(), 0, 2)]);
4339 /* Refrain from updating the z position of the vehicle when on
4340 * a bridge, because UpdateInclination() will put the vehicle under
4341 * the bridge in that case */
4342 if (v->track != TRACK_BIT_WORMHOLE) {
4343 v->UpdatePosition();
4344 v->UpdateInclination(false, true);
4345 } else {
4346 v->UpdateViewport(false, true);
4349 } while ((v = v->Next()) != nullptr);
4353 * Handle a crashed train.
4354 * @param v First train vehicle.
4355 * @return %Vehicle chain still exists.
4357 static bool HandleCrashedTrain(Train *v)
4359 int state = ++v->crash_anim_pos;
4361 if (state == 4 && !(v->vehstatus & VS_HIDDEN)) {
4362 CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE);
4365 uint32 r;
4366 if (state <= 200 && Chance16R(1, 7, r)) {
4367 int index = (r * 10 >> 16);
4369 Vehicle *u = v;
4370 do {
4371 if (--index < 0) {
4372 r = Random();
4374 CreateEffectVehicleRel(u,
4375 GB(r, 8, 3) + 2,
4376 GB(r, 16, 3) + 2,
4377 GB(r, 0, 3) + 5,
4378 EV_EXPLOSION_SMALL);
4379 break;
4381 } while ((u = u->Next()) != nullptr);
4384 if (state <= 240 && !(v->tick_counter & 3)) ChangeTrainDirRandomly(v);
4386 if (state >= 4440 && !(v->tick_counter & 0x1F)) {
4387 bool ret = v->Next() != nullptr;
4388 DeleteLastWagon(v);
4389 return ret;
4392 return true;
4395 /** Maximum speeds for train that is broken down or approaching line end */
4396 static const uint16 _breakdown_speeds[16] = {
4397 225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
4402 * Train is approaching line end, slow down and possibly reverse
4404 * @param v front train engine
4405 * @param signal not line end, just a red signal
4406 * @param reverse Set to false to not execute the vehicle reversing. This does not change any other logic.
4407 * @return true iff we did NOT have to reverse
4409 static bool TrainApproachingLineEnd(Train *v, bool signal, bool reverse)
4411 /* Calc position within the current tile */
4412 uint x = v->x_pos & 0xF;
4413 uint y = v->y_pos & 0xF;
4415 /* for diagonal directions, 'x' will be 0..15 -
4416 * for other directions, it will be 1, 3, 5, ..., 15 */
4417 switch (v->direction) {
4418 case DIR_N : x = ~x + ~y + 25; break;
4419 case DIR_NW: x = y; FALLTHROUGH;
4420 case DIR_NE: x = ~x + 16; break;
4421 case DIR_E : x = ~x + y + 9; break;
4422 case DIR_SE: x = y; break;
4423 case DIR_S : x = x + y - 7; break;
4424 case DIR_W : x = ~y + x + 9; break;
4425 default: break;
4428 /* Do not reverse when approaching red signal. Make sure the vehicle's front
4429 * does not cross the tile boundary when we do reverse, but as the vehicle's
4430 * location is based on their center, use half a vehicle's length as offset.
4431 * Multiply the half-length by two for straight directions to compensate that
4432 * we only get odd x offsets there. */
4433 if (!signal && x + (v->gcache.cached_veh_length + 1) / 2 * (IsDiagonalDirection(v->direction) ? 1 : 2) >= TILE_SIZE) {
4434 /* we are too near the tile end, reverse now */
4435 v->cur_speed = 0;
4436 if (reverse) ReverseTrainDirection(v);
4437 return false;
4440 /* slow down */
4441 v->vehstatus |= VS_TRAIN_SLOWING;
4442 uint16 break_speed = _breakdown_speeds[x & 0xF];
4443 if (break_speed < v->cur_speed) v->cur_speed = break_speed;
4445 return true;
4450 * Determines whether train would like to leave the tile
4451 * @param v train to test
4452 * @return true iff vehicle is NOT entering or inside a depot or tunnel/bridge
4454 static bool TrainCanLeaveTile(const Train *v)
4456 /* Exit if inside a tunnel/bridge or a depot */
4457 if (v->track == TRACK_BIT_WORMHOLE || v->track == TRACK_BIT_DEPOT) return false;
4459 TileIndex tile = v->tile;
4461 /* entering a tunnel/bridge? */
4462 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
4463 DiagDirection dir = GetTunnelBridgeDirection(tile);
4464 if (DiagDirToDir(dir) == v->direction) return false;
4467 /* entering a depot? */
4468 if (IsRailDepotTile(tile)) {
4469 DiagDirection dir = ReverseDiagDir(GetRailDepotDirection(tile));
4470 if (DiagDirToDir(dir) == v->direction) return false;
4473 return true;
4478 * Determines whether train is approaching a rail-road crossing
4479 * (thus making it barred)
4480 * @param v front engine of train
4481 * @return TileIndex of crossing the train is approaching, else INVALID_TILE
4482 * @pre v in non-crashed front engine
4484 static TileIndex TrainApproachingCrossingTile(const Train *v)
4486 assert(v->IsFrontEngine());
4487 assert(!(v->vehstatus & VS_CRASHED));
4489 if (!TrainCanLeaveTile(v)) return INVALID_TILE;
4491 DiagDirection dir = TrainExitDir(v->direction, v->track);
4492 TileIndex tile = v->tile + TileOffsByDiagDir(dir);
4494 /* not a crossing || wrong axis || unusable rail (wrong type or owner) */
4495 if (!IsLevelCrossingTile(tile) || DiagDirToAxis(dir) == GetCrossingRoadAxis(tile) ||
4496 !CheckCompatibleRail(v, tile)) {
4497 return INVALID_TILE;
4500 return tile;
4505 * Checks for line end. Also, bars crossing at next tile if needed
4507 * @param v vehicle we are checking
4508 * @param reverse Set to false to not execute the vehicle reversing. This does not change any other logic.
4509 * @return true iff we did NOT have to reverse
4511 static bool TrainCheckIfLineEnds(Train *v, bool reverse)
4513 /* First, handle broken down train */
4515 int t = v->breakdown_ctr;
4516 if (t > 1) {
4517 v->vehstatus |= VS_TRAIN_SLOWING;
4519 uint16 break_speed = _breakdown_speeds[GB(~t, 4, 4)];
4520 if (break_speed < v->cur_speed) v->cur_speed = break_speed;
4521 } else {
4522 v->vehstatus &= ~VS_TRAIN_SLOWING;
4525 if (!TrainCanLeaveTile(v)) return true;
4527 /* Determine the non-diagonal direction in which we will exit this tile */
4528 DiagDirection dir = TrainExitDir(v->direction, v->track);
4529 /* Calculate next tile */
4530 TileIndex tile = v->tile + TileOffsByDiagDir(dir);
4532 /* Determine the track status on the next tile */
4533 TrackStatus ts = GetTileTrackStatus(tile, TRANSPORT_RAIL, 0, ReverseDiagDir(dir));
4534 TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(dir);
4536 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
4537 TrackdirBits red_signals = TrackStatusToRedSignals(ts) & reachable_trackdirs;
4539 /* We are sure the train is not entering a depot, it is detected above */
4541 /* mask unreachable track bits if we are forbidden to do 90deg turns */
4542 TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
4543 if (_settings_game.pf.forbid_90_deg) {
4544 bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
4547 /* no suitable trackbits at all || unusable rail (wrong type or owner) */
4548 if (bits == TRACK_BIT_NONE || !CheckCompatibleRail(v, tile)) {
4549 return TrainApproachingLineEnd(v, false, reverse);
4552 /* approaching red signal */
4553 if ((trackdirbits & red_signals) != 0) return TrainApproachingLineEnd(v, true, reverse);
4555 /* approaching a rail/road crossing? then make it red */
4556 if (IsLevelCrossingTile(tile)) MaybeBarCrossingWithSound(tile);
4558 if (IsTileType(tile, MP_TUNNELBRIDGE) && GetTunnelBridgeTransportType(tile) == TRANSPORT_RAIL &&
4559 IsTunnelBridgeSignalSimulationEntrance(tile) && GetTunnelBridgeSignalState(tile) == SIGNAL_STATE_RED) {
4560 return TrainApproachingLineEnd(v, true, reverse);
4563 return true;
4566 /* Calculate the summed up value of all parts of a train */
4567 Money Train::CalculateCurrentOverallValue() const
4569 Money ovr_value = 0;
4570 const Train *v = this;
4571 do {
4572 ovr_value += v->value;
4573 } while ( (v=v->GetNextVehicle()) != nullptr );
4574 return ovr_value;
4577 static bool TrainLocoHandler(Train *v, bool mode)
4579 /* train has crashed? */
4580 if (v->vehstatus & VS_CRASHED) {
4581 return mode ? true : HandleCrashedTrain(v); // 'this' can be deleted here
4584 if (v->force_proceed != TFP_NONE) {
4585 ClrBit(v->flags, VRF_TRAIN_STUCK);
4586 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4589 /* train is broken down? */
4590 if (v->HandleBreakdown()) return true;
4592 if (HasBit(v->flags, VRF_REVERSING) && v->cur_speed == 0) {
4593 ReverseTrainDirection(v);
4596 /* exit if train is stopped */
4597 if ((v->vehstatus & VS_STOPPED) && v->cur_speed == 0) return true;
4599 bool valid_order = !v->current_order.IsType(OT_NOTHING) && v->current_order.GetType() != OT_CONDITIONAL;
4600 if (ProcessOrders(v) && CheckReverseTrain(v)) {
4601 v->wait_counter = 0;
4602 v->cur_speed = 0;
4603 v->subspeed = 0;
4604 ClrBit(v->flags, VRF_LEAVING_STATION);
4605 ReverseTrainDirection(v);
4606 return true;
4607 } else if (HasBit(v->flags, VRF_LEAVING_STATION)) {
4608 /* Try to reserve a path when leaving the station as we
4609 * might not be marked as wanting a reservation, e.g.
4610 * when an overlength train gets turned around in a station. */
4611 DiagDirection dir = TrainExitDir(v->direction, v->track);
4612 if (IsRailDepotTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE)) dir = INVALID_DIAGDIR;
4614 if (UpdateSignalsOnSegment(v->tile, dir, v->owner) == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
4615 TryPathReserve(v, true, true);
4617 ClrBit(v->flags, VRF_LEAVING_STATION);
4620 v->HandleLoading(mode);
4622 if (v->current_order.IsType(OT_LOADING)) return true;
4624 if (CheckTrainStayInDepot(v)) return true;
4626 if (!mode) v->ShowVisualEffect();
4628 /* We had no order but have an order now, do look ahead. */
4629 if (!valid_order && !v->current_order.IsType(OT_NOTHING)) {
4630 CheckNextTrainTile(v);
4633 /* Handle stuck trains. */
4634 if (!mode && HasBit(v->flags, VRF_TRAIN_STUCK)) {
4635 ++v->wait_counter;
4637 /* Should we try reversing this tick if still stuck? */
4638 bool turn_around = v->wait_counter % (_settings_game.pf.wait_for_pbs_path * DAY_TICKS) == 0 && _settings_game.pf.reverse_at_signals;
4640 if (!turn_around && v->wait_counter % _settings_game.pf.path_backoff_interval != 0 && v->force_proceed == TFP_NONE) return true;
4641 if (!TryPathReserve(v)) {
4642 /* Still stuck. */
4643 if (turn_around) ReverseTrainDirection(v);
4645 if (HasBit(v->flags, VRF_TRAIN_STUCK) && v->wait_counter > 2 * _settings_game.pf.wait_for_pbs_path * DAY_TICKS) {
4646 /* Show message to player. */
4647 if (_settings_client.gui.lost_vehicle_warn && v->owner == _local_company) {
4648 SetDParam(0, v->index);
4649 AddVehicleAdviceNewsItem(STR_NEWS_TRAIN_IS_STUCK, v->index);
4651 v->wait_counter = 0;
4653 /* Exit if force proceed not pressed, else reset stuck flag anyway. */
4654 if (v->force_proceed == TFP_NONE) return true;
4655 ClrBit(v->flags, VRF_TRAIN_STUCK);
4656 v->wait_counter = 0;
4657 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4661 if (v->current_order.IsType(OT_LEAVESTATION)) {
4662 v->current_order.Free();
4663 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4664 return true;
4667 int j = v->UpdateSpeed();
4669 /* we need to invalidate the widget if we are stopping from 'Stopping 0 km/h' to 'Stopped' */
4670 if (v->cur_speed == 0 && (v->vehstatus & VS_STOPPED)) {
4671 /* If we manually stopped, we're not force-proceeding anymore. */
4672 v->force_proceed = TFP_NONE;
4673 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
4676 int adv_spd = v->GetAdvanceDistance();
4677 if (j < adv_spd) {
4678 /* if the vehicle has speed 0, update the last_speed field. */
4679 if (v->cur_speed == 0) v->SetLastSpeed();
4680 } else {
4681 TrainCheckIfLineEnds(v);
4682 /* Loop until the train has finished moving. */
4683 for (;;) {
4684 j -= adv_spd;
4685 TrainController(v, nullptr);
4686 /* Don't continue to move if the train crashed. */
4687 if (CheckTrainCollision(v)) break;
4688 /* Determine distance to next map position */
4689 adv_spd = v->GetAdvanceDistance();
4691 /* No more moving this tick */
4692 if (j < adv_spd || v->cur_speed == 0) break;
4694 OrderType order_type = v->current_order.GetType();
4695 /* Do not skip waypoints (incl. 'via' stations) when passing through at full speed. */
4696 if ((order_type == OT_GOTO_WAYPOINT || order_type == OT_GOTO_STATION) &&
4697 (v->current_order.GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) &&
4698 IsTileType(v->tile, MP_STATION) &&
4699 v->current_order.GetDestination() == GetStationIndex(v->tile)) {
4700 ProcessOrders(v);
4703 v->SetLastSpeed();
4706 for (Train *u = v; u != nullptr; u = u->Next()) {
4707 if (!(u->IsDrawn())) continue;
4709 u->UpdateViewport(false, false);
4712 if (v->progress == 0) v->progress = j; // Save unused spd for next time, if TrainController didn't set progress
4714 return true;
4718 * Get running cost for the train consist.
4719 * @return Yearly running costs.
4721 Money Train::GetRunningCost() const
4723 Money cost = 0;
4724 const Train *v = this;
4726 do {
4727 const Engine *e = v->GetEngine();
4728 if (e->u.rail.running_cost_class == INVALID_PRICE) continue;
4730 uint cost_factor = GetVehicleProperty(v, PROP_TRAIN_RUNNING_COST_FACTOR, e->u.rail.running_cost);
4731 if (cost_factor == 0) continue;
4733 /* Halve running cost for multiheaded parts */
4734 if (v->IsMultiheaded()) cost_factor /= 2;
4736 cost += GetPrice(e->u.rail.running_cost_class, cost_factor, e->GetGRF());
4737 } while ((v = v->GetNextVehicle()) != nullptr);
4739 return cost;
4743 * Update train vehicle data for a tick.
4744 * @return True if the vehicle still exists, false if it has ceased to exist (front of consists only).
4746 bool Train::Tick()
4748 this->tick_counter++;
4750 if (this->IsFrontEngine()) {
4751 if (!((this->vehstatus & VS_STOPPED) || this->IsChainInDepot()) || this->cur_speed > 0) this->running_ticks++;
4753 this->current_order_time++;
4755 if (!TrainLocoHandler(this, false)) return false;
4757 return TrainLocoHandler(this, true);
4758 } else if (this->IsFreeWagon() && (this->vehstatus & VS_CRASHED)) {
4759 /* Delete flooded standalone wagon chain */
4760 if (++this->crash_anim_pos >= 4400) {
4761 delete this;
4762 return false;
4766 return true;
4770 * Check whether a train needs service, and if so, find a depot or service it.
4771 * @return v %Train to check.
4773 static void CheckIfTrainNeedsService(Train *v)
4775 if (Company::Get(v->owner)->settings.vehicle.servint_trains == 0 || !v->NeedsAutomaticServicing()) return;
4776 if (v->IsChainInDepot()) {
4777 VehicleServiceInDepot(v);
4778 return;
4781 uint max_penalty;
4782 switch (_settings_game.pf.pathfinder_for_trains) {
4783 case VPF_NPF: max_penalty = _settings_game.pf.npf.maximum_go_to_depot_penalty; break;
4784 case VPF_YAPF: max_penalty = _settings_game.pf.yapf.maximum_go_to_depot_penalty; break;
4785 default: NOT_REACHED();
4788 FindDepotData tfdd = FindClosestTrainDepot(v, max_penalty);
4789 /* Only go to the depot if it is not too far out of our way. */
4790 if (tfdd.best_length == UINT_MAX || tfdd.best_length > max_penalty) {
4791 if (v->current_order.IsType(OT_GOTO_DEPOT)) {
4792 /* If we were already heading for a depot but it has
4793 * suddenly moved farther away, we continue our normal
4794 * schedule? */
4795 v->current_order.MakeDummy();
4796 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4798 return;
4801 DepotID depot = GetDepotIndex(tfdd.tile);
4803 if (v->current_order.IsType(OT_GOTO_DEPOT) &&
4804 v->current_order.GetDestination() != depot &&
4805 !Chance16(3, 16)) {
4806 return;
4809 SetBit(v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
4810 v->current_order.MakeGoToDepot(depot, ODTFB_SERVICE);
4811 v->dest_tile = tfdd.tile;
4812 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4815 /** Update day counters of the train vehicle. */
4816 void Train::OnNewDay()
4818 AgeVehicle(this);
4820 if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
4822 if (this->IsFrontEngine()) {
4823 CheckVehicleBreakdown(this);
4825 CheckIfTrainNeedsService(this);
4827 CheckOrders(this);
4829 /* update destination */
4830 if (this->current_order.IsType(OT_GOTO_STATION)) {
4831 TileIndex tile = Station::Get(this->current_order.GetDestination())->train_station.tile;
4832 if (tile != INVALID_TILE) this->dest_tile = tile;
4835 if (this->running_ticks != 0) {
4836 /* running costs */
4837 CommandCost cost(EXPENSES_TRAIN_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR * DAY_TICKS));
4839 this->profit_this_year -= cost.GetCost();
4840 this->running_ticks = 0;
4842 SubtractMoneyFromCompanyFract(this->owner, cost);
4844 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
4845 SetWindowClassesDirty(WC_TRAINS_LIST);
4846 SetWindowClassesDirty(WC_TRACE_RESTRICT_SLOTS);
4852 * Get the tracks of the train vehicle.
4853 * @return Current tracks of the vehicle.
4855 Trackdir Train::GetVehicleTrackdir() const
4857 if (this->vehstatus & VS_CRASHED)
4858 return INVALID_TRACKDIR;
4860 if (this->track == TRACK_BIT_DEPOT) {
4861 /* We'll assume the train is facing outwards */
4862 return DiagDirToDiagTrackdir(GetRailDepotDirection(this->tile)); // Train in depot
4865 if (this->track == TRACK_BIT_WORMHOLE) {
4866 /* train in tunnel or on bridge, so just use his direction and assume a diagonal track */
4867 return DiagDirToDiagTrackdir(DirToDiagDir(this->direction));
4870 return TrackDirectionToTrackdir(FindFirstTrack(this->track), this->direction);
4874 /* Get the pixel-width of the image that is used for the train vehicle
4875 * @return: the image width number in pixel
4877 int GetDisplayImageWidth(Train *t, Point *offset)
4879 int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
4880 int vehicle_pitch = 0;
4882 const Engine *e = Engine::Get(t->engine_type);
4883 if (e->grf_prop.grffile != nullptr && is_custom_sprite(e->u.rail.image_index)) {
4884 reference_width = e->grf_prop.grffile->traininfo_vehicle_width;
4885 vehicle_pitch = e->grf_prop.grffile->traininfo_vehicle_pitch;
4888 if (offset != nullptr) {
4889 offset->x = reference_width / 2;
4890 offset->y = vehicle_pitch;
4892 //printf(" refwid:%d gdiw.cachedvehlen(%d):%d ", reference_width, this->engine_type, this->gcache.cached_veh_length);
4893 return t->gcache.cached_veh_length * reference_width / VEHICLE_LENGTH;
4896 Train* CmdBuildVirtualRailWagon(const Engine *e)
4898 const RailVehicleInfo *rvi = &e->u.rail;
4900 Train *v = new Train();
4902 v->x_pos = 0;
4903 v->y_pos = 0;
4905 v->spritenum = rvi->image_index;
4907 v->engine_type = e->index;
4908 v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
4910 v->direction = DIR_W;
4911 v->tile = 0;//INVALID_TILE;
4913 v->owner = _current_company;
4914 v->track = TRACK_BIT_DEPOT;
4915 v->vehstatus = VS_HIDDEN | VS_DEFPAL;
4917 v->SetWagon();
4918 v->SetFreeWagon();
4920 v->cargo_type = e->GetDefaultCargoType();
4921 v->cargo_cap = rvi->capacity;
4923 v->railtype = rvi->railtype;
4925 v->build_year = _cur_year;
4926 v->sprite_seq.Set(SPR_IMG_QUERY);
4927 v->random_bits = VehicleRandomBits();
4929 v->group_id = DEFAULT_GROUP;
4931 AddArticulatedParts(v);
4933 // Make sure we set EVERYTHING to virtual, even articulated parts.
4934 for (Train* train_part = v; train_part != nullptr; train_part = train_part->Next()) {
4935 train_part->SetVirtual();
4938 _new_vehicle_id = v->index;
4940 v->UpdateViewport(true, false);
4942 v->First()->ConsistChanged(CCF_ARRANGE);
4944 CheckConsistencyOfArticulatedVehicle(v);
4946 return v;
4949 Train* CmdBuildVirtualRailVehicle(EngineID eid, bool lax_engine_check, StringID &error)
4951 if (lax_engine_check) {
4952 const Engine *e = Engine::GetIfValid(eid);
4953 if (e == nullptr || e->type != VEH_TRAIN) {
4954 error = STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE + VEH_TRAIN;
4955 return nullptr;
4958 else {
4959 if (!IsEngineBuildable(eid, VEH_TRAIN, _current_company)) {
4960 error = STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE + VEH_TRAIN;
4961 return nullptr;
4965 const Engine* e = Engine::Get(eid);
4966 const RailVehicleInfo *rvi = &e->u.rail;
4968 int num_vehicles = (e->u.rail.railveh_type == RAILVEH_MULTIHEAD ? 2 : 1) + CountArticulatedParts(eid, false);
4969 if (!Train::CanAllocateItem(num_vehicles)) {
4970 error = STR_ERROR_TOO_MANY_VEHICLES_IN_GAME;
4971 return nullptr;
4974 if (rvi->railveh_type == RAILVEH_WAGON)
4975 return CmdBuildVirtualRailWagon(e);
4977 Train *v = new Train();
4979 v->x_pos = 0;
4980 v->y_pos = 0;
4982 v->direction = DIR_W;
4983 v->tile = 0;//INVALID_TILE;
4984 v->owner = _current_company;
4985 v->track = TRACK_BIT_DEPOT;
4986 v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
4987 v->spritenum = rvi->image_index;
4988 v->cargo_type = e->GetDefaultCargoType();
4989 v->cargo_cap = rvi->capacity;
4990 v->last_station_visited = INVALID_STATION;
4992 v->engine_type = e->index;
4993 v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
4995 v->reliability = e->reliability;
4996 v->reliability_spd_dec = e->reliability_spd_dec;
4997 v->max_age = e->GetLifeLengthInDays();
4999 v->railtype = rvi->railtype;
5000 _new_vehicle_id = v->index;
5002 v->build_year = _cur_year;
5003 v->sprite_seq.Set(SPR_IMG_QUERY);
5004 v->random_bits = VehicleRandomBits();
5006 v->group_id = DEFAULT_GROUP;
5008 v->SetFrontEngine();
5009 v->SetEngine();
5011 if (rvi->railveh_type == RAILVEH_MULTIHEAD) {
5012 AddRearEngineToMultiheadedTrain(v);
5013 } else {
5014 AddArticulatedParts(v);
5017 // Make sure we set EVERYTHING to virtual, even articulated parts.
5018 for (Train* train_part = v; train_part != nullptr; train_part = train_part->Next()) {
5019 train_part->SetVirtual();
5022 v->UpdateViewport(true, false);
5024 v->ConsistChanged(CCF_ARRANGE);
5026 CheckConsistencyOfArticulatedVehicle(v);
5028 return v;
5032 * Build a virtual train vehicle.
5033 * @param tile unused
5034 * @param flags type of operation
5035 * @param p1 the engine ID to build
5036 * @param p2 unused
5037 * @param text unused
5038 * @return the cost of this operation or an error
5040 CommandCost CmdBuildVirtualRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
5042 EngineID eid = p1;
5044 if (!IsEngineBuildable(eid, VEH_TRAIN, _current_company)) {
5045 return CommandError(STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE + VEH_TRAIN);
5048 bool should_execute = (flags & DC_EXEC) != 0;
5050 if (should_execute) {
5051 StringID err = INVALID_STRING_ID;
5052 Train* train = CmdBuildVirtualRailVehicle(eid, false, err);
5054 if (train == nullptr) {
5055 return CommandError(err);
5059 return CommandCost();
5063 * Replace a vehicle based on a template replacement order.
5064 * @param tile unused
5065 * @param flags type of operation
5066 * @param p1 the ID of the vehicle to replace.
5067 * @param p2 whether the vehicle should stay in the depot.
5068 * @param text unused
5069 * @return the cost of this operation or an error
5071 CommandCost CmdTemplateReplaceVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
5073 VehicleID vehicle_id = p1;
5075 Vehicle* vehicle = Vehicle::GetIfValid(vehicle_id);
5077 if (vehicle == nullptr || vehicle->type != VEH_TRAIN)
5078 return CommandError();
5080 bool should_execute = (flags & DC_EXEC) != 0;
5082 if (!should_execute)
5083 return CommandCost();
5085 Train* incoming = Train::From(vehicle);
5086 bool stayInDepot = p2 != 0;
5088 Train *new_chain = 0,
5089 *remainder_chain = 0,
5090 *tmp_chain = 0;
5091 TemplateVehicle *tv = GetTemplateVehicleByGroupID(incoming->group_id);
5092 if (tv == nullptr) {
5093 return CommandError();
5096 CommandCost buy(EXPENSES_NEW_VEHICLES);
5097 CommandCost move_cost(EXPENSES_NEW_VEHICLES);
5098 CommandCost tmp_result(EXPENSES_NEW_VEHICLES);
5101 /* first some tests on necessity and sanity */
5102 if (tv == nullptr)
5103 return buy;
5105 EngineID eid = tv->engine_type;
5107 _new_vehicle_id = p1;
5109 bool need_replacement = !TrainMatchesTemplate(incoming, tv);
5110 bool need_refit = !TrainMatchesTemplateRefit(incoming, tv);
5111 bool use_refit = tv->refit_as_template;
5113 CargoID store_refit_ct = CT_INVALID;
5114 short store_refit_csubt = 0;
5115 // if a train shall keep its old refit, store the refit setting of its first vehicle
5116 if (!use_refit) {
5117 for (Train *getc = incoming; getc != nullptr; getc = getc->GetNextUnit()) {
5118 if (getc->cargo_type != CT_INVALID) {
5119 store_refit_ct = getc->cargo_type;
5120 break;
5125 // TODO: set result status to success/no success before returning
5126 if (!need_replacement) {
5127 if (!need_refit || !use_refit) {
5128 /* before returning, release incoming train first if 2nd param says so */
5129 if (!stayInDepot) incoming->vehstatus &= ~VS_STOPPED;
5130 return buy;
5133 else {
5134 CommandCost buyCost = TestBuyAllTemplateVehiclesInChain(tv, tile);
5135 if (!buyCost.Succeeded() || !CheckCompanyHasMoney(buyCost)) {
5136 if (!stayInDepot) incoming->vehstatus &= ~VS_STOPPED;
5138 if (!buyCost.Succeeded() && buyCost.GetErrorMessage() != INVALID_STRING_ID) {
5139 return buyCost;
5140 } else {
5141 return CommandError(STR_ERROR_NOT_ENOUGH_CASH_REQUIRES_CURRENCY);
5146 /* define replacement behavior */
5147 bool reuseDepot = tv->IsSetReuseDepotVehicles();
5148 bool keepRemainders = tv->IsSetKeepRemainingVehicles();
5150 if (need_replacement) {
5151 /// step 1: generate primary for newchain and generate remainder_chain
5152 // 1. primary of incoming might already fit the template
5153 // leave incoming's primary as is and move the rest to a free chain = remainder_chain
5154 // 2. needed primary might be one of incoming's member vehicles
5155 // 3. primary might be available as orphan vehicle in the depot
5156 // 4. we need to buy a new engine for the primary
5157 // all options other than 1. need to make sure to copy incoming's primary's status
5158 if (eid == incoming->engine_type) { // 1
5159 new_chain = incoming;
5160 remainder_chain = incoming->GetNextUnit();
5161 if (remainder_chain)
5162 move_cost.AddCost(CmdMoveRailVehicle(tile, flags, remainder_chain->index | (1 << 20), INVALID_VEHICLE, 0));
5164 else if ((tmp_chain = ChainContainsEngine(eid, incoming)) && tmp_chain != nullptr) { // 2
5165 // new_chain is the needed engine, move it to an empty spot in the depot
5166 new_chain = tmp_chain;
5167 move_cost.AddCost(DoCommand(tile, new_chain->index, INVALID_VEHICLE, flags, CMD_MOVE_RAIL_VEHICLE));
5168 remainder_chain = incoming;
5170 else if (reuseDepot && (tmp_chain = DepotContainsEngine(tile, eid, incoming)) && tmp_chain != nullptr) { // 3
5171 new_chain = tmp_chain;
5172 move_cost.AddCost(DoCommand(tile, new_chain->index, INVALID_VEHICLE, flags, CMD_MOVE_RAIL_VEHICLE));
5173 remainder_chain = incoming;
5175 else { // 4
5176 tmp_result = DoCommand(tile, eid, 0, flags, CMD_BUILD_VEHICLE);
5177 /* break up in case buying the vehicle didn't succeed */
5178 if (!tmp_result.Succeeded())
5179 return tmp_result;
5180 buy.AddCost(tmp_result);
5181 new_chain = Train::Get(_new_vehicle_id);
5182 /* make sure the newly built engine is not attached to any free wagons inside the depot */
5183 move_cost.AddCost(DoCommand(tile, new_chain->index, INVALID_VEHICLE, flags, CMD_MOVE_RAIL_VEHICLE));
5184 /* prepare the remainder chain */
5185 remainder_chain = incoming;
5187 // If we bought a new engine or reused one from the depot, copy some parameters from the incoming primary engine
5188 if (incoming != new_chain && flags == DC_EXEC) {
5189 CopyHeadSpecificThings(incoming, new_chain, flags);
5190 NeutralizeStatus(incoming);
5193 // additionally, if we don't want to use the template refit, refit as incoming
5194 // the template refit will be set further down, if we use it at all
5195 if (!use_refit) {
5196 uint32 cb = GetCmdRefitVeh(new_chain);
5197 DoCommand(new_chain->tile, new_chain->index, store_refit_ct | store_refit_csubt << 8 | 1 << 16 | (1 << 5), flags, cb);
5202 /// step 2: fill up newchain according to the template
5203 // foreach member of template (after primary):
5204 // 1. needed engine might be within remainder_chain already
5205 // 2. needed engine might be orphaned within the depot (copy status)
5206 // 3. we need to buy (again) (copy status)
5207 TemplateVehicle *cur_tmpl = tv->GetNextUnit();
5208 Train *last_veh = new_chain;
5209 while (cur_tmpl) {
5210 // 1. engine contained in remainder chain
5211 if ((tmp_chain = ChainContainsEngine(cur_tmpl->engine_type, remainder_chain)) && tmp_chain != nullptr) {
5212 // advance remainder_chain (if necessary) to not lose track of it
5213 if (tmp_chain == remainder_chain)
5214 remainder_chain = remainder_chain->GetNextUnit();
5215 move_cost.AddCost(CmdMoveRailVehicle(tile, flags, tmp_chain->index, last_veh->index, 0));
5217 // 2. engine contained somewhere else in the depot
5218 else if (reuseDepot && (tmp_chain = DepotContainsEngine(tile, cur_tmpl->engine_type, new_chain)) && tmp_chain != nullptr) {
5219 move_cost.AddCost(CmdMoveRailVehicle(tile, flags, tmp_chain->index, last_veh->index, 0));
5221 // 3. must buy new engine
5222 else {
5223 tmp_result = DoCommand(tile, cur_tmpl->engine_type, 0, flags, CMD_BUILD_VEHICLE);
5224 if (!tmp_result.Succeeded()) {
5225 return tmp_result;
5227 buy.AddCost(tmp_result);
5228 tmp_chain = Train::Get(_new_vehicle_id);
5229 move_cost.AddCost(CmdMoveRailVehicle(tile, flags, tmp_chain->index, last_veh->index, 0));
5231 // TODO: is this enough ? might it be that we bought a new wagon here and it now has std refit ?
5232 if (need_refit && flags == DC_EXEC) {
5233 if (use_refit) {
5234 uint32 cb = GetCmdRefitVeh(tmp_chain);
5235 DoCommand(tmp_chain->tile, tmp_chain->index, cur_tmpl->cargo_type | cur_tmpl->cargo_subtype << 8 | 1 << 16 | (1 << 5), flags, cb);
5236 // old
5237 // CopyWagonStatus(cur_tmpl, tmp_chain);
5238 } else {
5239 uint32 cb = GetCmdRefitVeh(tmp_chain);
5240 DoCommand(tmp_chain->tile, tmp_chain->index, store_refit_ct | store_refit_csubt << 8 | 1 << 16 | (1 << 5), flags, cb);
5243 cur_tmpl = cur_tmpl->GetNextUnit();
5244 last_veh = tmp_chain;
5247 /* no replacement done */
5248 else {
5249 new_chain = incoming;
5251 /// step 3: reorder and neutralize the remaining vehicles from incoming
5252 // wagons remaining from remainder_chain should be filled up in as few freewagonchains as possible
5253 // each locos might be left as singular in the depot
5254 // neutralize each remaining engine's status
5256 // refit, only if the template option is set so
5257 if (use_refit && (need_refit || need_replacement)) {
5258 CmdRefitTrainFromTemplate(new_chain, tv, flags);
5261 if (new_chain && remainder_chain)
5262 for (Train *ct = remainder_chain; ct; ct = ct->GetNextUnit())
5263 TransferCargoForTrain(ct, new_chain);
5265 // point incoming to the newly created train so that starting/stopping from the calling function can be done
5266 incoming = new_chain;
5267 if (!stayInDepot && flags == DC_EXEC)
5268 new_chain->vehstatus &= ~VS_STOPPED;
5270 if (remainder_chain && keepRemainders && flags == DC_EXEC)
5271 BreakUpRemainders(remainder_chain);
5272 else if (remainder_chain) {
5273 buy.AddCost(DoCommand(tile, remainder_chain->index | (1 << 20), 0, flags, CMD_SELL_VEHICLE));
5276 /* Redraw main gui for changed statistics */
5277 SetWindowClassesDirty(WC_TEMPLATEGUI_MAIN);
5279 _new_vehicle_id = new_chain->index;
5281 return buy;