Fix incorrect tile and trackdir in reserve through program execution
[openttd-joker.git] / src / train_cmd.cpp
blob262c636c4f4c1cbdb2f85bc02f69f77da821f9dd
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 TrainCheckIfLineEnds(Train *v, bool reverse = true);
54 bool TrainController(Train *v, Vehicle *nomove, bool reverse = true); // Also used in vehicle_sl.cpp.
55 static TileIndex TrainApproachingCrossingTile(const Train *v);
56 static void CheckIfTrainNeedsService(Train *v);
57 static void CheckNextTrainTile(Train *v);
59 static const byte _vehicle_initial_x_fract[4] = {10, 8, 4, 8};
60 static const byte _vehicle_initial_y_fract[4] = { 8, 4, 8, 10};
62 template <>
63 bool IsValidImageIndex<VEH_TRAIN>(uint8 image_index)
65 return image_index < lengthof(_engine_sprite_base);
68 /**
69 * Determine the side in which the train will leave the tile
71 * @param direction vehicle direction
72 * @param track vehicle track bits
73 * @return side of tile the train will leave
75 static inline DiagDirection TrainExitDir(Direction direction, TrackBits track)
77 static const TrackBits state_dir_table[DIAGDIR_END] = { TRACK_BIT_RIGHT, TRACK_BIT_LOWER, TRACK_BIT_LEFT, TRACK_BIT_UPPER };
79 DiagDirection diagdir = DirToDiagDir(direction);
81 /* Determine the diagonal direction in which we will exit this tile */
82 if (!HasBit(direction, 0) && track != state_dir_table[diagdir]) {
83 diagdir = ChangeDiagDir(diagdir, DIAGDIRDIFF_90LEFT);
86 return diagdir;
90 /**
91 * Return the cargo weight multiplier to use for a rail vehicle
92 * @param cargo Cargo type to get multiplier for
93 * @return Cargo weight multiplier
95 byte FreightWagonMult(CargoID cargo)
97 if (!CargoSpec::Get(cargo)->is_freight) return 1;
98 return _settings_game.vehicle.freight_trains;
101 /** Checks if lengths of all rail vehicles are valid. If not, shows an error message. */
102 void CheckTrainsLengths()
104 const Train *v;
105 bool first = true;
107 FOR_ALL_TRAINS(v) {
108 if (v->First() == v && !(v->vehstatus & VS_CRASHED)) {
109 for (const Train *u = v, *w = v->Next(); w != NULL; u = w, w = w->Next()) {
110 if (u->track != TRACK_BIT_DEPOT) {
111 if ((w->track != TRACK_BIT_DEPOT &&
112 max(abs(u->x_pos - w->x_pos), abs(u->y_pos - w->y_pos)) != u->CalcNextVehicleOffset()) ||
113 (w->track == TRACK_BIT_DEPOT && TicksToLeaveDepot(u) <= 0)) {
114 SetDParam(0, v->index);
115 SetDParam(1, v->owner);
116 ShowErrorMessage(STR_BROKEN_VEHICLE_LENGTH, INVALID_STRING_ID, WL_CRITICAL);
118 if (!_networking && first) {
119 first = false;
120 DoCommandP(0, PM_PAUSED_ERROR, 1, CMD_PAUSE);
122 /* Break so we warn only once for each train. */
123 break;
132 * Recalculates the cached stuff of a train. Should be called each time a vehicle is added
133 * to/removed from the chain, and when the game is loaded.
134 * Note: this needs to be called too for 'wagon chains' (in the depot, without an engine)
135 * @param allowed_changes Stuff that is allowed to change.
137 void Train::ConsistChanged(ConsistChangeFlags allowed_changes)
139 uint16 max_speed = UINT16_MAX;
141 assert(this->IsFrontEngine() || this->IsFreeWagon());
143 const RailVehicleInfo *rvi_v = RailVehInfo(this->engine_type);
144 EngineID first_engine = this->IsFrontEngine() ? this->engine_type : INVALID_ENGINE;
145 this->gcache.cached_total_length = 0;
146 this->compatible_railtypes = RAILTYPES_NONE;
148 bool train_can_tilt = true;
150 for (Train *u = this; u != NULL; u = u->Next()) {
151 const RailVehicleInfo *rvi_u = RailVehInfo(u->engine_type);
153 /* Check the this->first cache. */
154 assert(u->First() == this);
156 /* update the 'first engine' */
157 u->gcache.first_engine = this == u ? INVALID_ENGINE : first_engine;
158 u->railtype = rvi_u->railtype;
160 if (u->IsEngine()) first_engine = u->engine_type;
162 /* Set user defined data to its default value */
163 u->tcache.user_def_data = rvi_u->user_def_data;
164 this->InvalidateNewGRFCache();
165 u->InvalidateNewGRFCache();
168 for (Train *u = this; u != NULL; u = u->Next()) {
169 /* Update user defined data (must be done before other properties) */
170 u->tcache.user_def_data = GetVehicleProperty(u, PROP_TRAIN_USER_DATA, u->tcache.user_def_data);
171 this->InvalidateNewGRFCache();
172 u->InvalidateNewGRFCache();
175 for (Train *u = this; u != NULL; u = u->Next()) {
176 const Engine *e_u = u->GetEngine();
177 const RailVehicleInfo *rvi_u = &e_u->u.rail;
179 if (!HasBit(e_u->info.misc_flags, EF_RAIL_TILTS)) train_can_tilt = false;
181 /* Cache wagon override sprite group. NULL is returned if there is none */
182 u->tcache.cached_override = GetWagonOverrideSpriteSet(u->engine_type, u->cargo_type, u->gcache.first_engine);
184 /* Reset colour map */
185 u->colourmap = PAL_NONE;
187 RailType rt = u->railtype;
189 /* Update powered-wagon-status and visual effect */
190 u->UpdateVisualEffect(true);
192 if (rvi_v->pow_wag_power != 0 && rvi_u->railveh_type == RAILVEH_WAGON &&
193 UsesWagonOverride(u) && !HasBit(u->vcache.cached_vis_effect, VE_DISABLE_WAGON_POWER)) {
194 /* wagon is powered */
195 SetBit(u->flags, VRF_POWEREDWAGON); // cache 'powered' status
196 } else {
197 ClrBit(u->flags, VRF_POWEREDWAGON);
200 if (!u->IsArticulatedPart()) {
201 /* Do not count powered wagons for the compatible railtypes, as wagons always
202 have railtype normal */
203 if (rvi_u->power > 0) {
204 this->compatible_railtypes |= GetRailTypeInfo(u->railtype)->powered_railtypes;
207 /* Some electric engines can be allowed to run on normal rail. It happens to all
208 * existing electric engines when elrails are disabled and then re-enabled */
209 if (HasBit(u->flags, VRF_EL_ENGINE_ALLOWED_NORMAL_RAIL)) {
210 u->railtype = RAILTYPE_RAIL;
211 u->compatible_railtypes |= RAILTYPES_RAIL;
214 /* max speed is the minimum of the speed limits of all vehicles in the consist */
215 if ((rvi_u->railveh_type != RAILVEH_WAGON || _settings_game.vehicle.wagon_speed_limits) && !UsesWagonOverride(u)) {
216 uint16 speed = GetVehicleProperty(u, PROP_TRAIN_SPEED, rvi_u->max_speed);
217 if (speed != 0) max_speed = min(speed, max_speed);
221 uint16 new_cap = e_u->DetermineCapacity(u);
222 if (allowed_changes & CCF_CAPACITY) {
223 /* Update vehicle capacity. */
224 if (u->cargo_cap > new_cap) u->cargo.Truncate(new_cap);
225 u->refit_cap = min(new_cap, u->refit_cap);
226 u->cargo_cap = new_cap;
227 } else {
228 /* Verify capacity hasn't changed. */
229 if (new_cap != u->cargo_cap) ShowNewGrfVehicleError(u->engine_type, STR_NEWGRF_BROKEN, STR_NEWGRF_BROKEN_CAPACITY, GBUG_VEH_CAPACITY, true);
231 u->vcache.cached_cargo_age_period = GetVehicleProperty(u, PROP_TRAIN_CARGO_AGE_PERIOD, e_u->info.cargo_age_period);
233 /* check the vehicle length (callback) */
234 uint16 veh_len = CALLBACK_FAILED;
235 if (e_u->GetGRF() != NULL && e_u->GetGRF()->grf_version >= 8) {
236 /* Use callback 36 */
237 veh_len = GetVehicleProperty(u, PROP_TRAIN_SHORTEN_FACTOR, CALLBACK_FAILED);
239 if (veh_len != CALLBACK_FAILED && veh_len >= VEHICLE_LENGTH) {
240 ErrorUnknownCallbackResult(e_u->GetGRFID(), CBID_VEHICLE_LENGTH, veh_len);
242 } else if (HasBit(e_u->info.callback_mask, CBM_VEHICLE_LENGTH)) {
243 /* Use callback 11 */
244 veh_len = GetVehicleCallback(CBID_VEHICLE_LENGTH, 0, 0, u->engine_type, u);
246 if (veh_len == CALLBACK_FAILED) veh_len = rvi_u->shorten_factor;
247 veh_len = VEHICLE_LENGTH - Clamp(veh_len, 0, VEHICLE_LENGTH - 1);
249 if (allowed_changes & CCF_LENGTH) {
250 /* Update vehicle length. */
251 u->gcache.cached_veh_length = veh_len;
252 } else {
253 /* Verify length hasn't changed. */
254 if (veh_len != u->gcache.cached_veh_length) VehicleLengthChanged(u);
257 this->gcache.cached_total_length += u->gcache.cached_veh_length;
258 this->InvalidateNewGRFCache();
259 u->InvalidateNewGRFCache();
262 /* store consist weight/max speed in cache */
263 this->vcache.cached_max_speed = max_speed;
264 this->tcache.cached_tilt = train_can_tilt;
265 this->tcache.cached_max_curve_speed = this->GetCurveSpeedLimit();
267 /* 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) */
268 this->CargoChanged();
270 if (this->IsFrontEngine()) {
271 this->UpdateAcceleration();
272 if ( !HasBit(this->subtype, GVSF_VIRTUAL) ) SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
273 InvalidateWindowData(WC_VEHICLE_REFIT, this->index, VIWD_CONSIST_CHANGED);
274 InvalidateWindowData(WC_VEHICLE_ORDERS, this->index, VIWD_CONSIST_CHANGED);
275 InvalidateNewGRFInspectWindow(GSF_TRAINS, this->index);
280 * Get the stop location of (the center) of the front vehicle of a train at
281 * a platform of a station.
282 * @param station_id the ID of the station where we're stopping
283 * @param tile the tile where the vehicle currently is
284 * @param v the vehicle to get the stop location of
285 * @param station_ahead 'return' the amount of 1/16th tiles in front of the train
286 * @param station_length 'return' the station length in 1/16th tiles
287 * @return the location, calculated from the begin of the station to stop at.
289 int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *v, int *station_ahead, int *station_length)
291 const Station *st = Station::Get(station_id);
292 *station_ahead = st->GetPlatformLength(tile, DirToDiagDir(v->direction)) * TILE_SIZE;
293 *station_length = st->GetPlatformLength(tile) * TILE_SIZE;
295 /* Default to the middle of the station for stations stops that are not in
296 * the order list like intermediate stations when non-stop is disabled */
297 OrderStopLocation osl = OSL_PLATFORM_MIDDLE;
298 if (v->gcache.cached_total_length >= *station_length) {
299 /* The train is longer than the station, make it stop at the far end of the platform */
300 osl = OSL_PLATFORM_FAR_END;
301 } else if (v->current_order.IsType(OT_GOTO_STATION) && v->current_order.GetDestination() == station_id) {
302 osl = v->current_order.GetStopLocation();
305 /* The stop location of the FRONT! of the train */
306 int stop;
307 switch (osl) {
308 default: NOT_REACHED();
310 case OSL_PLATFORM_NEAR_END:
311 stop = v->gcache.cached_total_length;
312 break;
314 case OSL_PLATFORM_MIDDLE:
315 stop = *station_length - (*station_length - v->gcache.cached_total_length) / 2;
316 break;
318 case OSL_PLATFORM_FAR_END:
319 stop = *station_length;
320 break;
323 /* Subtract half the front vehicle length of the train so we get the real
324 * stop location of the train. */
325 return stop - (v->gcache.cached_veh_length + 1) / 2;
330 * Computes train speed limit caused by curves
331 * @return imposed speed limit
333 int Train::GetCurveSpeedLimit() const
335 assert(this->First() == this);
337 static const int absolute_max_speed = UINT16_MAX;
338 int max_speed = absolute_max_speed;
340 if (_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) return max_speed;
342 int curvecount[2] = {0, 0};
344 /* first find the curve speed limit */
345 int numcurve = 0;
346 int sum = 0;
347 int pos = 0;
348 int lastpos = -1;
349 for (const Vehicle *u = this; u->Next() != NULL; u = u->Next(), pos++) {
350 Direction this_dir = u->direction;
351 Direction next_dir = u->Next()->direction;
353 DirDiff dirdiff = DirDifference(this_dir, next_dir);
354 if (dirdiff == DIRDIFF_SAME) continue;
356 if (dirdiff == DIRDIFF_45LEFT) curvecount[0]++;
357 if (dirdiff == DIRDIFF_45RIGHT) curvecount[1]++;
358 if (dirdiff == DIRDIFF_45LEFT || dirdiff == DIRDIFF_45RIGHT) {
359 if (lastpos != -1) {
360 numcurve++;
361 sum += pos - lastpos;
362 if (pos - lastpos == 1 && max_speed > 88) {
363 max_speed = 88;
366 lastpos = pos;
369 /* if we have a 90 degree turn, fix the speed limit to 60 */
370 if (dirdiff == DIRDIFF_90LEFT || dirdiff == DIRDIFF_90RIGHT) {
371 max_speed = 61;
375 if (numcurve > 0 && max_speed > 88) {
376 if (curvecount[0] == 1 && curvecount[1] == 1) {
377 max_speed = absolute_max_speed;
378 } else {
379 sum /= numcurve;
380 max_speed = 232 - (13 - Clamp(sum, 1, 12)) * (13 - Clamp(sum, 1, 12));
384 if (max_speed != absolute_max_speed) {
385 /* Apply the engine's rail type curve speed advantage, if it slowed by curves */
386 const RailtypeInfo *rti = GetRailTypeInfo(this->railtype);
387 max_speed += (max_speed / 2) * rti->curve_speed;
389 if (this->tcache.cached_tilt) {
390 /* Apply max_speed bonus of 20% for a tilting train */
391 max_speed += max_speed / 5;
395 return max_speed;
398 enum TrackBits;
401 * Calculates the maximum speed of the vehicle under its current conditions.
402 * @return Maximum speed of the vehicle.
404 int Train::GetCurrentMaxSpeed() const
406 int max_speed = _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL ?
407 this->gcache.cached_max_track_speed :
408 this->tcache.cached_max_curve_speed;
410 if (!(this->vehstatus & VS_CRASHED) && _settings_game.vehicle.train_speed_adaption) {
411 int atc_speed = max_speed;
413 CFollowTrackRail ft(this);
414 Trackdir old_td = this->GetVehicleTrackdir();
416 if (ft.Follow(this->tile, this->GetVehicleTrackdir())) {
417 /* Basic idea: Follow the track for 20 tiles or 3 signals (i.e. at most two signal blocks) looking for other trains. */
418 /* If we find one (that meets certain restrictions), we limit the max speed to the speed of that train. */
419 int num_tiles = 0;
420 int num_signals = 0;
422 do {
423 old_td = ft.m_old_td;
425 /* If we are on a depot or rail station tile stop searching */
426 if (IsDepotTile(ft.m_new_tile) || IsRailStationTile(ft.m_new_tile))
427 break;
429 /* Increment signal counter if we're on a signal */
430 if (IsTileType(ft.m_new_tile, MP_RAILWAY) && ///< Tile has rails
431 KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE && ///< Tile has exactly *one* track
432 HasSignalOnTrack(ft.m_new_tile, TrackBitsToTrack(TrackdirBitsToTrackBits(ft.m_new_td_bits)))) { ///< Tile has signal
433 num_signals++;
436 /* Check if tile has train/is reserved */
437 if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE && ///< Tile has exactly *one* track
438 HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(ft.m_new_td_bits))) { ///< Tile is reserved
439 Train* other_train = GetTrainForReservation(ft.m_new_tile, TrackBitsToTrack(TrackdirBitsToTrackBits(ft.m_new_td_bits)));
442 if (other_train != nullptr &&
443 other_train != this && ///< Other train is not this train
444 other_train->GetAccelerationStatus() != AS_BRAKE) { ///< Other train is not braking
445 atc_speed = other_train->GetCurrentSpeed();
446 break;
450 /* Decide what in direction to continue: reservation, straight or "first/only" direction. */
451 /* Abort if there's no reservation even though the tile contains multiple tracks. */
452 TrackdirBits reserved = ft.m_new_td_bits & TrackBitsToTrackdirBits(GetReservedTrackbits(ft.m_new_tile));
454 if (reserved != TRACKDIR_BIT_NONE) {
455 // There is a reservation to follow.
456 old_td = FindFirstTrackdir(reserved);
458 else if (KillFirstBit(ft.m_new_td_bits) != TRACKDIR_BIT_NONE) {
459 // Tile has more than one track and we have no reservation. Bail out.
460 break;
462 else {
463 // There was no reservation but there is only one direction to follow, so follow it.
464 old_td = FindFirstTrackdir(ft.m_new_td_bits);
467 num_tiles++;
468 } while (num_tiles < 20 && num_signals < 3 && ft.Follow(ft.m_new_tile, old_td));
471 /* Check that the ATC speed is sufficiently large.
472 Avoids assertion error in UpdateSpeed(). */
473 max_speed = max(25, min(max_speed, atc_speed));
476 if (_settings_game.vehicle.train_acceleration_model == AM_REALISTIC && IsRailStationTile(this->tile)) {
477 StationID sid = GetStationIndex(this->tile);
478 if (this->current_order.ShouldStopAtStation(this, sid)) {
479 int station_ahead;
480 int station_length;
481 int stop_at = GetTrainStopLocation(sid, this->tile, this, &station_ahead, &station_length);
483 /* The distance to go is whatever is still ahead of the train minus the
484 * distance from the train's stop location to the end of the platform */
485 int distance_to_go = station_ahead / TILE_SIZE - (station_length - stop_at) / TILE_SIZE;
487 if (distance_to_go > 0) {
488 int st_max_speed = 120;
490 int delta_v = this->cur_speed / (distance_to_go + 1);
491 if (max_speed > (this->cur_speed - delta_v)) {
492 st_max_speed = this->cur_speed - (delta_v / 10);
495 st_max_speed = max(st_max_speed, 25 * distance_to_go);
496 max_speed = min(max_speed, st_max_speed);
501 for (const Train *u = this; u != NULL; u = u->Next()) {
502 if (_settings_game.vehicle.train_acceleration_model == AM_REALISTIC && u->track == TRACK_BIT_DEPOT) {
503 max_speed = min(max_speed, 61);
504 break;
507 /* Vehicle is on the middle part of a bridge. */
508 if (u->track == TRACK_BIT_WORMHOLE && !(u->vehstatus & VS_HIDDEN)) {
509 max_speed = min(max_speed, GetBridgeSpec(GetBridgeType(u->tile))->speed);
513 max_speed = min(max_speed, this->current_order.GetMaxSpeed());
514 return min(max_speed, this->gcache.cached_max_track_speed);
517 /** Update acceleration of the train from the cached power and weight. */
518 void Train::UpdateAcceleration()
520 assert(this->IsFrontEngine() || this->IsFreeWagon());
522 uint power = this->gcache.cached_power;
523 uint weight = this->gcache.cached_weight;
524 assert(weight != 0);
525 this->acceleration = Clamp(power / weight * 4, 1, 255);
529 * Get the width of a train vehicle image in the GUI.
530 * @param offset Additional offset for positioning the sprite; set to NULL if not needed
531 * @return Width in pixels
533 int Train::GetDisplayImageWidth(Point *offset) const
535 int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
536 int vehicle_pitch = 0;
538 const Engine *e = this->GetEngine();
539 if (e->GetGRF() != NULL && is_custom_sprite(e->u.rail.image_index)) {
540 reference_width = e->GetGRF()->traininfo_vehicle_width;
541 vehicle_pitch = e->GetGRF()->traininfo_vehicle_pitch;
544 if (offset != NULL) {
545 offset->x = ScaleGUITrad(reference_width) / 2;
546 offset->y = ScaleGUITrad(vehicle_pitch);
548 return ScaleGUITrad(this->gcache.cached_veh_length * reference_width / VEHICLE_LENGTH);
551 static SpriteID GetDefaultTrainSprite(uint8 spritenum, Direction direction)
553 assert(IsValidImageIndex<VEH_TRAIN>(spritenum));
554 return ((direction + _engine_sprite_add[spritenum]) & _engine_sprite_and[spritenum]) + _engine_sprite_base[spritenum];
558 * Get the sprite to display the train.
559 * @param direction Direction of view/travel.
560 * @param image_type Visualisation context.
561 * @return Sprite to display.
563 void Train::GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const
565 uint8 spritenum = this->spritenum;
567 if (HasBit(this->flags, VRF_REVERSE_DIRECTION)) direction = ReverseDir(direction);
569 if (is_custom_sprite(spritenum)) {
570 GetCustomVehicleSprite(this, (Direction)(direction + 4 * IS_CUSTOM_SECONDHEAD_SPRITE(spritenum)), image_type, result);
571 if (result->IsValid()) return;
573 spritenum = this->GetEngine()->original_image_index;
576 assert(IsValidImageIndex<VEH_TRAIN>(spritenum));
577 SpriteID sprite = GetDefaultTrainSprite(spritenum, direction);
579 if (this->cargo.StoredCount() >= this->cargo_cap / 2U) sprite += _wagon_full_adder[spritenum];
581 result->Set(sprite);
584 static void GetRailIcon(EngineID engine, bool rear_head, int &y, EngineImageType image_type, VehicleSpriteSeq *result)
586 const Engine *e = Engine::Get(engine);
587 Direction dir = rear_head ? DIR_E : DIR_W;
588 uint8 spritenum = e->u.rail.image_index;
590 if (is_custom_sprite(spritenum)) {
591 GetCustomVehicleIcon(engine, dir, image_type, result);
592 if (result->IsValid()) {
593 if (e->GetGRF() != NULL) {
594 y += ScaleGUITrad(e->GetGRF()->traininfo_vehicle_pitch);
596 return;
599 spritenum = Engine::Get(engine)->original_image_index;
602 if (rear_head) spritenum++;
604 result->Set(GetDefaultTrainSprite(spritenum, DIR_W));
607 void DrawTrainEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
609 if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
610 int yf = y;
611 int yr = y;
613 VehicleSpriteSeq seqf, seqr;
614 GetRailIcon(engine, false, yf, image_type, &seqf);
615 GetRailIcon(engine, true, yr, image_type, &seqr);
617 Rect16 rectf = seqf.GetBounds();
618 Rect16 rectr = seqr.GetBounds();
620 preferred_x = SoftClamp(preferred_x,
621 left - UnScaleGUI(rectf.left) + ScaleGUITrad(14),
622 right - UnScaleGUI(rectr.right) - ScaleGUITrad(15));
624 seqf.Draw(preferred_x - ScaleGUITrad(14), yf, pal, pal == PALETTE_CRASH);
625 seqr.Draw(preferred_x + ScaleGUITrad(15), yr, pal, pal == PALETTE_CRASH);
626 } else {
627 VehicleSpriteSeq seq;
628 GetRailIcon(engine, false, y, image_type, &seq);
630 Rect16 rect = seq.GetBounds();
631 preferred_x = Clamp(preferred_x,
632 left - UnScaleGUI(rect.left),
633 right - UnScaleGUI(rect.right));
635 seq.Draw(preferred_x, y, pal, pal == PALETTE_CRASH);
640 * Get the size of the sprite of a train sprite heading west, or both heads (used for lists).
641 * @param engine The engine to get the sprite from.
642 * @param[out] width The width of the sprite.
643 * @param[out] height The height of the sprite.
644 * @param[out] xoffs Number of pixels to shift the sprite to the right.
645 * @param[out] yoffs Number of pixels to shift the sprite downwards.
646 * @param image_type Context the sprite is used in.
648 void GetTrainSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
650 int y = 0;
652 VehicleSpriteSeq seq;
653 GetRailIcon(engine, false, y, image_type, &seq);
655 Rect16 rect = seq.GetBounds();
657 width = UnScaleGUI(rect.right - rect.left + 1);
658 height = UnScaleGUI(rect.bottom - rect.top + 1);
659 xoffs = UnScaleGUI(rect.left);
660 yoffs = UnScaleGUI(rect.top);
662 if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
663 GetRailIcon(engine, true, y, image_type, &seq);
664 rect = seq.GetBounds();
666 /* Calculate values relative to an imaginary center between the two sprites. */
667 width = ScaleGUITrad(TRAININFO_DEFAULT_VEHICLE_WIDTH) + UnScaleGUI(rect.right) - xoffs;
668 height = max<uint>(height, UnScaleGUI(rect.bottom - rect.top + 1));
669 xoffs = xoffs - ScaleGUITrad(TRAININFO_DEFAULT_VEHICLE_WIDTH) / 2;
670 yoffs = min(yoffs, UnScaleGUI(rect.top));
675 * Build a railroad wagon.
676 * @param tile tile of the depot where rail-vehicle is built.
677 * @param flags type of operation.
678 * @param e the engine to build.
679 * @param ret[out] the vehicle that has been built.
680 * @return the cost of this operation or an error.
682 static CommandCost CmdBuildRailWagon(TileIndex tile, DoCommandFlag flags, const Engine *e, Vehicle **ret)
684 const RailVehicleInfo *rvi = &e->u.rail;
686 /* Check that the wagon can drive on the track in question */
687 if (!IsCompatibleRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
689 if (flags & DC_EXEC) {
690 Train *v = new Train();
691 *ret = v;
692 v->spritenum = rvi->image_index;
694 v->engine_type = e->index;
695 v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
697 DiagDirection dir = GetRailDepotDirection(tile);
699 v->direction = DiagDirToDir(dir);
700 v->tile = tile;
702 int x = TileX(tile) * TILE_SIZE | _vehicle_initial_x_fract[dir];
703 int y = TileY(tile) * TILE_SIZE | _vehicle_initial_y_fract[dir];
705 v->x_pos = x;
706 v->y_pos = y;
707 v->z_pos = GetSlopePixelZ(x, y);
708 v->owner = _current_company;
709 v->track = TRACK_BIT_DEPOT;
710 v->vehstatus = VS_HIDDEN | VS_DEFPAL;
711 v->reverse_distance = 0;
713 v->SetWagon();
715 v->SetFreeWagon();
716 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
718 v->cargo_type = e->GetDefaultCargoType();
719 v->cargo_cap = rvi->capacity;
720 v->refit_cap = 0;
722 v->railtype = rvi->railtype;
724 v->date_of_last_service = _date;
725 v->build_year = _cur_year;
726 v->sprite_seq.Set(SPR_IMG_QUERY);
727 v->random_bits = VehicleRandomBits();
729 v->group_id = DEFAULT_GROUP;
731 AddArticulatedParts(v);
733 _new_vehicle_id = v->index;
735 v->UpdatePosition();
736 v->First()->ConsistChanged(CCF_ARRANGE);
737 UpdateTrainGroupID(v->First());
739 CheckConsistencyOfArticulatedVehicle(v);
741 /* Try to connect the vehicle to one of free chains of wagons. */
742 Train *w;
743 FOR_ALL_TRAINS(w) {
744 if (w->tile == tile && ///< Same depot
745 w->IsFreeWagon() && ///< A free wagon chain
746 w->engine_type == e->index && ///< Same type
747 w->First() != v && ///< Don't connect to ourself
748 !(w->vehstatus & VS_CRASHED)) { ///< Not crashed/flooded
749 DoCommand(0, v->index | 1 << 20, w->Last()->index, DC_EXEC, CMD_MOVE_RAIL_VEHICLE);
750 break;
755 return CommandCost();
758 /** Move all free vehicles in the depot to the train */
759 static void NormalizeTrainVehInDepot(const Train *u)
761 const Train *v;
762 FOR_ALL_TRAINS(v) {
763 if (v->IsFreeWagon() && v->tile == u->tile &&
764 v->track == TRACK_BIT_DEPOT) {
765 if (DoCommand(0, v->index | 1 << 20, u->index, DC_EXEC,
766 CMD_MOVE_RAIL_VEHICLE).Failed())
767 break;
772 static void AddRearEngineToMultiheadedTrain(Train *v)
774 Train *u = new Train();
775 v->value >>= 1;
776 u->value = v->value;
777 u->direction = v->direction;
778 u->owner = v->owner;
779 u->tile = v->tile;
780 u->x_pos = v->x_pos;
781 u->y_pos = v->y_pos;
782 u->z_pos = v->z_pos;
783 u->track = TRACK_BIT_DEPOT;
784 u->vehstatus = v->vehstatus & ~VS_STOPPED;
785 u->spritenum = v->spritenum + 1;
786 u->cargo_type = v->cargo_type;
787 u->cargo_subtype = v->cargo_subtype;
788 u->cargo_cap = v->cargo_cap;
789 u->refit_cap = v->refit_cap;
790 u->railtype = v->railtype;
791 u->engine_type = v->engine_type;
792 u->date_of_last_service = v->date_of_last_service;
793 u->build_year = v->build_year;
794 u->sprite_seq.Set(SPR_IMG_QUERY);
795 u->random_bits = VehicleRandomBits();
796 v->SetMultiheaded();
797 u->SetMultiheaded();
798 v->SetNext(u);
799 u->UpdatePosition();
801 /* Now we need to link the front and rear engines together */
802 v->other_multiheaded_part = u;
803 u->other_multiheaded_part = v;
807 * Build a railroad vehicle.
808 * @param tile tile of the depot where rail-vehicle is built.
809 * @param flags type of operation.
810 * @param e the engine to build.
811 * @param data bit 0 prevents any free cars from being added to the train.
812 * @param ret[out] the vehicle that has been built.
813 * @return the cost of this operation or an error.
815 CommandCost CmdBuildRailVehicle(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **ret)
817 const RailVehicleInfo *rvi = &e->u.rail;
819 if (rvi->railveh_type == RAILVEH_WAGON) return CmdBuildRailWagon(tile, flags, e, ret);
821 /* Check if depot and new engine uses the same kind of tracks *
822 * We need to see if the engine got power on the tile to avoid electric engines in non-electric depots */
823 if (!HasPowerOnRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
825 if (flags & DC_EXEC) {
826 DiagDirection dir = GetRailDepotDirection(tile);
827 int x = TileX(tile) * TILE_SIZE + _vehicle_initial_x_fract[dir];
828 int y = TileY(tile) * TILE_SIZE + _vehicle_initial_y_fract[dir];
830 Train *v = new Train();
831 *ret = v;
832 v->direction = DiagDirToDir(dir);
833 v->tile = tile;
834 v->owner = _current_company;
835 v->x_pos = x;
836 v->y_pos = y;
837 v->z_pos = GetSlopePixelZ(x, y);
838 v->track = TRACK_BIT_DEPOT;
839 v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
840 v->spritenum = rvi->image_index;
841 v->cargo_type = e->GetDefaultCargoType();
842 v->cargo_cap = rvi->capacity;
843 v->refit_cap = 0;
844 v->last_station_visited = INVALID_STATION;
845 v->last_loading_station = INVALID_STATION;
846 v->reverse_distance = 0;
848 v->engine_type = e->index;
849 v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
851 v->reliability = e->reliability;
852 v->reliability_spd_dec = e->reliability_spd_dec;
853 v->max_age = e->GetLifeLengthInDays();
855 v->railtype = rvi->railtype;
856 _new_vehicle_id = v->index;
858 v->SetServiceInterval(Company::Get(_current_company)->settings.vehicle.servint_trains);
859 v->date_of_last_service = _date;
860 v->build_year = _cur_year;
861 v->sprite_seq.Set(SPR_IMG_QUERY);
862 v->random_bits = VehicleRandomBits();
864 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
865 v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
867 v->group_id = DEFAULT_GROUP;
869 v->SetFrontEngine();
870 v->SetEngine();
872 v->UpdatePosition();
874 if (rvi->railveh_type == RAILVEH_MULTIHEAD) {
875 AddRearEngineToMultiheadedTrain(v);
876 } else {
877 AddArticulatedParts(v);
880 v->ConsistChanged(CCF_ARRANGE);
881 UpdateTrainGroupID(v);
883 if (!HasBit(data, 0) && !(flags & DC_AUTOREPLACE)) { // check if the cars should be added to the new vehicle
884 NormalizeTrainVehInDepot(v);
887 CheckConsistencyOfArticulatedVehicle(v);
890 return CommandCost();
893 static Train *FindGoodVehiclePos(const Train *src)
895 EngineID eng = src->engine_type;
896 TileIndex tile = src->tile;
898 Train *dst;
899 FOR_ALL_TRAINS(dst) {
900 if (dst->IsFreeWagon() && dst->tile == tile && !(dst->vehstatus & VS_CRASHED)) {
901 /* check so all vehicles in the line have the same engine. */
902 Train *t = dst;
903 while (t->engine_type == eng) {
904 t = t->Next();
905 if (t == NULL) return dst;
910 return NULL;
913 /** Helper type for lists/vectors of trains */
914 typedef SmallVector<Train *, 16> TrainList;
917 * Make a backup of a train into a train list.
918 * @param list to make the backup in
919 * @param t the train to make the backup of
921 static void MakeTrainBackup(TrainList &list, Train *t)
923 for (; t != NULL; t = t->Next()) *list.Append() = t;
927 * Restore the train from the backup list.
928 * @param list the train to restore.
930 static void RestoreTrainBackup(TrainList &list)
932 /* No train, nothing to do. */
933 if (list.Length() == 0) return;
935 Train *prev = NULL;
936 /* Iterate over the list and rebuild it. */
937 for (Train **iter = list.Begin(); iter != list.End(); iter++) {
938 Train *t = *iter;
939 if (prev != NULL) {
940 prev->SetNext(t);
941 } else if (t->Previous() != NULL) {
942 /* Make sure the head of the train is always the first in the chain. */
943 t->Previous()->SetNext(NULL);
945 prev = t;
950 * Remove the given wagon from its consist.
951 * @param part the part of the train to remove.
952 * @param chain whether to remove the whole chain.
954 static void RemoveFromConsist(Train *part, bool chain = false)
956 Train *tail = chain ? part->Last() : part->GetLastEnginePart();
958 /* Unlink at the front, but make it point to the next
959 * vehicle after the to be remove part. */
960 if (part->Previous() != NULL) part->Previous()->SetNext(tail->Next());
962 /* Unlink at the back */
963 tail->SetNext(NULL);
967 * Inserts a chain into the train at dst.
968 * @param dst the place where to append after.
969 * @param chain the chain to actually add.
971 static void InsertInConsist(Train *dst, Train *chain)
973 /* We do not want to add something in the middle of an articulated part. */
974 assert(dst->Next() == NULL || !dst->Next()->IsArticulatedPart());
976 chain->Last()->SetNext(dst->Next());
977 dst->SetNext(chain);
981 * Normalise the dual heads in the train, i.e. if one is
982 * missing move that one to this train.
983 * @param t the train to normalise.
985 static void NormaliseDualHeads(Train *t)
987 for (; t != NULL; t = t->GetNextVehicle()) {
988 if (!t->IsMultiheaded() || !t->IsEngine()) continue;
990 /* Make sure that there are no free cars before next engine */
991 Train *u;
992 for (u = t; u->Next() != NULL && !u->Next()->IsEngine(); u = u->Next()) {}
994 if (u == t->other_multiheaded_part) continue;
996 /* Remove the part from the 'wrong' train */
997 RemoveFromConsist(t->other_multiheaded_part);
998 /* And add it to the 'right' train */
999 InsertInConsist(u, t->other_multiheaded_part);
1004 * Normalise the sub types of the parts in this chain.
1005 * @param chain the chain to normalise.
1007 static void NormaliseSubtypes(Train *chain)
1009 /* Nothing to do */
1010 if (chain == NULL) return;
1012 /* We must be the first in the chain. */
1013 assert(chain->Previous() == NULL);
1015 /* Set the appropriate bits for the first in the chain. */
1016 if (chain->IsWagon()) {
1017 chain->SetFreeWagon();
1018 } else {
1019 assert(chain->IsEngine());
1020 chain->SetFrontEngine();
1023 /* Now clear the bits for the rest of the chain */
1024 for (Train *t = chain->Next(); t != NULL; t = t->Next()) {
1025 t->ClearFreeWagon();
1026 t->ClearFrontEngine();
1031 * Check/validate whether we may actually build a new train.
1032 * @note All vehicles are/were 'heads' of their chains.
1033 * @param original_dst The original destination chain.
1034 * @param dst The destination chain after constructing the train.
1035 * @param original_dst The original source chain.
1036 * @param dst The source chain after constructing the train.
1037 * @return possible error of this command.
1039 static CommandCost CheckNewTrain(Train *original_dst, Train *dst, Train *original_src, Train *src)
1041 /* Just add 'new' engines and subtract the original ones.
1042 * If that's less than or equal to 0 we can be sure we did
1043 * not add any engines (read: trains) along the way. */
1044 if ((src != NULL && src->IsEngine() ? 1 : 0) +
1045 (dst != NULL && dst->IsEngine() ? 1 : 0) -
1046 (original_src != NULL && original_src->IsEngine() ? 1 : 0) -
1047 (original_dst != NULL && original_dst->IsEngine() ? 1 : 0) <= 0) {
1048 return CommandCost();
1051 /* Get a free unit number and check whether it's within the bounds.
1052 * There will always be a maximum of one new train. */
1053 if (GetFreeUnitNumber(VEH_TRAIN) <= _settings_game.vehicle.max_trains) return CommandCost();
1055 return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
1059 * Check whether the train parts can be attached.
1060 * @param t the train to check
1061 * @return possible error of this command.
1063 static CommandCost CheckTrainAttachment(Train *t)
1065 /* No multi-part train, no need to check. */
1066 if (t == NULL || t->Next() == NULL || !t->IsEngine()) return CommandCost();
1068 /* The maximum length for a train. For each part we decrease this by one
1069 * and if the result is negative the train is simply too long. */
1070 int allowed_len = _settings_game.vehicle.max_train_length * TILE_SIZE - t->gcache.cached_veh_length;
1072 Train *head = t;
1073 Train *prev = t;
1075 /* Break the prev -> t link so it always holds within the loop. */
1076 t = t->Next();
1077 prev->SetNext(NULL);
1079 /* Make sure the cache is cleared. */
1080 head->InvalidateNewGRFCache();
1082 while (t != NULL) {
1083 allowed_len -= t->gcache.cached_veh_length;
1085 Train *next = t->Next();
1087 /* Unlink the to-be-added piece; it is already unlinked from the previous
1088 * part due to the fact that the prev -> t link is broken. */
1089 t->SetNext(NULL);
1091 /* Don't check callback for articulated or rear dual headed parts */
1092 if (!t->IsArticulatedPart() && !t->IsRearDualheaded()) {
1093 /* Back up and clear the first_engine data to avoid using wagon override group */
1094 EngineID first_engine = t->gcache.first_engine;
1095 t->gcache.first_engine = INVALID_ENGINE;
1097 /* We don't want the cache to interfere. head's cache is cleared before
1098 * the loop and after each callback does not need to be cleared here. */
1099 t->InvalidateNewGRFCache();
1101 uint16 callback = GetVehicleCallbackParent(CBID_TRAIN_ALLOW_WAGON_ATTACH, 0, 0, head->engine_type, t, head);
1103 /* Restore original first_engine data */
1104 t->gcache.first_engine = first_engine;
1106 /* We do not want to remember any cached variables from the test run */
1107 t->InvalidateNewGRFCache();
1108 head->InvalidateNewGRFCache();
1110 if (callback != CALLBACK_FAILED) {
1111 /* A failing callback means everything is okay */
1112 StringID error = STR_NULL;
1114 if (head->GetGRF()->grf_version < 8) {
1115 if (callback == 0xFD) error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1116 if (callback < 0xFD) error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
1117 if (callback >= 0x100) ErrorUnknownCallbackResult(head->GetGRFID(), CBID_TRAIN_ALLOW_WAGON_ATTACH, callback);
1118 } else {
1119 if (callback < 0x400) {
1120 error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
1121 } else {
1122 switch (callback) {
1123 case 0x400: // allow if railtypes match (always the case for OpenTTD)
1124 case 0x401: // allow
1125 break;
1127 default: // unknown reason -> disallow
1128 case 0x402: // disallow attaching
1129 error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1130 break;
1135 if (error != STR_NULL) return_cmd_error(error);
1139 /* And link it to the new part. */
1140 prev->SetNext(t);
1141 prev = t;
1142 t = next;
1145 if (allowed_len < 0) return_cmd_error(STR_ERROR_TRAIN_TOO_LONG);
1146 return CommandCost();
1150 * Validate whether we are going to create valid trains.
1151 * @note All vehicles are/were 'heads' of their chains.
1152 * @param original_dst The original destination chain.
1153 * @param dst The destination chain after constructing the train.
1154 * @param original_dst The original source chain.
1155 * @param dst The source chain after constructing the train.
1156 * @param check_limit Whether to check the vehicle limit.
1157 * @return possible error of this command.
1159 static CommandCost ValidateTrains(Train *original_dst, Train *dst, Train *original_src, Train *src, bool check_limit)
1161 /* Check whether we may actually construct the trains. */
1162 CommandCost ret = CheckTrainAttachment(src);
1163 if (ret.Failed()) return ret;
1164 ret = CheckTrainAttachment(dst);
1165 if (ret.Failed()) return ret;
1167 /* Check whether we need to build a new train. */
1168 return check_limit ? CheckNewTrain(original_dst, dst, original_src, src) : CommandCost();
1172 * Arrange the trains in the wanted way.
1173 * @param dst_head The destination chain of the to be moved vehicle.
1174 * @param dst The destination for the to be moved vehicle.
1175 * @param src_head The source chain of the to be moved vehicle.
1176 * @param src The to be moved vehicle.
1177 * @param move_chain Whether to move all vehicles after src or not.
1179 static void ArrangeTrains(Train **dst_head, Train *dst, Train **src_head, Train *src, bool move_chain)
1181 /* First determine the front of the two resulting trains */
1182 if (*src_head == *dst_head) {
1183 /* If we aren't moving part(s) to a new train, we are just moving the
1184 * front back and there is not destination head. */
1185 *dst_head = NULL;
1186 } else if (*dst_head == NULL) {
1187 /* If we are moving to a new train the head of the move train would become
1188 * the head of the new vehicle. */
1189 *dst_head = src;
1192 if (src == *src_head) {
1193 /* If we are moving the front of a train then we are, in effect, creating
1194 * a new head for the train. Point to that. Unless we are moving the whole
1195 * train in which case there is not 'source' train anymore.
1196 * In case we are a multiheaded part we want the complete thing to come
1197 * with us, so src->GetNextUnit(), however... when we are e.g. a wagon
1198 * that is followed by a rear multihead we do not want to include that. */
1199 *src_head = move_chain ? NULL :
1200 (src->IsMultiheaded() ? src->GetNextUnit() : src->GetNextVehicle());
1203 /* Now it's just simply removing the part that we are going to move from the
1204 * source train and *if* the destination is a not a new train add the chain
1205 * at the destination location. */
1206 RemoveFromConsist(src, move_chain);
1207 if (*dst_head != src) InsertInConsist(dst, src);
1209 /* Now normalise the dual heads, that is move the dual heads around in such
1210 * a way that the head and rear of a dual head are in the same train */
1211 NormaliseDualHeads(*src_head);
1212 NormaliseDualHeads(*dst_head);
1216 * Normalise the head of the train again, i.e. that is tell the world that
1217 * we have changed and update all kinds of variables.
1218 * @param head the train to update.
1220 static void NormaliseTrainHead(Train *head)
1222 /* Not much to do! */
1223 if (head == NULL) return;
1225 /* Tell the 'world' the train changed. */
1226 head->ConsistChanged(CCF_ARRANGE);
1227 UpdateTrainGroupID(head);
1229 /* Not a front engine, i.e. a free wagon chain. No need to do more. */
1230 if (!head->IsFrontEngine()) return;
1232 /* Update the refit button and window */
1233 InvalidateWindowData(WC_VEHICLE_REFIT, head->index, VIWD_CONSIST_CHANGED);
1234 SetWindowWidgetDirty(WC_VEHICLE_VIEW, head->index, WID_VV_REFIT);
1236 /* If we don't have a unit number yet, set one. */
1237 if (head->unitnumber != 0) return;
1238 head->unitnumber = GetFreeUnitNumber(VEH_TRAIN);
1242 * Move a rail vehicle around inside the depot.
1243 * @param tile unused
1244 * @param flags type of operation
1245 * Note: DC_AUTOREPLACE is set when autoreplace tries to undo its modifications or moves vehicles to temporary locations inside the depot.
1246 * @param p1 various bitstuffed elements
1247 * - p1 (bit 0 - 19) source vehicle index
1248 * - p1 (bit 20) move all vehicles following the source vehicle
1249 * - p1 (bit 21) this is a virtual vehicle (for creating TemplateVehicles)
1250 * @param p2 what wagon to put the source wagon AFTER, XXX - INVALID_VEHICLE to make a new line
1251 * @param text unused
1252 * @return the cost of this operation or an error
1254 CommandCost CmdMoveRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1256 VehicleID s = GB(p1, 0, 20);
1257 VehicleID d = GB(p2, 0, 20);
1258 bool move_chain = HasBit(p1, 20);
1260 Train *src = Train::GetIfValid(s);
1261 if (src == NULL) return CMD_ERROR;
1263 CommandCost ret = CheckOwnership(src->owner);
1264 if (ret.Failed()) return ret;
1266 /* Do not allow moving crashed vehicles inside the depot, it is likely to cause asserts later */
1267 if (src->vehstatus & VS_CRASHED) return CMD_ERROR;
1269 /* if nothing is selected as destination, try and find a matching vehicle to drag to. */
1270 Train *dst;
1271 if (d == INVALID_VEHICLE) {
1272 dst = src->IsEngine() ? NULL : FindGoodVehiclePos(src);
1273 } else {
1274 dst = Train::GetIfValid(d);
1275 if (dst == NULL) return CMD_ERROR;
1277 CommandCost ret = CheckOwnership(dst->owner);
1278 if (ret.Failed()) return ret;
1280 /* Do not allow appending to crashed vehicles, too */
1281 if (dst->vehstatus & VS_CRASHED) return CMD_ERROR;
1284 /* if an articulated part is being handled, deal with its parent vehicle */
1285 src = src->GetFirstEnginePart();
1286 if (dst != NULL) {
1287 dst = dst->GetFirstEnginePart();
1288 assert(HasBit(dst->subtype, GVSF_VIRTUAL) == HasBit(src->subtype, GVSF_VIRTUAL));
1291 /* don't move the same vehicle.. */
1292 if (src == dst) return CommandCost();
1294 /* locate the head of the two chains */
1295 Train *src_head = src->First();
1296 assert(HasBit(src_head->subtype, GVSF_VIRTUAL) == HasBit(src->subtype, GVSF_VIRTUAL));
1297 Train *dst_head;
1298 if (dst != NULL) {
1299 dst_head = dst->First();
1300 assert(HasBit(dst_head->subtype, GVSF_VIRTUAL) == HasBit(dst->subtype, GVSF_VIRTUAL));
1301 if (dst_head->tile != src_head->tile) return CMD_ERROR;
1302 /* Now deal with articulated part of destination wagon */
1303 dst = dst->GetLastEnginePart();
1304 } else {
1305 dst_head = NULL;
1308 if (src->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
1310 /* When moving all wagons, we can't have the same src_head and dst_head */
1311 if (move_chain && src_head == dst_head) return CommandCost();
1313 /* When moving a multiheaded part to be place after itself, bail out. */
1314 if (!move_chain && dst != NULL && dst->IsRearDualheaded() && src == dst->other_multiheaded_part) return CommandCost();
1316 /* Check if all vehicles in the source train are stopped inside a depot. */
1317 /* Do this check only if the vehicle to be moved is non-virtual */
1318 if ( !HasBit(p1, 21) )
1319 if (!src_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1321 /* Check if all vehicles in the destination train are stopped inside a depot. */
1322 /* Do this check only if the destination vehicle is non-virtual */
1323 if ( !HasBit(p1, 21) )
1324 if (dst_head != NULL && !dst_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1326 /* First make a backup of the order of the trains. That way we can do
1327 * whatever we want with the order and later on easily revert. */
1328 TrainList original_src;
1329 TrainList original_dst;
1331 MakeTrainBackup(original_src, src_head);
1332 MakeTrainBackup(original_dst, dst_head);
1334 /* Also make backup of the original heads as ArrangeTrains can change them.
1335 * For the destination head we do not care if it is the same as the source
1336 * head because in that case it's just a copy. */
1337 Train *original_src_head = src_head;
1338 Train *original_dst_head = (dst_head == src_head ? NULL : dst_head);
1340 /* We want this information from before the rearrangement, but execute this after the validation.
1341 * original_src_head can't be NULL; src is by definition != NULL, so src_head can't be NULL as
1342 * src->GetFirst() always yields non-NULL, so eventually original_src_head != NULL as well. */
1343 bool original_src_head_front_engine = original_src_head->IsFrontEngine();
1344 bool original_dst_head_front_engine = original_dst_head != NULL && original_dst_head->IsFrontEngine();
1346 /* (Re)arrange the trains in the wanted arrangement. */
1347 ArrangeTrains(&dst_head, dst, &src_head, src, move_chain);
1349 if ((flags & DC_AUTOREPLACE) == 0) {
1350 /* If the autoreplace flag is set we do not need to test for the validity
1351 * because we are going to revert the train to its original state. As we
1352 * assume the original state was correct autoreplace can skip this. */
1353 CommandCost ret = ValidateTrains(original_dst_head, dst_head, original_src_head, src_head, true);
1354 if (ret.Failed()) {
1355 /* Restore the train we had. */
1356 RestoreTrainBackup(original_src);
1357 RestoreTrainBackup(original_dst);
1358 return ret;
1362 /* do it? */
1363 if (flags & DC_EXEC) {
1364 /* Remove old heads from the statistics */
1365 if (original_src_head_front_engine) GroupStatistics::CountVehicle(original_src_head, -1);
1366 if (original_dst_head_front_engine) GroupStatistics::CountVehicle(original_dst_head, -1);
1368 /* First normalise the sub types of the chains. */
1369 NormaliseSubtypes(src_head);
1370 NormaliseSubtypes(dst_head);
1372 /* There are 14 different cases:
1373 * 1) front engine gets moved to a new train, it stays a front engine.
1374 * a) the 'next' part is a wagon that becomes a free wagon chain.
1375 * b) the 'next' part is an engine that becomes a front engine.
1376 * c) there is no 'next' part, nothing else happens
1377 * 2) front engine gets moved to another train, it is not a front engine anymore
1378 * a) the 'next' part is a wagon that becomes a free wagon chain.
1379 * b) the 'next' part is an engine that becomes a front engine.
1380 * c) there is no 'next' part, nothing else happens
1381 * 3) front engine gets moved to later in the current train, it is not a front engine anymore.
1382 * a) the 'next' part is a wagon that becomes a free wagon chain.
1383 * b) the 'next' part is an engine that becomes a front engine.
1384 * 4) free wagon gets moved
1385 * a) the 'next' part is a wagon that becomes a free wagon chain.
1386 * b) the 'next' part is an engine that becomes a front engine.
1387 * c) there is no 'next' part, nothing else happens
1388 * 5) non front engine gets moved and becomes a new train, nothing else happens
1389 * 6) non front engine gets moved within a train / to another train, nothing hapens
1390 * 7) wagon gets moved, nothing happens
1392 if (src == original_src_head && src->IsEngine() && !src->IsFrontEngine()) {
1393 /* Cases #2 and #3: the front engine gets trashed. */
1394 DeleteWindowById(WC_VEHICLE_VIEW, src->index);
1395 DeleteWindowById(WC_VEHICLE_ORDERS, src->index);
1396 DeleteWindowById(WC_VEHICLE_REFIT, src->index);
1397 DeleteWindowById(WC_VEHICLE_DETAILS, src->index);
1398 DeleteWindowById(WC_VEHICLE_TIMETABLE, src->index);
1399 DeleteNewGRFInspectWindow(GSF_TRAINS, src->index);
1400 SetWindowDirty(WC_COMPANY, _current_company);
1402 /* Delete orders, group stuff and the unit number as we're not the
1403 * front of any vehicle anymore. */
1404 DeleteVehicleOrders(src);
1405 RemoveVehicleFromGroup(src);
1406 src->unitnumber = 0;
1407 if (HasBit(src->flags, VRF_HAVE_SLOT)) {
1408 TraceRestrictRemoveVehicleFromAllSlots(src->index);
1409 ClrBit(src->flags, VRF_HAVE_SLOT);
1413 /* We weren't a front engine but are becoming one. So
1414 * we should be put in the default group. */
1415 if (original_src_head != src && dst_head == src) {
1416 SetTrainGroupID(src, DEFAULT_GROUP);
1417 SetWindowDirty(WC_COMPANY, _current_company);
1420 /* Add new heads to statistics */
1421 if (src_head != NULL && src_head->IsFrontEngine()) GroupStatistics::CountVehicle(src_head, 1);
1422 if (dst_head != NULL && dst_head->IsFrontEngine()) GroupStatistics::CountVehicle(dst_head, 1);
1424 /* Handle 'new engine' part of cases #1b, #2b, #3b, #4b and #5 in NormaliseTrainHead. */
1425 NormaliseTrainHead(src_head);
1426 NormaliseTrainHead(dst_head);
1428 if ((flags & DC_NO_CARGO_CAP_CHECK) == 0) {
1429 CheckCargoCapacity(src_head);
1430 CheckCargoCapacity(dst_head);
1433 if (src_head != NULL) {
1434 src_head->last_loading_station = INVALID_STATION;
1435 ClrBit(src_head->vehicle_flags, VF_LAST_LOAD_ST_SEP);
1437 if (dst_head != NULL) {
1438 dst_head->last_loading_station = INVALID_STATION;
1439 ClrBit(dst_head->vehicle_flags, VF_LAST_LOAD_ST_SEP);
1442 if (src_head != NULL) src_head->First()->MarkDirty();
1443 if (dst_head != NULL) dst_head->First()->MarkDirty();
1445 /* We are undoubtedly changing something in the depot and train list. */
1446 /* But only if the moved vehicle is not virtual */
1447 if ( !HasBit(src->subtype, GVSF_VIRTUAL) ) {
1448 InvalidateWindowData(WC_VEHICLE_DEPOT, src->tile);
1449 InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
1450 } else {
1451 InvalidateWindowClassesData(WC_CREATE_TEMPLATE);
1453 } else {
1454 /* We don't want to execute what we're just tried. */
1455 RestoreTrainBackup(original_src);
1456 RestoreTrainBackup(original_dst);
1459 return CommandCost();
1463 * Sell a (single) train wagon/engine.
1464 * @param flags type of operation
1465 * @param t the train wagon to sell
1466 * @param data the selling mode
1467 * - data = 0: only sell the single dragged wagon/engine (and any belonging rear-engines)
1468 * - data = 1: sell the vehicle and all vehicles following it in the chain
1469 * if the wagon is dragged, don't delete the possibly belonging rear-engine to some front
1470 * @param user the user for the order backup.
1471 * @return the cost of this operation or an error
1473 CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *t, uint16 data, uint32 user)
1475 /* Sell a chain of vehicles or not? */
1476 bool sell_chain = HasBit(data, 0);
1478 Train *v = Train::From(t)->GetFirstEnginePart();
1479 Train *first = v->First();
1481 if (v->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
1483 /* First make a backup of the order of the train. That way we can do
1484 * whatever we want with the order and later on easily revert. */
1485 TrainList original;
1486 MakeTrainBackup(original, first);
1488 /* We need to keep track of the new head and the head of what we're going to sell. */
1489 Train *new_head = first;
1490 Train *sell_head = NULL;
1492 /* Split the train in the wanted way. */
1493 ArrangeTrains(&sell_head, NULL, &new_head, v, sell_chain);
1495 /* We don't need to validate the second train; it's going to be sold. */
1496 CommandCost ret = ValidateTrains(NULL, NULL, first, new_head, (flags & DC_AUTOREPLACE) == 0);
1497 if (ret.Failed()) {
1498 /* Restore the train we had. */
1499 RestoreTrainBackup(original);
1500 return ret;
1503 if (first->orders.list == NULL && !OrderList::CanAllocateItem()) {
1504 /* Restore the train we had. */
1505 RestoreTrainBackup(original);
1506 return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
1509 CommandCost cost(EXPENSES_NEW_VEHICLES);
1510 for (Train *t = sell_head; t != NULL; t = t->Next()) cost.AddCost(-t->value);
1512 /* do it? */
1513 if (flags & DC_EXEC) {
1514 /* First normalise the sub types of the chain. */
1515 NormaliseSubtypes(new_head);
1517 if (v == first && v->IsEngine() && !sell_chain && new_head != NULL && new_head->IsFrontEngine()) {
1518 /* We are selling the front engine. In this case we want to
1519 * 'give' the order, unit number and such to the new head. */
1520 new_head->orders.list = first->orders.list;
1521 new_head->AddToShared(first);
1522 DeleteVehicleOrders(first);
1524 /* Copy other important data from the front engine */
1525 new_head->CopyVehicleConfigAndStatistics(first);
1526 GroupStatistics::CountVehicle(new_head, 1); // after copying over the profit
1527 } else if (v->IsPrimaryVehicle() && data & (MAKE_ORDER_BACKUP_FLAG >> 20)) {
1528 OrderBackup::Backup(v, user);
1531 /* We need to update the information about the train. */
1532 NormaliseTrainHead(new_head);
1534 /* We are undoubtedly changing something in the depot and train list. */
1535 /* Unless its a virtual train */
1536 if ( !HasBit(v->subtype, GVSF_VIRTUAL) ) {
1537 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1538 InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
1539 } else {
1540 InvalidateWindowClassesData(WC_CREATE_TEMPLATE);
1543 /* Actually delete the sold 'goods' */
1544 delete sell_head;
1545 } else {
1546 /* We don't want to execute what we're just tried. */
1547 RestoreTrainBackup(original);
1550 return cost;
1553 void Train::UpdateDeltaXY(Direction direction)
1555 /* Set common defaults. */
1556 this->x_offs = -1;
1557 this->y_offs = -1;
1558 this->x_extent = 3;
1559 this->y_extent = 3;
1560 this->z_extent = 6;
1561 this->x_bb_offs = 0;
1562 this->y_bb_offs = 0;
1564 if (!IsDiagonalDirection(direction)) {
1565 static const int _sign_table[] =
1567 /* x, y */
1568 -1, -1, // DIR_N
1569 -1, 1, // DIR_E
1570 1, 1, // DIR_S
1571 1, -1, // DIR_W
1574 int half_shorten = (VEHICLE_LENGTH - this->gcache.cached_veh_length) / 2;
1576 /* For all straight directions, move the bound box to the centre of the vehicle, but keep the size. */
1577 this->x_offs -= half_shorten * _sign_table[direction];
1578 this->y_offs -= half_shorten * _sign_table[direction + 1];
1579 this->x_extent += this->x_bb_offs = half_shorten * _sign_table[direction];
1580 this->y_extent += this->y_bb_offs = half_shorten * _sign_table[direction + 1];
1581 } else {
1582 switch (direction) {
1583 /* Shorten southern corner of the bounding box according the vehicle length
1584 * and center the bounding box on the vehicle. */
1585 case DIR_NE:
1586 this->x_offs = 1 - (this->gcache.cached_veh_length + 1) / 2;
1587 this->x_extent = this->gcache.cached_veh_length - 1;
1588 this->x_bb_offs = -1;
1589 break;
1591 case DIR_NW:
1592 this->y_offs = 1 - (this->gcache.cached_veh_length + 1) / 2;
1593 this->y_extent = this->gcache.cached_veh_length - 1;
1594 this->y_bb_offs = -1;
1595 break;
1597 /* Move northern corner of the bounding box down according to vehicle length
1598 * and center the bounding box on the vehicle. */
1599 case DIR_SW:
1600 this->x_offs = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH;
1601 this->x_extent = VEHICLE_LENGTH - 1;
1602 this->x_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
1603 break;
1605 case DIR_SE:
1606 this->y_offs = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH;
1607 this->y_extent = VEHICLE_LENGTH - 1;
1608 this->y_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
1609 break;
1611 default:
1612 NOT_REACHED();
1618 * Mark a train as stuck and stop it if it isn't stopped right now.
1619 * @param v %Train to mark as being stuck.
1621 static void MarkTrainAsStuck(Train *v, bool waiting_restriction = false)
1623 if (!HasBit(v->flags, VRF_TRAIN_STUCK)) {
1624 /* It is the first time the problem occurred, set the "train stuck" flag. */
1625 SetBit(v->flags, VRF_TRAIN_STUCK);
1626 SB(v->flags, VRF_WAITING_RESTRICTION, 1, waiting_restriction ? 1 : 0);
1628 v->wait_counter = 0;
1630 /* Stop train */
1631 v->cur_speed = 0;
1632 v->subspeed = 0;
1633 v->SetLastSpeed();
1635 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
1636 } else if (waiting_restriction != HasBit(v->flags, VRF_WAITING_RESTRICTION)) {
1637 ToggleBit(v->flags, VRF_WAITING_RESTRICTION);
1638 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
1643 * Swap the two up/down flags in two ways:
1644 * - Swap values of \a swap_flag1 and \a swap_flag2, and
1645 * - If going up previously (#GVF_GOINGUP_BIT set), the #GVF_GOINGDOWN_BIT is set, and vice versa.
1646 * @param swap_flag1 [inout] First train flag.
1647 * @param swap_flag2 [inout] Second train flag.
1649 static void SwapTrainFlags(uint16 *swap_flag1, uint16 *swap_flag2)
1651 uint16 flag1 = *swap_flag1;
1652 uint16 flag2 = *swap_flag2;
1654 /* Clear the flags */
1655 ClrBit(*swap_flag1, GVF_GOINGUP_BIT);
1656 ClrBit(*swap_flag1, GVF_GOINGDOWN_BIT);
1657 ClrBit(*swap_flag1, GVF_CHUNNEL_BIT);
1658 ClrBit(*swap_flag2, GVF_GOINGUP_BIT);
1659 ClrBit(*swap_flag2, GVF_GOINGDOWN_BIT);
1660 ClrBit(*swap_flag2, GVF_CHUNNEL_BIT);
1662 /* Reverse the rail-flags (if needed) */
1663 if (HasBit(flag1, GVF_GOINGUP_BIT)) {
1664 SetBit(*swap_flag2, GVF_GOINGDOWN_BIT);
1665 } else if (HasBit(flag1, GVF_GOINGDOWN_BIT)) {
1666 SetBit(*swap_flag2, GVF_GOINGUP_BIT);
1669 if (HasBit(flag2, GVF_GOINGUP_BIT)) {
1670 SetBit(*swap_flag1, GVF_GOINGDOWN_BIT);
1671 } else if (HasBit(flag2, GVF_GOINGDOWN_BIT)) {
1672 SetBit(*swap_flag1, GVF_GOINGUP_BIT);
1675 if (HasBit(flag1, GVF_CHUNNEL_BIT)) {
1676 SetBit(*swap_flag2, GVF_CHUNNEL_BIT);
1679 if (HasBit(flag2, GVF_CHUNNEL_BIT)) {
1680 SetBit(*swap_flag1, GVF_CHUNNEL_BIT);
1685 * Updates some variables after swapping the vehicle.
1686 * @param v swapped vehicle
1688 static void UpdateStatusAfterSwap(Train *v)
1690 /* Reverse the direction. */
1691 if (v->track != TRACK_BIT_DEPOT) v->direction = ReverseDir(v->direction);
1693 /* Call the proper EnterTile function unless we are in a wormhole. */
1694 if (v->track != TRACK_BIT_WORMHOLE) {
1695 VehicleEnterTile(v, v->tile, v->x_pos, v->y_pos);
1696 } else {
1697 /* VehicleEnter_TunnelBridge() sets TRACK_BIT_WORMHOLE when the vehicle
1698 * is on the last bit of the bridge head (frame == TILE_SIZE - 1).
1699 * If we were swapped with such a vehicle, we have set TRACK_BIT_WORMHOLE,
1700 * when we shouldn't have. Check if this is the case. */
1701 TileIndex vt = TileVirtXY(v->x_pos, v->y_pos);
1702 if (IsTileType(vt, MP_TUNNELBRIDGE)) {
1703 VehicleEnterTile(v, vt, v->x_pos, v->y_pos);
1704 if (v->track != TRACK_BIT_WORMHOLE && IsBridgeTile(v->tile)) {
1705 /* We have just left the wormhole, possibly set the
1706 * "goingdown" bit. UpdateInclination() can be used
1707 * because we are at the border of the tile. */
1708 v->UpdatePosition();
1709 v->UpdateInclination(true, true);
1710 return;
1715 v->UpdatePosition();
1716 if (v->track == TRACK_BIT_WORMHOLE) v->UpdateInclination(false, false, true);
1717 v->UpdateViewport(true, true);
1721 * Swap vehicles \a l and \a r in consist \a v, and reverse their direction.
1722 * @param v Consist to change.
1723 * @param l %Vehicle index in the consist of the first vehicle.
1724 * @param r %Vehicle index in the consist of the second vehicle.
1726 void ReverseTrainSwapVeh(Train *v, int l, int r)
1728 Train *a, *b;
1730 /* locate vehicles to swap */
1731 for (a = v; l != 0; l--) a = a->Next();
1732 for (b = v; r != 0; r--) b = b->Next();
1734 if (a != b) {
1735 /* swap the hidden bits */
1737 uint16 tmp = (a->vehstatus & ~VS_HIDDEN) | (b->vehstatus & VS_HIDDEN);
1738 b->vehstatus = (b->vehstatus & ~VS_HIDDEN) | (a->vehstatus & VS_HIDDEN);
1739 a->vehstatus = tmp;
1742 Swap(a->track, b->track);
1743 Swap(a->direction, b->direction);
1744 Swap(a->x_pos, b->x_pos);
1745 Swap(a->y_pos, b->y_pos);
1746 Swap(a->tile, b->tile);
1747 Swap(a->z_pos, b->z_pos);
1749 SwapTrainFlags(&a->gv_flags, &b->gv_flags);
1751 UpdateStatusAfterSwap(a);
1752 UpdateStatusAfterSwap(b);
1753 } else {
1754 /* Swap GVF_GOINGUP_BIT/GVF_GOINGDOWN_BIT.
1755 * This is a little bit redundant way, a->gv_flags will
1756 * be (re)set twice, but it reduces code duplication */
1757 SwapTrainFlags(&a->gv_flags, &a->gv_flags);
1758 UpdateStatusAfterSwap(a);
1764 * Check if the vehicle is a train
1765 * @param v vehicle on tile
1766 * @return v if it is a train, NULL otherwise
1768 static Vehicle *TrainOnTileEnum(Vehicle *v, void *)
1770 return (v->type == VEH_TRAIN) ? v : NULL;
1775 * Checks if a train is approaching a rail-road crossing
1776 * @param v vehicle on tile
1777 * @param data tile with crossing we are testing
1778 * @return v if it is approaching a crossing, NULL otherwise
1780 static Vehicle *TrainApproachingCrossingEnum(Vehicle *v, void *data)
1782 if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return NULL;
1784 Train *t = Train::From(v);
1785 if (!t->IsFrontEngine()) return NULL;
1787 TileIndex tile = *(TileIndex *)data;
1789 if (TrainApproachingCrossingTile(t) != tile) return NULL;
1791 return t;
1796 * Finds a vehicle approaching rail-road crossing
1797 * @param tile tile to test
1798 * @return true if a vehicle is approaching the crossing
1799 * @pre tile is a rail-road crossing
1801 static bool TrainApproachingCrossing(TileIndex tile)
1803 assert(IsLevelCrossingTile(tile));
1805 DiagDirection dir = AxisToDiagDir(GetCrossingRailAxis(tile));
1806 TileIndex tile_from = tile + TileOffsByDiagDir(dir);
1808 if (HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum)) return true;
1810 dir = ReverseDiagDir(dir);
1811 tile_from = tile + TileOffsByDiagDir(dir);
1813 return HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum);
1816 /** Check if the crossing should be closed
1817 * @return train on crossing || train approaching crossing || reserved
1819 static inline bool CheckLevelCrossing(TileIndex tile)
1821 return HasCrossingReservation(tile) || HasVehicleOnPos(tile, NULL, &TrainOnTileEnum) || TrainApproachingCrossing(tile);
1825 * Sets correct crossing state
1826 * @param tile tile to update
1827 * @param sound should we play sound?
1828 * @param is_forced force set the crossing state to that of forced_state
1829 * @param forced_state the crossing state to set when using is_forced
1830 * @pre tile is a rail-road crossing
1832 static void UpdateLevelCrossingTile(TileIndex tile, bool sound, bool is_forced, bool forced_state)
1834 assert(IsLevelCrossingTile(tile));
1835 bool new_state;
1837 if (is_forced) {
1838 new_state = forced_state;
1839 } else {
1840 new_state = CheckLevelCrossing(tile);
1843 if (new_state != IsCrossingBarred(tile)) {
1844 if (new_state && sound) {
1845 RailTypeLabel railTypeLabel = GetRailTypeInfo(GetTileRailType(tile))->label;
1847 if (railTypeLabel != _planning_tracks_label &&
1848 railTypeLabel != _pipeline_tracks_label &&
1849 railTypeLabel != _wires_tracks_label &&
1850 _settings_client.sound.ambient) {
1851 SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
1854 SetCrossingBarred(tile, new_state);
1855 MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
1860 * Cycles the adjacent crossings and sets their state
1861 * @param tile tile to update
1862 * @param sound should we play sound?
1863 * @param force_close force close the crossing
1865 void UpdateLevelCrossing(TileIndex tile, bool sound, bool force_close)
1867 bool forced_state = force_close;
1868 if (!IsLevelCrossingTile(tile)) return;
1870 const Axis axis = GetCrossingRoadAxis(tile);
1871 const DiagDirection dir = AxisToDiagDir(axis);
1872 const DiagDirection reverse_dir = ReverseDiagDir(dir);
1874 for (TileIndex t = tile; !forced_state && IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == axis; t = TileAddByDiagDir(t, dir)) {
1875 forced_state |= CheckLevelCrossing(t);
1877 for (TileIndex t = TileAddByDiagDir(tile, reverse_dir); !forced_state && IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == axis; t = TileAddByDiagDir(t, reverse_dir)) {
1878 forced_state |= CheckLevelCrossing(t);
1881 UpdateLevelCrossingTile(tile, sound, force_close, forced_state);
1882 for (TileIndex t = TileAddByDiagDir(tile, dir); IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == axis; t = TileAddByDiagDir(t, dir)) {
1883 UpdateLevelCrossingTile(t, sound, true, forced_state);
1885 for (TileIndex t = TileAddByDiagDir(tile, reverse_dir); IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == axis; t = TileAddByDiagDir(t, reverse_dir)) {
1886 UpdateLevelCrossingTile(t, sound, true, forced_state);
1892 * Bars crossing and plays ding-ding sound if not barred already
1893 * @param tile tile with crossing
1894 * @pre tile is a rail-road crossing
1896 static inline void MaybeBarCrossingWithSound(TileIndex tile)
1898 if (!IsCrossingBarred(tile)) {
1899 UpdateLevelCrossing(tile, true, true);
1905 * Advances wagons for train reversing, needed for variable length wagons.
1906 * This one is called before the train is reversed.
1907 * @param v First vehicle in chain
1909 static void AdvanceWagonsBeforeSwap(Train *v)
1911 Train *base = v;
1912 Train *first = base; // first vehicle to move
1913 Train *last = v->Last(); // last vehicle to move
1914 uint length = CountVehiclesInChain(v);
1916 while (length > 2) {
1917 last = last->Previous();
1918 first = first->Next();
1920 int differential = base->CalcNextVehicleOffset() - last->CalcNextVehicleOffset();
1922 /* do not update images now
1923 * negative differential will be handled in AdvanceWagonsAfterSwap() */
1924 for (int i = 0; i < differential; i++) TrainController(first, last->Next());
1926 base = first; // == base->Next()
1927 length -= 2;
1933 * Advances wagons for train reversing, needed for variable length wagons.
1934 * This one is called after the train is reversed.
1935 * @param v First vehicle in chain
1937 static void AdvanceWagonsAfterSwap(Train *v)
1939 /* first of all, fix the situation when the train was entering a depot */
1940 Train *dep = v; // last vehicle in front of just left depot
1941 while (dep->Next() != NULL && (dep->track == TRACK_BIT_DEPOT || dep->Next()->track != TRACK_BIT_DEPOT)) {
1942 dep = dep->Next(); // find first vehicle outside of a depot, with next vehicle inside a depot
1945 Train *leave = dep->Next(); // first vehicle in a depot we are leaving now
1947 if (leave != NULL) {
1948 /* 'pull' next wagon out of the depot, so we won't miss it (it could stay in depot forever) */
1949 int d = TicksToLeaveDepot(dep);
1951 if (d <= 0) {
1952 leave->vehstatus &= ~VS_HIDDEN; // move it out of the depot
1953 leave->track = TrackToTrackBits(GetRailDepotTrack(leave->tile));
1954 for (int i = 0; i >= d; i--) TrainController(leave, NULL); // maybe move it, and maybe let another wagon leave
1956 } else {
1957 dep = NULL; // no vehicle in a depot, so no vehicle leaving a depot
1960 Train *base = v;
1961 Train *first = base; // first vehicle to move
1962 Train *last = v->Last(); // last vehicle to move
1963 uint length = CountVehiclesInChain(v);
1965 /* We have to make sure all wagons that leave a depot because of train reversing are moved correctly
1966 * they have already correct spacing, so we have to make sure they are moved how they should */
1967 bool nomove = (dep == NULL); // If there is no vehicle leaving a depot, limit the number of wagons moved immediately.
1969 while (length > 2) {
1970 /* we reached vehicle (originally) in front of a depot, stop now
1971 * (we would move wagons that are already moved with new wagon length). */
1972 if (base == dep) break;
1974 /* the last wagon was that one leaving a depot, so do not move it anymore */
1975 if (last == dep) nomove = true;
1977 last = last->Previous();
1978 first = first->Next();
1980 int differential = last->CalcNextVehicleOffset() - base->CalcNextVehicleOffset();
1982 /* do not update images now */
1983 for (int i = 0; i < differential; i++) TrainController(first, (nomove ? last->Next() : NULL));
1985 base = first; // == base->Next()
1986 length -= 2;
1991 * Turn a train around.
1992 * @param v %Train to turn around.
1994 void ReverseTrainDirection(Train *v)
1996 if (IsRailDepotTile(v->tile)) {
1997 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
2000 v->reverse_distance = 0;
2002 /* Clear path reservation in front if train is not stuck. */
2003 if (!HasBit(v->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(v);
2005 /* Check if we were approaching a rail/road-crossing */
2006 TileIndex crossing = TrainApproachingCrossingTile(v);
2008 /* count number of vehicles */
2009 int r = CountVehiclesInChain(v) - 1; // number of vehicles - 1
2011 AdvanceWagonsBeforeSwap(v);
2013 /* swap start<>end, start+1<>end-1, ... */
2014 int l = 0;
2015 do {
2016 ReverseTrainSwapVeh(v, l++, r--);
2017 } while (l <= r);
2019 AdvanceWagonsAfterSwap(v);
2021 if (IsRailDepotTile(v->tile)) {
2022 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
2025 ToggleBit(v->flags, VRF_TOGGLE_REVERSE);
2027 ClrBit(v->flags, VRF_REVERSING);
2029 /* recalculate cached data */
2030 v->ConsistChanged(CCF_TRACK);
2032 /* update all images */
2033 for (Train *u = v; u != NULL; u = u->Next()) u->UpdateViewport(false, false);
2035 /* update crossing we were approaching */
2036 if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
2038 /* maybe we are approaching crossing now, after reversal */
2039 crossing = TrainApproachingCrossingTile(v);
2040 if (crossing != INVALID_TILE) MaybeBarCrossingWithSound(crossing);
2042 /* If we are inside a depot after reversing, don't bother with path reserving. */
2043 if (v->track == TRACK_BIT_DEPOT) {
2044 /* Can't be stuck here as inside a depot is always a safe tile. */
2045 if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2046 ClrBit(v->flags, VRF_TRAIN_STUCK);
2047 return;
2050 /* We are inside tunnel/bidge with signals, reversing will close the entrance. */
2051 if (IsTunnelBridgeWithSignalSimulation(v->tile)) {
2052 /* Flip signal on tunnel entrance tile red. */
2053 SetTunnelBridgeSignalState(v->tile, SIGNAL_STATE_RED);
2054 MarkTileDirtyByTile(v->tile);
2055 /* Clear counters. */
2056 v->wait_counter = 0;
2057 v->load_unload_ticks = 0;
2058 return;
2061 /* TrainExitDir does not always produce the desired dir for depots and
2062 * tunnels/bridges that is needed for UpdateSignalsOnSegment. */
2063 DiagDirection dir = TrainExitDir(v->direction, v->track);
2064 if (IsRailDepotTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE)) dir = INVALID_DIAGDIR;
2066 if (UpdateSignalsOnSegment(v->tile, dir, v->owner) == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
2067 /* If we are currently on a tile with conventional signals, we can't treat the
2068 * current tile as a safe tile or we would enter a PBS block without a reservation. */
2069 bool first_tile_okay = !(IsTileType(v->tile, MP_RAILWAY) &&
2070 HasSignalOnTrackdir(v->tile, v->GetVehicleTrackdir()) &&
2071 !IsPbsSignal(GetSignalType(v->tile, FindFirstTrack(v->track))));
2073 /* If we are on a depot tile facing outwards, do not treat the current tile as safe. */
2074 if (IsRailDepotTile(v->tile) && TrackdirToExitdir(v->GetVehicleTrackdir()) == GetRailDepotDirection(v->tile)) first_tile_okay = false;
2076 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
2077 if (TryPathReserve(v, false, first_tile_okay)) {
2078 /* Do a look-ahead now in case our current tile was already a safe tile. */
2079 CheckNextTrainTile(v);
2080 } else if (v->current_order.GetType() != OT_LOADING) {
2081 /* Do not wait for a way out when we're still loading */
2082 MarkTrainAsStuck(v);
2084 } else if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
2085 /* A train not inside a PBS block can't be stuck. */
2086 ClrBit(v->flags, VRF_TRAIN_STUCK);
2087 v->wait_counter = 0;
2092 * Reverse train.
2093 * @param tile unused
2094 * @param flags type of operation
2095 * @param p1 train to reverse
2096 * @param p2 if true, reverse a unit in a train (needs to be in a depot)
2097 * @param text unused
2098 * @return the cost of this operation or an error
2100 CommandCost CmdReverseTrainDirection(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2102 Train *v = Train::GetIfValid(p1);
2103 if (v == NULL) return CMD_ERROR;
2105 CommandCost ret = CheckOwnership(v->owner);
2106 if (ret.Failed()) return ret;
2108 if (p2 != 0) {
2109 /* turn a single unit around */
2111 if (v->IsMultiheaded() || HasBit(EngInfo(v->engine_type)->callback_mask, CBM_VEHICLE_ARTIC_ENGINE)) {
2112 return_cmd_error(STR_ERROR_CAN_T_REVERSE_DIRECTION_RAIL_VEHICLE_MULTIPLE_UNITS);
2114 if (!HasBit(EngInfo(v->engine_type)->misc_flags, EF_RAIL_FLIPS)) return CMD_ERROR;
2116 Train *front = v->First();
2117 /* make sure the vehicle is stopped in the depot */
2118 if (!front->IsStoppedInDepot()) {
2119 return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
2122 if (flags & DC_EXEC) {
2123 ToggleBit(v->flags, VRF_REVERSE_DIRECTION);
2125 front->ConsistChanged(CCF_ARRANGE);
2126 SetWindowDirty(WC_VEHICLE_DEPOT, front->tile);
2127 SetWindowDirty(WC_VEHICLE_DETAILS, front->index);
2128 SetWindowDirty(WC_VEHICLE_VIEW, front->index);
2129 SetWindowClassesDirty(WC_TRAINS_LIST);
2131 } else {
2132 /* turn the whole train around */
2133 if ((v->vehstatus & VS_CRASHED) || v->breakdown_ctr != 0) return CMD_ERROR;
2135 if (flags & DC_EXEC) {
2136 /* Properly leave the station if we are loading and won't be loading anymore */
2137 if (v->current_order.IsType(OT_LOADING)) {
2138 const Vehicle *last = v;
2139 while (last->Next() != NULL) last = last->Next();
2141 /* not a station || different station --> leave the station */
2142 if (!IsTileType(last->tile, MP_STATION) || GetStationIndex(last->tile) != GetStationIndex(v->tile)) {
2143 v->LeaveStation();
2147 /* We cancel any 'skip signal at dangers' here */
2148 v->force_proceed = TFP_NONE;
2149 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
2151 if (_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL && v->cur_speed != 0) {
2152 ToggleBit(v->flags, VRF_REVERSING);
2153 } else {
2154 v->cur_speed = 0;
2155 v->SetLastSpeed();
2156 HideFillingPercent(&v->fill_percent_te_id);
2157 ReverseTrainDirection(v);
2161 return CommandCost();
2165 * Force a train through a red signal
2166 * @param tile unused
2167 * @param flags type of operation
2168 * @param p1 train to ignore the red signal
2169 * @param p2 unused
2170 * @param text unused
2171 * @return the cost of this operation or an error
2173 CommandCost CmdForceTrainProceed(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2175 Train *t = Train::GetIfValid(p1);
2176 if (t == NULL) return CMD_ERROR;
2178 if (!t->IsPrimaryVehicle()) return CMD_ERROR;
2180 CommandCost ret = CheckOwnership(t->owner);
2181 if (ret.Failed()) return ret;
2184 if (flags & DC_EXEC) {
2185 /* If we are forced to proceed, cancel that order.
2186 * If we are marked stuck we would want to force the train
2187 * to proceed to the next signal. In the other cases we
2188 * would like to pass the signal at danger and run till the
2189 * next signal we encounter. */
2190 t->force_proceed = t->force_proceed == TFP_SIGNAL ? TFP_NONE : HasBit(t->flags, VRF_TRAIN_STUCK) || t->IsChainInDepot() ? TFP_STUCK : TFP_SIGNAL;
2191 SetWindowDirty(WC_VEHICLE_VIEW, t->index);
2194 return CommandCost();
2198 * Try to find a depot nearby.
2199 * @param v %Train that wants a depot.
2200 * @param max_distance Maximal search distance.
2201 * @return Information where the closest train depot is located.
2202 * @pre The given vehicle must not be crashed!
2204 static FindDepotData FindClosestTrainDepot(Train *v, int max_distance)
2206 assert(!(v->vehstatus & VS_CRASHED));
2208 if (IsRailDepotTile(v->tile)) return FindDepotData(v->tile, 0);
2210 PBSTileInfo origin = FollowTrainReservation(v);
2211 if (IsRailDepotTile(origin.tile)) return FindDepotData(origin.tile, 0);
2213 switch (_settings_game.pf.pathfinder_for_trains) {
2214 case VPF_NPF: return NPFTrainFindNearestDepot(v, max_distance);
2215 case VPF_YAPF: return YapfTrainFindNearestDepot(v, max_distance);
2217 default: NOT_REACHED();
2222 * Locate the closest depot for this consist, and return the information to the caller.
2223 * @param location [out] If not \c NULL and a depot is found, store its location in the given address.
2224 * @param destination [out] If not \c NULL and a depot is found, store its index in the given address.
2225 * @param reverse [out] If not \c NULL and a depot is found, store reversal information in the given address.
2226 * @return A depot has been found.
2228 bool Train::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
2230 FindDepotData tfdd = FindClosestTrainDepot(this, 0);
2231 if (tfdd.best_length == UINT_MAX) return false;
2233 if (location != NULL) *location = tfdd.tile;
2234 if (destination != NULL) *destination = GetDepotIndex(tfdd.tile);
2235 if (reverse != NULL) *reverse = tfdd.reverse;
2237 return true;
2240 /** Play a sound for a train leaving the station. */
2241 void Train::PlayLeaveStationSound() const
2243 static const SoundFx sfx[] = {
2244 SND_04_TRAIN,
2245 SND_0A_TRAIN_HORN,
2246 SND_0A_TRAIN_HORN,
2247 SND_47_MAGLEV_2,
2248 SND_41_MAGLEV
2251 if (PlayVehicleSound(this, VSE_START)) return;
2253 EngineID engtype = this->engine_type;
2254 SndPlayVehicleFx(sfx[RailVehInfo(engtype)->engclass], this);
2258 * Check if the train is on the last reserved tile and try to extend the path then.
2259 * @param v %Train that needs its path extended.
2261 static void CheckNextTrainTile(Train *v)
2263 /* Don't do any look-ahead if path_backoff_interval is 255. */
2264 if (_settings_game.pf.path_backoff_interval == 255) return;
2266 /* Exit if we are inside a depot. */
2267 if (v->track == TRACK_BIT_DEPOT) return;
2269 switch (v->current_order.GetType()) {
2270 /* Exit if we reached our destination depot. */
2271 case OT_GOTO_DEPOT:
2272 if (v->tile == v->dest_tile) return;
2273 break;
2275 case OT_GOTO_WAYPOINT:
2276 /* If we reached our waypoint, make sure we see that. */
2277 if (IsRailWaypointTile(v->tile) && GetStationIndex(v->tile) == v->current_order.GetDestination()) ProcessOrders(v);
2278 break;
2280 case OT_NOTHING:
2281 case OT_LEAVESTATION:
2282 case OT_LOADING:
2283 /* Exit if the current order doesn't have a destination, but the train has orders. */
2284 if (v->GetNumOrders() > 0) return;
2285 break;
2287 default:
2288 break;
2290 /* Exit if we are on a station tile and are going to stop. */
2291 if (IsRailStationTile(v->tile) && v->current_order.ShouldStopAtStation(v, GetStationIndex(v->tile))) return;
2293 Trackdir td = v->GetVehicleTrackdir();
2295 /* On a tile with a red non-pbs signal, don't look ahead. */
2296 if (IsTileType(v->tile, MP_RAILWAY) && HasSignalOnTrackdir(v->tile, td) &&
2297 !IsPbsSignal(GetSignalType(v->tile, TrackdirToTrack(td))) &&
2298 GetSignalStateByTrackdir(v->tile, td) == SIGNAL_STATE_RED) return;
2300 CFollowTrackRail ft(v);
2301 if (!ft.Follow(v->tile, td)) return;
2303 if (!HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(ft.m_new_td_bits))) {
2304 /* Next tile is not reserved. */
2305 if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
2306 if (HasPbsSignalOnTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) {
2307 /* If the next tile is a PBS signal, try to make a reservation. */
2308 TrackBits tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
2309 if (_settings_game.pf.forbid_90_deg) {
2310 tracks &= ~TrackCrossesTracks(TrackdirToTrack(ft.m_old_td));
2312 ChooseTrainTrack(v, ft.m_new_tile, ft.m_exitdir, tracks, false, NULL, false);
2319 * Will the train stay in the depot the next tick?
2320 * @param v %Train to check.
2321 * @return True if it stays in the depot, false otherwise.
2323 static bool CheckTrainStayInDepot(Train *v)
2325 /* bail out if not all wagons are in the same depot or not in a depot at all */
2326 for (const Train *u = v; u != NULL; u = u->Next()) {
2327 if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return false;
2330 /* if the train got no power, then keep it in the depot */
2331 if (v->gcache.cached_power == 0) {
2332 v->vehstatus |= VS_STOPPED;
2333 SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
2334 return true;
2337 if (v->current_order.IsWaitTimetabled())
2338 v->HandleWaiting(false);
2339 if (v->current_order.IsType(OT_WAITING))
2340 return true;
2342 SigSegState seg_state;
2344 if (v->force_proceed == TFP_NONE) {
2345 /* force proceed was not pressed */
2346 if (++v->wait_counter < 37) {
2347 SetWindowClassesDirty(WC_TRAINS_LIST);
2348 return true;
2351 v->wait_counter = 0;
2353 seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
2354 if (seg_state == SIGSEG_FULL || HasDepotReservation(v->tile)) {
2355 /* Full and no PBS signal in block or depot reserved, can't exit. */
2356 SetWindowClassesDirty(WC_TRAINS_LIST);
2357 return true;
2359 } else {
2360 seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
2363 /* We are leaving a depot, but have to go to the exact same one; re-enter */
2364 if (v->current_order.IsType(OT_GOTO_DEPOT) && v->tile == v->dest_tile) {
2365 /* We need to have a reservation for this to work. */
2366 if (HasDepotReservation(v->tile)) return true;
2367 SetDepotReservation(v->tile, true);
2368 VehicleEnterDepot(v);
2369 return true;
2372 /* Only leave when we can reserve a path to our destination. */
2373 if (seg_state == SIGSEG_PBS && !TryPathReserve(v) && v->force_proceed == TFP_NONE) {
2374 /* No path and no force proceed. */
2375 SetWindowClassesDirty(WC_TRAINS_LIST);
2376 MarkTrainAsStuck(v);
2377 return true;
2380 SetDepotReservation(v->tile, true);
2381 if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile, ZOOM_LVL_DRAW_MAP);
2383 VehicleServiceInDepot(v);
2384 SetWindowClassesDirty(WC_TRAINS_LIST);
2385 v->PlayLeaveStationSound();
2387 v->track = TRACK_BIT_X;
2388 if (v->direction & 2) v->track = TRACK_BIT_Y;
2390 v->vehstatus &= ~VS_HIDDEN;
2391 v->cur_speed = 0;
2393 v->UpdateViewport(true, true);
2394 v->UpdatePosition();
2395 UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
2396 v->UpdateAcceleration();
2397 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
2399 return false;
2402 static int GetAndClearLastBridgeEntranceSetSignalIndex(TileIndex bridge_entrance)
2404 uint16 m = _m[bridge_entrance].m2;
2405 if (m & 0x8000) {
2406 auto it = _long_bridge_signal_sim_map.find(bridge_entrance);
2407 if (it != _long_bridge_signal_sim_map.end()) {
2408 LongBridgeSignalStorage &lbss = it->second;
2409 size_t slot = lbss.signal_red_bits.size();
2410 while (slot > 0) {
2411 slot--;
2412 uint64 &slot_bits = lbss.signal_red_bits[slot];
2413 if (slot_bits) {
2414 uint8 i = FindLastBit(slot_bits);
2415 ClrBit(slot_bits, i);
2416 return 1 + 15 + (64 * slot) + i;
2421 if (m & 0x7FFF) {
2422 uint8 i = FindLastBit(m & 0x7FFF);
2423 ClrBit(_m[bridge_entrance].m2, i);
2424 return 1 + i;
2427 return 0;
2430 static void HandleLastTunnelBridgeSignals(TileIndex tile, TileIndex end, DiagDirection dir, bool free)
2432 if (IsBridge(end) && _m[end].m2 != 0) {
2433 /* Clearing last bridge signal. */
2434 int signal_offset = GetAndClearLastBridgeEntranceSetSignalIndex(end);
2435 if (signal_offset) {
2436 TileIndex last_signal_tile = end + (TileOffsByDiagDir(dir) * _settings_game.construction.simulated_wormhole_signals * signal_offset);
2437 MarkTileDirtyByTile(last_signal_tile);
2439 MarkTileDirtyByTile(tile);
2441 if (free) {
2442 /* Open up the wormhole and clear m2. */
2443 if (IsBridge(end)) {
2444 SetAllBridgeEntranceSimulatedSignalsGreen(end);
2447 if (IsTunnelBridgeSignalSimulationEntrance(end) && GetTunnelBridgeSignalState(end) == SIGNAL_STATE_RED) {
2448 SetTunnelBridgeSignalState(end, SIGNAL_STATE_GREEN);
2449 MarkTileDirtyByTile(end);
2450 } else if (IsTunnelBridgeSignalSimulationEntrance(tile) && GetTunnelBridgeSignalState(tile) == SIGNAL_STATE_RED) {
2451 SetTunnelBridgeSignalState(tile, SIGNAL_STATE_GREEN);
2452 MarkTileDirtyByTile(tile);
2457 static void UnreserveBridgeTunnelTile(TileIndex tile)
2459 SetTunnelBridgeReservation(tile, false);
2460 if (IsTunnelBridgeSignalSimulationExit(tile) && IsTunnelBridgePBS(tile)) SetTunnelBridgeSignalState(tile, SIGNAL_STATE_RED);
2464 * Clear the reservation of \a tile that was just left by a wagon on \a track_dir.
2465 * @param v %Train owning the reservation.
2466 * @param tile Tile with reservation to clear.
2467 * @param track_dir Track direction to clear.
2469 static void ClearPathReservation(const Train *v, TileIndex tile, Trackdir track_dir)
2471 DiagDirection dir = TrackdirToExitdir(track_dir);
2473 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
2474 /* Are we just leaving a tunnel/bridge? */
2475 if (GetTunnelBridgeDirection(tile) == ReverseDiagDir(dir)) {
2476 TileIndex end = GetOtherTunnelBridgeEnd(tile);
2478 bool free = TunnelBridgeIsFree(tile, end, v).Succeeded();
2480 if (IsTunnelBridgeWithSignalSimulation(tile)) {
2481 UnreserveBridgeTunnelTile(tile);
2482 HandleLastTunnelBridgeSignals(tile, end, dir, free);
2483 if (_settings_client.gui.show_track_reservation) {
2484 MarkTileDirtyByTile(tile);
2487 else if (free) {
2488 /* Free the reservation only if no other train is on the tiles. */
2489 UnreserveBridgeTunnelTile(tile);
2490 UnreserveBridgeTunnelTile(end);
2492 if (_settings_client.gui.show_track_reservation) {
2493 if (IsBridge(tile)) {
2494 MarkBridgeDirty(tile);
2496 else {
2497 MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
2498 MarkTileDirtyByTile(end, ZOOM_LVL_DRAW_MAP);
2502 else if (GetTunnelBridgeDirection(tile) == dir && IsTunnelBridgeWithSignalSimulation(tile)) {
2503 /* canceling reservation of entry ramp, due to reverse */
2504 UnreserveBridgeTunnelTile(tile);
2505 if (_settings_client.gui.show_track_reservation) {
2506 MarkTileDirtyByTile(tile);
2510 } else if (IsRailStationTile(tile)) {
2511 TileIndex new_tile = TileAddByDiagDir(tile, dir);
2512 /* If the new tile is not a further tile of the same station, we
2513 * clear the reservation for the whole platform. */
2514 if (!IsCompatibleTrainStationTile(new_tile, tile)) {
2515 SetRailStationPlatformReservation(tile, ReverseDiagDir(dir), false);
2517 } else {
2518 /* Any other tile */
2519 UnreserveRailTrack(tile, TrackdirToTrack(track_dir));
2524 * Free the reserved path in front of a vehicle.
2525 * @param v %Train owning the reserved path.
2526 * @param origin %Tile to start clearing (if #INVALID_TILE, use the current tile of \a v).
2527 * @param orig_td Track direction (if #INVALID_TRACKDIR, use the track direction of \a v).
2529 void FreeTrainTrackReservation(const Train *v, TileIndex origin, Trackdir orig_td)
2531 assert(v->IsFrontEngine());
2533 TileIndex tile = origin != INVALID_TILE ? origin : v->tile;
2534 Trackdir td = orig_td != INVALID_TRACKDIR ? orig_td : v->GetVehicleTrackdir();
2535 bool free_tile = tile != v->tile || !(IsRailStationTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE));
2536 StationID station_id = IsRailStationTile(v->tile) ? GetStationIndex(v->tile) : INVALID_STATION;
2538 /* Can't be holding a reservation if we enter a depot. */
2539 if (IsRailDepotTile(tile) && TrackdirToExitdir(td) != GetRailDepotDirection(tile)) return;
2540 if (v->track == TRACK_BIT_DEPOT) {
2541 /* Front engine is in a depot. We enter if some part is not in the depot. */
2542 for (const Train *u = v; u != NULL; u = u->Next()) {
2543 if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return;
2546 /* Don't free reservation if it's not ours. */
2547 if (TracksOverlap(GetReservedTrackbits(tile) | TrackToTrackBits(TrackdirToTrack(td)))) return;
2549 CFollowTrackRail ft(v, GetRailTypeInfo(v->railtype)->compatible_railtypes);
2550 while (ft.Follow(tile, td)) {
2551 tile = ft.m_new_tile;
2552 TrackdirBits bits = ft.m_new_td_bits & TrackBitsToTrackdirBits(GetReservedTrackbits(tile));
2553 td = RemoveFirstTrackdir(&bits);
2554 assert(bits == TRACKDIR_BIT_NONE);
2556 if (!IsValidTrackdir(td)) break;
2558 if (IsTileType(tile, MP_RAILWAY)) {
2559 if (HasSignalOnTrackdir(tile, td) && !IsPbsSignal(GetSignalType(tile, TrackdirToTrack(td)))) {
2560 /* Conventional signal along trackdir: remove reservation and stop. */
2561 UnreserveRailTrack(tile, TrackdirToTrack(td));
2562 break;
2564 if (HasPbsSignalOnTrackdir(tile, td)) {
2565 if (GetSignalStateByTrackdir(tile, td) == SIGNAL_STATE_RED) {
2566 /* Red PBS signal? Can't be our reservation, would be green then. */
2567 break;
2568 } else {
2569 /* Turn the signal back to red. */
2570 SetSignalStateByTrackdir(tile, td, SIGNAL_STATE_RED);
2571 MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
2573 /* notify logic signals of the state change */
2574 SignalStateChanged(tile, TrackdirToTrack(td), 1);
2576 } else if (HasSignalOnTrackdir(tile, ReverseTrackdir(td)) && IsOnewaySignal(tile, TrackdirToTrack(td))) {
2577 break;
2581 /* Don't free first station/bridge/tunnel if we are on it. */
2582 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);
2584 free_tile = true;
2588 static const byte _initial_tile_subcoord[6][4][3] = {
2589 {{ 15, 8, 1 }, { 0, 0, 0 }, { 0, 8, 5 }, { 0, 0, 0 }},
2590 {{ 0, 0, 0 }, { 8, 0, 3 }, { 0, 0, 0 }, { 8, 15, 7 }},
2591 {{ 0, 0, 0 }, { 7, 0, 2 }, { 0, 7, 6 }, { 0, 0, 0 }},
2592 {{ 15, 8, 2 }, { 0, 0, 0 }, { 0, 0, 0 }, { 8, 15, 6 }},
2593 {{ 15, 7, 0 }, { 8, 0, 4 }, { 0, 0, 0 }, { 0, 0, 0 }},
2594 {{ 0, 0, 0 }, { 0, 0, 0 }, { 0, 8, 4 }, { 7, 15, 0 }},
2598 * Perform pathfinding for a train.
2600 * @param v The train
2601 * @param tile The tile the train is about to enter
2602 * @param enterdir Diagonal direction the train is coming from
2603 * @param tracks Usable tracks on the new tile
2604 * @param path_found [out] Whether a path has been found or not.
2605 * @param do_track_reservation Path reservation is requested
2606 * @param dest [out] State and destination of the requested path
2607 * @return The best track the train should follow
2609 static Track DoTrainPathfind(const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found, bool do_track_reservation, PBSTileInfo *dest)
2611 switch (_settings_game.pf.pathfinder_for_trains) {
2612 case VPF_NPF: return NPFTrainChooseTrack(v, tile, enterdir, tracks, path_found, do_track_reservation, dest);
2613 case VPF_YAPF: return YapfTrainChooseTrack(v, tile, enterdir, tracks, path_found, do_track_reservation, dest);
2615 default: NOT_REACHED();
2620 * Extend a train path as far as possible. Stops on encountering a safe tile,
2621 * another reservation or a track choice.
2622 * @param v The train.
2623 * @param origin The tile from which the reservation have to be extended
2624 * @param new_tracks [out] Tracks to choose from when encountering a choice
2625 * @param enterdir [out] The direction from which the choice tile is to be entered
2626 * @return INVALID_TILE indicates that the reservation failed.
2628 static PBSTileInfo ExtendTrainReservation(const Train *v, const PBSTileInfo &origin, TrackBits *new_tracks, DiagDirection *enterdir)
2630 CFollowTrackRail ft(v);
2632 TileIndex tile = origin.tile;
2633 Trackdir cur_td = origin.trackdir;
2634 while (ft.Follow(tile, cur_td)) {
2635 if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
2636 /* Possible signal tile. */
2637 if (HasOnewaySignalBlockingTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) break;
2640 if (_settings_game.pf.forbid_90_deg) {
2641 ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
2642 if (ft.m_new_td_bits == TRACKDIR_BIT_NONE) break;
2645 /* Station, depot or waypoint are a possible target. */
2646 bool target_seen = ft.m_is_station || (IsTileType(ft.m_new_tile, MP_RAILWAY) && !IsPlainRail(ft.m_new_tile));
2647 if (target_seen || KillFirstBit(ft.m_new_td_bits) != TRACKDIR_BIT_NONE) {
2648 /* Choice found or possible target encountered.
2649 * On finding a possible target, we need to stop and let the pathfinder handle the
2650 * remaining path. This is because we don't know if this target is in one of our
2651 * orders, so we might cause pathfinding to fail later on if we find a choice.
2652 * This failure would cause a bogous call to TryReserveSafePath which might reserve
2653 * a wrong path not leading to our next destination. */
2654 if (HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(TrackdirReachesTrackdirs(ft.m_old_td)))) break;
2656 /* If we did skip some tiles, backtrack to the first skipped tile so the pathfinder
2657 * actually starts its search at the first unreserved tile. */
2658 if (ft.m_tiles_skipped != 0) ft.m_new_tile -= TileOffsByDiagDir(ft.m_exitdir) * ft.m_tiles_skipped;
2660 /* Choice found, path valid but not okay. Save info about the choice tile as well. */
2661 if (new_tracks != NULL) *new_tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
2662 if (enterdir != NULL) *enterdir = ft.m_exitdir;
2663 return PBSTileInfo(ft.m_new_tile, ft.m_old_td, false);
2666 tile = ft.m_new_tile;
2667 cur_td = FindFirstTrackdir(ft.m_new_td_bits);
2669 if (IsSafeWaitingPosition(v, tile, cur_td, true, _settings_game.pf.forbid_90_deg)) {
2670 bool wp_free = IsWaitingPositionFree(v, tile, cur_td, _settings_game.pf.forbid_90_deg);
2671 if (!(wp_free && TryReserveRailTrack(tile, TrackdirToTrack(cur_td)))) break;
2672 /* Safe position is all good, path valid and okay. */
2673 return PBSTileInfo(tile, cur_td, true);
2676 if (!TryReserveRailTrackdir(tile, cur_td)) break;
2679 if (ft.m_err == CFollowTrackRail::EC_OWNER || ft.m_err == CFollowTrackRail::EC_NO_WAY) {
2680 /* End of line, path valid and okay. */
2681 return PBSTileInfo(ft.m_old_tile, ft.m_old_td, true);
2684 /* Sorry, can't reserve path, back out. */
2685 tile = origin.tile;
2686 cur_td = origin.trackdir;
2687 TileIndex stopped = ft.m_old_tile;
2688 Trackdir stopped_td = ft.m_old_td;
2689 while (tile != stopped || cur_td != stopped_td) {
2690 if (!ft.Follow(tile, cur_td)) break;
2692 if (_settings_game.pf.forbid_90_deg) {
2693 ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
2694 assert(ft.m_new_td_bits != TRACKDIR_BIT_NONE);
2696 assert(KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE);
2698 tile = ft.m_new_tile;
2699 cur_td = FindFirstTrackdir(ft.m_new_td_bits);
2701 UnreserveRailTrackdir(tile, cur_td);
2704 /* Path invalid. */
2705 return PBSTileInfo();
2709 * Try to reserve any path to a safe tile, ignoring the vehicle's destination.
2710 * Safe tiles are tiles in front of a signal, depots and station tiles at end of line.
2712 * @param v The vehicle.
2713 * @param tile The tile the search should start from.
2714 * @param td The trackdir the search should start from.
2715 * @param override_railtype Whether all physically compatible railtypes should be followed.
2716 * @return True if a path to a safe stopping tile could be reserved.
2718 static bool TryReserveSafeTrack(const Train *v, TileIndex tile, Trackdir td, bool override_tailtype)
2720 switch (_settings_game.pf.pathfinder_for_trains) {
2721 case VPF_NPF: return NPFTrainFindNearestSafeTile(v, tile, td, override_tailtype);
2722 case VPF_YAPF: return YapfTrainFindNearestSafeTile(v, tile, td, override_tailtype);
2724 default: NOT_REACHED();
2728 /** This class will save the current order of a vehicle and restore it on destruction. */
2729 class VehicleOrderSaver {
2730 private:
2731 Train *v;
2732 Order old_order;
2733 TileIndex old_dest_tile;
2734 StationID old_last_station_visited;
2735 VehicleOrderID index;
2736 bool suppress_implicit_orders;
2738 public:
2739 VehicleOrderSaver(Train *_v) :
2740 v(_v),
2741 old_order(_v->current_order),
2742 old_dest_tile(_v->dest_tile),
2743 old_last_station_visited(_v->last_station_visited),
2744 index(_v->cur_real_order_index),
2745 suppress_implicit_orders(HasBit(_v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS))
2749 ~VehicleOrderSaver()
2751 this->v->current_order = this->old_order;
2752 this->v->dest_tile = this->old_dest_tile;
2753 this->v->last_station_visited = this->old_last_station_visited;
2754 SB(this->v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS, 1, suppress_implicit_orders ? 1: 0);
2758 * Set the current vehicle order to the next order in the order list.
2759 * @param skip_first Shall the first (i.e. active) order be skipped?
2760 * @return True if a suitable next order could be found.
2762 bool SwitchToNextOrder(bool skip_first)
2764 if (this->v->GetNumOrders() == 0) return false;
2766 if (skip_first) ++this->index;
2768 int depth = 0;
2769 bool has_manual_depot_order = (HasBit(v->vehicle_flags, VF_SHOULD_GOTO_DEPOT) || HasBit(v->vehicle_flags, VF_SHOULD_SERVICE_AT_DEPOT));
2771 do {
2772 /* Wrap around. */
2773 if (this->index >= this->v->GetNumOrders()) this->index = 0;
2775 Order *order = this->v->GetOrder(this->index);
2776 assert(order != NULL);
2778 switch (order->GetType()) {
2779 case OT_GOTO_DEPOT:
2780 /* Skip service in depot orders when the train doesn't need service. */
2781 if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !(this->v->NeedsServicing() || has_manual_depot_order)) break;
2782 FALLTHROUGH;
2783 case OT_GOTO_STATION:
2784 case OT_GOTO_WAYPOINT:
2785 this->v->current_order = *order;
2786 return UpdateOrderDest(this->v, order, 0, true);
2787 case OT_CONDITIONAL: {
2788 VehicleOrderID next = ProcessConditionalOrder(order, this->v);
2789 if (next != INVALID_VEH_ORDER_ID) {
2790 depth++;
2791 this->index = next;
2792 /* Don't increment next, so no break here. */
2793 continue;
2795 break;
2797 default:
2798 break;
2800 /* Don't increment inside the while because otherwise conditional
2801 * orders can lead to an infinite loop. */
2802 ++this->index;
2803 depth++;
2804 } while (this->index != this->v->cur_real_order_index && depth < this->v->GetNumOrders());
2806 return false;
2811 * This is called to retrieve the previous signal, as required
2812 * This is not run all the time as it is somewhat expensive and most restrictions will not test for the previous signal
2814 static TileIndex ChooseTrainTrackTraceRestrictPreviousSignalCallback(const Train *v, const void *)
2816 // scan forwards from vehicle position, for the case that train is waiting at/approaching PBS signal
2818 TileIndex tile = v->tile;
2819 Trackdir trackdir = v->GetVehicleTrackdir();
2821 CFollowTrackRail ft(v);
2823 for (;;) {
2824 if (IsTileType(tile, MP_RAILWAY) && HasSignalOnTrackdir(tile, trackdir)) {
2825 if (HasPbsSignalOnTrackdir(tile, trackdir)) {
2826 // found PBS signal
2827 return tile;
2828 } else {
2829 // wrong type of signal
2830 return INVALID_TILE;
2834 // advance to next tile
2835 if (!ft.Follow(tile, trackdir)) {
2836 // ran out of track
2837 return INVALID_TILE;
2840 if (KillFirstBit(ft.m_new_td_bits) != TRACKDIR_BIT_NONE) {
2841 // reached a junction tile
2842 return INVALID_TILE;
2845 tile = ft.m_new_tile;
2846 trackdir = FindFirstTrackdir(ft.m_new_td_bits);
2850 static bool HasLongReservePbsSignalOnTrackdir(Train* v, TileIndex tile, Trackdir trackdir)
2852 if (HasPbsSignalOnTrackdir(tile, trackdir)) {
2853 if (IsRestrictedSignal(tile)) {
2854 const TraceRestrictProgram *prog = GetExistingTraceRestrictProgram(tile, TrackdirToTrack(trackdir));
2855 if (prog && prog->actions_used_flags & TRPAUF_LONG_RESERVE) {
2856 TraceRestrictProgramResult out;
2857 prog->Execute(v, TraceRestrictProgramInput(tile, trackdir, &ChooseTrainTrackTraceRestrictPreviousSignalCallback, nullptr), out);
2858 if (out.flags & TRPRF_LONG_RESERVE) {
2859 return true;
2865 return false;
2869 * Choose a track and reserve if necessary
2871 * @param v The vehicle
2872 * @param tile The tile from which to start
2873 * @param enterdir
2874 * @param tracks
2875 * @param force_res Force a reservation to be made
2876 * @param p_got_reservation [out] If the train has a reservation
2877 * @param mark_stuck The train has to be marked as stuck when needed
2878 * @return The track the train should take.
2880 static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *p_got_reservation, bool mark_stuck)
2882 Track best_track = INVALID_TRACK;
2883 bool do_track_reservation = _settings_game.pf.reserve_paths || force_res;
2884 bool changed_signal = false;
2885 bool got_reservation = false;
2886 if (p_got_reservation != NULL) *p_got_reservation = got_reservation;
2888 assert((tracks & ~TRACK_BIT_MASK) == 0);
2890 /* Don't use tracks here as the setting to forbid 90 deg turns might have been switched between reservation and now. */
2891 TrackBits res_tracks = (TrackBits)(GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir));
2892 /* Do we have a suitable reserved track? */
2893 if (res_tracks != TRACK_BIT_NONE) return FindFirstTrack(res_tracks);
2895 /* Quick return in case only one possible track is available */
2896 if (KillFirstBit(tracks) == TRACK_BIT_NONE) {
2897 Track track = FindFirstTrack(tracks);
2898 /* We need to check for signals only here, as a junction tile can't have signals. */
2899 if (track != INVALID_TRACK && HasPbsSignalOnTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir))) {
2900 if (IsRestrictedSignal(tile) && v->force_proceed != TFP_SIGNAL) {
2901 const TraceRestrictProgram *prog = GetExistingTraceRestrictProgram(tile, track);
2902 if (prog && prog->actions_used_flags & (TRPAUF_WAIT_AT_PBS | TRPAUF_SLOT_ACQUIRE)) {
2903 TraceRestrictProgramResult out;
2904 TraceRestrictProgramInput input(tile, TrackEnterdirToTrackdir(track, enterdir), NULL, NULL);
2905 input.permitted_slot_operations = TRPISP_ACQUIRE;
2906 prog->Execute(v, input, out);
2907 if (out.flags & TRPRF_WAIT_AT_PBS) {
2908 if (mark_stuck) MarkTrainAsStuck(v, true);
2909 return track;
2913 ClrBit(v->flags, VRF_WAITING_RESTRICTION);
2915 do_track_reservation = true;
2916 changed_signal = true;
2917 SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir), SIGNAL_STATE_GREEN);
2919 /* notify logic signals of the state change */
2920 SignalStateChanged(tile, TrackdirToTrack(TrackEnterdirToTrackdir(track, enterdir)), 1);
2921 } else if (!do_track_reservation) {
2922 return track;
2924 best_track = track;
2927 PBSTileInfo origin = FollowTrainReservation(v);
2928 PBSTileInfo res_dest(tile, INVALID_TRACKDIR, false);
2929 DiagDirection dest_enterdir = enterdir;
2930 if (do_track_reservation) {
2931 res_dest = ExtendTrainReservation(v, origin, &tracks, &dest_enterdir);
2932 if (res_dest.tile == INVALID_TILE) {
2933 /* Reservation failed? */
2934 if (mark_stuck) MarkTrainAsStuck(v);
2935 if (changed_signal) {
2936 SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(best_track, enterdir), SIGNAL_STATE_RED);
2938 /* notify logic signals of the state change */
2939 SignalStateChanged(tile, TrackdirToTrack(TrackEnterdirToTrackdir(best_track, enterdir)), 1);
2941 return FindFirstTrack(tracks);
2944 if (res_dest.okay) {
2945 CFollowTrackRail ft(v);
2946 if (ft.Follow(res_dest.tile, res_dest.trackdir)) {
2947 Trackdir new_td = FindFirstTrackdir(ft.m_new_td_bits);
2949 if (!HasLongReservePbsSignalOnTrackdir(v, ft.m_new_tile, new_td)) {
2950 /* Got a valid reservation that ends at a safe target, quick exit. */
2951 if (p_got_reservation != NULL) *p_got_reservation = true;
2952 if (changed_signal) MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
2953 TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
2954 return best_track;
2959 /* Check if the train needs service here, so it has a chance to always find a depot.
2960 * Also check if the current order is a service order so we don't reserve a path to
2961 * the destination but instead to the next one if service isn't needed. */
2962 CheckIfTrainNeedsService(v);
2963 if (v->current_order.IsType(OT_DUMMY) || v->current_order.IsType(OT_CONDITIONAL) || v->current_order.IsType(OT_GOTO_DEPOT)) ProcessOrders(v);
2966 /* Save the current train order. The destructor will restore the old order on function exit. */
2967 VehicleOrderSaver orders(v);
2969 /* If the current tile is the destination of the current order and
2970 * a reservation was requested, advance to the next order.
2971 * Don't advance on a depot order as depots are always safe end points
2972 * for a path and no look-ahead is necessary. This also avoids a
2973 * problem with depot orders not part of the order list when the
2974 * order list itself is empty. */
2975 if (v->current_order.IsType(OT_LEAVESTATION)) {
2976 orders.SwitchToNextOrder(false);
2977 } else if (v->current_order.IsType(OT_LOADING) || (!v->current_order.IsType(OT_GOTO_DEPOT) && (
2978 v->current_order.IsType(OT_GOTO_STATION) ?
2979 IsRailStationTile(v->tile) && v->current_order.GetDestination() == GetStationIndex(v->tile) :
2980 v->tile == v->dest_tile))) {
2981 orders.SwitchToNextOrder(true);
2984 if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
2985 /* Pathfinders are able to tell that route was only 'guessed'. */
2986 bool path_found = true;
2987 TileIndex new_tile = res_dest.tile;
2989 Track next_track = DoTrainPathfind(v, new_tile, dest_enterdir, tracks, path_found, do_track_reservation, &res_dest);
2990 if (new_tile == tile) best_track = next_track;
2991 v->HandlePathfindingResult(path_found);
2994 /* No track reservation requested -> finished. */
2995 if (!do_track_reservation) return best_track;
2997 /* A path was found, but could not be reserved. */
2998 if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
2999 if (mark_stuck) MarkTrainAsStuck(v);
3000 FreeTrainTrackReservation(v, origin.tile, origin.trackdir);
3001 return best_track;
3004 /* No possible reservation target found, we are probably lost. */
3005 if (res_dest.tile == INVALID_TILE) {
3006 /* Try to find any safe destination. */
3007 PBSTileInfo path_end = FollowTrainReservation(v);
3008 if (TryReserveSafeTrack(v, path_end.tile, path_end.trackdir, false)) {
3009 TrackBits res = GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir);
3010 best_track = FindFirstTrack(res);
3011 TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
3012 // Use p_got_reservation because were going to return
3013 if (p_got_reservation != NULL) *p_got_reservation = true;
3014 if (changed_signal) MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
3015 } else {
3016 FreeTrainTrackReservation(v, origin.tile, origin.trackdir);
3017 if (mark_stuck) MarkTrainAsStuck(v);
3019 return best_track;
3022 got_reservation = true;
3024 /* Reservation target found and free, check if it is safe. */
3025 while (!IsSafeWaitingPosition(v, res_dest.tile, res_dest.trackdir, true, _settings_game.pf.forbid_90_deg)) {
3026 /* Extend reservation until we have found a safe position. */
3027 DiagDirection exitdir = TrackdirToExitdir(res_dest.trackdir);
3028 TileIndex next_tile = TileAddByDiagDir(res_dest.tile, exitdir);
3029 TrackBits reachable = TrackdirBitsToTrackBits((TrackdirBits)(GetTileTrackStatus(next_tile, TRANSPORT_RAIL, 0))) & DiagdirReachesTracks(exitdir);
3030 if (_settings_game.pf.forbid_90_deg) {
3031 reachable &= ~TrackCrossesTracks(TrackdirToTrack(res_dest.trackdir));
3034 /* Get next order with destination. */
3035 if (orders.SwitchToNextOrder(true)) {
3036 PBSTileInfo cur_dest;
3037 bool path_found;
3038 DoTrainPathfind(v, next_tile, exitdir, reachable, path_found, true, &cur_dest);
3039 if (cur_dest.tile != INVALID_TILE) {
3040 res_dest = cur_dest;
3041 if (res_dest.okay) continue;
3042 /* Path found, but could not be reserved. */
3043 FreeTrainTrackReservation(v, origin.tile, origin.trackdir);
3044 if (mark_stuck) MarkTrainAsStuck(v);
3045 got_reservation = false;
3046 changed_signal = false;
3047 break;
3050 /* No order or no safe position found, try any position. */
3051 if (!TryReserveSafeTrack(v, res_dest.tile, res_dest.trackdir, true)) {
3052 FreeTrainTrackReservation(v, origin.tile, origin.trackdir);
3053 if (mark_stuck) MarkTrainAsStuck(v);
3054 got_reservation = false;
3055 changed_signal = false;
3057 break;
3060 if (got_reservation) {
3061 CFollowTrackRail ft(v);
3062 if (ft.Follow(res_dest.tile, res_dest.trackdir)) {
3063 Trackdir new_td = FindFirstTrackdir(ft.m_new_td_bits);
3065 if (HasLongReservePbsSignalOnTrackdir(v, ft.m_new_tile, new_td)) {
3066 // We reserved up to a LR signal, reserve past it as well. recursion
3067 ChooseTrainTrack(v, ft.m_new_tile, ft.m_exitdir, TrackdirBitsToTrackBits(ft.m_new_td_bits), force_res, NULL, mark_stuck);
3072 TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
3074 if (changed_signal) MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
3075 if (p_got_reservation != NULL) *p_got_reservation = got_reservation;
3077 return best_track;
3081 * Try to reserve a path to a safe position.
3083 * @param v The vehicle
3084 * @param mark_as_stuck Should the train be marked as stuck on a failed reservation?
3085 * @param first_tile_okay True if no path should be reserved if the current tile is a safe position.
3086 * @return True if a path could be reserved.
3088 bool TryPathReserve(Train *v, bool mark_as_stuck, bool first_tile_okay)
3090 assert(v->IsFrontEngine());
3092 /* We have to handle depots specially as the track follower won't look
3093 * at the depot tile itself but starts from the next tile. If we are still
3094 * inside the depot, a depot reservation can never be ours. */
3095 if (v->track == TRACK_BIT_DEPOT) {
3096 if (HasDepotReservation(v->tile)) {
3097 if (mark_as_stuck) MarkTrainAsStuck(v);
3098 return false;
3099 } else {
3100 /* Depot not reserved, but the next tile might be. */
3101 TileIndex next_tile = TileAddByDiagDir(v->tile, GetRailDepotDirection(v->tile));
3102 if (HasReservedTracks(next_tile, DiagdirReachesTracks(GetRailDepotDirection(v->tile)))) return false;
3106 if (IsTileType(v->tile, MP_TUNNELBRIDGE) && IsTunnelBridgeSignalSimulationExit(v->tile) &&
3107 DiagDirToDiagTrackBits(GetTunnelBridgeDirection(v->tile)) == v->track) {
3108 // prevent any attempt to reserve the wrong way onto a tunnel/bridge exit
3109 return false;
3112 Vehicle *other_train = NULL;
3113 PBSTileInfo origin = FollowTrainReservation(v, &other_train);
3114 /* The path we are driving on is already blocked by some other train.
3115 * This can only happen in certain situations when mixing path and
3116 * block signals or when changing tracks and/or signals.
3117 * Exit here as doing any further reservations will probably just
3118 * make matters worse. */
3119 if (other_train != NULL && other_train->index != v->index) {
3120 if (mark_as_stuck) MarkTrainAsStuck(v);
3121 return false;
3123 /* If we have a reserved path and the path ends at a safe tile, we are finished already. */
3124 if (origin.okay && (v->tile != origin.tile || first_tile_okay)) {
3125 /* Can't be stuck then. */
3126 if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
3127 ClrBit(v->flags, VRF_TRAIN_STUCK);
3128 return true;
3131 /* If we are in a depot, tentatively reserve the depot. */
3132 if (v->track == TRACK_BIT_DEPOT && v->tile == origin.tile) {
3133 SetDepotReservation(v->tile, true);
3134 if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile, ZOOM_LVL_DRAW_MAP);
3137 DiagDirection exitdir = TrackdirToExitdir(origin.trackdir);
3138 TileIndex new_tile = TileAddByDiagDir(origin.tile, exitdir);
3139 TrackBits reachable = TrackdirBitsToTrackBits(TrackStatusToTrackdirBits(GetTileTrackStatus(new_tile, TRANSPORT_RAIL, 0)) & DiagdirReachesTrackdirs(exitdir));
3141 if (_settings_game.pf.forbid_90_deg) reachable &= ~TrackCrossesTracks(TrackdirToTrack(origin.trackdir));
3143 bool res_made = false;
3144 ChooseTrainTrack(v, new_tile, exitdir, reachable, true, &res_made, mark_as_stuck);
3146 if (!res_made) {
3147 /* Free the depot reservation as well. */
3148 if (v->track == TRACK_BIT_DEPOT && v->tile == origin.tile) SetDepotReservation(v->tile, false);
3149 return false;
3152 if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
3153 v->wait_counter = 0;
3154 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
3156 ClrBit(v->flags, VRF_TRAIN_STUCK);
3157 return true;
3161 static bool CheckReverseTrain(const Train *v)
3163 if (_settings_game.difficulty.line_reverse_mode != 0 ||
3164 v->track == TRACK_BIT_DEPOT || v->track == TRACK_BIT_WORMHOLE ||
3165 !(v->direction & 1)) {
3166 return false;
3169 assert(v->track != TRACK_BIT_NONE);
3171 switch (_settings_game.pf.pathfinder_for_trains) {
3172 case VPF_NPF: return NPFTrainCheckReverse(v);
3173 case VPF_YAPF: return YapfTrainCheckReverse(v);
3175 default: NOT_REACHED();
3180 * Get the location of the next station to visit.
3181 * @param station Next station to visit.
3182 * @return Location of the new station.
3184 TileIndex Train::GetOrderStationLocation(StationID station)
3186 if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
3188 const Station *st = Station::Get(station);
3189 if (!(st->facilities & FACIL_TRAIN)) {
3190 /* The destination station has no trainstation tiles. */
3191 this->IncrementRealOrderIndex();
3192 return 0;
3195 return st->xy;
3198 /** Goods at the consist have changed, update the graphics, cargo, and acceleration. */
3199 void Train::MarkDirty()
3201 Train *v = this;
3202 do {
3203 v->colourmap = PAL_NONE;
3204 v->UpdateViewport(true, false);
3205 } while ((v = v->Next()) != NULL);
3207 /* need to update acceleration and cached values since the goods on the train changed. */
3208 this->CargoChanged();
3209 this->UpdateAcceleration();
3213 * This function looks at the vehicle and updates its speed (cur_speed
3214 * and subspeed) variables. Furthermore, it returns the distance that
3215 * the train can drive this tick. #Vehicle::GetAdvanceDistance() determines
3216 * the distance to drive before moving a step on the map.
3217 * @return distance to drive.
3219 int Train::UpdateSpeed()
3221 switch (_settings_game.vehicle.train_acceleration_model) {
3222 default: NOT_REACHED();
3223 case AM_ORIGINAL:
3224 return this->DoUpdateSpeed(this->acceleration * (this->GetAccelerationStatus() == AS_BRAKE ? -4 : 2), 0, this->GetCurrentMaxSpeed());
3226 case AM_REALISTIC:
3227 return this->DoUpdateSpeed(this->GetAcceleration(), this->GetAccelerationStatus() == AS_BRAKE ? 0 : 2, this->GetCurrentMaxSpeed());
3232 * Trains enters a station, send out a news item if it is the first train, and start loading.
3233 * @param v Train that entered the station.
3234 * @param station Station visited.
3236 static void TrainEnterStation(Train *v, StationID station)
3238 v->last_station_visited = station;
3240 /* check if a train ever visited this station before */
3241 Station *st = Station::Get(station);
3242 if (!(st->had_vehicle_of_type & HVOT_TRAIN)) {
3243 st->had_vehicle_of_type |= HVOT_TRAIN;
3244 SetDParam(0, st->index);
3245 AddVehicleNewsItem(
3246 STR_NEWS_FIRST_TRAIN_ARRIVAL,
3247 v->owner == _local_company ? NT_ARRIVAL_COMPANY : NT_ARRIVAL_OTHER,
3248 v->index,
3249 st->index
3251 AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
3252 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
3255 v->force_proceed = TFP_NONE;
3256 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
3258 v->BeginLoading();
3260 TriggerStationRandomisation(st, v->tile, SRT_TRAIN_ARRIVES);
3261 TriggerStationAnimation(st, v->tile, SAT_TRAIN_ARRIVES);
3264 /* Check if the vehicle is compatible with the specified tile */
3265 static inline bool CheckCompatibleRail(const Train *v, TileIndex tile)
3267 return IsTileOwner(tile, v->owner) &&
3268 (!v->IsFrontEngine() || HasBit(v->compatible_railtypes, GetRailType(tile)));
3271 /** Data structure for storing engine speed changes of an acceleration type. */
3272 struct AccelerationSlowdownParams {
3273 byte small_turn; ///< Speed change due to a small turn.
3274 byte large_turn; ///< Speed change due to a large turn.
3275 byte z_up; ///< Fraction to remove when moving up.
3276 byte z_down; ///< Fraction to add when moving down.
3279 /** Speed update fractions for each acceleration type. */
3280 static const AccelerationSlowdownParams _accel_slowdown[] = {
3281 /* normal accel */
3282 {256 / 4, 256 / 2, 256 / 4, 2}, ///< normal
3283 {256 / 4, 256 / 2, 256 / 4, 2}, ///< monorail
3284 {0, 256 / 2, 256 / 4, 2}, ///< maglev
3288 * Modify the speed of the vehicle due to a change in altitude.
3289 * @param v %Train to update.
3290 * @param old_z Previous height.
3292 static inline void AffectSpeedByZChange(Train *v, int old_z)
3294 if (old_z == v->z_pos || _settings_game.vehicle.train_acceleration_model != AM_ORIGINAL) return;
3296 const AccelerationSlowdownParams *asp = &_accel_slowdown[GetRailTypeInfo(v->railtype)->acceleration_type];
3298 if (old_z < v->z_pos) {
3299 v->cur_speed -= (v->cur_speed * asp->z_up >> 8);
3300 } else {
3301 uint16 spd = v->cur_speed + asp->z_down;
3302 if (spd <= v->gcache.cached_max_track_speed) v->cur_speed = spd;
3306 enum TrainMovedChangeSignalEnum {
3307 CHANGED_NOTHING, ///< No special signals were changed
3308 CHANGED_NORMAL_TO_PBS_BLOCK, ///< A PBS block with a non-PBS signal facing us
3309 CHANGED_LR_PBS ///< A long reserve PBS signal
3312 static TrainMovedChangeSignalEnum TrainMovedChangeSignal(Train* v, TileIndex tile, DiagDirection dir)
3314 if (IsTileType(tile, MP_RAILWAY) &&
3315 GetRailTileType(tile) == RAIL_TILE_SIGNALS) {
3316 TrackdirBits tracks = TrackBitsToTrackdirBits(GetTrackBits(tile)) & DiagdirReachesTrackdirs(dir);
3317 Trackdir trackdir = FindFirstTrackdir(tracks);
3318 if (UpdateSignalsOnSegment(tile, TrackdirToExitdir(trackdir), GetTileOwner(tile)) == SIGSEG_PBS && HasSignalOnTrackdir(tile, trackdir)) {
3319 /* A PBS block with a non-PBS signal facing us? */
3320 if (!IsPbsSignal(GetSignalType(tile, TrackdirToTrack(trackdir)))) return CHANGED_NORMAL_TO_PBS_BLOCK;
3322 if (HasLongReservePbsSignalOnTrackdir(v, tile, trackdir)) return CHANGED_LR_PBS;
3326 if (IsTileType(tile, MP_TUNNELBRIDGE) && IsTunnelBridgeSignalSimulationExit(tile) && GetTunnelBridgeDirection(tile) == ReverseDiagDir(dir)) {
3327 if (UpdateSignalsOnSegment(tile, dir, GetTileOwner(tile)) == SIGSEG_PBS) {
3328 return CHANGED_NORMAL_TO_PBS_BLOCK;
3332 return CHANGED_NOTHING;
3335 /** Tries to reserve track under whole train consist. */
3336 void Train::ReserveTrackUnderConsist() const
3338 for (const Train *u = this; u != NULL; u = u->Next()) {
3339 switch (u->track) {
3340 case TRACK_BIT_WORMHOLE:
3341 TryReserveRailTrack(u->tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(u->tile)));
3342 break;
3343 case TRACK_BIT_DEPOT:
3344 break;
3345 default:
3346 TryReserveRailTrack(u->tile, TrackBitsToTrack(u->track));
3347 break;
3353 * The train vehicle crashed!
3354 * Update its status and other parts around it.
3355 * @param flooded Crash was caused by flooding.
3356 * @return Number of people killed.
3358 uint Train::Crash(bool flooded)
3360 uint pass = 0;
3361 if (this->IsFrontEngine()) {
3362 pass += 2; // driver
3364 /* Remove the reserved path in front of the train if it is not stuck.
3365 * Also clear all reserved tracks the train is currently on. */
3366 if (!HasBit(this->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(this);
3367 for (const Train *v = this; v != NULL; v = v->Next()) {
3368 ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
3369 if (IsTileType(v->tile, MP_TUNNELBRIDGE)) {
3370 /* ClearPathReservation will not free the wormhole exit
3371 * if the train has just entered the wormhole. */
3372 UnreserveBridgeTunnelTile(GetOtherTunnelBridgeEnd(v->tile));
3376 /* we may need to update crossing we were approaching,
3377 * but must be updated after the train has been marked crashed */
3378 TileIndex crossing = TrainApproachingCrossingTile(this);
3379 if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
3381 /* Remove the loading indicators (if any) */
3382 HideFillingPercent(&this->fill_percent_te_id);
3385 pass += this->GroundVehicleBase::Crash(flooded);
3387 this->crash_anim_pos = flooded ? 4000 : 1; // max 4440, disappear pretty fast when flooded
3388 return pass;
3392 * Marks train as crashed and creates an AI event.
3393 * Doesn't do anything if the train is crashed already.
3394 * @param v first vehicle of chain
3395 * @return number of victims (including 2 drivers; zero if train was already crashed)
3397 static uint TrainCrashed(Train *v)
3399 uint num = 0;
3401 /* do not crash train twice */
3402 if (!(v->vehstatus & VS_CRASHED)) {
3403 num = v->Crash();
3404 AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
3405 Game::NewEvent(new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
3408 /* Try to re-reserve track under already crashed train too.
3409 * Crash() clears the reservation! */
3410 v->ReserveTrackUnderConsist();
3412 return num;
3415 /** Temporary data storage for testing collisions. */
3416 struct TrainCollideChecker {
3417 Train *v; ///< %Vehicle we are testing for collision.
3418 uint num; ///< Total number of victims if train collided.
3422 * Collision test function.
3423 * @param v %Train vehicle to test collision with.
3424 * @param data %Train being examined.
3425 * @return \c NULL (always continue search)
3427 static Vehicle *FindTrainCollideEnum(Vehicle *v, void *data)
3429 TrainCollideChecker *tcc = (TrainCollideChecker*)data;
3431 /* not a train or in depot */
3432 if (v->type != VEH_TRAIN || Train::From(v)->track == TRACK_BIT_DEPOT) return NULL;
3434 /* do not crash into trains of another company. */
3435 if (v->owner != tcc->v->owner) return NULL;
3437 /* get first vehicle now to make most usual checks faster */
3438 Train *coll = Train::From(v)->First();
3440 /* can't collide with own wagons */
3441 if (coll == tcc->v) return NULL;
3443 int x_diff = v->x_pos - tcc->v->x_pos;
3444 int y_diff = v->y_pos - tcc->v->y_pos;
3446 /* Do fast calculation to check whether trains are not in close vicinity
3447 * and quickly reject trains distant enough for any collision.
3448 * Differences are shifted by 7, mapping range [-7 .. 8] into [0 .. 15]
3449 * Differences are then ORed and then we check for any higher bits */
3450 uint hash = (y_diff + 7) | (x_diff + 7);
3451 if (hash & ~15) return NULL;
3453 /* Slower check using multiplication */
3454 int min_diff = (Train::From(v)->gcache.cached_veh_length + 1) / 2 + (tcc->v->gcache.cached_veh_length + 1) / 2 - 1;
3455 if (x_diff * x_diff + y_diff * y_diff >= min_diff * min_diff) return NULL;
3457 /* Happens when there is a train under bridge next to bridge head */
3458 if (abs(v->z_pos - tcc->v->z_pos) > 5) return NULL;
3460 /* crash both trains */
3461 tcc->num += TrainCrashed(tcc->v);
3462 tcc->num += TrainCrashed(coll);
3464 return NULL; // continue searching
3468 * Checks whether the specified train has a collision with another vehicle. If
3469 * so, destroys this vehicle, and the other vehicle if its subtype has TS_Front.
3470 * Reports the incident in a flashy news item, modifies station ratings and
3471 * plays a sound.
3472 * @param v %Train to test.
3474 static bool CheckTrainCollision(Train *v)
3476 /* can't collide in depot */
3477 if (v->track == TRACK_BIT_DEPOT) return false;
3479 assert(v->track == TRACK_BIT_WORMHOLE || TileVirtXY(v->x_pos, v->y_pos) == v->tile);
3481 TrainCollideChecker tcc;
3482 tcc.v = v;
3483 tcc.num = 0;
3485 /* find colliding vehicles */
3486 if (v->track == TRACK_BIT_WORMHOLE) {
3487 FindVehicleOnPos(v->tile, &tcc, FindTrainCollideEnum);
3488 FindVehicleOnPos(GetOtherTunnelBridgeEnd(v->tile), &tcc, FindTrainCollideEnum);
3489 } else {
3490 FindVehicleOnPosXY(v->x_pos, v->y_pos, &tcc, FindTrainCollideEnum);
3493 /* any dead -> no crash */
3494 if (tcc.num == 0) return false;
3496 SetDParam(0, tcc.num);
3497 AddVehicleNewsItem(STR_NEWS_TRAIN_CRASH, NT_ACCIDENT, v->index);
3499 ModifyStationRatingAround(v->tile, v->owner, -160, 30);
3500 if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_13_BIG_CRASH, v);
3501 return true;
3504 static Vehicle *CheckTrainAtSignal(Vehicle *v, void *data)
3506 if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return NULL;
3508 Train *t = Train::From(v);
3509 DiagDirection exitdir = *(DiagDirection *)data;
3511 /* not front engine of a train, inside wormhole or depot, crashed */
3512 if (!t->IsFrontEngine() || !(t->track & TRACK_BIT_MASK)) return NULL;
3514 if (t->cur_speed > 5 || TrainExitDir(t->direction, t->track) != exitdir) return NULL;
3516 return t;
3519 /** Find train in front and keep distance between trains in tunnel/bridge. */
3520 static Vehicle *FindSpaceBetweenTrainsEnum(Vehicle *v, void *data)
3522 /* Don't look at wagons between front and back of train. */
3523 if (v->type != VEH_TRAIN || (v->Previous() != NULL && v->Next() != NULL)) return NULL;
3525 const Vehicle *u = (Vehicle*)data;
3526 int32 a, b = 0;
3528 switch (u->direction) {
3529 default: NOT_REACHED();
3530 case DIR_NE: a = u->x_pos; b = v->x_pos; break;
3531 case DIR_SE: a = v->y_pos; b = u->y_pos; break;
3532 case DIR_SW: a = v->x_pos; b = u->x_pos; break;
3533 case DIR_NW: a = u->y_pos; b = v->y_pos; break;
3536 if (a > b && a <= (b + (int)(Train::From(u)->wait_counter)) + (int)(TILE_SIZE)) return v;
3537 return NULL;
3540 static bool IsToCloseBehindTrain(Vehicle *v, TileIndex tile, bool check_endtile)
3542 Train *t = (Train *)v;
3544 if (t->force_proceed != 0) return false;
3546 if (HasVehicleOnPos(t->tile, v, &FindSpaceBetweenTrainsEnum)) {
3547 /* Revert train if not going with tunnel direction. */
3548 if (DirToDiagDir(t->direction) != GetTunnelBridgeDirection(t->tile)) {
3549 v->cur_speed = 0;
3550 ToggleBit(t->flags, VRF_REVERSING);
3552 return true;
3554 /* Cover blind spot at end of tunnel bridge. */
3555 if (check_endtile){
3556 if (HasVehicleOnPos(GetOtherTunnelBridgeEnd(t->tile), v, &FindSpaceBetweenTrainsEnum)) {
3557 /* Revert train if not going with tunnel direction. */
3558 if (DirToDiagDir(t->direction) != GetTunnelBridgeDirection(t->tile)) {
3559 v->cur_speed = 0;
3560 ToggleBit(t->flags, VRF_REVERSING);
3562 return true;
3566 return false;
3569 static bool CheckTrainStayInWormHolePathReserve(Train *t, TileIndex tile)
3571 TileIndex veh_orig = t->tile;
3572 t->tile = tile;
3573 CFollowTrackRail ft(GetTileOwner(tile), GetRailTypeInfo(t->railtype)->compatible_railtypes);
3574 if (ft.Follow(tile, DiagDirToDiagTrackdir(ReverseDiagDir(GetTunnelBridgeDirection(tile))))) {
3575 TrackdirBits reserved = ft.m_new_td_bits & TrackBitsToTrackdirBits(GetReservedTrackbits(ft.m_new_tile));
3576 if (reserved == TRACKDIR_BIT_NONE) {
3577 /* next tile is not reserved, so reserve the exit tile */
3578 SetTunnelBridgeReservation(tile, true);
3581 bool ok = TryPathReserve(t);
3582 t->tile = veh_orig;
3583 if (ok && IsTunnelBridgePBS(tile)) SetTunnelBridgeSignalState(tile, SIGNAL_STATE_GREEN);
3584 return ok;
3587 /** Simulate signals in tunnel - bridge. */
3588 static bool CheckTrainStayInWormHole(Train *t, TileIndex tile)
3590 if (t->force_proceed != 0) return false;
3592 /* When not exit reverse train. */
3593 if (!IsTunnelBridgeSignalSimulationExit(tile)) {
3594 t->cur_speed = 0;
3595 ToggleBit(t->flags, VRF_REVERSING);
3596 return true;
3598 SigSegState seg_state = (_settings_game.pf.reserve_paths || IsTunnelBridgePBS(tile)) ? SIGSEG_PBS : UpdateSignalsOnSegment(tile, INVALID_DIAGDIR, t->owner);
3599 if (seg_state != SIGSEG_PBS) {
3600 CFollowTrackRail ft(GetTileOwner(tile), GetRailTypeInfo(t->railtype)->compatible_railtypes);
3601 if (ft.Follow(tile, DiagDirToDiagTrackdir(ReverseDiagDir(GetTunnelBridgeDirection(tile))))) {
3602 if (ft.m_new_td_bits != TRACKDIR_BIT_NONE && KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
3603 Trackdir td = FindFirstTrackdir(ft.m_new_td_bits);
3604 if (HasPbsSignalOnTrackdir(ft.m_new_tile, td)) {
3605 /* immediately after the exit, there is a PBS signal, switch to PBS mode */
3606 seg_state = SIGSEG_PBS;
3611 if (seg_state == SIGSEG_FULL || (seg_state == SIGSEG_PBS && !CheckTrainStayInWormHolePathReserve(t, tile))) {
3612 t->vehstatus |= VS_TRAIN_SLOWING;
3613 t->cur_speed = 0;
3614 return true;
3617 return false;
3620 static void HandleSignalBehindTrain(Train *v, int signal_number)
3622 TileIndex tile;
3623 switch (v->direction) {
3624 default: NOT_REACHED();
3625 case DIR_NE: tile = TileVirtXY(v->x_pos + (TILE_SIZE * _settings_game.construction.simulated_wormhole_signals), v->y_pos); break;
3626 case DIR_SE: tile = TileVirtXY(v->x_pos, v->y_pos - (TILE_SIZE * _settings_game.construction.simulated_wormhole_signals) ); break;
3627 case DIR_SW: tile = TileVirtXY(v->x_pos - (TILE_SIZE * _settings_game.construction.simulated_wormhole_signals), v->y_pos); break;
3628 case DIR_NW: tile = TileVirtXY(v->x_pos, v->y_pos + (TILE_SIZE * _settings_game.construction.simulated_wormhole_signals)); break;
3631 if(tile == v->tile) {
3632 /* Flip signal on ramp. */
3633 if (IsTunnelBridgeSignalSimulationEntrance(tile) && GetTunnelBridgeSignalState(tile) == SIGNAL_STATE_RED) {
3634 SetTunnelBridgeSignalState(tile, SIGNAL_STATE_GREEN);
3635 MarkTileDirtyByTile(tile);
3637 } else if (IsBridge(v->tile) && signal_number >= 0) {
3638 SetBridgeEntranceSimulatedSignalState(v->tile, signal_number, SIGNAL_STATE_GREEN);
3639 MarkTileDirtyByTile(tile);
3643 static inline void IncreaseTrackUsage(TileIndex ti, Track track_piece)
3645 if (!IsTileType(ti, MP_RAILWAY))
3646 return;
3647 if (!IsPlainRailTile(ti))
3648 return;
3650 /* ignore track_piece, 1 state per tile */
3651 byte age = GetRailAge(ti);
3653 static byte train_clean_strength = 32;
3655 if (age <= train_clean_strength)
3656 age = 0;
3657 else
3658 age -= train_clean_strength;
3660 byte old_growth = GetTrackGrowthPhase(ti);
3662 SetRailAge(ti, age);
3664 /* If rounded growth amount changes, redraw */
3665 if (GetTrackGrowthPhase(ti) != old_growth)
3666 MarkTileDirtyByTile(ti);
3669 uint16 ReversingDistanceTargetSpeed(const Train *v)
3671 int target_speed;
3672 if (_settings_game.vehicle.train_acceleration_model == AM_REALISTIC) {
3673 target_speed = ((v->reverse_distance - 1) * 5) / 2;
3675 else {
3676 target_speed = (v->reverse_distance - 1) * 10 - 5;
3678 return max(0, target_speed);
3682 * Move a vehicle chain one movement stop forwards.
3683 * @param v First vehicle to move.
3684 * @param nomove Stop moving this and all following vehicles.
3685 * @param reverse Set to false to not execute the vehicle reversing. This does not change any other logic.
3686 * @return True if the vehicle could be moved forward, false otherwise.
3688 bool TrainController(Train *v, Vehicle *nomove, bool reverse)
3690 Train *first = v->First();
3691 Train *prev;
3692 bool direction_changed = false; // has direction of any part changed?
3694 if (reverse && v->reverse_distance == 1) {
3695 goto reverse_train_direction;
3698 if (v->reverse_distance > 1) {
3699 uint16 spd = ReversingDistanceTargetSpeed(v);
3700 if (spd < v->cur_speed) v->cur_speed = spd;
3703 /* For every vehicle after and including the given vehicle */
3704 for (prev = v->Previous(); v != nomove; prev = v, v = v->Next()) {
3705 DiagDirection enterdir = DIAGDIR_BEGIN;
3706 bool update_signals_crossing = false; // will we update signals or crossing state?
3708 GetNewVehiclePosResult gp = GetNewVehiclePos(v);
3709 if (v->track != TRACK_BIT_WORMHOLE) {
3710 /* Not inside tunnel */
3711 if (gp.old_tile == gp.new_tile) {
3712 /* Staying in the old tile */
3713 if (v->track == TRACK_BIT_DEPOT) {
3714 /* Inside depot */
3715 gp.x = v->x_pos;
3716 gp.y = v->y_pos;
3717 v->reverse_distance = 0;
3718 } else {
3719 /* Not inside depot */
3721 /* Reverse when we are at the end of the track already, do not move to the new position */
3722 if (v->IsFrontEngine() && !TrainCheckIfLineEnds(v, reverse)) return false;
3724 uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
3725 if (HasBit(r, VETS_CANNOT_ENTER)) {
3726 goto invalid_rail;
3728 if (HasBit(r, VETS_ENTERED_STATION)) {
3729 /* The new position is the end of the platform */
3730 TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
3733 } else {
3734 /* A new tile is about to be entered. */
3736 /* Determine what direction we're entering the new tile from */
3737 enterdir = DiagdirBetweenTiles(gp.old_tile, gp.new_tile);
3738 assert(IsValidDiagDirection(enterdir));
3740 /* Get the status of the tracks in the new tile and mask
3741 * away the bits that aren't reachable. */
3742 TrackStatus ts = GetTileTrackStatus(gp.new_tile, TRANSPORT_RAIL, 0, ReverseDiagDir(enterdir));
3743 TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(enterdir);
3745 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
3746 TrackBits red_signals = TrackdirBitsToTrackBits(TrackStatusToRedSignals(ts) & reachable_trackdirs);
3748 TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
3749 if (_settings_game.pf.forbid_90_deg && prev == NULL) {
3750 /* We allow wagons to make 90 deg turns, because forbid_90_deg
3751 * can be switched on halfway a turn */
3752 bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
3755 if (bits == TRACK_BIT_NONE)
3756 goto invalid_rail;
3758 /* Check if the new tile constrains tracks that are compatible
3759 * with the current train, if not, bail out. */
3760 if (!CheckCompatibleRail(v, gp.new_tile))
3761 goto invalid_rail;
3763 TrackBits chosen_track;
3764 if (prev == NULL) {
3765 /* Currently the locomotive is active. Determine which one of the
3766 * available tracks to choos/// e */
3767 Track chosen_track_num = ChooseTrainTrack(v, gp.new_tile, enterdir, bits, false, NULL, true);
3768 chosen_track = TrackToTrackBits(chosen_track_num);
3769 assert(chosen_track & (bits | GetReservedTrackbits(gp.new_tile)));
3771 if (v->force_proceed != TFP_NONE && IsPlainRailTile(gp.new_tile) && HasSignals(gp.new_tile)) {
3772 /* For each signal we find decrease the counter by one.
3773 * We start at two, so the first signal we pass decreases
3774 * this to one, then if we reach the next signal it is
3775 * decreased to zero and we won't pass that new signal. */
3776 Trackdir dir = FindFirstTrackdir(trackdirbits);
3777 if (HasSignalOnTrackdir(gp.new_tile, dir) ||
3778 (HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(dir)) &&
3779 GetSignalType(gp.new_tile, TrackdirToTrack(dir)) != SIGTYPE_PBS)) {
3780 /* However, we do not want to be stopped by PBS signals
3781 * entered via the back. */
3782 v->force_proceed = (v->force_proceed == TFP_SIGNAL) ? TFP_STUCK : TFP_NONE;
3783 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
3787 /* Check if it's a red signal and that force proceed is not clicked. */
3788 if ((red_signals & chosen_track) && v->force_proceed == TFP_NONE) {
3789 /* In front of a red signal */
3790 Trackdir i = FindFirstTrackdir(trackdirbits);
3792 /* Don't handle stuck trains here. */
3793 if (HasBit(v->flags, VRF_TRAIN_STUCK)) return false;
3795 if (!HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(i))) {
3796 v->cur_speed = 0;
3797 v->subspeed = 0;
3798 v->progress = 255 - 100;
3799 if (!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_oneway_signal * 20) return false;
3800 } else if (HasSignalOnTrackdir(gp.new_tile, i)) {
3801 v->cur_speed = 0;
3802 v->subspeed = 0;
3803 v->progress = 255 - 10;
3804 if (!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_twoway_signal * 73) {
3805 DiagDirection exitdir = TrackdirToExitdir(i);
3806 TileIndex o_tile = TileAddByDiagDir(gp.new_tile, exitdir);
3808 exitdir = ReverseDiagDir(exitdir);
3810 /* check if a train is waiting on the other side */
3811 if (!HasVehicleOnPos(o_tile, &exitdir, &CheckTrainAtSignal)) return false;
3815 /* If we would reverse but are currently in a PBS block and
3816 * reversing of stuck trains is disabled, don't reverse.
3817 * This does not apply if the reason for reversing is a one-way
3818 * signal blocking us, because a train would then be stuck forever. */
3819 if (!_settings_game.pf.reverse_at_signals && !HasOnewaySignalBlockingTrackdir(gp.new_tile, i) &&
3820 UpdateSignalsOnSegment(v->tile, enterdir, v->owner) == SIGSEG_PBS) {
3821 v->wait_counter = 0;
3822 return false;
3824 goto reverse_train_direction;
3825 } else {
3826 TryReserveRailTrack(gp.new_tile, TrackBitsToTrack(chosen_track), false);
3828 if (IsPlainRailTile(gp.new_tile) && HasSignals(gp.new_tile) && IsRestrictedSignal(gp.new_tile)) {
3829 const Trackdir dir = FindFirstTrackdir(trackdirbits);
3830 if (HasSignalOnTrack(gp.new_tile, TrackdirToTrack(dir))) {
3831 const TraceRestrictProgram *prog = GetExistingTraceRestrictProgram(gp.new_tile, TrackdirToTrack(dir));
3832 if (prog && prog->actions_used_flags & (TRPAUF_SLOT_ACQUIRE | TRPAUF_SLOT_RELEASE_FRONT)) {
3833 TraceRestrictProgramResult out;
3834 TraceRestrictProgramInput input(gp.new_tile, dir, NULL, NULL);
3835 input.permitted_slot_operations = TRPISP_ACQUIRE | TRPISP_RELEASE_FRONT;
3836 prog->Execute(v, input, out);
3841 IncreaseTrackUsage(gp.new_tile, chosen_track_num);
3842 } else {
3843 /* The wagon is active, simply follow the prev vehicle. */
3844 if (prev->tile == gp.new_tile) {
3845 /* Choose the same track as prev */
3846 if (prev->track == TRACK_BIT_WORMHOLE) {
3847 /* Vehicles entering tunnels enter the wormhole earlier than for bridges.
3848 * However, just choose the track into the wormhole. */
3849 assert(IsTunnel(prev->tile));
3850 chosen_track = bits;
3851 } else {
3852 chosen_track = prev->track;
3854 } else {
3855 /* Choose the track that leads to the tile where prev is.
3856 * This case is active if 'prev' is already on the second next tile, when 'v' just enters the next tile.
3857 * I.e. when the tile between them has only space for a single vehicle like
3858 * 1) horizontal/vertical track tiles and
3859 * 2) some orientations of tunnel entries, where the vehicle is already inside the wormhole at 8/16 from the tile edge.
3860 * Is also the train just reversing, the wagon inside the tunnel is 'on' the tile of the opposite tunnel entry.
3862 static const TrackBits _connecting_track[DIAGDIR_END][DIAGDIR_END] = {
3863 {TRACK_BIT_X, TRACK_BIT_LOWER, TRACK_BIT_NONE, TRACK_BIT_LEFT },
3864 {TRACK_BIT_UPPER, TRACK_BIT_Y, TRACK_BIT_LEFT, TRACK_BIT_NONE },
3865 {TRACK_BIT_NONE, TRACK_BIT_RIGHT, TRACK_BIT_X, TRACK_BIT_UPPER},
3866 {TRACK_BIT_RIGHT, TRACK_BIT_NONE, TRACK_BIT_LOWER, TRACK_BIT_Y }
3868 DiagDirection exitdir = DiagdirBetweenTiles(gp.new_tile, prev->tile);
3869 assert(IsValidDiagDirection(exitdir));
3870 chosen_track = _connecting_track[enterdir][exitdir];
3872 chosen_track &= bits;
3875 /* Make sure chosen track is a valid track */
3876 assert(
3877 chosen_track == TRACK_BIT_X || chosen_track == TRACK_BIT_Y ||
3878 chosen_track == TRACK_BIT_UPPER || chosen_track == TRACK_BIT_LOWER ||
3879 chosen_track == TRACK_BIT_LEFT || chosen_track == TRACK_BIT_RIGHT);
3881 /* Update XY to reflect the entrance to the new tile, and select the direction to use */
3882 const byte *b = _initial_tile_subcoord[FIND_FIRST_BIT(chosen_track)][enterdir];
3883 gp.x = (gp.x & ~0xF) | b[0];
3884 gp.y = (gp.y & ~0xF) | b[1];
3885 Direction chosen_dir = (Direction)b[2];
3887 /* Call the landscape function and tell it that the vehicle entered the tile */
3888 uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
3889 if (HasBit(r, VETS_CANNOT_ENTER)) {
3890 goto invalid_rail;
3893 if (IsTunnelBridgeWithSignalSimulation(gp.new_tile)) {
3894 /* If red signal stop. */
3895 if (v->IsFrontEngine() && v->force_proceed == 0) {
3896 if (IsTunnelBridgeSignalSimulationEntrance(gp.new_tile) && GetTunnelBridgeSignalState(gp.new_tile) == SIGNAL_STATE_RED) {
3897 v->cur_speed = 0;
3898 v->vehstatus |= VS_TRAIN_SLOWING;
3899 return false;
3901 if (IsTunnelBridgeSignalSimulationExit(gp.new_tile)) {
3902 v->cur_speed = 0;
3903 goto invalid_rail;
3905 /* Flip signal on tunnel entrance tile red. */
3906 SetTunnelBridgeSignalState(gp.new_tile, SIGNAL_STATE_RED);
3907 MarkTileDirtyByTile(gp.new_tile);
3911 if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
3912 Track track = FindFirstTrack(chosen_track);
3913 Trackdir tdir = TrackDirectionToTrackdir(track, chosen_dir);
3914 if (v->IsFrontEngine() && HasPbsSignalOnTrackdir(gp.new_tile, tdir)) {
3915 SetSignalStateByTrackdir(gp.new_tile, tdir, SIGNAL_STATE_RED);
3916 MarkTileDirtyByTile(gp.new_tile);
3918 /* notify logic signals of the state change */
3919 SignalStateChanged(gp.new_tile, TrackdirToTrack(tdir), 1);
3922 /* Clear any track reservation when the last vehicle leaves the tile */
3923 if (v->Next() == NULL) ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
3925 v->tile = gp.new_tile;
3927 if (GetTileRailType(gp.new_tile) != GetTileRailType(gp.old_tile)) {
3928 v->First()->ConsistChanged(CCF_TRACK);
3931 v->track = chosen_track;
3932 assert(v->track);
3935 /* We need to update signal status, but after the vehicle position hash
3936 * has been updated by UpdateInclination() */
3937 update_signals_crossing = true;
3939 if (chosen_dir != v->direction) {
3940 if (prev == NULL && _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) {
3941 const AccelerationSlowdownParams *asp = &_accel_slowdown[GetRailTypeInfo(v->railtype)->acceleration_type];
3942 DirDiff diff = DirDifference(v->direction, chosen_dir);
3943 v->cur_speed -= (diff == DIRDIFF_45RIGHT || diff == DIRDIFF_45LEFT ? asp->small_turn : asp->large_turn) * v->cur_speed >> 8;
3945 direction_changed = true;
3946 v->direction = chosen_dir;
3949 if (v->IsFrontEngine()) {
3950 v->wait_counter = 0;
3952 /* If we are approaching a crossing that is reserved, play the sound now. */
3953 TileIndex crossing = TrainApproachingCrossingTile(v);
3955 if (crossing != INVALID_TILE)
3957 RailTypeLabel railTypeLabel = GetRailTypeInfo(GetTileRailType(crossing))->label;
3958 bool is_no_sound_rail_type = (railTypeLabel == _planning_tracks_label || railTypeLabel == _pipeline_tracks_label || railTypeLabel == _wires_tracks_label);
3960 if (HasCrossingReservation(crossing) && _settings_client.sound.ambient && !is_no_sound_rail_type)
3961 SndPlayTileFx(SND_0E_LEVEL_CROSSING, crossing);
3964 /* Always try to extend the reservation when entering a tile. */
3965 CheckNextTrainTile(v);
3968 if (HasBit(r, VETS_ENTERED_STATION)) {
3969 /* The new position is the location where we want to stop */
3970 TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
3973 } else {
3974 /* Handle signal simulation on tunnel/bridge. */
3975 TileIndex old_tile = TileVirtXY(v->x_pos, v->y_pos);
3976 if (old_tile != gp.new_tile && IsTunnelBridgeWithSignalSimulation(v->tile) && (v->IsFrontEngine() || v->Next() == NULL)) {
3977 if (old_tile == v->tile) {
3978 if (v->IsFrontEngine() && v->force_proceed == 0 && IsTunnelBridgeSignalSimulationExit(v->tile))
3979 goto invalid_rail;
3980 /* Entered wormhole set counters. */
3981 v->wait_counter = (TILE_SIZE * _settings_game.construction.simulated_wormhole_signals) - TILE_SIZE;
3982 v->load_unload_ticks = 0;
3985 uint distance = v->wait_counter;
3986 bool leaving = false;
3987 if (distance == 0) v->wait_counter = (TILE_SIZE * _settings_game.construction.simulated_wormhole_signals);
3989 if (v->IsFrontEngine()) {
3990 /* Check if track in front is free and see if we can leave wormhole. */
3991 int z = GetSlopePixelZ(gp.x, gp.y) - v->z_pos;
3992 if (IsTileType(gp.new_tile, MP_TUNNELBRIDGE) && !(abs(z) > 2)) {
3993 if (CheckTrainStayInWormHole(v, gp.new_tile)) return false;
3994 leaving = true;
3995 } else {
3996 if (IsToCloseBehindTrain(v, gp.new_tile, distance == 0)) {
3997 if (distance == 0) v->wait_counter = 0;
3998 v->cur_speed = 0;
3999 v->vehstatus |= VS_TRAIN_SLOWING;
4000 return false;
4002 /* flip signal in front to red on bridges*/
4003 if (distance == 0 && IsBridge(v->tile)) {
4004 SetBridgeEntranceSimulatedSignalState(v->tile, v->load_unload_ticks, SIGNAL_STATE_RED);
4005 MarkTileDirtyByTile(gp.new_tile);
4009 if (v->Next() == NULL) {
4010 if (v->load_unload_ticks > 0 && distance == (TILE_SIZE * _settings_game.construction.simulated_wormhole_signals) - TILE_SIZE) HandleSignalBehindTrain(v, v->load_unload_ticks - 2);
4011 if (old_tile == v->tile) {
4012 /* We left ramp into wormhole. */
4013 v->x_pos = gp.x;
4014 v->y_pos = gp.y;
4015 UpdateSignalsOnSegment(old_tile, INVALID_DIAGDIR, v->owner);
4016 UnreserveBridgeTunnelTile(old_tile);
4019 if (distance == 0) v->load_unload_ticks++;
4020 v->wait_counter -= TILE_SIZE;
4022 if (leaving) { // Reset counters.
4023 v->force_proceed = 0;
4024 v->wait_counter = 0;
4025 v->load_unload_ticks = 0;
4026 v->x_pos = gp.x;
4027 v->y_pos = gp.y;
4028 v->UpdatePosition();
4029 v->UpdateViewport(false, false);
4030 UpdateSignalsOnSegment(gp.new_tile, INVALID_DIAGDIR, v->owner);
4031 continue;
4035 if (IsTileType(gp.new_tile, MP_TUNNELBRIDGE) && HasBit(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y), VETS_ENTERED_WORMHOLE)) {
4036 /* Perform look-ahead on tunnel exit. */
4037 if (v->IsFrontEngine()) {
4038 TryReserveRailTrack(gp.new_tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(gp.new_tile)));
4039 CheckNextTrainTile(v);
4041 /* Prevent v->UpdateInclination() being called with wrong parameters.
4042 * This could happen if the train was reversed inside the tunnel/bridge. */
4043 if (gp.old_tile == gp.new_tile) {
4044 gp.old_tile = GetOtherTunnelBridgeEnd(gp.old_tile);
4046 } else {
4047 v->x_pos = gp.x;
4048 v->y_pos = gp.y;
4049 v->UpdatePosition();
4050 if (HasBit(v->gv_flags, GVF_CHUNNEL_BIT)) {
4051 /* update the Z position of the vehicle */
4052 int old_z = v->UpdateInclination(false, false, true);
4054 if (prev == NULL) {
4055 /* This is the first vehicle in the train */
4056 AffectSpeedByZChange(v, old_z);
4059 if (v->IsDrawn()) v->Vehicle::UpdateViewport(true);
4060 continue;
4064 /* update image of train, as well as delta XY */
4065 v->UpdateDeltaXY(v->direction);
4067 v->x_pos = gp.x;
4068 v->y_pos = gp.y;
4069 v->UpdatePosition();
4070 if (v->reverse_distance > 1) {
4071 v->reverse_distance--;
4074 /* update the Z position of the vehicle */
4075 int old_z = v->UpdateInclination(gp.new_tile != gp.old_tile, false, v->track == TRACK_BIT_WORMHOLE);
4077 if (prev == NULL) {
4078 /* This is the first vehicle in the train */
4079 AffectSpeedByZChange(v, old_z);
4082 if (update_signals_crossing) {
4083 if (v->IsFrontEngine()) {
4084 switch(TrainMovedChangeSignal(v, gp.new_tile, enterdir)) {
4085 case CHANGED_NORMAL_TO_PBS_BLOCK:
4086 /* We are entering a block with PBS signals right now, but
4087 * not through a PBS signal. This means we don't have a
4088 * reservation right now. As a conventional signal will only
4089 * ever be green if no other train is in the block, getting
4090 * a path should always be possible. If the player built
4091 * such a strange network that it is not possible, the train
4092 * will be marked as stuck and the player has to deal with
4093 * the problem. */
4094 if ((!HasReservedTracks(gp.new_tile, v->track) &&
4095 !TryReserveRailTrack(gp.new_tile, FindFirstTrack(v->track))) ||
4096 !TryPathReserve(v)) {
4097 MarkTrainAsStuck(v);
4100 break;
4101 case CHANGED_LR_PBS:
4103 /* We went past a long reserve PBS signal. Try to extend the
4104 * reservation if reserving failed at another LR signal. */
4105 PBSTileInfo origin = FollowTrainReservation(v);
4106 CFollowTrackRail ft(v);
4108 if (ft.Follow(origin.tile, origin.trackdir)) {
4109 Trackdir new_td = FindFirstTrackdir(ft.m_new_td_bits);
4111 if (HasLongReservePbsSignalOnTrackdir(v, ft.m_new_tile, new_td)) {
4112 ChooseTrainTrack(v, ft.m_new_tile, ft.m_exitdir, TrackdirBitsToTrackBits(ft.m_new_td_bits), true, NULL, false);
4116 break;
4118 default: break;
4122 /* Signals can only change when the first
4123 * (above) or the last vehicle moves. */
4124 if (v->Next() == NULL) {
4125 TrainMovedChangeSignal(v, gp.old_tile, ReverseDiagDir(enterdir));
4126 if (IsLevelCrossingTile(gp.old_tile)) UpdateLevelCrossing(gp.old_tile);
4128 if (IsTileType(gp.old_tile, MP_RAILWAY) && HasSignals(gp.old_tile) && IsRestrictedSignal(gp.old_tile)) {
4129 const TrackdirBits rev_tracks = TrackBitsToTrackdirBits(GetTrackBits(gp.old_tile)) & DiagdirReachesTrackdirs(ReverseDiagDir(enterdir));
4130 const Trackdir rev_trackdir = FindFirstTrackdir(rev_tracks);
4131 const Track track = TrackdirToTrack(rev_trackdir);
4132 if (HasSignalOnTrack(gp.old_tile, track)) {
4133 const TraceRestrictProgram *prog = GetExistingTraceRestrictProgram(gp.old_tile, track);
4134 if (prog && prog->actions_used_flags & TRPAUF_SLOT_RELEASE_BACK) {
4135 TraceRestrictProgramResult out;
4136 TraceRestrictProgramInput input(gp.old_tile, ReverseTrackdir(rev_trackdir), NULL, NULL);
4137 input.permitted_slot_operations = TRPISP_RELEASE_BACK;
4138 prog->Execute(first, input, out);
4145 /* Do not check on every tick to save some computing time. */
4146 if (v->IsFrontEngine() && v->tick_counter % _settings_game.pf.path_backoff_interval == 0) CheckNextTrainTile(v);
4149 if (direction_changed) first->tcache.cached_max_curve_speed = first->GetCurveSpeedLimit();
4151 return true;
4153 invalid_rail:
4154 /* We've reached end of line?? */
4155 if (prev != NULL) error("Disconnecting train");
4157 reverse_train_direction:
4158 if (reverse) {
4159 v->wait_counter = 0;
4160 v->cur_speed = 0;
4161 v->subspeed = 0;
4162 ReverseTrainDirection(v);
4165 return false;
4169 * Collect trackbits of all crashed train vehicles on a tile
4170 * @param v Vehicle passed from Find/HasVehicleOnPos()
4171 * @param data trackdirbits for the result
4172 * @return NULL to iterate over all vehicles on the tile.
4174 static Vehicle *CollectTrackbitsFromCrashedVehiclesEnum(Vehicle *v, void *data)
4176 TrackBits *trackbits = (TrackBits *)data;
4178 if (v->type == VEH_TRAIN && (v->vehstatus & VS_CRASHED) != 0) {
4179 TrackBits train_tbits = Train::From(v)->track;
4180 if (train_tbits == TRACK_BIT_WORMHOLE) {
4181 /* Vehicle is inside a wormhole, v->track contains no useful value then. */
4182 *trackbits |= DiagDirToDiagTrackBits(GetTunnelBridgeDirection(v->tile));
4183 } else if (train_tbits != TRACK_BIT_DEPOT) {
4184 *trackbits |= train_tbits;
4188 return NULL;
4192 * Deletes/Clears the last wagon of a crashed train. It takes the engine of the
4193 * train, then goes to the last wagon and deletes that. Each call to this function
4194 * will remove the last wagon of a crashed train. If this wagon was on a crossing,
4195 * or inside a tunnel/bridge, recalculate the signals as they might need updating
4196 * @param v the Vehicle of which last wagon is to be removed
4198 static void DeleteLastWagon(Train *v)
4200 Train *first = v->First();
4202 /* Go to the last wagon and delete the link pointing there
4203 * *u is then the one-before-last wagon, and *v the last
4204 * one which will physically be removed */
4205 Train *u = v;
4206 for (; v->Next() != NULL; v = v->Next()) u = v;
4207 u->SetNext(NULL);
4209 if (first != v) {
4210 /* Recalculate cached train properties */
4211 first->ConsistChanged(CCF_ARRANGE);
4212 /* Update the depot window if the first vehicle is in depot -
4213 * if v == first, then it is updated in PreDestructor() */
4214 if (first->track == TRACK_BIT_DEPOT) {
4215 SetWindowDirty(WC_VEHICLE_DEPOT, first->tile);
4217 v->last_station_visited = first->last_station_visited; // for PreDestructor
4220 /* 'v' shouldn't be accessed after it has been deleted */
4221 TrackBits trackbits = v->track;
4222 TileIndex tile = v->tile;
4223 Owner owner = v->owner;
4225 delete v;
4226 v = NULL; // make sure nobody will try to read 'v' anymore
4228 if (trackbits == TRACK_BIT_WORMHOLE) {
4229 /* Vehicle is inside a wormhole, v->track contains no useful value then. */
4230 trackbits = DiagDirToDiagTrackBits(GetTunnelBridgeDirection(tile));
4233 Track track = TrackBitsToTrack(trackbits);
4234 if (HasReservedTracks(tile, trackbits)) {
4235 UnreserveRailTrack(tile, track);
4237 /* If there are still crashed vehicles on the tile, give the track reservation to them */
4238 TrackBits remaining_trackbits = TRACK_BIT_NONE;
4239 FindVehicleOnPos(tile, &remaining_trackbits, CollectTrackbitsFromCrashedVehiclesEnum);
4241 /* It is important that these two are the first in the loop, as reservation cannot deal with every trackbit combination */
4242 assert(TRACK_BEGIN == TRACK_X && TRACK_Y == TRACK_BEGIN + 1);
4243 Track t;
4244 FOR_EACH_SET_TRACK(t, remaining_trackbits) TryReserveRailTrack(tile, t);
4247 /* check if the wagon was on a road/rail-crossing */
4248 if (IsLevelCrossingTile(tile)) UpdateLevelCrossing(tile);
4250 /* Update signals */
4251 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
4252 UpdateSignalsOnSegment(tile, INVALID_DIAGDIR, owner);
4253 if (IsTunnelBridgeWithSignalSimulation(tile)) {
4254 TileIndex end = GetOtherTunnelBridgeEnd(tile);
4255 UpdateSignalsOnSegment(end, INVALID_DIAGDIR, owner);
4256 bool is_entrance = IsTunnelBridgeSignalSimulationEntrance(tile);
4257 TileIndex entrance = is_entrance ? tile : end;
4258 if (TunnelBridgeIsFree(tile, end, nullptr).Succeeded()) {
4259 if (IsBridge(entrance)) {
4260 SetAllBridgeEntranceSimulatedSignalsGreen(entrance);
4261 MarkBridgeDirty(entrance, ZOOM_LVL_DRAW_MAP);
4263 if (IsTunnelBridgeSignalSimulationEntrance(entrance) && GetTunnelBridgeSignalState(entrance) == SIGNAL_STATE_RED) {
4264 SetTunnelBridgeSignalState(entrance, SIGNAL_STATE_GREEN);
4265 MarkTileDirtyByTile(entrance);
4269 } else if (IsRailDepotTile(tile)) {
4270 UpdateSignalsOnSegment(tile, INVALID_DIAGDIR, owner);
4271 } else {
4272 SetSignalsOnBothDir(tile, track, owner);
4277 * Rotate all vehicles of a (crashed) train chain randomly to animate the crash.
4278 * @param v First crashed vehicle.
4280 static void ChangeTrainDirRandomly(Train *v)
4282 static const DirDiff delta[] = {
4283 DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT
4286 do {
4287 /* We don't need to twist around vehicles if they're not visible */
4288 if (!(v->vehstatus & VS_HIDDEN)) {
4289 v->direction = ChangeDir(v->direction, delta[GB(Random(), 0, 2)]);
4290 /* Refrain from updating the z position of the vehicle when on
4291 * a bridge, because UpdateInclination() will put the vehicle under
4292 * the bridge in that case */
4293 if (v->track != TRACK_BIT_WORMHOLE) {
4294 v->UpdatePosition();
4295 v->UpdateInclination(false, true);
4296 } else {
4297 v->UpdateViewport(false, true);
4300 } while ((v = v->Next()) != NULL);
4304 * Handle a crashed train.
4305 * @param v First train vehicle.
4306 * @return %Vehicle chain still exists.
4308 static bool HandleCrashedTrain(Train *v)
4310 int state = ++v->crash_anim_pos;
4312 if (state == 4 && !(v->vehstatus & VS_HIDDEN)) {
4313 CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE);
4316 uint32 r;
4317 if (state <= 200 && Chance16R(1, 7, r)) {
4318 int index = (r * 10 >> 16);
4320 Vehicle *u = v;
4321 do {
4322 if (--index < 0) {
4323 r = Random();
4325 CreateEffectVehicleRel(u,
4326 GB(r, 8, 3) + 2,
4327 GB(r, 16, 3) + 2,
4328 GB(r, 0, 3) + 5,
4329 EV_EXPLOSION_SMALL);
4330 break;
4332 } while ((u = u->Next()) != NULL);
4335 if (state <= 240 && !(v->tick_counter & 3)) ChangeTrainDirRandomly(v);
4337 if (state >= 4440 && !(v->tick_counter & 0x1F)) {
4338 bool ret = v->Next() != NULL;
4339 DeleteLastWagon(v);
4340 return ret;
4343 return true;
4346 /** Maximum speeds for train that is broken down or approaching line end */
4347 static const uint16 _breakdown_speeds[16] = {
4348 225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
4353 * Train is approaching line end, slow down and possibly reverse
4355 * @param v front train engine
4356 * @param signal not line end, just a red signal
4357 * @param reverse Set to false to not execute the vehicle reversing. This does not change any other logic.
4358 * @return true iff we did NOT have to reverse
4360 static bool TrainApproachingLineEnd(Train *v, bool signal, bool reverse)
4362 /* Calc position within the current tile */
4363 uint x = v->x_pos & 0xF;
4364 uint y = v->y_pos & 0xF;
4366 /* for diagonal directions, 'x' will be 0..15 -
4367 * for other directions, it will be 1, 3, 5, ..., 15 */
4368 switch (v->direction) {
4369 case DIR_N : x = ~x + ~y + 25; break;
4370 case DIR_NW: x = y; FALLTHROUGH;
4371 case DIR_NE: x = ~x + 16; break;
4372 case DIR_E : x = ~x + y + 9; break;
4373 case DIR_SE: x = y; break;
4374 case DIR_S : x = x + y - 7; break;
4375 case DIR_W : x = ~y + x + 9; break;
4376 default: break;
4379 /* Do not reverse when approaching red signal. Make sure the vehicle's front
4380 * does not cross the tile boundary when we do reverse, but as the vehicle's
4381 * location is based on their center, use half a vehicle's length as offset.
4382 * Multiply the half-length by two for straight directions to compensate that
4383 * we only get odd x offsets there. */
4384 if (!signal && x + (v->gcache.cached_veh_length + 1) / 2 * (IsDiagonalDirection(v->direction) ? 1 : 2) >= TILE_SIZE) {
4385 /* we are too near the tile end, reverse now */
4386 v->cur_speed = 0;
4387 if (reverse) ReverseTrainDirection(v);
4388 return false;
4391 /* slow down */
4392 v->vehstatus |= VS_TRAIN_SLOWING;
4393 uint16 break_speed = _breakdown_speeds[x & 0xF];
4394 if (break_speed < v->cur_speed) v->cur_speed = break_speed;
4396 return true;
4401 * Determines whether train would like to leave the tile
4402 * @param v train to test
4403 * @return true iff vehicle is NOT entering or inside a depot or tunnel/bridge
4405 static bool TrainCanLeaveTile(const Train *v)
4407 /* Exit if inside a tunnel/bridge or a depot */
4408 if (v->track == TRACK_BIT_WORMHOLE || v->track == TRACK_BIT_DEPOT) return false;
4410 TileIndex tile = v->tile;
4412 /* entering a tunnel/bridge? */
4413 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
4414 DiagDirection dir = GetTunnelBridgeDirection(tile);
4415 if (DiagDirToDir(dir) == v->direction) return false;
4418 /* entering a depot? */
4419 if (IsRailDepotTile(tile)) {
4420 DiagDirection dir = ReverseDiagDir(GetRailDepotDirection(tile));
4421 if (DiagDirToDir(dir) == v->direction) return false;
4424 return true;
4429 * Determines whether train is approaching a rail-road crossing
4430 * (thus making it barred)
4431 * @param v front engine of train
4432 * @return TileIndex of crossing the train is approaching, else INVALID_TILE
4433 * @pre v in non-crashed front engine
4435 static TileIndex TrainApproachingCrossingTile(const Train *v)
4437 assert(v->IsFrontEngine());
4438 assert(!(v->vehstatus & VS_CRASHED));
4440 if (!TrainCanLeaveTile(v)) return INVALID_TILE;
4442 DiagDirection dir = TrainExitDir(v->direction, v->track);
4443 TileIndex tile = v->tile + TileOffsByDiagDir(dir);
4445 /* not a crossing || wrong axis || unusable rail (wrong type or owner) */
4446 if (!IsLevelCrossingTile(tile) || DiagDirToAxis(dir) == GetCrossingRoadAxis(tile) ||
4447 !CheckCompatibleRail(v, tile)) {
4448 return INVALID_TILE;
4451 return tile;
4456 * Checks for line end. Also, bars crossing at next tile if needed
4458 * @param v vehicle we are checking
4459 * @param reverse Set to false to not execute the vehicle reversing. This does not change any other logic.
4460 * @return true iff we did NOT have to reverse
4462 static bool TrainCheckIfLineEnds(Train *v, bool reverse)
4464 /* First, handle broken down train */
4466 int t = v->breakdown_ctr;
4467 if (t > 1) {
4468 v->vehstatus |= VS_TRAIN_SLOWING;
4470 uint16 break_speed = _breakdown_speeds[GB(~t, 4, 4)];
4471 if (break_speed < v->cur_speed) v->cur_speed = break_speed;
4472 } else {
4473 v->vehstatus &= ~VS_TRAIN_SLOWING;
4476 if (!TrainCanLeaveTile(v)) return true;
4478 /* Determine the non-diagonal direction in which we will exit this tile */
4479 DiagDirection dir = TrainExitDir(v->direction, v->track);
4480 /* Calculate next tile */
4481 TileIndex tile = v->tile + TileOffsByDiagDir(dir);
4483 /* Determine the track status on the next tile */
4484 TrackStatus ts = GetTileTrackStatus(tile, TRANSPORT_RAIL, 0, ReverseDiagDir(dir));
4485 TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(dir);
4487 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
4488 TrackdirBits red_signals = TrackStatusToRedSignals(ts) & reachable_trackdirs;
4490 /* We are sure the train is not entering a depot, it is detected above */
4492 /* mask unreachable track bits if we are forbidden to do 90deg turns */
4493 TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
4494 if (_settings_game.pf.forbid_90_deg) {
4495 bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
4498 /* no suitable trackbits at all || unusable rail (wrong type or owner) */
4499 if (bits == TRACK_BIT_NONE || !CheckCompatibleRail(v, tile)) {
4500 return TrainApproachingLineEnd(v, false, reverse);
4503 /* approaching red signal */
4504 if ((trackdirbits & red_signals) != 0) return TrainApproachingLineEnd(v, true, reverse);
4506 /* approaching a rail/road crossing? then make it red */
4507 if (IsLevelCrossingTile(tile)) MaybeBarCrossingWithSound(tile);
4509 return true;
4512 /* Calculate the summed up value of all parts of a train */
4513 Money Train::CalculateCurrentOverallValue() const
4515 Money ovr_value = 0;
4516 const Train *v = this;
4517 do {
4518 ovr_value += v->value;
4519 } while ( (v=v->GetNextVehicle()) != NULL );
4520 return ovr_value;
4523 static bool TrainLocoHandler(Train *v, bool mode)
4525 /* train has crashed? */
4526 if (v->vehstatus & VS_CRASHED) {
4527 return mode ? true : HandleCrashedTrain(v); // 'this' can be deleted here
4530 if (v->force_proceed != TFP_NONE) {
4531 ClrBit(v->flags, VRF_TRAIN_STUCK);
4532 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4535 /* train is broken down? */
4536 if (v->HandleBreakdown()) return true;
4538 if (HasBit(v->flags, VRF_REVERSING) && v->cur_speed == 0) {
4539 ReverseTrainDirection(v);
4542 /* exit if train is stopped */
4543 if ((v->vehstatus & VS_STOPPED) && v->cur_speed == 0) return true;
4545 bool valid_order = !v->current_order.IsType(OT_NOTHING) && v->current_order.GetType() != OT_CONDITIONAL;
4546 if (ProcessOrders(v) && CheckReverseTrain(v)) {
4547 v->wait_counter = 0;
4548 v->cur_speed = 0;
4549 v->subspeed = 0;
4550 ClrBit(v->flags, VRF_LEAVING_STATION);
4551 ReverseTrainDirection(v);
4552 return true;
4553 } else if (HasBit(v->flags, VRF_LEAVING_STATION)) {
4554 /* Try to reserve a path when leaving the station as we
4555 * might not be marked as wanting a reservation, e.g.
4556 * when an overlength train gets turned around in a station. */
4557 DiagDirection dir = TrainExitDir(v->direction, v->track);
4558 if (IsRailDepotTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE)) dir = INVALID_DIAGDIR;
4560 if (UpdateSignalsOnSegment(v->tile, dir, v->owner) == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
4561 TryPathReserve(v, true, true);
4563 ClrBit(v->flags, VRF_LEAVING_STATION);
4566 v->HandleLoading(mode);
4568 if (v->current_order.IsType(OT_LOADING)) return true;
4570 if (CheckTrainStayInDepot(v)) return true;
4572 if (!mode) v->ShowVisualEffect();
4574 /* We had no order but have an order now, do look ahead. */
4575 if (!valid_order && !v->current_order.IsType(OT_NOTHING)) {
4576 CheckNextTrainTile(v);
4579 /* Handle stuck trains. */
4580 if (!mode && HasBit(v->flags, VRF_TRAIN_STUCK)) {
4581 ++v->wait_counter;
4583 /* Should we try reversing this tick if still stuck? */
4584 bool turn_around = v->wait_counter % (_settings_game.pf.wait_for_pbs_path * DAY_TICKS) == 0 && _settings_game.pf.reverse_at_signals;
4586 if (!turn_around && v->wait_counter % _settings_game.pf.path_backoff_interval != 0 && v->force_proceed == TFP_NONE) return true;
4587 if (!TryPathReserve(v)) {
4588 /* Still stuck. */
4589 if (turn_around) ReverseTrainDirection(v);
4591 if (HasBit(v->flags, VRF_TRAIN_STUCK) && v->wait_counter > 2 * _settings_game.pf.wait_for_pbs_path * DAY_TICKS) {
4592 /* Show message to player. */
4593 if (_settings_client.gui.lost_vehicle_warn && v->owner == _local_company) {
4594 SetDParam(0, v->index);
4595 AddVehicleAdviceNewsItem(STR_NEWS_TRAIN_IS_STUCK, v->index);
4597 v->wait_counter = 0;
4599 /* Exit if force proceed not pressed, else reset stuck flag anyway. */
4600 if (v->force_proceed == TFP_NONE) return true;
4601 ClrBit(v->flags, VRF_TRAIN_STUCK);
4602 v->wait_counter = 0;
4603 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4607 if (v->current_order.IsType(OT_LEAVESTATION)) {
4608 v->current_order.Free();
4609 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4610 return true;
4613 int j = v->UpdateSpeed();
4615 /* we need to invalidate the widget if we are stopping from 'Stopping 0 km/h' to 'Stopped' */
4616 if (v->cur_speed == 0 && (v->vehstatus & VS_STOPPED)) {
4617 /* If we manually stopped, we're not force-proceeding anymore. */
4618 v->force_proceed = TFP_NONE;
4619 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
4622 int adv_spd = v->GetAdvanceDistance();
4623 if (j < adv_spd) {
4624 /* if the vehicle has speed 0, update the last_speed field. */
4625 if (v->cur_speed == 0) v->SetLastSpeed();
4626 } else {
4627 TrainCheckIfLineEnds(v);
4628 /* Loop until the train has finished moving. */
4629 for (;;) {
4630 j -= adv_spd;
4631 TrainController(v, NULL);
4632 /* Don't continue to move if the train crashed. */
4633 if (CheckTrainCollision(v)) break;
4634 /* Determine distance to next map position */
4635 adv_spd = v->GetAdvanceDistance();
4637 /* No more moving this tick */
4638 if (j < adv_spd || v->cur_speed == 0) break;
4640 OrderType order_type = v->current_order.GetType();
4641 /* Do not skip waypoints (incl. 'via' stations) when passing through at full speed. */
4642 if ((order_type == OT_GOTO_WAYPOINT || order_type == OT_GOTO_STATION) &&
4643 (v->current_order.GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) &&
4644 IsTileType(v->tile, MP_STATION) &&
4645 v->current_order.GetDestination() == GetStationIndex(v->tile)) {
4646 ProcessOrders(v);
4649 v->SetLastSpeed();
4652 for (Train *u = v; u != NULL; u = u->Next()) {
4653 if (!(u->IsDrawn())) continue;
4655 u->UpdateViewport(false, false);
4658 if (v->progress == 0) v->progress = j; // Save unused spd for next time, if TrainController didn't set progress
4660 return true;
4664 * Get running cost for the train consist.
4665 * @return Yearly running costs.
4667 Money Train::GetRunningCost() const
4669 Money cost = 0;
4670 const Train *v = this;
4672 do {
4673 const Engine *e = v->GetEngine();
4674 if (e->u.rail.running_cost_class == INVALID_PRICE) continue;
4676 uint cost_factor = GetVehicleProperty(v, PROP_TRAIN_RUNNING_COST_FACTOR, e->u.rail.running_cost);
4677 if (cost_factor == 0) continue;
4679 /* Halve running cost for multiheaded parts */
4680 if (v->IsMultiheaded()) cost_factor /= 2;
4682 cost += GetPrice(e->u.rail.running_cost_class, cost_factor, e->GetGRF());
4683 } while ((v = v->GetNextVehicle()) != NULL);
4685 return cost;
4689 * Update train vehicle data for a tick.
4690 * @return True if the vehicle still exists, false if it has ceased to exist (front of consists only).
4692 bool Train::Tick()
4694 this->tick_counter++;
4696 if (this->IsFrontEngine()) {
4697 if (!((this->vehstatus & VS_STOPPED) || this->IsChainInDepot()) || this->cur_speed > 0) this->running_ticks++;
4699 this->current_order_time++;
4701 if (!TrainLocoHandler(this, false)) return false;
4703 return TrainLocoHandler(this, true);
4704 } else if (this->IsFreeWagon() && (this->vehstatus & VS_CRASHED)) {
4705 /* Delete flooded standalone wagon chain */
4706 if (++this->crash_anim_pos >= 4400) {
4707 delete this;
4708 return false;
4712 return true;
4716 * Check whether a train needs service, and if so, find a depot or service it.
4717 * @return v %Train to check.
4719 static void CheckIfTrainNeedsService(Train *v)
4721 if (Company::Get(v->owner)->settings.vehicle.servint_trains == 0 || !v->NeedsAutomaticServicing()) return;
4722 if (v->IsChainInDepot()) {
4723 VehicleServiceInDepot(v);
4724 return;
4727 uint max_penalty;
4728 switch (_settings_game.pf.pathfinder_for_trains) {
4729 case VPF_NPF: max_penalty = _settings_game.pf.npf.maximum_go_to_depot_penalty; break;
4730 case VPF_YAPF: max_penalty = _settings_game.pf.yapf.maximum_go_to_depot_penalty; break;
4731 default: NOT_REACHED();
4734 FindDepotData tfdd = FindClosestTrainDepot(v, max_penalty);
4735 /* Only go to the depot if it is not too far out of our way. */
4736 if (tfdd.best_length == UINT_MAX || tfdd.best_length > max_penalty) {
4737 if (v->current_order.IsType(OT_GOTO_DEPOT)) {
4738 /* If we were already heading for a depot but it has
4739 * suddenly moved farther away, we continue our normal
4740 * schedule? */
4741 v->current_order.MakeDummy();
4742 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4744 return;
4747 DepotID depot = GetDepotIndex(tfdd.tile);
4749 if (v->current_order.IsType(OT_GOTO_DEPOT) &&
4750 v->current_order.GetDestination() != depot &&
4751 !Chance16(3, 16)) {
4752 return;
4755 SetBit(v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
4756 v->current_order.MakeGoToDepot(depot, ODTFB_SERVICE);
4757 v->dest_tile = tfdd.tile;
4758 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4761 /** Update day counters of the train vehicle. */
4762 void Train::OnNewDay()
4764 AgeVehicle(this);
4766 if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
4768 if (this->IsFrontEngine()) {
4769 CheckVehicleBreakdown(this);
4771 CheckIfTrainNeedsService(this);
4773 CheckOrders(this);
4775 /* update destination */
4776 if (this->current_order.IsType(OT_GOTO_STATION)) {
4777 TileIndex tile = Station::Get(this->current_order.GetDestination())->train_station.tile;
4778 if (tile != INVALID_TILE) this->dest_tile = tile;
4781 if (this->running_ticks != 0) {
4782 /* running costs */
4783 CommandCost cost(EXPENSES_TRAIN_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR * DAY_TICKS));
4785 this->profit_this_year -= cost.GetCost();
4786 this->running_ticks = 0;
4788 SubtractMoneyFromCompanyFract(this->owner, cost);
4790 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
4791 SetWindowClassesDirty(WC_TRAINS_LIST);
4797 * Get the tracks of the train vehicle.
4798 * @return Current tracks of the vehicle.
4800 Trackdir Train::GetVehicleTrackdir() const
4802 if (this->vehstatus & VS_CRASHED)
4803 return INVALID_TRACKDIR;
4805 if (this->track == TRACK_BIT_DEPOT) {
4806 /* We'll assume the train is facing outwards */
4807 return DiagDirToDiagTrackdir(GetRailDepotDirection(this->tile)); // Train in depot
4810 if (this->track == TRACK_BIT_WORMHOLE) {
4811 /* train in tunnel or on bridge, so just use his direction and assume a diagonal track */
4812 return DiagDirToDiagTrackdir(DirToDiagDir(this->direction));
4815 return TrackDirectionToTrackdir(FindFirstTrack(this->track), this->direction);
4819 /* Get the pixel-width of the image that is used for the train vehicle
4820 * @return: the image width number in pixel
4822 int GetDisplayImageWidth(Train *t, Point *offset)
4824 int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
4825 int vehicle_pitch = 0;
4827 const Engine *e = Engine::Get(t->engine_type);
4828 if (e->grf_prop.grffile != NULL && is_custom_sprite(e->u.rail.image_index)) {
4829 reference_width = e->grf_prop.grffile->traininfo_vehicle_width;
4830 vehicle_pitch = e->grf_prop.grffile->traininfo_vehicle_pitch;
4833 if (offset != NULL) {
4834 offset->x = reference_width / 2;
4835 offset->y = vehicle_pitch;
4837 //printf(" refwid:%d gdiw.cachedvehlen(%d):%d ", reference_width, this->engine_type, this->gcache.cached_veh_length);
4838 return t->gcache.cached_veh_length * reference_width / VEHICLE_LENGTH;
4841 Train* CmdBuildVirtualRailWagon(const Engine *e)
4843 const RailVehicleInfo *rvi = &e->u.rail;
4845 Train *v = new Train();
4847 v->x_pos = 0;
4848 v->y_pos = 0;
4850 v->spritenum = rvi->image_index;
4852 v->engine_type = e->index;
4853 v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
4855 v->direction = DIR_W;
4856 v->tile = 0;//INVALID_TILE;
4858 v->owner = _current_company;
4859 v->track = TRACK_BIT_DEPOT;
4860 v->vehstatus = VS_HIDDEN | VS_DEFPAL;
4862 v->SetWagon();
4863 v->SetFreeWagon();
4865 v->cargo_type = e->GetDefaultCargoType();
4866 v->cargo_cap = rvi->capacity;
4868 v->railtype = rvi->railtype;
4870 v->build_year = _cur_year;
4871 v->sprite_seq.Set(SPR_IMG_QUERY);
4872 v->random_bits = VehicleRandomBits();
4874 v->group_id = DEFAULT_GROUP;
4876 AddArticulatedParts(v);
4878 // Make sure we set EVERYTHING to virtual, even articulated parts.
4879 for (Train* train_part = v; train_part != NULL; train_part = train_part->Next()) {
4880 train_part->SetVirtual();
4883 _new_vehicle_id = v->index;
4885 v->UpdateViewport(true, false);
4887 v->First()->ConsistChanged(CCF_ARRANGE);
4889 CheckConsistencyOfArticulatedVehicle(v);
4891 return v;
4894 Train* CmdBuildVirtualRailVehicle(EngineID eid, bool lax_engine_check, StringID &error)
4896 if (lax_engine_check) {
4897 const Engine *e = Engine::GetIfValid(eid);
4898 if (e == NULL || e->type != VEH_TRAIN) {
4899 error = STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE + VEH_TRAIN;
4900 return NULL;
4903 else {
4904 if (!IsEngineBuildable(eid, VEH_TRAIN, _current_company)) {
4905 error = STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE + VEH_TRAIN;
4906 return NULL;
4910 const Engine* e = Engine::Get(eid);
4911 const RailVehicleInfo *rvi = &e->u.rail;
4913 int num_vehicles = (e->u.rail.railveh_type == RAILVEH_MULTIHEAD ? 2 : 1) + CountArticulatedParts(eid, false);
4914 if (!Train::CanAllocateItem(num_vehicles)) {
4915 error = STR_ERROR_TOO_MANY_VEHICLES_IN_GAME;
4916 return nullptr;
4919 if (rvi->railveh_type == RAILVEH_WAGON)
4920 return CmdBuildVirtualRailWagon(e);
4922 Train *v = new Train();
4924 v->x_pos = 0;
4925 v->y_pos = 0;
4927 v->direction = DIR_W;
4928 v->tile = 0;//INVALID_TILE;
4929 v->owner = _current_company;
4930 v->track = TRACK_BIT_DEPOT;
4931 v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
4932 v->spritenum = rvi->image_index;
4933 v->cargo_type = e->GetDefaultCargoType();
4934 v->cargo_cap = rvi->capacity;
4935 v->last_station_visited = INVALID_STATION;
4937 v->engine_type = e->index;
4938 v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
4940 v->reliability = e->reliability;
4941 v->reliability_spd_dec = e->reliability_spd_dec;
4942 v->max_age = e->GetLifeLengthInDays();
4944 v->railtype = rvi->railtype;
4945 _new_vehicle_id = v->index;
4947 v->build_year = _cur_year;
4948 v->sprite_seq.Set(SPR_IMG_QUERY);
4949 v->random_bits = VehicleRandomBits();
4951 v->group_id = DEFAULT_GROUP;
4953 v->SetFrontEngine();
4954 v->SetEngine();
4956 if (rvi->railveh_type == RAILVEH_MULTIHEAD) {
4957 AddRearEngineToMultiheadedTrain(v);
4958 } else {
4959 AddArticulatedParts(v);
4962 // Make sure we set EVERYTHING to virtual, even articulated parts.
4963 for (Train* train_part = v; train_part != NULL; train_part = train_part->Next()) {
4964 train_part->SetVirtual();
4967 v->UpdateViewport(true, false);
4969 v->ConsistChanged(CCF_ARRANGE);
4971 CheckConsistencyOfArticulatedVehicle(v);
4973 return v;
4977 * Build a virtual train vehicle.
4978 * @param tile unused
4979 * @param flags type of operation
4980 * @param p1 the engine ID to build
4981 * @param p2 unused
4982 * @param text unused
4983 * @return the cost of this operation or an error
4985 CommandCost CmdBuildVirtualRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
4987 EngineID eid = p1;
4989 if (!IsEngineBuildable(eid, VEH_TRAIN, _current_company)) {
4990 return_cmd_error(STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE + VEH_TRAIN);
4993 bool should_execute = (flags & DC_EXEC) != 0;
4995 if (should_execute) {
4996 StringID err = INVALID_STRING_ID;
4997 Train* train = CmdBuildVirtualRailVehicle(eid, false, err);
4999 if (train == nullptr) {
5000 return_cmd_error(err);
5004 return CommandCost();
5008 * Replace a vehicle based on a template replacement order.
5009 * @param tile unused
5010 * @param flags type of operation
5011 * @param p1 the ID of the vehicle to replace.
5012 * @param p2 whether the vehicle should stay in the depot.
5013 * @param text unused
5014 * @return the cost of this operation or an error
5016 CommandCost CmdTemplateReplaceVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
5018 VehicleID vehicle_id = p1;
5020 Vehicle* vehicle = Vehicle::GetIfValid(vehicle_id);
5022 if (vehicle == nullptr || vehicle->type != VEH_TRAIN)
5023 return CMD_ERROR;
5025 bool should_execute = (flags & DC_EXEC) != 0;
5027 if (!should_execute)
5028 return CommandCost();
5030 Train* incoming = Train::From(vehicle);
5031 bool stayInDepot = p2 != 0;
5033 Train *new_chain = 0,
5034 *remainder_chain = 0,
5035 *tmp_chain = 0;
5036 TemplateVehicle *tv = GetTemplateVehicleByGroupID(incoming->group_id);
5037 if (tv == nullptr) {
5038 return CMD_ERROR;
5041 CommandCost buy(EXPENSES_NEW_VEHICLES);
5042 CommandCost move_cost(EXPENSES_NEW_VEHICLES);
5043 CommandCost tmp_result(EXPENSES_NEW_VEHICLES);
5046 /* first some tests on necessity and sanity */
5047 if (tv == nullptr)
5048 return buy;
5050 EngineID eid = tv->engine_type;
5052 _new_vehicle_id = p1;
5054 bool need_replacement = !TrainMatchesTemplate(incoming, tv);
5055 bool need_refit = !TrainMatchesTemplateRefit(incoming, tv);
5056 bool use_refit = tv->refit_as_template;
5058 CargoID store_refit_ct = CT_INVALID;
5059 short store_refit_csubt = 0;
5060 // if a train shall keep its old refit, store the refit setting of its first vehicle
5061 if (!use_refit) {
5062 for (Train *getc = incoming; getc != NULL; getc = getc->GetNextUnit()) {
5063 if (getc->cargo_type != CT_INVALID) {
5064 store_refit_ct = getc->cargo_type;
5065 break;
5070 // TODO: set result status to success/no success before returning
5071 if (!need_replacement) {
5072 if (!need_refit || !use_refit) {
5073 /* before returning, release incoming train first if 2nd param says so */
5074 if (!stayInDepot) incoming->vehstatus &= ~VS_STOPPED;
5075 return buy;
5078 else {
5079 CommandCost buyCost = TestBuyAllTemplateVehiclesInChain(tv, tile);
5080 if (!buyCost.Succeeded() || !CheckCompanyHasMoney(buyCost)) {
5081 if (!stayInDepot) incoming->vehstatus &= ~VS_STOPPED;
5083 if (!buyCost.Succeeded() && buyCost.GetErrorMessage() != INVALID_STRING_ID) {
5084 return buyCost;
5085 } else {
5086 return_cmd_error(STR_ERROR_NOT_ENOUGH_CASH_REQUIRES_CURRENCY);
5091 /* define replacement behavior */
5092 bool reuseDepot = tv->IsSetReuseDepotVehicles();
5093 bool keepRemainders = tv->IsSetKeepRemainingVehicles();
5095 if (need_replacement) {
5096 /// step 1: generate primary for newchain and generate remainder_chain
5097 // 1. primary of incoming might already fit the template
5098 // leave incoming's primary as is and move the rest to a free chain = remainder_chain
5099 // 2. needed primary might be one of incoming's member vehicles
5100 // 3. primary might be available as orphan vehicle in the depot
5101 // 4. we need to buy a new engine for the primary
5102 // all options other than 1. need to make sure to copy incoming's primary's status
5103 if (eid == incoming->engine_type) { // 1
5104 new_chain = incoming;
5105 remainder_chain = incoming->GetNextUnit();
5106 if (remainder_chain)
5107 move_cost.AddCost(CmdMoveRailVehicle(tile, flags, remainder_chain->index | (1 << 20), INVALID_VEHICLE, 0));
5109 else if ((tmp_chain = ChainContainsEngine(eid, incoming)) && tmp_chain != NULL) { // 2
5110 // new_chain is the needed engine, move it to an empty spot in the depot
5111 new_chain = tmp_chain;
5112 move_cost.AddCost(DoCommand(tile, new_chain->index, INVALID_VEHICLE, flags, CMD_MOVE_RAIL_VEHICLE));
5113 remainder_chain = incoming;
5115 else if (reuseDepot && (tmp_chain = DepotContainsEngine(tile, eid, incoming)) && tmp_chain != NULL) { // 3
5116 new_chain = tmp_chain;
5117 move_cost.AddCost(DoCommand(tile, new_chain->index, INVALID_VEHICLE, flags, CMD_MOVE_RAIL_VEHICLE));
5118 remainder_chain = incoming;
5120 else { // 4
5121 tmp_result = DoCommand(tile, eid, 0, flags, CMD_BUILD_VEHICLE);
5122 /* break up in case buying the vehicle didn't succeed */
5123 if (!tmp_result.Succeeded())
5124 return tmp_result;
5125 buy.AddCost(tmp_result);
5126 new_chain = Train::Get(_new_vehicle_id);
5127 /* make sure the newly built engine is not attached to any free wagons inside the depot */
5128 move_cost.AddCost(DoCommand(tile, new_chain->index, INVALID_VEHICLE, flags, CMD_MOVE_RAIL_VEHICLE));
5129 /* prepare the remainder chain */
5130 remainder_chain = incoming;
5132 // If we bought a new engine or reused one from the depot, copy some parameters from the incoming primary engine
5133 if (incoming != new_chain && flags == DC_EXEC) {
5134 CopyHeadSpecificThings(incoming, new_chain, flags);
5135 NeutralizeStatus(incoming);
5138 // additionally, if we don't want to use the template refit, refit as incoming
5139 // the template refit will be set further down, if we use it at all
5140 if (!use_refit) {
5141 uint32 cb = GetCmdRefitVeh(new_chain);
5142 DoCommand(new_chain->tile, new_chain->index, store_refit_ct | store_refit_csubt << 8 | 1 << 16 | (1 << 5), flags, cb);
5147 /// step 2: fill up newchain according to the template
5148 // foreach member of template (after primary):
5149 // 1. needed engine might be within remainder_chain already
5150 // 2. needed engine might be orphaned within the depot (copy status)
5151 // 3. we need to buy (again) (copy status)
5152 TemplateVehicle *cur_tmpl = tv->GetNextUnit();
5153 Train *last_veh = new_chain;
5154 while (cur_tmpl) {
5155 // 1. engine contained in remainder chain
5156 if ((tmp_chain = ChainContainsEngine(cur_tmpl->engine_type, remainder_chain)) && tmp_chain != NULL) {
5157 // advance remainder_chain (if necessary) to not lose track of it
5158 if (tmp_chain == remainder_chain)
5159 remainder_chain = remainder_chain->GetNextUnit();
5160 move_cost.AddCost(CmdMoveRailVehicle(tile, flags, tmp_chain->index, last_veh->index, 0));
5162 // 2. engine contained somewhere else in the depot
5163 else if (reuseDepot && (tmp_chain = DepotContainsEngine(tile, cur_tmpl->engine_type, new_chain)) && tmp_chain != NULL) {
5164 move_cost.AddCost(CmdMoveRailVehicle(tile, flags, tmp_chain->index, last_veh->index, 0));
5166 // 3. must buy new engine
5167 else {
5168 tmp_result = DoCommand(tile, cur_tmpl->engine_type, 0, flags, CMD_BUILD_VEHICLE);
5169 if (!tmp_result.Succeeded()) {
5170 return tmp_result;
5172 buy.AddCost(tmp_result);
5173 tmp_chain = Train::Get(_new_vehicle_id);
5174 move_cost.AddCost(CmdMoveRailVehicle(tile, flags, tmp_chain->index, last_veh->index, 0));
5176 // TODO: is this enough ? might it be that we bought a new wagon here and it now has std refit ?
5177 if (need_refit && flags == DC_EXEC) {
5178 if (use_refit) {
5179 uint32 cb = GetCmdRefitVeh(tmp_chain);
5180 DoCommand(tmp_chain->tile, tmp_chain->index, cur_tmpl->cargo_type | cur_tmpl->cargo_subtype << 8 | 1 << 16 | (1 << 5), flags, cb);
5181 // old
5182 // CopyWagonStatus(cur_tmpl, tmp_chain);
5183 } else {
5184 uint32 cb = GetCmdRefitVeh(tmp_chain);
5185 DoCommand(tmp_chain->tile, tmp_chain->index, store_refit_ct | store_refit_csubt << 8 | 1 << 16 | (1 << 5), flags, cb);
5188 cur_tmpl = cur_tmpl->GetNextUnit();
5189 last_veh = tmp_chain;
5192 /* no replacement done */
5193 else {
5194 new_chain = incoming;
5196 /// step 3: reorder and neutralize the remaining vehicles from incoming
5197 // wagons remaining from remainder_chain should be filled up in as few freewagonchains as possible
5198 // each locos might be left as singular in the depot
5199 // neutralize each remaining engine's status
5201 // refit, only if the template option is set so
5202 if (use_refit && (need_refit || need_replacement)) {
5203 CmdRefitTrainFromTemplate(new_chain, tv, flags);
5206 if (new_chain && remainder_chain)
5207 for (Train *ct = remainder_chain; ct; ct = ct->GetNextUnit())
5208 TransferCargoForTrain(ct, new_chain);
5210 // point incoming to the newly created train so that starting/stopping from the calling function can be done
5211 incoming = new_chain;
5212 if (!stayInDepot && flags == DC_EXEC)
5213 new_chain->vehstatus &= ~VS_STOPPED;
5215 if (remainder_chain && keepRemainders && flags == DC_EXEC)
5216 BreakUpRemainders(remainder_chain);
5217 else if (remainder_chain) {
5218 buy.AddCost(DoCommand(tile, remainder_chain->index | (1 << 20), 0, flags, CMD_SELL_VEHICLE));
5221 /* Redraw main gui for changed statistics */
5222 SetWindowClassesDirty(WC_TEMPLATEGUI_MAIN);
5224 _new_vehicle_id = new_chain->index;
5226 return buy;