Maintain a circular buffer of recent commands, add to crashlog.
[openttd-joker.git] / src / train_cmd.cpp
blob8304611deff933ca3bcec5a7ee01bfba0235629a
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 Rect rectf, rectr;
618 seqf.GetBounds(&rectf);
619 seqr.GetBounds(&rectr);
621 preferred_x = SoftClamp(preferred_x,
622 left - UnScaleGUI(rectf.left) + ScaleGUITrad(14),
623 right - UnScaleGUI(rectr.right) - ScaleGUITrad(15));
625 seqf.Draw(preferred_x - ScaleGUITrad(14), yf, pal, pal == PALETTE_CRASH);
626 seqr.Draw(preferred_x + ScaleGUITrad(15), yr, pal, pal == PALETTE_CRASH);
627 } else {
628 VehicleSpriteSeq seq;
629 GetRailIcon(engine, false, y, image_type, &seq);
631 Rect rect;
632 seq.GetBounds(&rect);
633 preferred_x = Clamp(preferred_x,
634 left - UnScaleGUI(rect.left),
635 right - UnScaleGUI(rect.right));
637 seq.Draw(preferred_x, y, pal, pal == PALETTE_CRASH);
642 * Get the size of the sprite of a train sprite heading west, or both heads (used for lists).
643 * @param engine The engine to get the sprite from.
644 * @param[out] width The width of the sprite.
645 * @param[out] height The height of the sprite.
646 * @param[out] xoffs Number of pixels to shift the sprite to the right.
647 * @param[out] yoffs Number of pixels to shift the sprite downwards.
648 * @param image_type Context the sprite is used in.
650 void GetTrainSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
652 int y = 0;
654 VehicleSpriteSeq seq;
655 GetRailIcon(engine, false, y, image_type, &seq);
657 Rect rect;
658 seq.GetBounds(&rect);
660 width = UnScaleGUI(rect.right - rect.left + 1);
661 height = UnScaleGUI(rect.bottom - rect.top + 1);
662 xoffs = UnScaleGUI(rect.left);
663 yoffs = UnScaleGUI(rect.top);
665 if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
666 GetRailIcon(engine, true, y, image_type, &seq);
667 seq.GetBounds(&rect);
669 /* Calculate values relative to an imaginary center between the two sprites. */
670 width = ScaleGUITrad(TRAININFO_DEFAULT_VEHICLE_WIDTH) + UnScaleGUI(rect.right) - xoffs;
671 height = max<uint>(height, UnScaleGUI(rect.bottom - rect.top + 1));
672 xoffs = xoffs - ScaleGUITrad(TRAININFO_DEFAULT_VEHICLE_WIDTH) / 2;
673 yoffs = min(yoffs, UnScaleGUI(rect.top));
678 * Build a railroad wagon.
679 * @param tile tile of the depot where rail-vehicle is built.
680 * @param flags type of operation.
681 * @param e the engine to build.
682 * @param ret[out] the vehicle that has been built.
683 * @return the cost of this operation or an error.
685 static CommandCost CmdBuildRailWagon(TileIndex tile, DoCommandFlag flags, const Engine *e, Vehicle **ret)
687 const RailVehicleInfo *rvi = &e->u.rail;
689 /* Check that the wagon can drive on the track in question */
690 if (!IsCompatibleRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
692 if (flags & DC_EXEC) {
693 Train *v = new Train();
694 *ret = v;
695 v->spritenum = rvi->image_index;
697 v->engine_type = e->index;
698 v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
700 DiagDirection dir = GetRailDepotDirection(tile);
702 v->direction = DiagDirToDir(dir);
703 v->tile = tile;
705 int x = TileX(tile) * TILE_SIZE | _vehicle_initial_x_fract[dir];
706 int y = TileY(tile) * TILE_SIZE | _vehicle_initial_y_fract[dir];
708 v->x_pos = x;
709 v->y_pos = y;
710 v->z_pos = GetSlopePixelZ(x, y);
711 v->owner = _current_company;
712 v->track = TRACK_BIT_DEPOT;
713 v->vehstatus = VS_HIDDEN | VS_DEFPAL;
714 v->reverse_distance = 0;
716 v->SetWagon();
718 v->SetFreeWagon();
719 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
721 v->cargo_type = e->GetDefaultCargoType();
722 v->cargo_cap = rvi->capacity;
723 v->refit_cap = 0;
725 v->railtype = rvi->railtype;
727 v->date_of_last_service = _date;
728 v->build_year = _cur_year;
729 v->sprite_seq.Set(SPR_IMG_QUERY);
730 v->random_bits = VehicleRandomBits();
732 v->group_id = DEFAULT_GROUP;
734 AddArticulatedParts(v);
736 _new_vehicle_id = v->index;
738 v->UpdatePosition();
739 v->First()->ConsistChanged(CCF_ARRANGE);
740 UpdateTrainGroupID(v->First());
742 CheckConsistencyOfArticulatedVehicle(v);
744 /* Try to connect the vehicle to one of free chains of wagons. */
745 Train *w;
746 FOR_ALL_TRAINS(w) {
747 if (w->tile == tile && ///< Same depot
748 w->IsFreeWagon() && ///< A free wagon chain
749 w->engine_type == e->index && ///< Same type
750 w->First() != v && ///< Don't connect to ourself
751 !(w->vehstatus & VS_CRASHED)) { ///< Not crashed/flooded
752 DoCommand(0, v->index | 1 << 20, w->Last()->index, DC_EXEC, CMD_MOVE_RAIL_VEHICLE);
753 break;
758 return CommandCost();
761 /** Move all free vehicles in the depot to the train */
762 static void NormalizeTrainVehInDepot(const Train *u)
764 const Train *v;
765 FOR_ALL_TRAINS(v) {
766 if (v->IsFreeWagon() && v->tile == u->tile &&
767 v->track == TRACK_BIT_DEPOT) {
768 if (DoCommand(0, v->index | 1 << 20, u->index, DC_EXEC,
769 CMD_MOVE_RAIL_VEHICLE).Failed())
770 break;
775 static void AddRearEngineToMultiheadedTrain(Train *v)
777 Train *u = new Train();
778 v->value >>= 1;
779 u->value = v->value;
780 u->direction = v->direction;
781 u->owner = v->owner;
782 u->tile = v->tile;
783 u->x_pos = v->x_pos;
784 u->y_pos = v->y_pos;
785 u->z_pos = v->z_pos;
786 u->track = TRACK_BIT_DEPOT;
787 u->vehstatus = v->vehstatus & ~VS_STOPPED;
788 u->spritenum = v->spritenum + 1;
789 u->cargo_type = v->cargo_type;
790 u->cargo_subtype = v->cargo_subtype;
791 u->cargo_cap = v->cargo_cap;
792 u->refit_cap = v->refit_cap;
793 u->railtype = v->railtype;
794 u->engine_type = v->engine_type;
795 u->date_of_last_service = v->date_of_last_service;
796 u->build_year = v->build_year;
797 u->sprite_seq.Set(SPR_IMG_QUERY);
798 u->random_bits = VehicleRandomBits();
799 v->SetMultiheaded();
800 u->SetMultiheaded();
801 v->SetNext(u);
802 u->UpdatePosition();
804 /* Now we need to link the front and rear engines together */
805 v->other_multiheaded_part = u;
806 u->other_multiheaded_part = v;
810 * Build a railroad vehicle.
811 * @param tile tile of the depot where rail-vehicle is built.
812 * @param flags type of operation.
813 * @param e the engine to build.
814 * @param data bit 0 prevents any free cars from being added to the train.
815 * @param ret[out] the vehicle that has been built.
816 * @return the cost of this operation or an error.
818 CommandCost CmdBuildRailVehicle(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **ret)
820 const RailVehicleInfo *rvi = &e->u.rail;
822 if (rvi->railveh_type == RAILVEH_WAGON) return CmdBuildRailWagon(tile, flags, e, ret);
824 /* Check if depot and new engine uses the same kind of tracks *
825 * We need to see if the engine got power on the tile to avoid electric engines in non-electric depots */
826 if (!HasPowerOnRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
828 if (flags & DC_EXEC) {
829 DiagDirection dir = GetRailDepotDirection(tile);
830 int x = TileX(tile) * TILE_SIZE + _vehicle_initial_x_fract[dir];
831 int y = TileY(tile) * TILE_SIZE + _vehicle_initial_y_fract[dir];
833 Train *v = new Train();
834 *ret = v;
835 v->direction = DiagDirToDir(dir);
836 v->tile = tile;
837 v->owner = _current_company;
838 v->x_pos = x;
839 v->y_pos = y;
840 v->z_pos = GetSlopePixelZ(x, y);
841 v->track = TRACK_BIT_DEPOT;
842 v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
843 v->spritenum = rvi->image_index;
844 v->cargo_type = e->GetDefaultCargoType();
845 v->cargo_cap = rvi->capacity;
846 v->refit_cap = 0;
847 v->last_station_visited = INVALID_STATION;
848 v->last_loading_station = INVALID_STATION;
849 v->reverse_distance = 0;
851 v->engine_type = e->index;
852 v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
854 v->reliability = e->reliability;
855 v->reliability_spd_dec = e->reliability_spd_dec;
856 v->max_age = e->GetLifeLengthInDays();
858 v->railtype = rvi->railtype;
859 _new_vehicle_id = v->index;
861 v->SetServiceInterval(Company::Get(_current_company)->settings.vehicle.servint_trains);
862 v->date_of_last_service = _date;
863 v->build_year = _cur_year;
864 v->sprite_seq.Set(SPR_IMG_QUERY);
865 v->random_bits = VehicleRandomBits();
867 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
868 v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
870 v->group_id = DEFAULT_GROUP;
872 v->SetFrontEngine();
873 v->SetEngine();
875 v->UpdatePosition();
877 if (rvi->railveh_type == RAILVEH_MULTIHEAD) {
878 AddRearEngineToMultiheadedTrain(v);
879 } else {
880 AddArticulatedParts(v);
883 v->ConsistChanged(CCF_ARRANGE);
884 UpdateTrainGroupID(v);
886 if (!HasBit(data, 0) && !(flags & DC_AUTOREPLACE)) { // check if the cars should be added to the new vehicle
887 NormalizeTrainVehInDepot(v);
890 CheckConsistencyOfArticulatedVehicle(v);
893 return CommandCost();
896 static Train *FindGoodVehiclePos(const Train *src)
898 EngineID eng = src->engine_type;
899 TileIndex tile = src->tile;
901 Train *dst;
902 FOR_ALL_TRAINS(dst) {
903 if (dst->IsFreeWagon() && dst->tile == tile && !(dst->vehstatus & VS_CRASHED)) {
904 /* check so all vehicles in the line have the same engine. */
905 Train *t = dst;
906 while (t->engine_type == eng) {
907 t = t->Next();
908 if (t == NULL) return dst;
913 return NULL;
916 /** Helper type for lists/vectors of trains */
917 typedef SmallVector<Train *, 16> TrainList;
920 * Make a backup of a train into a train list.
921 * @param list to make the backup in
922 * @param t the train to make the backup of
924 static void MakeTrainBackup(TrainList &list, Train *t)
926 for (; t != NULL; t = t->Next()) *list.Append() = t;
930 * Restore the train from the backup list.
931 * @param list the train to restore.
933 static void RestoreTrainBackup(TrainList &list)
935 /* No train, nothing to do. */
936 if (list.Length() == 0) return;
938 Train *prev = NULL;
939 /* Iterate over the list and rebuild it. */
940 for (Train **iter = list.Begin(); iter != list.End(); iter++) {
941 Train *t = *iter;
942 if (prev != NULL) {
943 prev->SetNext(t);
944 } else if (t->Previous() != NULL) {
945 /* Make sure the head of the train is always the first in the chain. */
946 t->Previous()->SetNext(NULL);
948 prev = t;
953 * Remove the given wagon from its consist.
954 * @param part the part of the train to remove.
955 * @param chain whether to remove the whole chain.
957 static void RemoveFromConsist(Train *part, bool chain = false)
959 Train *tail = chain ? part->Last() : part->GetLastEnginePart();
961 /* Unlink at the front, but make it point to the next
962 * vehicle after the to be remove part. */
963 if (part->Previous() != NULL) part->Previous()->SetNext(tail->Next());
965 /* Unlink at the back */
966 tail->SetNext(NULL);
970 * Inserts a chain into the train at dst.
971 * @param dst the place where to append after.
972 * @param chain the chain to actually add.
974 static void InsertInConsist(Train *dst, Train *chain)
976 /* We do not want to add something in the middle of an articulated part. */
977 assert(dst->Next() == NULL || !dst->Next()->IsArticulatedPart());
979 chain->Last()->SetNext(dst->Next());
980 dst->SetNext(chain);
984 * Normalise the dual heads in the train, i.e. if one is
985 * missing move that one to this train.
986 * @param t the train to normalise.
988 static void NormaliseDualHeads(Train *t)
990 for (; t != NULL; t = t->GetNextVehicle()) {
991 if (!t->IsMultiheaded() || !t->IsEngine()) continue;
993 /* Make sure that there are no free cars before next engine */
994 Train *u;
995 for (u = t; u->Next() != NULL && !u->Next()->IsEngine(); u = u->Next()) {}
997 if (u == t->other_multiheaded_part) continue;
999 /* Remove the part from the 'wrong' train */
1000 RemoveFromConsist(t->other_multiheaded_part);
1001 /* And add it to the 'right' train */
1002 InsertInConsist(u, t->other_multiheaded_part);
1007 * Normalise the sub types of the parts in this chain.
1008 * @param chain the chain to normalise.
1010 static void NormaliseSubtypes(Train *chain)
1012 /* Nothing to do */
1013 if (chain == NULL) return;
1015 /* We must be the first in the chain. */
1016 assert(chain->Previous() == NULL);
1018 /* Set the appropriate bits for the first in the chain. */
1019 if (chain->IsWagon()) {
1020 chain->SetFreeWagon();
1021 } else {
1022 assert(chain->IsEngine());
1023 chain->SetFrontEngine();
1026 /* Now clear the bits for the rest of the chain */
1027 for (Train *t = chain->Next(); t != NULL; t = t->Next()) {
1028 t->ClearFreeWagon();
1029 t->ClearFrontEngine();
1034 * Check/validate whether we may actually build a new train.
1035 * @note All vehicles are/were 'heads' of their chains.
1036 * @param original_dst The original destination chain.
1037 * @param dst The destination chain after constructing the train.
1038 * @param original_dst The original source chain.
1039 * @param dst The source chain after constructing the train.
1040 * @return possible error of this command.
1042 static CommandCost CheckNewTrain(Train *original_dst, Train *dst, Train *original_src, Train *src)
1044 /* Just add 'new' engines and subtract the original ones.
1045 * If that's less than or equal to 0 we can be sure we did
1046 * not add any engines (read: trains) along the way. */
1047 if ((src != NULL && src->IsEngine() ? 1 : 0) +
1048 (dst != NULL && dst->IsEngine() ? 1 : 0) -
1049 (original_src != NULL && original_src->IsEngine() ? 1 : 0) -
1050 (original_dst != NULL && original_dst->IsEngine() ? 1 : 0) <= 0) {
1051 return CommandCost();
1054 /* Get a free unit number and check whether it's within the bounds.
1055 * There will always be a maximum of one new train. */
1056 if (GetFreeUnitNumber(VEH_TRAIN) <= _settings_game.vehicle.max_trains) return CommandCost();
1058 return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
1062 * Check whether the train parts can be attached.
1063 * @param t the train to check
1064 * @return possible error of this command.
1066 static CommandCost CheckTrainAttachment(Train *t)
1068 /* No multi-part train, no need to check. */
1069 if (t == NULL || t->Next() == NULL || !t->IsEngine()) return CommandCost();
1071 /* The maximum length for a train. For each part we decrease this by one
1072 * and if the result is negative the train is simply too long. */
1073 int allowed_len = _settings_game.vehicle.max_train_length * TILE_SIZE - t->gcache.cached_veh_length;
1075 Train *head = t;
1076 Train *prev = t;
1078 /* Break the prev -> t link so it always holds within the loop. */
1079 t = t->Next();
1080 prev->SetNext(NULL);
1082 /* Make sure the cache is cleared. */
1083 head->InvalidateNewGRFCache();
1085 while (t != NULL) {
1086 allowed_len -= t->gcache.cached_veh_length;
1088 Train *next = t->Next();
1090 /* Unlink the to-be-added piece; it is already unlinked from the previous
1091 * part due to the fact that the prev -> t link is broken. */
1092 t->SetNext(NULL);
1094 /* Don't check callback for articulated or rear dual headed parts */
1095 if (!t->IsArticulatedPart() && !t->IsRearDualheaded()) {
1096 /* Back up and clear the first_engine data to avoid using wagon override group */
1097 EngineID first_engine = t->gcache.first_engine;
1098 t->gcache.first_engine = INVALID_ENGINE;
1100 /* We don't want the cache to interfere. head's cache is cleared before
1101 * the loop and after each callback does not need to be cleared here. */
1102 t->InvalidateNewGRFCache();
1104 uint16 callback = GetVehicleCallbackParent(CBID_TRAIN_ALLOW_WAGON_ATTACH, 0, 0, head->engine_type, t, head);
1106 /* Restore original first_engine data */
1107 t->gcache.first_engine = first_engine;
1109 /* We do not want to remember any cached variables from the test run */
1110 t->InvalidateNewGRFCache();
1111 head->InvalidateNewGRFCache();
1113 if (callback != CALLBACK_FAILED) {
1114 /* A failing callback means everything is okay */
1115 StringID error = STR_NULL;
1117 if (head->GetGRF()->grf_version < 8) {
1118 if (callback == 0xFD) error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1119 if (callback < 0xFD) error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
1120 if (callback >= 0x100) ErrorUnknownCallbackResult(head->GetGRFID(), CBID_TRAIN_ALLOW_WAGON_ATTACH, callback);
1121 } else {
1122 if (callback < 0x400) {
1123 error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
1124 } else {
1125 switch (callback) {
1126 case 0x400: // allow if railtypes match (always the case for OpenTTD)
1127 case 0x401: // allow
1128 break;
1130 default: // unknown reason -> disallow
1131 case 0x402: // disallow attaching
1132 error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1133 break;
1138 if (error != STR_NULL) return_cmd_error(error);
1142 /* And link it to the new part. */
1143 prev->SetNext(t);
1144 prev = t;
1145 t = next;
1148 if (allowed_len < 0) return_cmd_error(STR_ERROR_TRAIN_TOO_LONG);
1149 return CommandCost();
1153 * Validate whether we are going to create valid trains.
1154 * @note All vehicles are/were 'heads' of their chains.
1155 * @param original_dst The original destination chain.
1156 * @param dst The destination chain after constructing the train.
1157 * @param original_dst The original source chain.
1158 * @param dst The source chain after constructing the train.
1159 * @param check_limit Whether to check the vehicle limit.
1160 * @return possible error of this command.
1162 static CommandCost ValidateTrains(Train *original_dst, Train *dst, Train *original_src, Train *src, bool check_limit)
1164 /* Check whether we may actually construct the trains. */
1165 CommandCost ret = CheckTrainAttachment(src);
1166 if (ret.Failed()) return ret;
1167 ret = CheckTrainAttachment(dst);
1168 if (ret.Failed()) return ret;
1170 /* Check whether we need to build a new train. */
1171 return check_limit ? CheckNewTrain(original_dst, dst, original_src, src) : CommandCost();
1175 * Arrange the trains in the wanted way.
1176 * @param dst_head The destination chain of the to be moved vehicle.
1177 * @param dst The destination for the to be moved vehicle.
1178 * @param src_head The source chain of the to be moved vehicle.
1179 * @param src The to be moved vehicle.
1180 * @param move_chain Whether to move all vehicles after src or not.
1182 static void ArrangeTrains(Train **dst_head, Train *dst, Train **src_head, Train *src, bool move_chain)
1184 /* First determine the front of the two resulting trains */
1185 if (*src_head == *dst_head) {
1186 /* If we aren't moving part(s) to a new train, we are just moving the
1187 * front back and there is not destination head. */
1188 *dst_head = NULL;
1189 } else if (*dst_head == NULL) {
1190 /* If we are moving to a new train the head of the move train would become
1191 * the head of the new vehicle. */
1192 *dst_head = src;
1195 if (src == *src_head) {
1196 /* If we are moving the front of a train then we are, in effect, creating
1197 * a new head for the train. Point to that. Unless we are moving the whole
1198 * train in which case there is not 'source' train anymore.
1199 * In case we are a multiheaded part we want the complete thing to come
1200 * with us, so src->GetNextUnit(), however... when we are e.g. a wagon
1201 * that is followed by a rear multihead we do not want to include that. */
1202 *src_head = move_chain ? NULL :
1203 (src->IsMultiheaded() ? src->GetNextUnit() : src->GetNextVehicle());
1206 /* Now it's just simply removing the part that we are going to move from the
1207 * source train and *if* the destination is a not a new train add the chain
1208 * at the destination location. */
1209 RemoveFromConsist(src, move_chain);
1210 if (*dst_head != src) InsertInConsist(dst, src);
1212 /* Now normalise the dual heads, that is move the dual heads around in such
1213 * a way that the head and rear of a dual head are in the same train */
1214 NormaliseDualHeads(*src_head);
1215 NormaliseDualHeads(*dst_head);
1219 * Normalise the head of the train again, i.e. that is tell the world that
1220 * we have changed and update all kinds of variables.
1221 * @param head the train to update.
1223 static void NormaliseTrainHead(Train *head)
1225 /* Not much to do! */
1226 if (head == NULL) return;
1228 /* Tell the 'world' the train changed. */
1229 head->ConsistChanged(CCF_ARRANGE);
1230 UpdateTrainGroupID(head);
1232 /* Not a front engine, i.e. a free wagon chain. No need to do more. */
1233 if (!head->IsFrontEngine()) return;
1235 /* Update the refit button and window */
1236 InvalidateWindowData(WC_VEHICLE_REFIT, head->index, VIWD_CONSIST_CHANGED);
1237 SetWindowWidgetDirty(WC_VEHICLE_VIEW, head->index, WID_VV_REFIT);
1239 /* If we don't have a unit number yet, set one. */
1240 if (head->unitnumber != 0) return;
1241 head->unitnumber = GetFreeUnitNumber(VEH_TRAIN);
1245 * Move a rail vehicle around inside the depot.
1246 * @param tile unused
1247 * @param flags type of operation
1248 * Note: DC_AUTOREPLACE is set when autoreplace tries to undo its modifications or moves vehicles to temporary locations inside the depot.
1249 * @param p1 various bitstuffed elements
1250 * - p1 (bit 0 - 19) source vehicle index
1251 * - p1 (bit 20) move all vehicles following the source vehicle
1252 * - p1 (bit 21) this is a virtual vehicle (for creating TemplateVehicles)
1253 * @param p2 what wagon to put the source wagon AFTER, XXX - INVALID_VEHICLE to make a new line
1254 * @param text unused
1255 * @return the cost of this operation or an error
1257 CommandCost CmdMoveRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1259 VehicleID s = GB(p1, 0, 20);
1260 VehicleID d = GB(p2, 0, 20);
1261 bool move_chain = HasBit(p1, 20);
1263 Train *src = Train::GetIfValid(s);
1264 if (src == NULL) return CMD_ERROR;
1266 CommandCost ret = CheckOwnership(src->owner);
1267 if (ret.Failed()) return ret;
1269 /* Do not allow moving crashed vehicles inside the depot, it is likely to cause asserts later */
1270 if (src->vehstatus & VS_CRASHED) return CMD_ERROR;
1272 /* if nothing is selected as destination, try and find a matching vehicle to drag to. */
1273 Train *dst;
1274 if (d == INVALID_VEHICLE) {
1275 dst = src->IsEngine() ? NULL : FindGoodVehiclePos(src);
1276 } else {
1277 dst = Train::GetIfValid(d);
1278 if (dst == NULL) return CMD_ERROR;
1280 CommandCost ret = CheckOwnership(dst->owner);
1281 if (ret.Failed()) return ret;
1283 /* Do not allow appending to crashed vehicles, too */
1284 if (dst->vehstatus & VS_CRASHED) return CMD_ERROR;
1287 /* if an articulated part is being handled, deal with its parent vehicle */
1288 src = src->GetFirstEnginePart();
1289 if (dst != NULL) {
1290 dst = dst->GetFirstEnginePart();
1293 /* don't move the same vehicle.. */
1294 if (src == dst) return CommandCost();
1296 /* locate the head of the two chains */
1297 Train *src_head = src->First();
1298 Train *dst_head;
1299 if (dst != NULL) {
1300 dst_head = dst->First();
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;
1409 /* We weren't a front engine but are becoming one. So
1410 * we should be put in the default group. */
1411 if (original_src_head != src && dst_head == src) {
1412 SetTrainGroupID(src, DEFAULT_GROUP);
1413 SetWindowDirty(WC_COMPANY, _current_company);
1416 /* Add new heads to statistics */
1417 if (src_head != NULL && src_head->IsFrontEngine()) GroupStatistics::CountVehicle(src_head, 1);
1418 if (dst_head != NULL && dst_head->IsFrontEngine()) GroupStatistics::CountVehicle(dst_head, 1);
1420 /* Handle 'new engine' part of cases #1b, #2b, #3b, #4b and #5 in NormaliseTrainHead. */
1421 NormaliseTrainHead(src_head);
1422 NormaliseTrainHead(dst_head);
1424 if ((flags & DC_NO_CARGO_CAP_CHECK) == 0) {
1425 CheckCargoCapacity(src_head);
1426 CheckCargoCapacity(dst_head);
1429 if (src_head != NULL) {
1430 src_head->last_loading_station = INVALID_STATION;
1431 ClrBit(src_head->vehicle_flags, VF_LAST_LOAD_ST_SEP);
1433 if (dst_head != NULL) {
1434 dst_head->last_loading_station = INVALID_STATION;
1435 ClrBit(dst_head->vehicle_flags, VF_LAST_LOAD_ST_SEP);
1438 if (src_head != NULL) src_head->First()->MarkDirty();
1439 if (dst_head != NULL) dst_head->First()->MarkDirty();
1441 /* We are undoubtedly changing something in the depot and train list. */
1442 /* But only if the moved vehicle is not virtual */
1443 if ( !HasBit(src->subtype, GVSF_VIRTUAL) ) {
1444 InvalidateWindowData(WC_VEHICLE_DEPOT, src->tile);
1445 InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
1446 } else {
1447 InvalidateWindowClassesData(WC_CREATE_TEMPLATE);
1449 } else {
1450 /* We don't want to execute what we're just tried. */
1451 RestoreTrainBackup(original_src);
1452 RestoreTrainBackup(original_dst);
1455 return CommandCost();
1459 * Sell a (single) train wagon/engine.
1460 * @param flags type of operation
1461 * @param t the train wagon to sell
1462 * @param data the selling mode
1463 * - data = 0: only sell the single dragged wagon/engine (and any belonging rear-engines)
1464 * - data = 1: sell the vehicle and all vehicles following it in the chain
1465 * if the wagon is dragged, don't delete the possibly belonging rear-engine to some front
1466 * @param user the user for the order backup.
1467 * @return the cost of this operation or an error
1469 CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *t, uint16 data, uint32 user)
1471 /* Sell a chain of vehicles or not? */
1472 bool sell_chain = HasBit(data, 0);
1474 Train *v = Train::From(t)->GetFirstEnginePart();
1475 Train *first = v->First();
1477 if (v->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
1479 /* First make a backup of the order of the train. That way we can do
1480 * whatever we want with the order and later on easily revert. */
1481 TrainList original;
1482 MakeTrainBackup(original, first);
1484 /* We need to keep track of the new head and the head of what we're going to sell. */
1485 Train *new_head = first;
1486 Train *sell_head = NULL;
1488 /* Split the train in the wanted way. */
1489 ArrangeTrains(&sell_head, NULL, &new_head, v, sell_chain);
1491 /* We don't need to validate the second train; it's going to be sold. */
1492 CommandCost ret = ValidateTrains(NULL, NULL, first, new_head, (flags & DC_AUTOREPLACE) == 0);
1493 if (ret.Failed()) {
1494 /* Restore the train we had. */
1495 RestoreTrainBackup(original);
1496 return ret;
1499 if (first->orders.list == NULL && !OrderList::CanAllocateItem()) {
1500 /* Restore the train we had. */
1501 RestoreTrainBackup(original);
1502 return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
1505 CommandCost cost(EXPENSES_NEW_VEHICLES);
1506 for (Train *t = sell_head; t != NULL; t = t->Next()) cost.AddCost(-t->value);
1508 /* do it? */
1509 if (flags & DC_EXEC) {
1510 /* First normalise the sub types of the chain. */
1511 NormaliseSubtypes(new_head);
1513 if (v == first && v->IsEngine() && !sell_chain && new_head != NULL && new_head->IsFrontEngine()) {
1514 /* We are selling the front engine. In this case we want to
1515 * 'give' the order, unit number and such to the new head. */
1516 new_head->orders.list = first->orders.list;
1517 new_head->AddToShared(first);
1518 DeleteVehicleOrders(first);
1520 /* Copy other important data from the front engine */
1521 new_head->CopyVehicleConfigAndStatistics(first);
1522 GroupStatistics::CountVehicle(new_head, 1); // after copying over the profit
1523 } else if (v->IsPrimaryVehicle() && data & (MAKE_ORDER_BACKUP_FLAG >> 20)) {
1524 OrderBackup::Backup(v, user);
1527 /* We need to update the information about the train. */
1528 NormaliseTrainHead(new_head);
1530 /* We are undoubtedly changing something in the depot and train list. */
1531 /* Unless its a virtual train */
1532 if ( !HasBit(v->subtype, GVSF_VIRTUAL) ) {
1533 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1534 InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
1535 } else {
1536 InvalidateWindowClassesData(WC_CREATE_TEMPLATE);
1539 /* Actually delete the sold 'goods' */
1540 delete sell_head;
1541 } else {
1542 /* We don't want to execute what we're just tried. */
1543 RestoreTrainBackup(original);
1546 return cost;
1549 void Train::UpdateDeltaXY(Direction direction)
1551 /* Set common defaults. */
1552 this->x_offs = -1;
1553 this->y_offs = -1;
1554 this->x_extent = 3;
1555 this->y_extent = 3;
1556 this->z_extent = 6;
1557 this->x_bb_offs = 0;
1558 this->y_bb_offs = 0;
1560 if (!IsDiagonalDirection(direction)) {
1561 static const int _sign_table[] =
1563 /* x, y */
1564 -1, -1, // DIR_N
1565 -1, 1, // DIR_E
1566 1, 1, // DIR_S
1567 1, -1, // DIR_W
1570 int half_shorten = (VEHICLE_LENGTH - this->gcache.cached_veh_length) / 2;
1572 /* For all straight directions, move the bound box to the centre of the vehicle, but keep the size. */
1573 this->x_offs -= half_shorten * _sign_table[direction];
1574 this->y_offs -= half_shorten * _sign_table[direction + 1];
1575 this->x_extent += this->x_bb_offs = half_shorten * _sign_table[direction];
1576 this->y_extent += this->y_bb_offs = half_shorten * _sign_table[direction + 1];
1577 } else {
1578 switch (direction) {
1579 /* Shorten southern corner of the bounding box according the vehicle length
1580 * and center the bounding box on the vehicle. */
1581 case DIR_NE:
1582 this->x_offs = 1 - (this->gcache.cached_veh_length + 1) / 2;
1583 this->x_extent = this->gcache.cached_veh_length - 1;
1584 this->x_bb_offs = -1;
1585 break;
1587 case DIR_NW:
1588 this->y_offs = 1 - (this->gcache.cached_veh_length + 1) / 2;
1589 this->y_extent = this->gcache.cached_veh_length - 1;
1590 this->y_bb_offs = -1;
1591 break;
1593 /* Move northern corner of the bounding box down according to vehicle length
1594 * and center the bounding box on the vehicle. */
1595 case DIR_SW:
1596 this->x_offs = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH;
1597 this->x_extent = VEHICLE_LENGTH - 1;
1598 this->x_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
1599 break;
1601 case DIR_SE:
1602 this->y_offs = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH;
1603 this->y_extent = VEHICLE_LENGTH - 1;
1604 this->y_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
1605 break;
1607 default:
1608 NOT_REACHED();
1614 * Mark a train as stuck and stop it if it isn't stopped right now.
1615 * @param v %Train to mark as being stuck.
1617 static void MarkTrainAsStuck(Train *v)
1619 if (!HasBit(v->flags, VRF_TRAIN_STUCK)) {
1620 /* It is the first time the problem occurred, set the "train stuck" flag. */
1621 SetBit(v->flags, VRF_TRAIN_STUCK);
1623 v->wait_counter = 0;
1625 /* Stop train */
1626 v->cur_speed = 0;
1627 v->subspeed = 0;
1628 v->SetLastSpeed();
1630 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
1635 * Swap the two up/down flags in two ways:
1636 * - Swap values of \a swap_flag1 and \a swap_flag2, and
1637 * - If going up previously (#GVF_GOINGUP_BIT set), the #GVF_GOINGDOWN_BIT is set, and vice versa.
1638 * @param swap_flag1 [inout] First train flag.
1639 * @param swap_flag2 [inout] Second train flag.
1641 static void SwapTrainFlags(uint16 *swap_flag1, uint16 *swap_flag2)
1643 uint16 flag1 = *swap_flag1;
1644 uint16 flag2 = *swap_flag2;
1646 /* Clear the flags */
1647 ClrBit(*swap_flag1, GVF_GOINGUP_BIT);
1648 ClrBit(*swap_flag1, GVF_GOINGDOWN_BIT);
1649 ClrBit(*swap_flag2, GVF_GOINGUP_BIT);
1650 ClrBit(*swap_flag2, GVF_GOINGDOWN_BIT);
1652 /* Reverse the rail-flags (if needed) */
1653 if (HasBit(flag1, GVF_GOINGUP_BIT)) {
1654 SetBit(*swap_flag2, GVF_GOINGDOWN_BIT);
1655 } else if (HasBit(flag1, GVF_GOINGDOWN_BIT)) {
1656 SetBit(*swap_flag2, GVF_GOINGUP_BIT);
1658 if (HasBit(flag2, GVF_GOINGUP_BIT)) {
1659 SetBit(*swap_flag1, GVF_GOINGDOWN_BIT);
1660 } else if (HasBit(flag2, GVF_GOINGDOWN_BIT)) {
1661 SetBit(*swap_flag1, GVF_GOINGUP_BIT);
1666 * Updates some variables after swapping the vehicle.
1667 * @param v swapped vehicle
1669 static void UpdateStatusAfterSwap(Train *v)
1671 /* Reverse the direction. */
1672 if (v->track != TRACK_BIT_DEPOT) v->direction = ReverseDir(v->direction);
1674 /* Call the proper EnterTile function unless we are in a wormhole. */
1675 if (v->track != TRACK_BIT_WORMHOLE) {
1676 VehicleEnterTile(v, v->tile, v->x_pos, v->y_pos);
1677 } else {
1678 /* VehicleEnter_TunnelBridge() sets TRACK_BIT_WORMHOLE when the vehicle
1679 * is on the last bit of the bridge head (frame == TILE_SIZE - 1).
1680 * If we were swapped with such a vehicle, we have set TRACK_BIT_WORMHOLE,
1681 * when we shouldn't have. Check if this is the case. */
1682 TileIndex vt = TileVirtXY(v->x_pos, v->y_pos);
1683 if (IsTileType(vt, MP_TUNNELBRIDGE)) {
1684 VehicleEnterTile(v, vt, v->x_pos, v->y_pos);
1685 if (v->track != TRACK_BIT_WORMHOLE && IsBridgeTile(v->tile)) {
1686 /* We have just left the wormhole, possibly set the
1687 * "goingdown" bit. UpdateInclination() can be used
1688 * because we are at the border of the tile. */
1689 v->UpdatePosition();
1690 v->UpdateInclination(true, true);
1691 return;
1696 v->UpdatePosition();
1697 v->UpdateViewport(true, true);
1701 * Swap vehicles \a l and \a r in consist \a v, and reverse their direction.
1702 * @param v Consist to change.
1703 * @param l %Vehicle index in the consist of the first vehicle.
1704 * @param r %Vehicle index in the consist of the second vehicle.
1706 void ReverseTrainSwapVeh(Train *v, int l, int r)
1708 Train *a, *b;
1710 /* locate vehicles to swap */
1711 for (a = v; l != 0; l--) a = a->Next();
1712 for (b = v; r != 0; r--) b = b->Next();
1714 if (a != b) {
1715 /* swap the hidden bits */
1717 uint16 tmp = (a->vehstatus & ~VS_HIDDEN) | (b->vehstatus & VS_HIDDEN);
1718 b->vehstatus = (b->vehstatus & ~VS_HIDDEN) | (a->vehstatus & VS_HIDDEN);
1719 a->vehstatus = tmp;
1722 Swap(a->track, b->track);
1723 Swap(a->direction, b->direction);
1724 Swap(a->x_pos, b->x_pos);
1725 Swap(a->y_pos, b->y_pos);
1726 Swap(a->tile, b->tile);
1727 Swap(a->z_pos, b->z_pos);
1729 SwapTrainFlags(&a->gv_flags, &b->gv_flags);
1731 UpdateStatusAfterSwap(a);
1732 UpdateStatusAfterSwap(b);
1733 } else {
1734 /* Swap GVF_GOINGUP_BIT/GVF_GOINGDOWN_BIT.
1735 * This is a little bit redundant way, a->gv_flags will
1736 * be (re)set twice, but it reduces code duplication */
1737 SwapTrainFlags(&a->gv_flags, &a->gv_flags);
1738 UpdateStatusAfterSwap(a);
1744 * Check if the vehicle is a train
1745 * @param v vehicle on tile
1746 * @return v if it is a train, NULL otherwise
1748 static Vehicle *TrainOnTileEnum(Vehicle *v, void *)
1750 return (v->type == VEH_TRAIN) ? v : NULL;
1755 * Checks if a train is approaching a rail-road crossing
1756 * @param v vehicle on tile
1757 * @param data tile with crossing we are testing
1758 * @return v if it is approaching a crossing, NULL otherwise
1760 static Vehicle *TrainApproachingCrossingEnum(Vehicle *v, void *data)
1762 if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return NULL;
1764 Train *t = Train::From(v);
1765 if (!t->IsFrontEngine()) return NULL;
1767 TileIndex tile = *(TileIndex *)data;
1769 if (TrainApproachingCrossingTile(t) != tile) return NULL;
1771 return t;
1776 * Finds a vehicle approaching rail-road crossing
1777 * @param tile tile to test
1778 * @return true if a vehicle is approaching the crossing
1779 * @pre tile is a rail-road crossing
1781 static bool TrainApproachingCrossing(TileIndex tile)
1783 assert(IsLevelCrossingTile(tile));
1785 DiagDirection dir = AxisToDiagDir(GetCrossingRailAxis(tile));
1786 TileIndex tile_from = tile + TileOffsByDiagDir(dir);
1788 if (HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum)) return true;
1790 dir = ReverseDiagDir(dir);
1791 tile_from = tile + TileOffsByDiagDir(dir);
1793 return HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum);
1796 /** Check if the crossing should be closed
1797 * @return train on crossing || train approaching crossing || reserved
1799 static inline bool CheckLevelCrossing(TileIndex tile)
1801 return HasCrossingReservation(tile) || HasVehicleOnPos(tile, NULL, &TrainOnTileEnum) || TrainApproachingCrossing(tile);
1805 * Sets correct crossing state
1806 * @param tile tile to update
1807 * @param sound should we play sound?
1808 * @param force_state force close the crossing due to an adjacent tile
1809 * @pre tile is a rail-road crossing
1811 static void UpdateLevelCrossingTile(TileIndex tile, bool sound, bool force_state = false)
1813 assert(IsLevelCrossingTile(tile));
1814 bool new_state;
1816 if (force_state) {
1817 new_state = force_state;
1818 } else {
1819 new_state = CheckLevelCrossing(tile);
1822 if (new_state != IsCrossingBarred(tile)) {
1823 if (new_state && sound) {
1824 RailTypeLabel railTypeLabel = GetRailTypeInfo(GetTileRailType(tile))->label;
1826 if (railTypeLabel != _planning_tracks_label &&
1827 railTypeLabel != _pipeline_tracks_label &&
1828 railTypeLabel != _wires_tracks_label &&
1829 _settings_client.sound.ambient) {
1830 SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
1833 SetCrossingBarred(tile, new_state);
1834 MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
1839 * Cycles the adjacent crossings and sets their state
1840 * @param tile tile to update
1841 * @param sound should we play sound?
1843 void UpdateLevelCrossing(TileIndex tile, bool sound)
1845 bool is_forced = false;
1846 if (!IsLevelCrossingTile(tile)) return;
1848 Axis axis = GetCrossingRoadAxis(tile);
1850 for (TileIndex t = tile; !is_forced && IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == axis; t = TileAddByDiagDir(t, AxisToDiagDir(GetCrossingRoadAxis(t)))) {
1851 is_forced |= CheckLevelCrossing(t);
1853 for (TileIndex t = tile; !is_forced && IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == axis; t = TileAddByDiagDir(t, ReverseDiagDir(AxisToDiagDir(GetCrossingRoadAxis(t))))) {
1854 is_forced |= CheckLevelCrossing(t);
1857 for (TileIndex t = tile; IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == axis; t = TileAddByDiagDir(t, AxisToDiagDir(GetCrossingRoadAxis(t)))) {
1858 UpdateLevelCrossingTile(t, sound, is_forced);
1860 for (TileIndex t = tile; IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == axis; t = TileAddByDiagDir(t, ReverseDiagDir(AxisToDiagDir(GetCrossingRoadAxis(t))))) {
1861 UpdateLevelCrossingTile(t, sound, is_forced);
1867 * Bars crossing and plays ding-ding sound if not barred already
1868 * @param tile tile with crossing
1869 * @pre tile is a rail-road crossing
1871 static inline void MaybeBarCrossingWithSound(TileIndex tile)
1873 if (!IsCrossingBarred(tile)) {
1874 SetCrossingReservation(tile, true);
1875 UpdateLevelCrossing(tile, true);
1881 * Advances wagons for train reversing, needed for variable length wagons.
1882 * This one is called before the train is reversed.
1883 * @param v First vehicle in chain
1885 static void AdvanceWagonsBeforeSwap(Train *v)
1887 Train *base = v;
1888 Train *first = base; // first vehicle to move
1889 Train *last = v->Last(); // last vehicle to move
1890 uint length = CountVehiclesInChain(v);
1892 while (length > 2) {
1893 last = last->Previous();
1894 first = first->Next();
1896 int differential = base->CalcNextVehicleOffset() - last->CalcNextVehicleOffset();
1898 /* do not update images now
1899 * negative differential will be handled in AdvanceWagonsAfterSwap() */
1900 for (int i = 0; i < differential; i++) TrainController(first, last->Next());
1902 base = first; // == base->Next()
1903 length -= 2;
1909 * Advances wagons for train reversing, needed for variable length wagons.
1910 * This one is called after the train is reversed.
1911 * @param v First vehicle in chain
1913 static void AdvanceWagonsAfterSwap(Train *v)
1915 /* first of all, fix the situation when the train was entering a depot */
1916 Train *dep = v; // last vehicle in front of just left depot
1917 while (dep->Next() != NULL && (dep->track == TRACK_BIT_DEPOT || dep->Next()->track != TRACK_BIT_DEPOT)) {
1918 dep = dep->Next(); // find first vehicle outside of a depot, with next vehicle inside a depot
1921 Train *leave = dep->Next(); // first vehicle in a depot we are leaving now
1923 if (leave != NULL) {
1924 /* 'pull' next wagon out of the depot, so we won't miss it (it could stay in depot forever) */
1925 int d = TicksToLeaveDepot(dep);
1927 if (d <= 0) {
1928 leave->vehstatus &= ~VS_HIDDEN; // move it out of the depot
1929 leave->track = TrackToTrackBits(GetRailDepotTrack(leave->tile));
1930 for (int i = 0; i >= d; i--) TrainController(leave, NULL); // maybe move it, and maybe let another wagon leave
1932 } else {
1933 dep = NULL; // no vehicle in a depot, so no vehicle leaving a depot
1936 Train *base = v;
1937 Train *first = base; // first vehicle to move
1938 Train *last = v->Last(); // last vehicle to move
1939 uint length = CountVehiclesInChain(v);
1941 /* We have to make sure all wagons that leave a depot because of train reversing are moved correctly
1942 * they have already correct spacing, so we have to make sure they are moved how they should */
1943 bool nomove = (dep == NULL); // If there is no vehicle leaving a depot, limit the number of wagons moved immediately.
1945 while (length > 2) {
1946 /* we reached vehicle (originally) in front of a depot, stop now
1947 * (we would move wagons that are already moved with new wagon length). */
1948 if (base == dep) break;
1950 /* the last wagon was that one leaving a depot, so do not move it anymore */
1951 if (last == dep) nomove = true;
1953 last = last->Previous();
1954 first = first->Next();
1956 int differential = last->CalcNextVehicleOffset() - base->CalcNextVehicleOffset();
1958 /* do not update images now */
1959 for (int i = 0; i < differential; i++) TrainController(first, (nomove ? last->Next() : NULL));
1961 base = first; // == base->Next()
1962 length -= 2;
1967 * Turn a train around.
1968 * @param v %Train to turn around.
1970 void ReverseTrainDirection(Train *v)
1972 if (IsRailDepotTile(v->tile)) {
1973 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1976 v->reverse_distance = 0;
1978 /* Clear path reservation in front if train is not stuck. */
1979 if (!HasBit(v->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(v);
1981 /* Check if we were approaching a rail/road-crossing */
1982 TileIndex crossing = TrainApproachingCrossingTile(v);
1984 /* count number of vehicles */
1985 int r = CountVehiclesInChain(v) - 1; // number of vehicles - 1
1987 AdvanceWagonsBeforeSwap(v);
1989 /* swap start<>end, start+1<>end-1, ... */
1990 int l = 0;
1991 do {
1992 ReverseTrainSwapVeh(v, l++, r--);
1993 } while (l <= r);
1995 AdvanceWagonsAfterSwap(v);
1997 if (IsRailDepotTile(v->tile)) {
1998 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
2001 ToggleBit(v->flags, VRF_TOGGLE_REVERSE);
2003 ClrBit(v->flags, VRF_REVERSING);
2005 /* recalculate cached data */
2006 v->ConsistChanged(CCF_TRACK);
2008 /* update all images */
2009 for (Train *u = v; u != NULL; u = u->Next()) u->UpdateViewport(false, false);
2011 /* update crossing we were approaching */
2012 if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
2014 /* maybe we are approaching crossing now, after reversal */
2015 crossing = TrainApproachingCrossingTile(v);
2016 if (crossing != INVALID_TILE) MaybeBarCrossingWithSound(crossing);
2018 /* If we are inside a depot after reversing, don't bother with path reserving. */
2019 if (v->track == TRACK_BIT_DEPOT) {
2020 /* Can't be stuck here as inside a depot is always a safe tile. */
2021 if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2022 ClrBit(v->flags, VRF_TRAIN_STUCK);
2023 return;
2026 /* We are inside tunnel/bidge with signals, reversing will close the entrance. */
2027 if (IsTunnelBridgeWithSignalSimulation(v->tile)) {
2028 /* Flip signal on tunnel entrance tile red. */
2029 SetTunnelBridgeSignalState(v->tile, SIGNAL_STATE_RED);
2030 MarkTileDirtyByTile(v->tile);
2031 /* Clear counters. */
2032 v->wait_counter = 0;
2033 v->load_unload_ticks = 0;
2034 return;
2037 /* TrainExitDir does not always produce the desired dir for depots and
2038 * tunnels/bridges that is needed for UpdateSignalsOnSegment. */
2039 DiagDirection dir = TrainExitDir(v->direction, v->track);
2040 if (IsRailDepotTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE)) dir = INVALID_DIAGDIR;
2042 if (UpdateSignalsOnSegment(v->tile, dir, v->owner) == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
2043 /* If we are currently on a tile with conventional signals, we can't treat the
2044 * current tile as a safe tile or we would enter a PBS block without a reservation. */
2045 bool first_tile_okay = !(IsTileType(v->tile, MP_RAILWAY) &&
2046 HasSignalOnTrackdir(v->tile, v->GetVehicleTrackdir()) &&
2047 !IsPbsSignal(GetSignalType(v->tile, FindFirstTrack(v->track))));
2049 /* If we are on a depot tile facing outwards, do not treat the current tile as safe. */
2050 if (IsRailDepotTile(v->tile) && TrackdirToExitdir(v->GetVehicleTrackdir()) == GetRailDepotDirection(v->tile)) first_tile_okay = false;
2052 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
2053 if (TryPathReserve(v, false, first_tile_okay)) {
2054 /* Do a look-ahead now in case our current tile was already a safe tile. */
2055 CheckNextTrainTile(v);
2056 } else if (v->current_order.GetType() != OT_LOADING) {
2057 /* Do not wait for a way out when we're still loading */
2058 MarkTrainAsStuck(v);
2060 } else if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
2061 /* A train not inside a PBS block can't be stuck. */
2062 ClrBit(v->flags, VRF_TRAIN_STUCK);
2063 v->wait_counter = 0;
2068 * Reverse train.
2069 * @param tile unused
2070 * @param flags type of operation
2071 * @param p1 train to reverse
2072 * @param p2 if true, reverse a unit in a train (needs to be in a depot)
2073 * @param text unused
2074 * @return the cost of this operation or an error
2076 CommandCost CmdReverseTrainDirection(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2078 Train *v = Train::GetIfValid(p1);
2079 if (v == NULL) return CMD_ERROR;
2081 CommandCost ret = CheckOwnership(v->owner);
2082 if (ret.Failed()) return ret;
2084 if (p2 != 0) {
2085 /* turn a single unit around */
2087 if (v->IsMultiheaded() || HasBit(EngInfo(v->engine_type)->callback_mask, CBM_VEHICLE_ARTIC_ENGINE)) {
2088 return_cmd_error(STR_ERROR_CAN_T_REVERSE_DIRECTION_RAIL_VEHICLE_MULTIPLE_UNITS);
2090 if (!HasBit(EngInfo(v->engine_type)->misc_flags, EF_RAIL_FLIPS)) return CMD_ERROR;
2092 Train *front = v->First();
2093 /* make sure the vehicle is stopped in the depot */
2094 if (!front->IsStoppedInDepot()) {
2095 return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
2098 if (flags & DC_EXEC) {
2099 ToggleBit(v->flags, VRF_REVERSE_DIRECTION);
2101 front->ConsistChanged(CCF_ARRANGE);
2102 SetWindowDirty(WC_VEHICLE_DEPOT, front->tile);
2103 SetWindowDirty(WC_VEHICLE_DETAILS, front->index);
2104 SetWindowDirty(WC_VEHICLE_VIEW, front->index);
2105 SetWindowClassesDirty(WC_TRAINS_LIST);
2107 } else {
2108 /* turn the whole train around */
2109 if ((v->vehstatus & VS_CRASHED) || v->breakdown_ctr != 0) return CMD_ERROR;
2111 if (flags & DC_EXEC) {
2112 /* Properly leave the station if we are loading and won't be loading anymore */
2113 if (v->current_order.IsType(OT_LOADING)) {
2114 const Vehicle *last = v;
2115 while (last->Next() != NULL) last = last->Next();
2117 /* not a station || different station --> leave the station */
2118 if (!IsTileType(last->tile, MP_STATION) || GetStationIndex(last->tile) != GetStationIndex(v->tile)) {
2119 v->LeaveStation();
2123 /* We cancel any 'skip signal at dangers' here */
2124 v->force_proceed = TFP_NONE;
2125 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
2127 if (_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL && v->cur_speed != 0) {
2128 ToggleBit(v->flags, VRF_REVERSING);
2129 } else {
2130 v->cur_speed = 0;
2131 v->SetLastSpeed();
2132 HideFillingPercent(&v->fill_percent_te_id);
2133 ReverseTrainDirection(v);
2137 return CommandCost();
2141 * Force a train through a red signal
2142 * @param tile unused
2143 * @param flags type of operation
2144 * @param p1 train to ignore the red signal
2145 * @param p2 unused
2146 * @param text unused
2147 * @return the cost of this operation or an error
2149 CommandCost CmdForceTrainProceed(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2151 Train *t = Train::GetIfValid(p1);
2152 if (t == NULL) return CMD_ERROR;
2154 if (!t->IsPrimaryVehicle()) return CMD_ERROR;
2156 CommandCost ret = CheckOwnership(t->owner);
2157 if (ret.Failed()) return ret;
2160 if (flags & DC_EXEC) {
2161 /* If we are forced to proceed, cancel that order.
2162 * If we are marked stuck we would want to force the train
2163 * to proceed to the next signal. In the other cases we
2164 * would like to pass the signal at danger and run till the
2165 * next signal we encounter. */
2166 t->force_proceed = t->force_proceed == TFP_SIGNAL ? TFP_NONE : HasBit(t->flags, VRF_TRAIN_STUCK) || t->IsChainInDepot() ? TFP_STUCK : TFP_SIGNAL;
2167 SetWindowDirty(WC_VEHICLE_VIEW, t->index);
2170 return CommandCost();
2174 * Try to find a depot nearby.
2175 * @param v %Train that wants a depot.
2176 * @param max_distance Maximal search distance.
2177 * @return Information where the closest train depot is located.
2178 * @pre The given vehicle must not be crashed!
2180 static FindDepotData FindClosestTrainDepot(Train *v, int max_distance)
2182 assert(!(v->vehstatus & VS_CRASHED));
2184 if (IsRailDepotTile(v->tile)) return FindDepotData(v->tile, 0);
2186 PBSTileInfo origin = FollowTrainReservation(v);
2187 if (IsRailDepotTile(origin.tile)) return FindDepotData(origin.tile, 0);
2189 switch (_settings_game.pf.pathfinder_for_trains) {
2190 case VPF_NPF: return NPFTrainFindNearestDepot(v, max_distance);
2191 case VPF_YAPF: return YapfTrainFindNearestDepot(v, max_distance);
2193 default: NOT_REACHED();
2198 * Locate the closest depot for this consist, and return the information to the caller.
2199 * @param location [out] If not \c NULL and a depot is found, store its location in the given address.
2200 * @param destination [out] If not \c NULL and a depot is found, store its index in the given address.
2201 * @param reverse [out] If not \c NULL and a depot is found, store reversal information in the given address.
2202 * @return A depot has been found.
2204 bool Train::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
2206 FindDepotData tfdd = FindClosestTrainDepot(this, 0);
2207 if (tfdd.best_length == UINT_MAX) return false;
2209 if (location != NULL) *location = tfdd.tile;
2210 if (destination != NULL) *destination = GetDepotIndex(tfdd.tile);
2211 if (reverse != NULL) *reverse = tfdd.reverse;
2213 return true;
2216 /** Play a sound for a train leaving the station. */
2217 void Train::PlayLeaveStationSound() const
2219 static const SoundFx sfx[] = {
2220 SND_04_TRAIN,
2221 SND_0A_TRAIN_HORN,
2222 SND_0A_TRAIN_HORN,
2223 SND_47_MAGLEV_2,
2224 SND_41_MAGLEV
2227 if (PlayVehicleSound(this, VSE_START)) return;
2229 EngineID engtype = this->engine_type;
2230 SndPlayVehicleFx(sfx[RailVehInfo(engtype)->engclass], this);
2234 * Check if the train is on the last reserved tile and try to extend the path then.
2235 * @param v %Train that needs its path extended.
2237 static void CheckNextTrainTile(Train *v)
2239 /* Don't do any look-ahead if path_backoff_interval is 255. */
2240 if (_settings_game.pf.path_backoff_interval == 255) return;
2242 /* Exit if we are inside a depot. */
2243 if (v->track == TRACK_BIT_DEPOT) return;
2245 switch (v->current_order.GetType()) {
2246 /* Exit if we reached our destination depot. */
2247 case OT_GOTO_DEPOT:
2248 if (v->tile == v->dest_tile) return;
2249 break;
2251 case OT_GOTO_WAYPOINT:
2252 /* If we reached our waypoint, make sure we see that. */
2253 if (IsRailWaypointTile(v->tile) && GetStationIndex(v->tile) == v->current_order.GetDestination()) ProcessOrders(v);
2254 break;
2256 case OT_NOTHING:
2257 case OT_LEAVESTATION:
2258 case OT_LOADING:
2259 /* Exit if the current order doesn't have a destination, but the train has orders. */
2260 if (v->GetNumOrders() > 0) return;
2261 break;
2263 default:
2264 break;
2266 /* Exit if we are on a station tile and are going to stop. */
2267 if (IsRailStationTile(v->tile) && v->current_order.ShouldStopAtStation(v, GetStationIndex(v->tile))) return;
2269 Trackdir td = v->GetVehicleTrackdir();
2271 /* On a tile with a red non-pbs signal, don't look ahead. */
2272 if (IsTileType(v->tile, MP_RAILWAY) && HasSignalOnTrackdir(v->tile, td) &&
2273 !IsPbsSignal(GetSignalType(v->tile, TrackdirToTrack(td))) &&
2274 GetSignalStateByTrackdir(v->tile, td) == SIGNAL_STATE_RED) return;
2276 CFollowTrackRail ft(v);
2277 if (!ft.Follow(v->tile, td)) return;
2279 if (!HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(ft.m_new_td_bits))) {
2280 /* Next tile is not reserved. */
2281 if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
2282 if (HasPbsSignalOnTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) {
2283 /* If the next tile is a PBS signal, try to make a reservation. */
2284 TrackBits tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
2285 if (_settings_game.pf.forbid_90_deg) {
2286 tracks &= ~TrackCrossesTracks(TrackdirToTrack(ft.m_old_td));
2288 ChooseTrainTrack(v, ft.m_new_tile, ft.m_exitdir, tracks, false, NULL, false);
2295 * Will the train stay in the depot the next tick?
2296 * @param v %Train to check.
2297 * @return True if it stays in the depot, false otherwise.
2299 static bool CheckTrainStayInDepot(Train *v)
2301 /* bail out if not all wagons are in the same depot or not in a depot at all */
2302 for (const Train *u = v; u != NULL; u = u->Next()) {
2303 if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return false;
2306 /* if the train got no power, then keep it in the depot */
2307 if (v->gcache.cached_power == 0) {
2308 v->vehstatus |= VS_STOPPED;
2309 SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
2310 return true;
2313 if (v->current_order.IsWaitTimetabled())
2314 v->HandleWaiting(false);
2315 if (v->current_order.IsType(OT_WAITING))
2316 return true;
2318 SigSegState seg_state;
2320 if (v->force_proceed == TFP_NONE) {
2321 /* force proceed was not pressed */
2322 if (++v->wait_counter < 37) {
2323 SetWindowClassesDirty(WC_TRAINS_LIST);
2324 return true;
2327 v->wait_counter = 0;
2329 seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
2330 if (seg_state == SIGSEG_FULL || HasDepotReservation(v->tile)) {
2331 /* Full and no PBS signal in block or depot reserved, can't exit. */
2332 SetWindowClassesDirty(WC_TRAINS_LIST);
2333 return true;
2335 } else {
2336 seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
2339 /* We are leaving a depot, but have to go to the exact same one; re-enter */
2340 if (v->current_order.IsType(OT_GOTO_DEPOT) && v->tile == v->dest_tile) {
2341 /* We need to have a reservation for this to work. */
2342 if (HasDepotReservation(v->tile)) return true;
2343 SetDepotReservation(v->tile, true);
2344 VehicleEnterDepot(v);
2345 return true;
2348 /* Only leave when we can reserve a path to our destination. */
2349 if (seg_state == SIGSEG_PBS && !TryPathReserve(v) && v->force_proceed == TFP_NONE) {
2350 /* No path and no force proceed. */
2351 SetWindowClassesDirty(WC_TRAINS_LIST);
2352 MarkTrainAsStuck(v);
2353 return true;
2356 SetDepotReservation(v->tile, true);
2357 if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile, ZOOM_LVL_DRAW_MAP);
2359 VehicleServiceInDepot(v);
2360 SetWindowClassesDirty(WC_TRAINS_LIST);
2361 v->PlayLeaveStationSound();
2363 v->track = TRACK_BIT_X;
2364 if (v->direction & 2) v->track = TRACK_BIT_Y;
2366 v->vehstatus &= ~VS_HIDDEN;
2367 v->cur_speed = 0;
2369 v->UpdateViewport(true, true);
2370 v->UpdatePosition();
2371 UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
2372 v->UpdateAcceleration();
2373 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
2375 return false;
2378 static int GetAndClearLastBridgeEntranceSetSignalIndex(TileIndex bridge_entrance)
2380 uint16 m = _m[bridge_entrance].m2;
2381 if (m & 0x8000) {
2382 auto it = _long_bridge_signal_sim_map.find(bridge_entrance);
2383 if (it != _long_bridge_signal_sim_map.end()) {
2384 LongBridgeSignalStorage &lbss = it->second;
2385 size_t slot = lbss.signal_red_bits.size();
2386 while (slot > 0) {
2387 slot--;
2388 uint64 &slot_bits = lbss.signal_red_bits[slot];
2389 if (slot_bits) {
2390 uint8 i = FindLastBit(slot_bits);
2391 ClrBit(slot_bits, i);
2392 return 1 + 15 + (64 * slot) + i;
2397 if (m & 0x7FFF) {
2398 uint8 i = FindLastBit(m & 0x7FFF);
2399 ClrBit(_m[bridge_entrance].m2, i);
2400 return 1 + i;
2403 return 0;
2406 static void HandleLastTunnelBridgeSignals(TileIndex tile, TileIndex end, DiagDirection dir, bool free)
2408 if (IsBridge(end) && _m[end].m2 != 0) {
2409 /* Clearing last bridge signal. */
2410 int signal_offset = GetAndClearLastBridgeEntranceSetSignalIndex(end);
2411 if (signal_offset) {
2412 TileIndex last_signal_tile = end + (TileOffsByDiagDir(dir) * _settings_game.construction.simulated_wormhole_signals * signal_offset);
2413 MarkTileDirtyByTile(last_signal_tile);
2415 MarkTileDirtyByTile(tile);
2417 if (free) {
2418 /* Open up the wormhole and clear m2. */
2419 if (IsBridge(end)) {
2420 SetAllBridgeEntranceSimulatedSignalsGreen(end);
2423 if (IsTunnelBridgeSignalSimulationEntrance(end) && GetTunnelBridgeSignalState(end) == SIGNAL_STATE_RED) {
2424 SetTunnelBridgeSignalState(end, SIGNAL_STATE_GREEN);
2425 MarkTileDirtyByTile(end);
2426 } else if (IsTunnelBridgeSignalSimulationEntrance(tile) && GetTunnelBridgeSignalState(tile) == SIGNAL_STATE_RED) {
2427 SetTunnelBridgeSignalState(tile, SIGNAL_STATE_GREEN);
2428 MarkTileDirtyByTile(tile);
2433 static void UnreserveBridgeTunnelTile(TileIndex tile)
2435 SetTunnelBridgeReservation(tile, false);
2436 if (IsTunnelBridgeSignalSimulationExit(tile) && IsTunnelBridgePBS(tile)) SetTunnelBridgeSignalState(tile, SIGNAL_STATE_RED);
2440 * Clear the reservation of \a tile that was just left by a wagon on \a track_dir.
2441 * @param v %Train owning the reservation.
2442 * @param tile Tile with reservation to clear.
2443 * @param track_dir Track direction to clear.
2445 static void ClearPathReservation(const Train *v, TileIndex tile, Trackdir track_dir)
2447 DiagDirection dir = TrackdirToExitdir(track_dir);
2449 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
2450 /* Are we just leaving a tunnel/bridge? */
2451 if (GetTunnelBridgeDirection(tile) == ReverseDiagDir(dir)) {
2452 TileIndex end = GetOtherTunnelBridgeEnd(tile);
2454 bool free = TunnelBridgeIsFree(tile, end, v).Succeeded();
2456 if (IsTunnelBridgeWithSignalSimulation(tile)) {
2457 UnreserveBridgeTunnelTile(tile);
2458 HandleLastTunnelBridgeSignals(tile, end, dir, free);
2459 if (_settings_client.gui.show_track_reservation) {
2460 MarkTileDirtyByTile(tile);
2463 else if (free) {
2464 /* Free the reservation only if no other train is on the tiles. */
2465 UnreserveBridgeTunnelTile(tile);
2466 UnreserveBridgeTunnelTile(end);
2468 if (_settings_client.gui.show_track_reservation) {
2469 if (IsBridge(tile)) {
2470 MarkBridgeDirty(tile);
2472 else {
2473 MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
2474 MarkTileDirtyByTile(end, ZOOM_LVL_DRAW_MAP);
2478 else if (GetTunnelBridgeDirection(tile) == dir && IsTunnelBridgeWithSignalSimulation(tile)) {
2479 /* canceling reservation of entry ramp, due to reverse */
2480 UnreserveBridgeTunnelTile(tile);
2481 if (_settings_client.gui.show_track_reservation) {
2482 MarkTileDirtyByTile(tile);
2486 } else if (IsRailStationTile(tile)) {
2487 TileIndex new_tile = TileAddByDiagDir(tile, dir);
2488 /* If the new tile is not a further tile of the same station, we
2489 * clear the reservation for the whole platform. */
2490 if (!IsCompatibleTrainStationTile(new_tile, tile)) {
2491 SetRailStationPlatformReservation(tile, ReverseDiagDir(dir), false);
2493 } else {
2494 /* Any other tile */
2495 UnreserveRailTrack(tile, TrackdirToTrack(track_dir));
2500 * Free the reserved path in front of a vehicle.
2501 * @param v %Train owning the reserved path.
2502 * @param origin %Tile to start clearing (if #INVALID_TILE, use the current tile of \a v).
2503 * @param orig_td Track direction (if #INVALID_TRACKDIR, use the track direction of \a v).
2505 void FreeTrainTrackReservation(const Train *v, TileIndex origin, Trackdir orig_td)
2507 assert(v->IsFrontEngine());
2509 TileIndex tile = origin != INVALID_TILE ? origin : v->tile;
2510 Trackdir td = orig_td != INVALID_TRACKDIR ? orig_td : v->GetVehicleTrackdir();
2511 bool free_tile = tile != v->tile || !(IsRailStationTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE));
2512 StationID station_id = IsRailStationTile(v->tile) ? GetStationIndex(v->tile) : INVALID_STATION;
2514 /* Can't be holding a reservation if we enter a depot. */
2515 if (IsRailDepotTile(tile) && TrackdirToExitdir(td) != GetRailDepotDirection(tile)) return;
2516 if (v->track == TRACK_BIT_DEPOT) {
2517 /* Front engine is in a depot. We enter if some part is not in the depot. */
2518 for (const Train *u = v; u != NULL; u = u->Next()) {
2519 if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return;
2522 /* Don't free reservation if it's not ours. */
2523 if (TracksOverlap(GetReservedTrackbits(tile) | TrackToTrackBits(TrackdirToTrack(td)))) return;
2525 CFollowTrackRail ft(v, GetRailTypeInfo(v->railtype)->compatible_railtypes);
2526 while (ft.Follow(tile, td)) {
2527 tile = ft.m_new_tile;
2528 TrackdirBits bits = ft.m_new_td_bits & TrackBitsToTrackdirBits(GetReservedTrackbits(tile));
2529 td = RemoveFirstTrackdir(&bits);
2530 assert(bits == TRACKDIR_BIT_NONE);
2532 if (!IsValidTrackdir(td)) break;
2534 if (IsTileType(tile, MP_RAILWAY)) {
2535 if (HasSignalOnTrackdir(tile, td) && !IsPbsSignal(GetSignalType(tile, TrackdirToTrack(td)))) {
2536 /* Conventional signal along trackdir: remove reservation and stop. */
2537 UnreserveRailTrack(tile, TrackdirToTrack(td));
2538 break;
2540 if (HasPbsSignalOnTrackdir(tile, td)) {
2541 if (GetSignalStateByTrackdir(tile, td) == SIGNAL_STATE_RED) {
2542 /* Red PBS signal? Can't be our reservation, would be green then. */
2543 break;
2544 } else {
2545 /* Turn the signal back to red. */
2546 SetSignalStateByTrackdir(tile, td, SIGNAL_STATE_RED);
2547 MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
2549 /* notify logic signals of the state change */
2550 SignalStateChanged(tile, TrackdirToTrack(td), 1);
2552 } else if (HasSignalOnTrackdir(tile, ReverseTrackdir(td)) && IsOnewaySignal(tile, TrackdirToTrack(td))) {
2553 break;
2557 /* Don't free first station/bridge/tunnel if we are on it. */
2558 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);
2560 free_tile = true;
2564 static const byte _initial_tile_subcoord[6][4][3] = {
2565 {{ 15, 8, 1 }, { 0, 0, 0 }, { 0, 8, 5 }, { 0, 0, 0 }},
2566 {{ 0, 0, 0 }, { 8, 0, 3 }, { 0, 0, 0 }, { 8, 15, 7 }},
2567 {{ 0, 0, 0 }, { 7, 0, 2 }, { 0, 7, 6 }, { 0, 0, 0 }},
2568 {{ 15, 8, 2 }, { 0, 0, 0 }, { 0, 0, 0 }, { 8, 15, 6 }},
2569 {{ 15, 7, 0 }, { 8, 0, 4 }, { 0, 0, 0 }, { 0, 0, 0 }},
2570 {{ 0, 0, 0 }, { 0, 0, 0 }, { 0, 8, 4 }, { 7, 15, 0 }},
2574 * Perform pathfinding for a train.
2576 * @param v The train
2577 * @param tile The tile the train is about to enter
2578 * @param enterdir Diagonal direction the train is coming from
2579 * @param tracks Usable tracks on the new tile
2580 * @param path_found [out] Whether a path has been found or not.
2581 * @param do_track_reservation Path reservation is requested
2582 * @param dest [out] State and destination of the requested path
2583 * @return The best track the train should follow
2585 static Track DoTrainPathfind(const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found, bool do_track_reservation, PBSTileInfo *dest)
2587 switch (_settings_game.pf.pathfinder_for_trains) {
2588 case VPF_NPF: return NPFTrainChooseTrack(v, tile, enterdir, tracks, path_found, do_track_reservation, dest);
2589 case VPF_YAPF: return YapfTrainChooseTrack(v, tile, enterdir, tracks, path_found, do_track_reservation, dest);
2591 default: NOT_REACHED();
2596 * Extend a train path as far as possible. Stops on encountering a safe tile,
2597 * another reservation or a track choice.
2598 * @param v The train.
2599 * @param origin The tile from which the reservation have to be extended
2600 * @param new_tracks [out] Tracks to choose from when encountering a choice
2601 * @param enterdir [out] The direction from which the choice tile is to be entered
2602 * @return INVALID_TILE indicates that the reservation failed.
2604 static PBSTileInfo ExtendTrainReservation(const Train *v, const PBSTileInfo &origin, TrackBits *new_tracks, DiagDirection *enterdir)
2606 CFollowTrackRail ft(v);
2608 TileIndex tile = origin.tile;
2609 Trackdir cur_td = origin.trackdir;
2610 while (ft.Follow(tile, cur_td)) {
2611 if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
2612 /* Possible signal tile. */
2613 if (HasOnewaySignalBlockingTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) break;
2616 if (_settings_game.pf.forbid_90_deg) {
2617 ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
2618 if (ft.m_new_td_bits == TRACKDIR_BIT_NONE) break;
2621 /* Station, depot or waypoint are a possible target. */
2622 bool target_seen = ft.m_is_station || (IsTileType(ft.m_new_tile, MP_RAILWAY) && !IsPlainRail(ft.m_new_tile));
2623 if (target_seen || KillFirstBit(ft.m_new_td_bits) != TRACKDIR_BIT_NONE) {
2624 /* Choice found or possible target encountered.
2625 * On finding a possible target, we need to stop and let the pathfinder handle the
2626 * remaining path. This is because we don't know if this target is in one of our
2627 * orders, so we might cause pathfinding to fail later on if we find a choice.
2628 * This failure would cause a bogous call to TryReserveSafePath which might reserve
2629 * a wrong path not leading to our next destination. */
2630 if (HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(TrackdirReachesTrackdirs(ft.m_old_td)))) break;
2632 /* If we did skip some tiles, backtrack to the first skipped tile so the pathfinder
2633 * actually starts its search at the first unreserved tile. */
2634 if (ft.m_tiles_skipped != 0) ft.m_new_tile -= TileOffsByDiagDir(ft.m_exitdir) * ft.m_tiles_skipped;
2636 /* Choice found, path valid but not okay. Save info about the choice tile as well. */
2637 if (new_tracks != NULL) *new_tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
2638 if (enterdir != NULL) *enterdir = ft.m_exitdir;
2639 return PBSTileInfo(ft.m_new_tile, ft.m_old_td, false);
2642 tile = ft.m_new_tile;
2643 cur_td = FindFirstTrackdir(ft.m_new_td_bits);
2645 if (IsSafeWaitingPosition(v, tile, cur_td, true, _settings_game.pf.forbid_90_deg)) {
2646 bool wp_free = IsWaitingPositionFree(v, tile, cur_td, _settings_game.pf.forbid_90_deg);
2647 if (!(wp_free && TryReserveRailTrack(tile, TrackdirToTrack(cur_td)))) break;
2648 /* Safe position is all good, path valid and okay. */
2649 return PBSTileInfo(tile, cur_td, true);
2652 if (!TryReserveRailTrackdir(tile, cur_td)) break;
2655 if (ft.m_err == CFollowTrackRail::EC_OWNER || ft.m_err == CFollowTrackRail::EC_NO_WAY) {
2656 /* End of line, path valid and okay. */
2657 return PBSTileInfo(ft.m_old_tile, ft.m_old_td, true);
2660 /* Sorry, can't reserve path, back out. */
2661 tile = origin.tile;
2662 cur_td = origin.trackdir;
2663 TileIndex stopped = ft.m_old_tile;
2664 Trackdir stopped_td = ft.m_old_td;
2665 while (tile != stopped || cur_td != stopped_td) {
2666 if (!ft.Follow(tile, cur_td)) break;
2668 if (_settings_game.pf.forbid_90_deg) {
2669 ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
2670 assert(ft.m_new_td_bits != TRACKDIR_BIT_NONE);
2672 assert(KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE);
2674 tile = ft.m_new_tile;
2675 cur_td = FindFirstTrackdir(ft.m_new_td_bits);
2677 UnreserveRailTrackdir(tile, cur_td);
2680 /* Path invalid. */
2681 return PBSTileInfo();
2685 * Try to reserve any path to a safe tile, ignoring the vehicle's destination.
2686 * Safe tiles are tiles in front of a signal, depots and station tiles at end of line.
2688 * @param v The vehicle.
2689 * @param tile The tile the search should start from.
2690 * @param td The trackdir the search should start from.
2691 * @param override_railtype Whether all physically compatible railtypes should be followed.
2692 * @return True if a path to a safe stopping tile could be reserved.
2694 static bool TryReserveSafeTrack(const Train *v, TileIndex tile, Trackdir td, bool override_tailtype)
2696 switch (_settings_game.pf.pathfinder_for_trains) {
2697 case VPF_NPF: return NPFTrainFindNearestSafeTile(v, tile, td, override_tailtype);
2698 case VPF_YAPF: return YapfTrainFindNearestSafeTile(v, tile, td, override_tailtype);
2700 default: NOT_REACHED();
2704 /** This class will save the current order of a vehicle and restore it on destruction. */
2705 class VehicleOrderSaver {
2706 private:
2707 Train *v;
2708 Order old_order;
2709 TileIndex old_dest_tile;
2710 StationID old_last_station_visited;
2711 VehicleOrderID index;
2712 bool suppress_implicit_orders;
2714 public:
2715 VehicleOrderSaver(Train *_v) :
2716 v(_v),
2717 old_order(_v->current_order),
2718 old_dest_tile(_v->dest_tile),
2719 old_last_station_visited(_v->last_station_visited),
2720 index(_v->cur_real_order_index),
2721 suppress_implicit_orders(HasBit(_v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS))
2725 ~VehicleOrderSaver()
2727 this->v->current_order = this->old_order;
2728 this->v->dest_tile = this->old_dest_tile;
2729 this->v->last_station_visited = this->old_last_station_visited;
2730 SB(this->v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS, 1, suppress_implicit_orders ? 1: 0);
2734 * Set the current vehicle order to the next order in the order list.
2735 * @param skip_first Shall the first (i.e. active) order be skipped?
2736 * @return True if a suitable next order could be found.
2738 bool SwitchToNextOrder(bool skip_first)
2740 if (this->v->GetNumOrders() == 0) return false;
2742 if (skip_first) ++this->index;
2744 int depth = 0;
2745 bool has_manual_depot_order = (HasBit(v->vehicle_flags, VF_SHOULD_GOTO_DEPOT) || HasBit(v->vehicle_flags, VF_SHOULD_SERVICE_AT_DEPOT));
2747 do {
2748 /* Wrap around. */
2749 if (this->index >= this->v->GetNumOrders()) this->index = 0;
2751 Order *order = this->v->GetOrder(this->index);
2752 assert(order != NULL);
2754 switch (order->GetType()) {
2755 case OT_GOTO_DEPOT:
2756 /* Skip service in depot orders when the train doesn't need service. */
2757 if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !(this->v->NeedsServicing() || has_manual_depot_order)) break;
2758 FALLTHROUGH;
2759 case OT_GOTO_STATION:
2760 case OT_GOTO_WAYPOINT:
2761 this->v->current_order = *order;
2762 return UpdateOrderDest(this->v, order, 0, true);
2763 case OT_CONDITIONAL: {
2764 VehicleOrderID next = ProcessConditionalOrder(order, this->v);
2765 if (next != INVALID_VEH_ORDER_ID) {
2766 depth++;
2767 this->index = next;
2768 /* Don't increment next, so no break here. */
2769 continue;
2771 break;
2773 default:
2774 break;
2776 /* Don't increment inside the while because otherwise conditional
2777 * orders can lead to an infinite loop. */
2778 ++this->index;
2779 depth++;
2780 } while (this->index != this->v->cur_real_order_index && depth < this->v->GetNumOrders());
2782 return false;
2787 * This is called to retrieve the previous signal, as required
2788 * This is not run all the time as it is somewhat expensive and most restrictions will not test for the previous signal
2790 static TileIndex ChooseTrainTrackTraceRestrictPreviousSignalCallback(const Train *v, const void *)
2792 // scan forwards from vehicle position, for the case that train is waiting at/approaching PBS signal
2794 TileIndex tile = v->tile;
2795 Trackdir trackdir = v->GetVehicleTrackdir();
2797 CFollowTrackRail ft(v);
2799 for (;;) {
2800 if (IsTileType(tile, MP_RAILWAY) && HasSignalOnTrackdir(tile, trackdir)) {
2801 if (HasPbsSignalOnTrackdir(tile, trackdir)) {
2802 // found PBS signal
2803 return tile;
2804 } else {
2805 // wrong type of signal
2806 return INVALID_TILE;
2810 // advance to next tile
2811 if (!ft.Follow(tile, trackdir)) {
2812 // ran out of track
2813 return INVALID_TILE;
2816 if (KillFirstBit(ft.m_new_td_bits) != TRACKDIR_BIT_NONE) {
2817 // reached a junction tile
2818 return INVALID_TILE;
2821 tile = ft.m_new_tile;
2822 trackdir = FindFirstTrackdir(ft.m_new_td_bits);
2826 static bool HasLongReservePbsSignalOnTrackdir(Train* v, TileIndex tile, Trackdir trackdir)
2828 if (HasPbsSignalOnTrackdir(tile, trackdir)) {
2829 if (IsRestrictedSignal(tile)) {
2830 const TraceRestrictProgram *prog = GetExistingTraceRestrictProgram(tile, TrackdirToTrack(trackdir));
2831 if (prog && prog->actions_used_flags & TRPAUF_LONG_RESERVE) {
2832 TraceRestrictProgramResult out;
2833 prog->Execute(v, TraceRestrictProgramInput(tile, trackdir, &ChooseTrainTrackTraceRestrictPreviousSignalCallback, nullptr), out);
2834 if (out.flags & TRPRF_LONG_RESERVE) {
2835 return true;
2841 return false;
2845 * Choose a track and reserve if necessary
2847 * @param v The vehicle
2848 * @param tile The tile from which to start
2849 * @param enterdir
2850 * @param tracks
2851 * @param force_res Force a reservation to be made
2852 * @param p_got_reservation [out] If the train has a reservation
2853 * @param mark_stuck The train has to be marked as stuck when needed
2854 * @return The track the train should take.
2856 static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *p_got_reservation, bool mark_stuck)
2858 Track best_track = INVALID_TRACK;
2859 bool do_track_reservation = _settings_game.pf.reserve_paths || force_res;
2860 bool changed_signal = false;
2861 bool got_reservation = false;
2862 if (p_got_reservation != NULL) *p_got_reservation = got_reservation;
2864 assert((tracks & ~TRACK_BIT_MASK) == 0);
2866 /* Don't use tracks here as the setting to forbid 90 deg turns might have been switched between reservation and now. */
2867 TrackBits res_tracks = (TrackBits)(GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir));
2868 /* Do we have a suitable reserved track? */
2869 if (res_tracks != TRACK_BIT_NONE) return FindFirstTrack(res_tracks);
2871 /* Quick return in case only one possible track is available */
2872 if (KillFirstBit(tracks) == TRACK_BIT_NONE) {
2873 Track track = FindFirstTrack(tracks);
2874 /* We need to check for signals only here, as a junction tile can't have signals. */
2875 if (track != INVALID_TRACK && HasPbsSignalOnTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir))) {
2876 do_track_reservation = true;
2877 changed_signal = true;
2878 SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir), SIGNAL_STATE_GREEN);
2880 /* notify logic signals of the state change */
2881 SignalStateChanged(tile, TrackdirToTrack(TrackEnterdirToTrackdir(track, enterdir)), 1);
2882 } else if (!do_track_reservation) {
2883 return track;
2885 best_track = track;
2888 PBSTileInfo origin = FollowTrainReservation(v);
2889 PBSTileInfo res_dest(tile, INVALID_TRACKDIR, false);
2890 DiagDirection dest_enterdir = enterdir;
2891 if (do_track_reservation) {
2892 res_dest = ExtendTrainReservation(v, origin, &tracks, &dest_enterdir);
2893 if (res_dest.tile == INVALID_TILE) {
2894 /* Reservation failed? */
2895 if (mark_stuck) MarkTrainAsStuck(v);
2896 if (changed_signal) {
2897 SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(best_track, enterdir), SIGNAL_STATE_RED);
2899 /* notify logic signals of the state change */
2900 SignalStateChanged(tile, TrackdirToTrack(TrackEnterdirToTrackdir(best_track, enterdir)), 1);
2902 return FindFirstTrack(tracks);
2905 if (res_dest.okay) {
2906 CFollowTrackRail ft(v);
2907 if (ft.Follow(res_dest.tile, res_dest.trackdir)) {
2908 Trackdir new_td = FindFirstTrackdir(ft.m_new_td_bits);
2910 if (!HasLongReservePbsSignalOnTrackdir(v, ft.m_new_tile, new_td)) {
2911 /* Got a valid reservation that ends at a safe target, quick exit. */
2912 if (p_got_reservation != NULL) *p_got_reservation = true;
2913 if (changed_signal) MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
2914 TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
2915 return best_track;
2920 /* Check if the train needs service here, so it has a chance to always find a depot.
2921 * Also check if the current order is a service order so we don't reserve a path to
2922 * the destination but instead to the next one if service isn't needed. */
2923 CheckIfTrainNeedsService(v);
2924 if (v->current_order.IsType(OT_DUMMY) || v->current_order.IsType(OT_CONDITIONAL) || v->current_order.IsType(OT_GOTO_DEPOT)) ProcessOrders(v);
2927 /* Save the current train order. The destructor will restore the old order on function exit. */
2928 VehicleOrderSaver orders(v);
2930 /* If the current tile is the destination of the current order and
2931 * a reservation was requested, advance to the next order.
2932 * Don't advance on a depot order as depots are always safe end points
2933 * for a path and no look-ahead is necessary. This also avoids a
2934 * problem with depot orders not part of the order list when the
2935 * order list itself is empty. */
2936 if (v->current_order.IsType(OT_LEAVESTATION)) {
2937 orders.SwitchToNextOrder(false);
2938 } else if (v->current_order.IsType(OT_LOADING) || (!v->current_order.IsType(OT_GOTO_DEPOT) && (
2939 v->current_order.IsType(OT_GOTO_STATION) ?
2940 IsRailStationTile(v->tile) && v->current_order.GetDestination() == GetStationIndex(v->tile) :
2941 v->tile == v->dest_tile))) {
2942 orders.SwitchToNextOrder(true);
2945 if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
2946 /* Pathfinders are able to tell that route was only 'guessed'. */
2947 bool path_found = true;
2948 TileIndex new_tile = res_dest.tile;
2950 Track next_track = DoTrainPathfind(v, new_tile, dest_enterdir, tracks, path_found, do_track_reservation, &res_dest);
2951 if (new_tile == tile) best_track = next_track;
2952 v->HandlePathfindingResult(path_found);
2955 /* No track reservation requested -> finished. */
2956 if (!do_track_reservation) return best_track;
2958 /* A path was found, but could not be reserved. */
2959 if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
2960 if (mark_stuck) MarkTrainAsStuck(v);
2961 FreeTrainTrackReservation(v, origin.tile, origin.trackdir);
2962 return best_track;
2965 /* No possible reservation target found, we are probably lost. */
2966 if (res_dest.tile == INVALID_TILE) {
2967 /* Try to find any safe destination. */
2968 PBSTileInfo path_end = FollowTrainReservation(v);
2969 if (TryReserveSafeTrack(v, path_end.tile, path_end.trackdir, false)) {
2970 TrackBits res = GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir);
2971 best_track = FindFirstTrack(res);
2972 TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
2973 // Use p_got_reservation because were going to return
2974 if (p_got_reservation != NULL) *p_got_reservation = true;
2975 if (changed_signal) MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
2976 } else {
2977 FreeTrainTrackReservation(v, origin.tile, origin.trackdir);
2978 if (mark_stuck) MarkTrainAsStuck(v);
2980 return best_track;
2983 got_reservation = true;
2985 /* Reservation target found and free, check if it is safe. */
2986 while (!IsSafeWaitingPosition(v, res_dest.tile, res_dest.trackdir, true, _settings_game.pf.forbid_90_deg)) {
2987 /* Extend reservation until we have found a safe position. */
2988 DiagDirection exitdir = TrackdirToExitdir(res_dest.trackdir);
2989 TileIndex next_tile = TileAddByDiagDir(res_dest.tile, exitdir);
2990 TrackBits reachable = TrackdirBitsToTrackBits((TrackdirBits)(GetTileTrackStatus(next_tile, TRANSPORT_RAIL, 0))) & DiagdirReachesTracks(exitdir);
2991 if (_settings_game.pf.forbid_90_deg) {
2992 reachable &= ~TrackCrossesTracks(TrackdirToTrack(res_dest.trackdir));
2995 /* Get next order with destination. */
2996 if (orders.SwitchToNextOrder(true)) {
2997 PBSTileInfo cur_dest;
2998 bool path_found;
2999 DoTrainPathfind(v, next_tile, exitdir, reachable, path_found, true, &cur_dest);
3000 if (cur_dest.tile != INVALID_TILE) {
3001 res_dest = cur_dest;
3002 if (res_dest.okay) continue;
3003 /* Path found, but could not be reserved. */
3004 FreeTrainTrackReservation(v, origin.tile, origin.trackdir);
3005 if (mark_stuck) MarkTrainAsStuck(v);
3006 got_reservation = false;
3007 changed_signal = false;
3008 break;
3011 /* No order or no safe position found, try any position. */
3012 if (!TryReserveSafeTrack(v, res_dest.tile, res_dest.trackdir, true)) {
3013 FreeTrainTrackReservation(v, origin.tile, origin.trackdir);
3014 if (mark_stuck) MarkTrainAsStuck(v);
3015 got_reservation = false;
3016 changed_signal = false;
3018 break;
3021 if (got_reservation) {
3022 CFollowTrackRail ft(v);
3023 if (ft.Follow(res_dest.tile, res_dest.trackdir)) {
3024 Trackdir new_td = FindFirstTrackdir(ft.m_new_td_bits);
3026 if (HasLongReservePbsSignalOnTrackdir(v, ft.m_new_tile, new_td)) {
3027 // We reserved up to a LR signal, reserve past it as well. recursion
3028 ChooseTrainTrack(v, ft.m_new_tile, ft.m_exitdir, TrackdirBitsToTrackBits(ft.m_new_td_bits), force_res, NULL, mark_stuck);
3033 TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
3035 if (changed_signal) MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
3036 if (p_got_reservation != NULL) *p_got_reservation = got_reservation;
3038 return best_track;
3042 * Try to reserve a path to a safe position.
3044 * @param v The vehicle
3045 * @param mark_as_stuck Should the train be marked as stuck on a failed reservation?
3046 * @param first_tile_okay True if no path should be reserved if the current tile is a safe position.
3047 * @return True if a path could be reserved.
3049 bool TryPathReserve(Train *v, bool mark_as_stuck, bool first_tile_okay)
3051 assert(v->IsFrontEngine());
3053 /* We have to handle depots specially as the track follower won't look
3054 * at the depot tile itself but starts from the next tile. If we are still
3055 * inside the depot, a depot reservation can never be ours. */
3056 if (v->track == TRACK_BIT_DEPOT) {
3057 if (HasDepotReservation(v->tile)) {
3058 if (mark_as_stuck) MarkTrainAsStuck(v);
3059 return false;
3060 } else {
3061 /* Depot not reserved, but the next tile might be. */
3062 TileIndex next_tile = TileAddByDiagDir(v->tile, GetRailDepotDirection(v->tile));
3063 if (HasReservedTracks(next_tile, DiagdirReachesTracks(GetRailDepotDirection(v->tile)))) return false;
3067 if (IsTileType(v->tile, MP_TUNNELBRIDGE) && IsTunnelBridgeSignalSimulationExit(v->tile) &&
3068 DiagDirToDiagTrackBits(GetTunnelBridgeDirection(v->tile)) == v->track) {
3069 // prevent any attempt to reserve the wrong way onto a tunnel/bridge exit
3070 return false;
3073 Vehicle *other_train = NULL;
3074 PBSTileInfo origin = FollowTrainReservation(v, &other_train);
3075 /* The path we are driving on is already blocked by some other train.
3076 * This can only happen in certain situations when mixing path and
3077 * block signals or when changing tracks and/or signals.
3078 * Exit here as doing any further reservations will probably just
3079 * make matters worse. */
3080 if (other_train != NULL && other_train->index != v->index) {
3081 if (mark_as_stuck) MarkTrainAsStuck(v);
3082 return false;
3084 /* If we have a reserved path and the path ends at a safe tile, we are finished already. */
3085 if (origin.okay && (v->tile != origin.tile || first_tile_okay)) {
3086 /* Can't be stuck then. */
3087 if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
3088 ClrBit(v->flags, VRF_TRAIN_STUCK);
3089 return true;
3092 /* If we are in a depot, tentatively reserve the depot. */
3093 if (v->track == TRACK_BIT_DEPOT && v->tile == origin.tile) {
3094 SetDepotReservation(v->tile, true);
3095 if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile, ZOOM_LVL_DRAW_MAP);
3098 DiagDirection exitdir = TrackdirToExitdir(origin.trackdir);
3099 TileIndex new_tile = TileAddByDiagDir(origin.tile, exitdir);
3100 TrackBits reachable = TrackdirBitsToTrackBits(TrackStatusToTrackdirBits(GetTileTrackStatus(new_tile, TRANSPORT_RAIL, 0)) & DiagdirReachesTrackdirs(exitdir));
3102 if (_settings_game.pf.forbid_90_deg) reachable &= ~TrackCrossesTracks(TrackdirToTrack(origin.trackdir));
3104 bool res_made = false;
3105 ChooseTrainTrack(v, new_tile, exitdir, reachable, true, &res_made, mark_as_stuck);
3107 if (!res_made) {
3108 /* Free the depot reservation as well. */
3109 if (v->track == TRACK_BIT_DEPOT && v->tile == origin.tile) SetDepotReservation(v->tile, false);
3110 return false;
3113 if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
3114 v->wait_counter = 0;
3115 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
3117 ClrBit(v->flags, VRF_TRAIN_STUCK);
3118 return true;
3122 static bool CheckReverseTrain(const Train *v)
3124 if (_settings_game.difficulty.line_reverse_mode != 0 ||
3125 v->track == TRACK_BIT_DEPOT || v->track == TRACK_BIT_WORMHOLE ||
3126 !(v->direction & 1)) {
3127 return false;
3130 assert(v->track != TRACK_BIT_NONE);
3132 switch (_settings_game.pf.pathfinder_for_trains) {
3133 case VPF_NPF: return NPFTrainCheckReverse(v);
3134 case VPF_YAPF: return YapfTrainCheckReverse(v);
3136 default: NOT_REACHED();
3141 * Get the location of the next station to visit.
3142 * @param station Next station to visit.
3143 * @return Location of the new station.
3145 TileIndex Train::GetOrderStationLocation(StationID station)
3147 if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
3149 const Station *st = Station::Get(station);
3150 if (!(st->facilities & FACIL_TRAIN)) {
3151 /* The destination station has no trainstation tiles. */
3152 this->IncrementRealOrderIndex();
3153 return 0;
3156 return st->xy;
3159 /** Goods at the consist have changed, update the graphics, cargo, and acceleration. */
3160 void Train::MarkDirty()
3162 Train *v = this;
3163 do {
3164 v->colourmap = PAL_NONE;
3165 v->UpdateViewport(true, false);
3166 } while ((v = v->Next()) != NULL);
3168 /* need to update acceleration and cached values since the goods on the train changed. */
3169 this->CargoChanged();
3170 this->UpdateAcceleration();
3174 * This function looks at the vehicle and updates its speed (cur_speed
3175 * and subspeed) variables. Furthermore, it returns the distance that
3176 * the train can drive this tick. #Vehicle::GetAdvanceDistance() determines
3177 * the distance to drive before moving a step on the map.
3178 * @return distance to drive.
3180 int Train::UpdateSpeed()
3182 switch (_settings_game.vehicle.train_acceleration_model) {
3183 default: NOT_REACHED();
3184 case AM_ORIGINAL:
3185 return this->DoUpdateSpeed(this->acceleration * (this->GetAccelerationStatus() == AS_BRAKE ? -4 : 2), 0, this->GetCurrentMaxSpeed());
3187 case AM_REALISTIC:
3188 return this->DoUpdateSpeed(this->GetAcceleration(), this->GetAccelerationStatus() == AS_BRAKE ? 0 : 2, this->GetCurrentMaxSpeed());
3193 * Trains enters a station, send out a news item if it is the first train, and start loading.
3194 * @param v Train that entered the station.
3195 * @param station Station visited.
3197 static void TrainEnterStation(Train *v, StationID station)
3199 v->last_station_visited = station;
3201 /* check if a train ever visited this station before */
3202 Station *st = Station::Get(station);
3203 if (!(st->had_vehicle_of_type & HVOT_TRAIN)) {
3204 st->had_vehicle_of_type |= HVOT_TRAIN;
3205 SetDParam(0, st->index);
3206 AddVehicleNewsItem(
3207 STR_NEWS_FIRST_TRAIN_ARRIVAL,
3208 v->owner == _local_company ? NT_ARRIVAL_COMPANY : NT_ARRIVAL_OTHER,
3209 v->index,
3210 st->index
3212 AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
3213 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
3216 v->force_proceed = TFP_NONE;
3217 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
3219 v->BeginLoading();
3221 TriggerStationRandomisation(st, v->tile, SRT_TRAIN_ARRIVES);
3222 TriggerStationAnimation(st, v->tile, SAT_TRAIN_ARRIVES);
3225 /* Check if the vehicle is compatible with the specified tile */
3226 static inline bool CheckCompatibleRail(const Train *v, TileIndex tile)
3228 return IsTileOwner(tile, v->owner) &&
3229 (!v->IsFrontEngine() || HasBit(v->compatible_railtypes, GetRailType(tile)));
3232 /** Data structure for storing engine speed changes of an acceleration type. */
3233 struct AccelerationSlowdownParams {
3234 byte small_turn; ///< Speed change due to a small turn.
3235 byte large_turn; ///< Speed change due to a large turn.
3236 byte z_up; ///< Fraction to remove when moving up.
3237 byte z_down; ///< Fraction to add when moving down.
3240 /** Speed update fractions for each acceleration type. */
3241 static const AccelerationSlowdownParams _accel_slowdown[] = {
3242 /* normal accel */
3243 {256 / 4, 256 / 2, 256 / 4, 2}, ///< normal
3244 {256 / 4, 256 / 2, 256 / 4, 2}, ///< monorail
3245 {0, 256 / 2, 256 / 4, 2}, ///< maglev
3249 * Modify the speed of the vehicle due to a change in altitude.
3250 * @param v %Train to update.
3251 * @param old_z Previous height.
3253 static inline void AffectSpeedByZChange(Train *v, int old_z)
3255 if (old_z == v->z_pos || _settings_game.vehicle.train_acceleration_model != AM_ORIGINAL) return;
3257 const AccelerationSlowdownParams *asp = &_accel_slowdown[GetRailTypeInfo(v->railtype)->acceleration_type];
3259 if (old_z < v->z_pos) {
3260 v->cur_speed -= (v->cur_speed * asp->z_up >> 8);
3261 } else {
3262 uint16 spd = v->cur_speed + asp->z_down;
3263 if (spd <= v->gcache.cached_max_track_speed) v->cur_speed = spd;
3267 enum TrainMovedChangeSignalEnum {
3268 CHANGED_NOTHING, ///< No special signals were changed
3269 CHANGED_NORMAL_TO_PBS_BLOCK, ///< A PBS block with a non-PBS signal facing us
3270 CHANGED_LR_PBS ///< A long reserve PBS signal
3273 static TrainMovedChangeSignalEnum TrainMovedChangeSignal(Train* v, TileIndex tile, DiagDirection dir)
3275 if (IsTileType(tile, MP_RAILWAY) &&
3276 GetRailTileType(tile) == RAIL_TILE_SIGNALS) {
3277 TrackdirBits tracks = TrackBitsToTrackdirBits(GetTrackBits(tile)) & DiagdirReachesTrackdirs(dir);
3278 Trackdir trackdir = FindFirstTrackdir(tracks);
3279 if (UpdateSignalsOnSegment(tile, TrackdirToExitdir(trackdir), GetTileOwner(tile)) == SIGSEG_PBS && HasSignalOnTrackdir(tile, trackdir)) {
3280 /* A PBS block with a non-PBS signal facing us? */
3281 if (!IsPbsSignal(GetSignalType(tile, TrackdirToTrack(trackdir)))) return CHANGED_NORMAL_TO_PBS_BLOCK;
3283 if (HasLongReservePbsSignalOnTrackdir(v, tile, trackdir)) return CHANGED_LR_PBS;
3287 if (IsTileType(tile, MP_TUNNELBRIDGE) && IsTunnelBridgeSignalSimulationExit(tile) && GetTunnelBridgeDirection(tile) == ReverseDiagDir(dir)) {
3288 if (UpdateSignalsOnSegment(tile, dir, GetTileOwner(tile)) == SIGSEG_PBS) {
3289 return CHANGED_NORMAL_TO_PBS_BLOCK;
3293 return CHANGED_NOTHING;
3296 /** Tries to reserve track under whole train consist. */
3297 void Train::ReserveTrackUnderConsist() const
3299 for (const Train *u = this; u != NULL; u = u->Next()) {
3300 switch (u->track) {
3301 case TRACK_BIT_WORMHOLE:
3302 TryReserveRailTrack(u->tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(u->tile)));
3303 break;
3304 case TRACK_BIT_DEPOT:
3305 break;
3306 default:
3307 TryReserveRailTrack(u->tile, TrackBitsToTrack(u->track));
3308 break;
3314 * The train vehicle crashed!
3315 * Update its status and other parts around it.
3316 * @param flooded Crash was caused by flooding.
3317 * @return Number of people killed.
3319 uint Train::Crash(bool flooded)
3321 uint pass = 0;
3322 if (this->IsFrontEngine()) {
3323 pass += 2; // driver
3325 /* Remove the reserved path in front of the train if it is not stuck.
3326 * Also clear all reserved tracks the train is currently on. */
3327 if (!HasBit(this->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(this);
3328 for (const Train *v = this; v != NULL; v = v->Next()) {
3329 ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
3330 if (IsTileType(v->tile, MP_TUNNELBRIDGE)) {
3331 /* ClearPathReservation will not free the wormhole exit
3332 * if the train has just entered the wormhole. */
3333 UnreserveBridgeTunnelTile(GetOtherTunnelBridgeEnd(v->tile));
3337 /* we may need to update crossing we were approaching,
3338 * but must be updated after the train has been marked crashed */
3339 TileIndex crossing = TrainApproachingCrossingTile(this);
3340 if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
3342 /* Remove the loading indicators (if any) */
3343 HideFillingPercent(&this->fill_percent_te_id);
3346 pass += this->GroundVehicleBase::Crash(flooded);
3348 this->crash_anim_pos = flooded ? 4000 : 1; // max 4440, disappear pretty fast when flooded
3349 return pass;
3353 * Marks train as crashed and creates an AI event.
3354 * Doesn't do anything if the train is crashed already.
3355 * @param v first vehicle of chain
3356 * @return number of victims (including 2 drivers; zero if train was already crashed)
3358 static uint TrainCrashed(Train *v)
3360 uint num = 0;
3362 /* do not crash train twice */
3363 if (!(v->vehstatus & VS_CRASHED)) {
3364 num = v->Crash();
3365 AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
3366 Game::NewEvent(new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
3369 /* Try to re-reserve track under already crashed train too.
3370 * Crash() clears the reservation! */
3371 v->ReserveTrackUnderConsist();
3373 return num;
3376 /** Temporary data storage for testing collisions. */
3377 struct TrainCollideChecker {
3378 Train *v; ///< %Vehicle we are testing for collision.
3379 uint num; ///< Total number of victims if train collided.
3383 * Collision test function.
3384 * @param v %Train vehicle to test collision with.
3385 * @param data %Train being examined.
3386 * @return \c NULL (always continue search)
3388 static Vehicle *FindTrainCollideEnum(Vehicle *v, void *data)
3390 TrainCollideChecker *tcc = (TrainCollideChecker*)data;
3392 /* not a train or in depot */
3393 if (v->type != VEH_TRAIN || Train::From(v)->track == TRACK_BIT_DEPOT) return NULL;
3395 /* do not crash into trains of another company. */
3396 if (v->owner != tcc->v->owner) return NULL;
3398 /* get first vehicle now to make most usual checks faster */
3399 Train *coll = Train::From(v)->First();
3401 /* can't collide with own wagons */
3402 if (coll == tcc->v) return NULL;
3404 int x_diff = v->x_pos - tcc->v->x_pos;
3405 int y_diff = v->y_pos - tcc->v->y_pos;
3407 /* Do fast calculation to check whether trains are not in close vicinity
3408 * and quickly reject trains distant enough for any collision.
3409 * Differences are shifted by 7, mapping range [-7 .. 8] into [0 .. 15]
3410 * Differences are then ORed and then we check for any higher bits */
3411 uint hash = (y_diff + 7) | (x_diff + 7);
3412 if (hash & ~15) return NULL;
3414 /* Slower check using multiplication */
3415 int min_diff = (Train::From(v)->gcache.cached_veh_length + 1) / 2 + (tcc->v->gcache.cached_veh_length + 1) / 2 - 1;
3416 if (x_diff * x_diff + y_diff * y_diff >= min_diff * min_diff) return NULL;
3418 /* Happens when there is a train under bridge next to bridge head */
3419 if (abs(v->z_pos - tcc->v->z_pos) > 5) return NULL;
3421 /* crash both trains */
3422 tcc->num += TrainCrashed(tcc->v);
3423 tcc->num += TrainCrashed(coll);
3425 return NULL; // continue searching
3429 * Checks whether the specified train has a collision with another vehicle. If
3430 * so, destroys this vehicle, and the other vehicle if its subtype has TS_Front.
3431 * Reports the incident in a flashy news item, modifies station ratings and
3432 * plays a sound.
3433 * @param v %Train to test.
3435 static bool CheckTrainCollision(Train *v)
3437 /* can't collide in depot */
3438 if (v->track == TRACK_BIT_DEPOT) return false;
3440 assert(v->track == TRACK_BIT_WORMHOLE || TileVirtXY(v->x_pos, v->y_pos) == v->tile);
3442 TrainCollideChecker tcc;
3443 tcc.v = v;
3444 tcc.num = 0;
3446 /* find colliding vehicles */
3447 if (v->track == TRACK_BIT_WORMHOLE) {
3448 FindVehicleOnPos(v->tile, &tcc, FindTrainCollideEnum);
3449 FindVehicleOnPos(GetOtherTunnelBridgeEnd(v->tile), &tcc, FindTrainCollideEnum);
3450 } else {
3451 FindVehicleOnPosXY(v->x_pos, v->y_pos, &tcc, FindTrainCollideEnum);
3454 /* any dead -> no crash */
3455 if (tcc.num == 0) return false;
3457 SetDParam(0, tcc.num);
3458 AddVehicleNewsItem(STR_NEWS_TRAIN_CRASH, NT_ACCIDENT, v->index);
3460 ModifyStationRatingAround(v->tile, v->owner, -160, 30);
3461 if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_13_BIG_CRASH, v);
3462 return true;
3465 static Vehicle *CheckTrainAtSignal(Vehicle *v, void *data)
3467 if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return NULL;
3469 Train *t = Train::From(v);
3470 DiagDirection exitdir = *(DiagDirection *)data;
3472 /* not front engine of a train, inside wormhole or depot, crashed */
3473 if (!t->IsFrontEngine() || !(t->track & TRACK_BIT_MASK)) return NULL;
3475 if (t->cur_speed > 5 || TrainExitDir(t->direction, t->track) != exitdir) return NULL;
3477 return t;
3480 /** Find train in front and keep distance between trains in tunnel/bridge. */
3481 static Vehicle *FindSpaceBetweenTrainsEnum(Vehicle *v, void *data)
3483 /* Don't look at wagons between front and back of train. */
3484 if (v->type != VEH_TRAIN || (v->Previous() != NULL && v->Next() != NULL)) return NULL;
3486 const Vehicle *u = (Vehicle*)data;
3487 int32 a, b = 0;
3489 switch (u->direction) {
3490 default: NOT_REACHED();
3491 case DIR_NE: a = u->x_pos; b = v->x_pos; break;
3492 case DIR_SE: a = v->y_pos; b = u->y_pos; break;
3493 case DIR_SW: a = v->x_pos; b = u->x_pos; break;
3494 case DIR_NW: a = u->y_pos; b = v->y_pos; break;
3497 if (a > b && a <= (b + (int)(Train::From(u)->wait_counter)) + (int)(TILE_SIZE)) return v;
3498 return NULL;
3501 static bool IsToCloseBehindTrain(Vehicle *v, TileIndex tile, bool check_endtile)
3503 Train *t = (Train *)v;
3505 if (t->force_proceed != 0) return false;
3507 if (HasVehicleOnPos(t->tile, v, &FindSpaceBetweenTrainsEnum)) {
3508 /* Revert train if not going with tunnel direction. */
3509 if (DirToDiagDir(t->direction) != GetTunnelBridgeDirection(t->tile)) {
3510 v->cur_speed = 0;
3511 ToggleBit(t->flags, VRF_REVERSING);
3513 return true;
3515 /* Cover blind spot at end of tunnel bridge. */
3516 if (check_endtile){
3517 if (HasVehicleOnPos(GetOtherTunnelBridgeEnd(t->tile), v, &FindSpaceBetweenTrainsEnum)) {
3518 /* Revert train if not going with tunnel direction. */
3519 if (DirToDiagDir(t->direction) != GetTunnelBridgeDirection(t->tile)) {
3520 v->cur_speed = 0;
3521 ToggleBit(t->flags, VRF_REVERSING);
3523 return true;
3527 return false;
3530 static bool CheckTrainStayInWormHolePathReserve(Train *t, TileIndex tile)
3532 TileIndex veh_orig = t->tile;
3533 t->tile = tile;
3534 CFollowTrackRail ft(GetTileOwner(tile), GetRailTypeInfo(t->railtype)->compatible_railtypes);
3535 if (ft.Follow(tile, DiagDirToDiagTrackdir(ReverseDiagDir(GetTunnelBridgeDirection(tile))))) {
3536 TrackdirBits reserved = ft.m_new_td_bits & TrackBitsToTrackdirBits(GetReservedTrackbits(ft.m_new_tile));
3537 if (reserved == TRACKDIR_BIT_NONE) {
3538 /* next tile is not reserved, so reserve the exit tile */
3539 SetTunnelBridgeReservation(tile, true);
3542 bool ok = TryPathReserve(t);
3543 t->tile = veh_orig;
3544 return ok;
3547 /** Simulate signals in tunnel - bridge. */
3548 static bool CheckTrainStayInWormHole(Train *t, TileIndex tile)
3550 if (t->force_proceed != 0) return false;
3552 /* When not exit reverse train. */
3553 if (!IsTunnelBridgeSignalSimulationExit(tile)) {
3554 t->cur_speed = 0;
3555 ToggleBit(t->flags, VRF_REVERSING);
3556 return true;
3558 SigSegState seg_state = (_settings_game.pf.reserve_paths || IsTunnelBridgePBS(tile)) ? SIGSEG_PBS : UpdateSignalsOnSegment(tile, INVALID_DIAGDIR, t->owner);
3559 if (seg_state != SIGSEG_PBS) {
3560 CFollowTrackRail ft(GetTileOwner(tile), GetRailTypeInfo(t->railtype)->compatible_railtypes);
3561 if (ft.Follow(tile, DiagDirToDiagTrackdir(ReverseDiagDir(GetTunnelBridgeDirection(tile))))) {
3562 if (ft.m_new_td_bits != TRACKDIR_BIT_NONE && KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
3563 Trackdir td = FindFirstTrackdir(ft.m_new_td_bits);
3564 if (HasPbsSignalOnTrackdir(ft.m_new_tile, td)) {
3565 /* immediately after the exit, there is a PBS signal, switch to PBS mode */
3566 seg_state = SIGSEG_PBS;
3571 if (seg_state == SIGSEG_FULL || (seg_state == SIGSEG_PBS && !CheckTrainStayInWormHolePathReserve(t, tile))) {
3572 t->vehstatus |= VS_TRAIN_SLOWING;
3573 t->cur_speed = 0;
3574 return true;
3577 return false;
3580 static void HandleSignalBehindTrain(Train *v, int signal_number)
3582 TileIndex tile;
3583 switch (v->direction) {
3584 default: NOT_REACHED();
3585 case DIR_NE: tile = TileVirtXY(v->x_pos + (TILE_SIZE * _settings_game.construction.simulated_wormhole_signals), v->y_pos); break;
3586 case DIR_SE: tile = TileVirtXY(v->x_pos, v->y_pos - (TILE_SIZE * _settings_game.construction.simulated_wormhole_signals) ); break;
3587 case DIR_SW: tile = TileVirtXY(v->x_pos - (TILE_SIZE * _settings_game.construction.simulated_wormhole_signals), v->y_pos); break;
3588 case DIR_NW: tile = TileVirtXY(v->x_pos, v->y_pos + (TILE_SIZE * _settings_game.construction.simulated_wormhole_signals)); break;
3591 if(tile == v->tile) {
3592 /* Flip signal on ramp. */
3593 if (IsTunnelBridgeSignalSimulationEntrance(tile) && GetTunnelBridgeSignalState(tile) == SIGNAL_STATE_RED) {
3594 SetTunnelBridgeSignalState(tile, SIGNAL_STATE_GREEN);
3595 MarkTileDirtyByTile(tile);
3597 } else if (IsBridge(v->tile) && signal_number >= 0) {
3598 SetBridgeEntranceSimulatedSignalState(v->tile, signal_number, SIGNAL_STATE_GREEN);
3599 MarkTileDirtyByTile(tile);
3603 static inline void IncreaseTrackUsage(TileIndex ti, Track track_piece)
3605 if (!IsTileType(ti, MP_RAILWAY))
3606 return;
3607 if (!IsPlainRailTile(ti))
3608 return;
3610 /* ignore track_piece, 1 state per tile */
3611 byte age = GetRailAge(ti);
3613 static byte train_clean_strength = 32;
3615 if (age <= train_clean_strength)
3616 age = 0;
3617 else
3618 age -= train_clean_strength;
3620 byte old_growth = GetTrackGrowthPhase(ti);
3622 SetRailAge(ti, age);
3624 /* If rounded growth amount changes, redraw */
3625 if (GetTrackGrowthPhase(ti) != old_growth)
3626 MarkTileDirtyByTile(ti);
3629 uint16 ReversingDistanceTargetSpeed(const Train *v)
3631 int target_speed;
3632 if (_settings_game.vehicle.train_acceleration_model == AM_REALISTIC) {
3633 target_speed = ((v->reverse_distance - 1) * 5) / 2;
3635 else {
3636 target_speed = (v->reverse_distance - 1) * 10 - 5;
3638 return max(0, target_speed);
3642 * Move a vehicle chain one movement stop forwards.
3643 * @param v First vehicle to move.
3644 * @param nomove Stop moving this and all following vehicles.
3645 * @param reverse Set to false to not execute the vehicle reversing. This does not change any other logic.
3646 * @return True if the vehicle could be moved forward, false otherwise.
3648 bool TrainController(Train *v, Vehicle *nomove, bool reverse)
3650 Train *first = v->First();
3651 Train *prev;
3652 bool direction_changed = false; // has direction of any part changed?
3654 if (reverse && v->reverse_distance == 1) {
3655 goto reverse_train_direction;
3658 if (v->reverse_distance > 1) {
3659 uint16 spd = ReversingDistanceTargetSpeed(v);
3660 if (spd < v->cur_speed) v->cur_speed = spd;
3663 /* For every vehicle after and including the given vehicle */
3664 for (prev = v->Previous(); v != nomove; prev = v, v = v->Next()) {
3665 DiagDirection enterdir = DIAGDIR_BEGIN;
3666 bool update_signals_crossing = false; // will we update signals or crossing state?
3668 GetNewVehiclePosResult gp = GetNewVehiclePos(v);
3669 if (v->track != TRACK_BIT_WORMHOLE) {
3670 /* Not inside tunnel */
3671 if (gp.old_tile == gp.new_tile) {
3672 /* Staying in the old tile */
3673 if (v->track == TRACK_BIT_DEPOT) {
3674 /* Inside depot */
3675 gp.x = v->x_pos;
3676 gp.y = v->y_pos;
3677 v->reverse_distance = 0;
3678 } else {
3679 /* Not inside depot */
3681 /* Reverse when we are at the end of the track already, do not move to the new position */
3682 if (v->IsFrontEngine() && !TrainCheckIfLineEnds(v, reverse)) return false;
3684 uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
3685 if (HasBit(r, VETS_CANNOT_ENTER)) {
3686 goto invalid_rail;
3688 if (HasBit(r, VETS_ENTERED_STATION)) {
3689 /* The new position is the end of the platform */
3690 TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
3693 } else {
3694 /* A new tile is about to be entered. */
3696 /* Determine what direction we're entering the new tile from */
3697 enterdir = DiagdirBetweenTiles(gp.old_tile, gp.new_tile);
3698 assert(IsValidDiagDirection(enterdir));
3700 /* Get the status of the tracks in the new tile and mask
3701 * away the bits that aren't reachable. */
3702 TrackStatus ts = GetTileTrackStatus(gp.new_tile, TRANSPORT_RAIL, 0, ReverseDiagDir(enterdir));
3703 TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(enterdir);
3705 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
3706 TrackBits red_signals = TrackdirBitsToTrackBits(TrackStatusToRedSignals(ts) & reachable_trackdirs);
3708 TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
3709 if (_settings_game.pf.forbid_90_deg && prev == NULL) {
3710 /* We allow wagons to make 90 deg turns, because forbid_90_deg
3711 * can be switched on halfway a turn */
3712 bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
3715 if (bits == TRACK_BIT_NONE)
3716 goto invalid_rail;
3718 /* Check if the new tile constrains tracks that are compatible
3719 * with the current train, if not, bail out. */
3720 if (!CheckCompatibleRail(v, gp.new_tile))
3721 goto invalid_rail;
3723 TrackBits chosen_track;
3724 if (prev == NULL) {
3725 /* Currently the locomotive is active. Determine which one of the
3726 * available tracks to choos/// e */
3727 Track chosen_track_num = ChooseTrainTrack(v, gp.new_tile, enterdir, bits, false, NULL, true);
3728 chosen_track = TrackToTrackBits(chosen_track_num);
3729 assert(chosen_track & (bits | GetReservedTrackbits(gp.new_tile)));
3731 if (v->force_proceed != TFP_NONE && IsPlainRailTile(gp.new_tile) && HasSignals(gp.new_tile)) {
3732 /* For each signal we find decrease the counter by one.
3733 * We start at two, so the first signal we pass decreases
3734 * this to one, then if we reach the next signal it is
3735 * decreased to zero and we won't pass that new signal. */
3736 Trackdir dir = FindFirstTrackdir(trackdirbits);
3737 if (HasSignalOnTrackdir(gp.new_tile, dir) ||
3738 (HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(dir)) &&
3739 GetSignalType(gp.new_tile, TrackdirToTrack(dir)) != SIGTYPE_PBS)) {
3740 /* However, we do not want to be stopped by PBS signals
3741 * entered via the back. */
3742 v->force_proceed = (v->force_proceed == TFP_SIGNAL) ? TFP_STUCK : TFP_NONE;
3743 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
3747 /* Check if it's a red signal and that force proceed is not clicked. */
3748 if ((red_signals & chosen_track) && v->force_proceed == TFP_NONE) {
3749 /* In front of a red signal */
3750 Trackdir i = FindFirstTrackdir(trackdirbits);
3752 /* Don't handle stuck trains here. */
3753 if (HasBit(v->flags, VRF_TRAIN_STUCK)) return false;
3755 if (!HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(i))) {
3756 v->cur_speed = 0;
3757 v->subspeed = 0;
3758 v->progress = 255 - 100;
3759 if (!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_oneway_signal * 20) return false;
3760 } else if (HasSignalOnTrackdir(gp.new_tile, i)) {
3761 v->cur_speed = 0;
3762 v->subspeed = 0;
3763 v->progress = 255 - 10;
3764 if (!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_twoway_signal * 73) {
3765 DiagDirection exitdir = TrackdirToExitdir(i);
3766 TileIndex o_tile = TileAddByDiagDir(gp.new_tile, exitdir);
3768 exitdir = ReverseDiagDir(exitdir);
3770 /* check if a train is waiting on the other side */
3771 if (!HasVehicleOnPos(o_tile, &exitdir, &CheckTrainAtSignal)) return false;
3775 /* If we would reverse but are currently in a PBS block and
3776 * reversing of stuck trains is disabled, don't reverse.
3777 * This does not apply if the reason for reversing is a one-way
3778 * signal blocking us, because a train would then be stuck forever. */
3779 if (!_settings_game.pf.reverse_at_signals && !HasOnewaySignalBlockingTrackdir(gp.new_tile, i) &&
3780 UpdateSignalsOnSegment(v->tile, enterdir, v->owner) == SIGSEG_PBS) {
3781 v->wait_counter = 0;
3782 return false;
3784 goto reverse_train_direction;
3785 } else {
3786 TryReserveRailTrack(gp.new_tile, TrackBitsToTrack(chosen_track), false);
3788 IncreaseTrackUsage(gp.new_tile, chosen_track_num);
3789 } else {
3790 /* The wagon is active, simply follow the prev vehicle. */
3791 if (prev->tile == gp.new_tile) {
3792 /* Choose the same track as prev */
3793 if (prev->track == TRACK_BIT_WORMHOLE) {
3794 /* Vehicles entering tunnels enter the wormhole earlier than for bridges.
3795 * However, just choose the track into the wormhole. */
3796 assert(IsTunnel(prev->tile));
3797 chosen_track = bits;
3798 } else {
3799 chosen_track = prev->track;
3801 } else {
3802 /* Choose the track that leads to the tile where prev is.
3803 * This case is active if 'prev' is already on the second next tile, when 'v' just enters the next tile.
3804 * I.e. when the tile between them has only space for a single vehicle like
3805 * 1) horizontal/vertical track tiles and
3806 * 2) some orientations of tunnel entries, where the vehicle is already inside the wormhole at 8/16 from the tile edge.
3807 * Is also the train just reversing, the wagon inside the tunnel is 'on' the tile of the opposite tunnel entry.
3809 static const TrackBits _connecting_track[DIAGDIR_END][DIAGDIR_END] = {
3810 {TRACK_BIT_X, TRACK_BIT_LOWER, TRACK_BIT_NONE, TRACK_BIT_LEFT },
3811 {TRACK_BIT_UPPER, TRACK_BIT_Y, TRACK_BIT_LEFT, TRACK_BIT_NONE },
3812 {TRACK_BIT_NONE, TRACK_BIT_RIGHT, TRACK_BIT_X, TRACK_BIT_UPPER},
3813 {TRACK_BIT_RIGHT, TRACK_BIT_NONE, TRACK_BIT_LOWER, TRACK_BIT_Y }
3815 DiagDirection exitdir = DiagdirBetweenTiles(gp.new_tile, prev->tile);
3816 assert(IsValidDiagDirection(exitdir));
3817 chosen_track = _connecting_track[enterdir][exitdir];
3819 chosen_track &= bits;
3822 /* Make sure chosen track is a valid track */
3823 assert(
3824 chosen_track == TRACK_BIT_X || chosen_track == TRACK_BIT_Y ||
3825 chosen_track == TRACK_BIT_UPPER || chosen_track == TRACK_BIT_LOWER ||
3826 chosen_track == TRACK_BIT_LEFT || chosen_track == TRACK_BIT_RIGHT);
3828 /* Update XY to reflect the entrance to the new tile, and select the direction to use */
3829 const byte *b = _initial_tile_subcoord[FIND_FIRST_BIT(chosen_track)][enterdir];
3830 gp.x = (gp.x & ~0xF) | b[0];
3831 gp.y = (gp.y & ~0xF) | b[1];
3832 Direction chosen_dir = (Direction)b[2];
3834 /* Call the landscape function and tell it that the vehicle entered the tile */
3835 uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
3836 if (HasBit(r, VETS_CANNOT_ENTER)) {
3837 goto invalid_rail;
3840 if (IsTunnelBridgeWithSignalSimulation(gp.new_tile)) {
3841 /* If red signal stop. */
3842 if (v->IsFrontEngine() && v->force_proceed == 0) {
3843 if (IsTunnelBridgeSignalSimulationEntrance(gp.new_tile) && GetTunnelBridgeSignalState(gp.new_tile) == SIGNAL_STATE_RED) {
3844 v->cur_speed = 0;
3845 v->vehstatus |= VS_TRAIN_SLOWING;
3846 return false;
3848 if (IsTunnelBridgeSignalSimulationExit(gp.new_tile)) {
3849 v->cur_speed = 0;
3850 goto invalid_rail;
3852 /* Flip signal on tunnel entrance tile red. */
3853 SetTunnelBridgeSignalState(gp.new_tile, SIGNAL_STATE_RED);
3854 MarkTileDirtyByTile(gp.new_tile);
3858 if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
3859 Track track = FindFirstTrack(chosen_track);
3860 Trackdir tdir = TrackDirectionToTrackdir(track, chosen_dir);
3861 if (v->IsFrontEngine() && HasPbsSignalOnTrackdir(gp.new_tile, tdir)) {
3862 SetSignalStateByTrackdir(gp.new_tile, tdir, SIGNAL_STATE_RED);
3863 MarkTileDirtyByTile(gp.new_tile);
3865 /* notify logic signals of the state change */
3866 SignalStateChanged(gp.new_tile, TrackdirToTrack(tdir), 1);
3869 /* Clear any track reservation when the last vehicle leaves the tile */
3870 if (v->Next() == NULL) ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
3872 v->tile = gp.new_tile;
3874 if (GetTileRailType(gp.new_tile) != GetTileRailType(gp.old_tile)) {
3875 v->First()->ConsistChanged(CCF_TRACK);
3878 v->track = chosen_track;
3879 assert(v->track);
3882 /* We need to update signal status, but after the vehicle position hash
3883 * has been updated by UpdateInclination() */
3884 update_signals_crossing = true;
3886 if (chosen_dir != v->direction) {
3887 if (prev == NULL && _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) {
3888 const AccelerationSlowdownParams *asp = &_accel_slowdown[GetRailTypeInfo(v->railtype)->acceleration_type];
3889 DirDiff diff = DirDifference(v->direction, chosen_dir);
3890 v->cur_speed -= (diff == DIRDIFF_45RIGHT || diff == DIRDIFF_45LEFT ? asp->small_turn : asp->large_turn) * v->cur_speed >> 8;
3892 direction_changed = true;
3893 v->direction = chosen_dir;
3896 if (v->IsFrontEngine()) {
3897 v->wait_counter = 0;
3899 /* If we are approaching a crossing that is reserved, play the sound now. */
3900 TileIndex crossing = TrainApproachingCrossingTile(v);
3902 if (crossing != INVALID_TILE)
3904 RailTypeLabel railTypeLabel = GetRailTypeInfo(GetTileRailType(crossing))->label;
3905 bool is_no_sound_rail_type = (railTypeLabel == _planning_tracks_label || railTypeLabel == _pipeline_tracks_label || railTypeLabel == _wires_tracks_label);
3907 if (HasCrossingReservation(crossing) && _settings_client.sound.ambient && !is_no_sound_rail_type)
3908 SndPlayTileFx(SND_0E_LEVEL_CROSSING, crossing);
3911 /* Always try to extend the reservation when entering a tile. */
3912 CheckNextTrainTile(v);
3915 if (HasBit(r, VETS_ENTERED_STATION)) {
3916 /* The new position is the location where we want to stop */
3917 TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
3920 } else {
3921 /* Handle signal simulation on tunnel/bridge. */
3922 TileIndex old_tile = TileVirtXY(v->x_pos, v->y_pos);
3923 if (old_tile != gp.new_tile && IsTunnelBridgeWithSignalSimulation(v->tile) && (v->IsFrontEngine() || v->Next() == NULL)) {
3924 if (old_tile == v->tile) {
3925 if (v->IsFrontEngine() && v->force_proceed == 0 && IsTunnelBridgeSignalSimulationExit(v->tile))
3926 goto invalid_rail;
3927 /* Entered wormhole set counters. */
3928 v->wait_counter = (TILE_SIZE * _settings_game.construction.simulated_wormhole_signals) - TILE_SIZE;
3929 v->load_unload_ticks = 0;
3932 uint distance = v->wait_counter;
3933 bool leaving = false;
3934 if (distance == 0) v->wait_counter = (TILE_SIZE * _settings_game.construction.simulated_wormhole_signals);
3936 if (v->IsFrontEngine()) {
3937 /* Check if track in front is free and see if we can leave wormhole. */
3938 int z = GetSlopePixelZ(gp.x, gp.y) - v->z_pos;
3939 if (IsTileType(gp.new_tile, MP_TUNNELBRIDGE) && !(abs(z) > 2)) {
3940 if (CheckTrainStayInWormHole(v, gp.new_tile)) return false;
3941 leaving = true;
3942 } else {
3943 if (IsToCloseBehindTrain(v, gp.new_tile, distance == 0)) {
3944 if (distance == 0) v->wait_counter = 0;
3945 v->cur_speed = 0;
3946 v->vehstatus |= VS_TRAIN_SLOWING;
3947 return false;
3949 /* flip signal in front to red on bridges*/
3950 if (distance == 0 && IsBridge(v->tile)) {
3951 SetBridgeEntranceSimulatedSignalState(v->tile, v->load_unload_ticks, SIGNAL_STATE_RED);
3952 MarkTileDirtyByTile(gp.new_tile);
3956 if (v->Next() == NULL) {
3957 if (v->load_unload_ticks > 0 && distance == (TILE_SIZE * _settings_game.construction.simulated_wormhole_signals) - TILE_SIZE) HandleSignalBehindTrain(v, v->load_unload_ticks - 2);
3958 if (old_tile == v->tile) {
3959 /* We left ramp into wormhole. */
3960 v->x_pos = gp.x;
3961 v->y_pos = gp.y;
3962 UpdateSignalsOnSegment(old_tile, INVALID_DIAGDIR, v->owner);
3963 UnreserveBridgeTunnelTile(old_tile);
3966 if (distance == 0) v->load_unload_ticks++;
3967 v->wait_counter -= TILE_SIZE;
3969 if (leaving) { // Reset counters.
3970 v->force_proceed = 0;
3971 v->wait_counter = 0;
3972 v->load_unload_ticks = 0;
3973 v->x_pos = gp.x;
3974 v->y_pos = gp.y;
3975 v->UpdatePosition();
3976 v->UpdateViewport(false, false);
3977 UpdateSignalsOnSegment(gp.new_tile, INVALID_DIAGDIR, v->owner);
3978 continue;
3982 if (IsTileType(gp.new_tile, MP_TUNNELBRIDGE) && HasBit(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y), VETS_ENTERED_WORMHOLE)) {
3983 /* Perform look-ahead on tunnel exit. */
3984 if (v->IsFrontEngine()) {
3985 TryReserveRailTrack(gp.new_tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(gp.new_tile)));
3986 CheckNextTrainTile(v);
3988 /* Prevent v->UpdateInclination() being called with wrong parameters.
3989 * This could happen if the train was reversed inside the tunnel/bridge. */
3990 if (gp.old_tile == gp.new_tile) {
3991 gp.old_tile = GetOtherTunnelBridgeEnd(gp.old_tile);
3993 } else {
3994 v->x_pos = gp.x;
3995 v->y_pos = gp.y;
3996 v->UpdatePosition();
3997 if (v->IsDrawn()) v->Vehicle::UpdateViewport(true);
3998 continue;
4002 /* update image of train, as well as delta XY */
4003 v->UpdateDeltaXY(v->direction);
4005 v->x_pos = gp.x;
4006 v->y_pos = gp.y;
4007 v->UpdatePosition();
4008 if (v->reverse_distance > 1) {
4009 v->reverse_distance--;
4012 /* update the Z position of the vehicle */
4013 int old_z = v->UpdateInclination(gp.new_tile != gp.old_tile, false);
4015 if (prev == NULL) {
4016 /* This is the first vehicle in the train */
4017 AffectSpeedByZChange(v, old_z);
4020 if (update_signals_crossing) {
4021 if (v->IsFrontEngine()) {
4022 switch(TrainMovedChangeSignal(v, gp.new_tile, enterdir)) {
4023 case CHANGED_NORMAL_TO_PBS_BLOCK:
4024 /* We are entering a block with PBS signals right now, but
4025 * not through a PBS signal. This means we don't have a
4026 * reservation right now. As a conventional signal will only
4027 * ever be green if no other train is in the block, getting
4028 * a path should always be possible. If the player built
4029 * such a strange network that it is not possible, the train
4030 * will be marked as stuck and the player has to deal with
4031 * the problem. */
4032 if ((!HasReservedTracks(gp.new_tile, v->track) &&
4033 !TryReserveRailTrack(gp.new_tile, FindFirstTrack(v->track))) ||
4034 !TryPathReserve(v)) {
4035 MarkTrainAsStuck(v);
4038 break;
4039 case CHANGED_LR_PBS:
4041 /* We went past a long reserve PBS signal. Try to extend the
4042 * reservation if reserving failed at another LR signal. */
4043 PBSTileInfo origin = FollowTrainReservation(v);
4044 CFollowTrackRail ft(v);
4046 if (ft.Follow(origin.tile, origin.trackdir)) {
4047 Trackdir new_td = FindFirstTrackdir(ft.m_new_td_bits);
4049 if (HasLongReservePbsSignalOnTrackdir(v, ft.m_new_tile, new_td)) {
4050 ChooseTrainTrack(v, ft.m_new_tile, ft.m_exitdir, TrackdirBitsToTrackBits(ft.m_new_td_bits), true, NULL, false);
4054 break;
4056 default: break;
4060 /* Signals can only change when the first
4061 * (above) or the last vehicle moves. */
4062 if (v->Next() == NULL) {
4063 TrainMovedChangeSignal(v, gp.old_tile, ReverseDiagDir(enterdir));
4064 if (IsLevelCrossingTile(gp.old_tile)) UpdateLevelCrossing(gp.old_tile);
4068 /* Do not check on every tick to save some computing time. */
4069 if (v->IsFrontEngine() && v->tick_counter % _settings_game.pf.path_backoff_interval == 0) CheckNextTrainTile(v);
4072 if (direction_changed) first->tcache.cached_max_curve_speed = first->GetCurveSpeedLimit();
4074 return true;
4076 invalid_rail:
4077 /* We've reached end of line?? */
4078 if (prev != NULL) error("Disconnecting train");
4080 reverse_train_direction:
4081 if (reverse) {
4082 v->wait_counter = 0;
4083 v->cur_speed = 0;
4084 v->subspeed = 0;
4085 ReverseTrainDirection(v);
4088 return false;
4092 * Collect trackbits of all crashed train vehicles on a tile
4093 * @param v Vehicle passed from Find/HasVehicleOnPos()
4094 * @param data trackdirbits for the result
4095 * @return NULL to iterate over all vehicles on the tile.
4097 static Vehicle *CollectTrackbitsFromCrashedVehiclesEnum(Vehicle *v, void *data)
4099 TrackBits *trackbits = (TrackBits *)data;
4101 if (v->type == VEH_TRAIN && (v->vehstatus & VS_CRASHED) != 0) {
4102 TrackBits train_tbits = Train::From(v)->track;
4103 if (train_tbits == TRACK_BIT_WORMHOLE) {
4104 /* Vehicle is inside a wormhole, v->track contains no useful value then. */
4105 *trackbits |= DiagDirToDiagTrackBits(GetTunnelBridgeDirection(v->tile));
4106 } else if (train_tbits != TRACK_BIT_DEPOT) {
4107 *trackbits |= train_tbits;
4111 return NULL;
4115 * Deletes/Clears the last wagon of a crashed train. It takes the engine of the
4116 * train, then goes to the last wagon and deletes that. Each call to this function
4117 * will remove the last wagon of a crashed train. If this wagon was on a crossing,
4118 * or inside a tunnel/bridge, recalculate the signals as they might need updating
4119 * @param v the Vehicle of which last wagon is to be removed
4121 static void DeleteLastWagon(Train *v)
4123 Train *first = v->First();
4125 /* Go to the last wagon and delete the link pointing there
4126 * *u is then the one-before-last wagon, and *v the last
4127 * one which will physically be removed */
4128 Train *u = v;
4129 for (; v->Next() != NULL; v = v->Next()) u = v;
4130 u->SetNext(NULL);
4132 if (first != v) {
4133 /* Recalculate cached train properties */
4134 first->ConsistChanged(CCF_ARRANGE);
4135 /* Update the depot window if the first vehicle is in depot -
4136 * if v == first, then it is updated in PreDestructor() */
4137 if (first->track == TRACK_BIT_DEPOT) {
4138 SetWindowDirty(WC_VEHICLE_DEPOT, first->tile);
4140 v->last_station_visited = first->last_station_visited; // for PreDestructor
4143 /* 'v' shouldn't be accessed after it has been deleted */
4144 TrackBits trackbits = v->track;
4145 TileIndex tile = v->tile;
4146 Owner owner = v->owner;
4148 delete v;
4149 v = NULL; // make sure nobody will try to read 'v' anymore
4151 if (trackbits == TRACK_BIT_WORMHOLE) {
4152 /* Vehicle is inside a wormhole, v->track contains no useful value then. */
4153 trackbits = DiagDirToDiagTrackBits(GetTunnelBridgeDirection(tile));
4156 Track track = TrackBitsToTrack(trackbits);
4157 if (HasReservedTracks(tile, trackbits)) {
4158 UnreserveRailTrack(tile, track);
4160 /* If there are still crashed vehicles on the tile, give the track reservation to them */
4161 TrackBits remaining_trackbits = TRACK_BIT_NONE;
4162 FindVehicleOnPos(tile, &remaining_trackbits, CollectTrackbitsFromCrashedVehiclesEnum);
4164 /* It is important that these two are the first in the loop, as reservation cannot deal with every trackbit combination */
4165 assert(TRACK_BEGIN == TRACK_X && TRACK_Y == TRACK_BEGIN + 1);
4166 Track t;
4167 FOR_EACH_SET_TRACK(t, remaining_trackbits) TryReserveRailTrack(tile, t);
4170 /* check if the wagon was on a road/rail-crossing */
4171 if (IsLevelCrossingTile(tile)) UpdateLevelCrossing(tile);
4173 /* Update signals */
4174 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
4175 UpdateSignalsOnSegment(tile, INVALID_DIAGDIR, owner);
4176 if (IsTunnelBridgeWithSignalSimulation(tile)) {
4177 TileIndex end = GetOtherTunnelBridgeEnd(tile);
4178 UpdateSignalsOnSegment(end, INVALID_DIAGDIR, owner);
4179 bool is_entrance = IsTunnelBridgeSignalSimulationEntrance(tile);
4180 TileIndex entrance = is_entrance ? tile : end;
4181 if (TunnelBridgeIsFree(tile, end, nullptr).Succeeded()) {
4182 if (IsBridge(entrance)) {
4183 SetAllBridgeEntranceSimulatedSignalsGreen(entrance);
4184 MarkBridgeDirty(entrance, ZOOM_LVL_DRAW_MAP);
4186 if (IsTunnelBridgeSignalSimulationEntrance(entrance) && GetTunnelBridgeSignalState(entrance) == SIGNAL_STATE_RED) {
4187 SetTunnelBridgeSignalState(entrance, SIGNAL_STATE_GREEN);
4188 MarkTileDirtyByTile(entrance);
4192 } else if (IsRailDepotTile(tile)) {
4193 UpdateSignalsOnSegment(tile, INVALID_DIAGDIR, owner);
4194 } else {
4195 SetSignalsOnBothDir(tile, track, owner);
4200 * Rotate all vehicles of a (crashed) train chain randomly to animate the crash.
4201 * @param v First crashed vehicle.
4203 static void ChangeTrainDirRandomly(Train *v)
4205 static const DirDiff delta[] = {
4206 DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT
4209 do {
4210 /* We don't need to twist around vehicles if they're not visible */
4211 if (!(v->vehstatus & VS_HIDDEN)) {
4212 v->direction = ChangeDir(v->direction, delta[GB(Random(), 0, 2)]);
4213 /* Refrain from updating the z position of the vehicle when on
4214 * a bridge, because UpdateInclination() will put the vehicle under
4215 * the bridge in that case */
4216 if (v->track != TRACK_BIT_WORMHOLE) {
4217 v->UpdatePosition();
4218 v->UpdateInclination(false, true);
4219 } else {
4220 v->UpdateViewport(false, true);
4223 } while ((v = v->Next()) != NULL);
4227 * Handle a crashed train.
4228 * @param v First train vehicle.
4229 * @return %Vehicle chain still exists.
4231 static bool HandleCrashedTrain(Train *v)
4233 int state = ++v->crash_anim_pos;
4235 if (state == 4 && !(v->vehstatus & VS_HIDDEN)) {
4236 CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE);
4239 uint32 r;
4240 if (state <= 200 && Chance16R(1, 7, r)) {
4241 int index = (r * 10 >> 16);
4243 Vehicle *u = v;
4244 do {
4245 if (--index < 0) {
4246 r = Random();
4248 CreateEffectVehicleRel(u,
4249 GB(r, 8, 3) + 2,
4250 GB(r, 16, 3) + 2,
4251 GB(r, 0, 3) + 5,
4252 EV_EXPLOSION_SMALL);
4253 break;
4255 } while ((u = u->Next()) != NULL);
4258 if (state <= 240 && !(v->tick_counter & 3)) ChangeTrainDirRandomly(v);
4260 if (state >= 4440 && !(v->tick_counter & 0x1F)) {
4261 bool ret = v->Next() != NULL;
4262 DeleteLastWagon(v);
4263 return ret;
4266 return true;
4269 /** Maximum speeds for train that is broken down or approaching line end */
4270 static const uint16 _breakdown_speeds[16] = {
4271 225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
4276 * Train is approaching line end, slow down and possibly reverse
4278 * @param v front train engine
4279 * @param signal not line end, just a red signal
4280 * @param reverse Set to false to not execute the vehicle reversing. This does not change any other logic.
4281 * @return true iff we did NOT have to reverse
4283 static bool TrainApproachingLineEnd(Train *v, bool signal, bool reverse)
4285 /* Calc position within the current tile */
4286 uint x = v->x_pos & 0xF;
4287 uint y = v->y_pos & 0xF;
4289 /* for diagonal directions, 'x' will be 0..15 -
4290 * for other directions, it will be 1, 3, 5, ..., 15 */
4291 switch (v->direction) {
4292 case DIR_N : x = ~x + ~y + 25; break;
4293 case DIR_NW: x = y; FALLTHROUGH;
4294 case DIR_NE: x = ~x + 16; break;
4295 case DIR_E : x = ~x + y + 9; break;
4296 case DIR_SE: x = y; break;
4297 case DIR_S : x = x + y - 7; break;
4298 case DIR_W : x = ~y + x + 9; break;
4299 default: break;
4302 /* Do not reverse when approaching red signal. Make sure the vehicle's front
4303 * does not cross the tile boundary when we do reverse, but as the vehicle's
4304 * location is based on their center, use half a vehicle's length as offset.
4305 * Multiply the half-length by two for straight directions to compensate that
4306 * we only get odd x offsets there. */
4307 if (!signal && x + (v->gcache.cached_veh_length + 1) / 2 * (IsDiagonalDirection(v->direction) ? 1 : 2) >= TILE_SIZE) {
4308 /* we are too near the tile end, reverse now */
4309 v->cur_speed = 0;
4310 if (reverse) ReverseTrainDirection(v);
4311 return false;
4314 /* slow down */
4315 v->vehstatus |= VS_TRAIN_SLOWING;
4316 uint16 break_speed = _breakdown_speeds[x & 0xF];
4317 if (break_speed < v->cur_speed) v->cur_speed = break_speed;
4319 return true;
4324 * Determines whether train would like to leave the tile
4325 * @param v train to test
4326 * @return true iff vehicle is NOT entering or inside a depot or tunnel/bridge
4328 static bool TrainCanLeaveTile(const Train *v)
4330 /* Exit if inside a tunnel/bridge or a depot */
4331 if (v->track == TRACK_BIT_WORMHOLE || v->track == TRACK_BIT_DEPOT) return false;
4333 TileIndex tile = v->tile;
4335 /* entering a tunnel/bridge? */
4336 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
4337 DiagDirection dir = GetTunnelBridgeDirection(tile);
4338 if (DiagDirToDir(dir) == v->direction) return false;
4341 /* entering a depot? */
4342 if (IsRailDepotTile(tile)) {
4343 DiagDirection dir = ReverseDiagDir(GetRailDepotDirection(tile));
4344 if (DiagDirToDir(dir) == v->direction) return false;
4347 return true;
4352 * Determines whether train is approaching a rail-road crossing
4353 * (thus making it barred)
4354 * @param v front engine of train
4355 * @return TileIndex of crossing the train is approaching, else INVALID_TILE
4356 * @pre v in non-crashed front engine
4358 static TileIndex TrainApproachingCrossingTile(const Train *v)
4360 assert(v->IsFrontEngine());
4361 assert(!(v->vehstatus & VS_CRASHED));
4363 if (!TrainCanLeaveTile(v)) return INVALID_TILE;
4365 DiagDirection dir = TrainExitDir(v->direction, v->track);
4366 TileIndex tile = v->tile + TileOffsByDiagDir(dir);
4368 /* not a crossing || wrong axis || unusable rail (wrong type or owner) */
4369 if (!IsLevelCrossingTile(tile) || DiagDirToAxis(dir) == GetCrossingRoadAxis(tile) ||
4370 !CheckCompatibleRail(v, tile)) {
4371 return INVALID_TILE;
4374 return tile;
4379 * Checks for line end. Also, bars crossing at next tile if needed
4381 * @param v vehicle we are checking
4382 * @param reverse Set to false to not execute the vehicle reversing. This does not change any other logic.
4383 * @return true iff we did NOT have to reverse
4385 static bool TrainCheckIfLineEnds(Train *v, bool reverse)
4387 /* First, handle broken down train */
4389 int t = v->breakdown_ctr;
4390 if (t > 1) {
4391 v->vehstatus |= VS_TRAIN_SLOWING;
4393 uint16 break_speed = _breakdown_speeds[GB(~t, 4, 4)];
4394 if (break_speed < v->cur_speed) v->cur_speed = break_speed;
4395 } else {
4396 v->vehstatus &= ~VS_TRAIN_SLOWING;
4399 if (!TrainCanLeaveTile(v)) return true;
4401 /* Determine the non-diagonal direction in which we will exit this tile */
4402 DiagDirection dir = TrainExitDir(v->direction, v->track);
4403 /* Calculate next tile */
4404 TileIndex tile = v->tile + TileOffsByDiagDir(dir);
4406 /* Determine the track status on the next tile */
4407 TrackStatus ts = GetTileTrackStatus(tile, TRANSPORT_RAIL, 0, ReverseDiagDir(dir));
4408 TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(dir);
4410 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
4411 TrackdirBits red_signals = TrackStatusToRedSignals(ts) & reachable_trackdirs;
4413 /* We are sure the train is not entering a depot, it is detected above */
4415 /* mask unreachable track bits if we are forbidden to do 90deg turns */
4416 TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
4417 if (_settings_game.pf.forbid_90_deg) {
4418 bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
4421 /* no suitable trackbits at all || unusable rail (wrong type or owner) */
4422 if (bits == TRACK_BIT_NONE || !CheckCompatibleRail(v, tile)) {
4423 return TrainApproachingLineEnd(v, false, reverse);
4426 /* approaching red signal */
4427 if ((trackdirbits & red_signals) != 0) return TrainApproachingLineEnd(v, true, reverse);
4429 /* approaching a rail/road crossing? then make it red */
4430 if (IsLevelCrossingTile(tile)) MaybeBarCrossingWithSound(tile);
4432 return true;
4435 /* Calculate the summed up value of all parts of a train */
4436 Money Train::CalculateCurrentOverallValue() const
4438 Money ovr_value = 0;
4439 const Train *v = this;
4440 do {
4441 ovr_value += v->value;
4442 } while ( (v=v->GetNextVehicle()) != NULL );
4443 return ovr_value;
4446 static bool TrainLocoHandler(Train *v, bool mode)
4448 /* train has crashed? */
4449 if (v->vehstatus & VS_CRASHED) {
4450 return mode ? true : HandleCrashedTrain(v); // 'this' can be deleted here
4453 if (v->force_proceed != TFP_NONE) {
4454 ClrBit(v->flags, VRF_TRAIN_STUCK);
4455 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4458 /* train is broken down? */
4459 if (v->HandleBreakdown()) return true;
4461 if (HasBit(v->flags, VRF_REVERSING) && v->cur_speed == 0) {
4462 ReverseTrainDirection(v);
4465 /* exit if train is stopped */
4466 if ((v->vehstatus & VS_STOPPED) && v->cur_speed == 0) return true;
4468 bool valid_order = !v->current_order.IsType(OT_NOTHING) && v->current_order.GetType() != OT_CONDITIONAL;
4469 if (ProcessOrders(v) && CheckReverseTrain(v)) {
4470 v->wait_counter = 0;
4471 v->cur_speed = 0;
4472 v->subspeed = 0;
4473 ClrBit(v->flags, VRF_LEAVING_STATION);
4474 ReverseTrainDirection(v);
4475 return true;
4476 } else if (HasBit(v->flags, VRF_LEAVING_STATION)) {
4477 /* Try to reserve a path when leaving the station as we
4478 * might not be marked as wanting a reservation, e.g.
4479 * when an overlength train gets turned around in a station. */
4480 DiagDirection dir = TrainExitDir(v->direction, v->track);
4481 if (IsRailDepotTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE)) dir = INVALID_DIAGDIR;
4483 if (UpdateSignalsOnSegment(v->tile, dir, v->owner) == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
4484 TryPathReserve(v, true, true);
4486 ClrBit(v->flags, VRF_LEAVING_STATION);
4489 v->HandleLoading(mode);
4491 if (v->current_order.IsType(OT_LOADING)) return true;
4493 if (CheckTrainStayInDepot(v)) return true;
4495 if (!mode) v->ShowVisualEffect();
4497 /* We had no order but have an order now, do look ahead. */
4498 if (!valid_order && !v->current_order.IsType(OT_NOTHING)) {
4499 CheckNextTrainTile(v);
4502 /* Handle stuck trains. */
4503 if (!mode && HasBit(v->flags, VRF_TRAIN_STUCK)) {
4504 ++v->wait_counter;
4506 /* Should we try reversing this tick if still stuck? */
4507 bool turn_around = v->wait_counter % (_settings_game.pf.wait_for_pbs_path * DAY_TICKS) == 0 && _settings_game.pf.reverse_at_signals;
4509 if (!turn_around && v->wait_counter % _settings_game.pf.path_backoff_interval != 0 && v->force_proceed == TFP_NONE) return true;
4510 if (!TryPathReserve(v)) {
4511 /* Still stuck. */
4512 if (turn_around) ReverseTrainDirection(v);
4514 if (HasBit(v->flags, VRF_TRAIN_STUCK) && v->wait_counter > 2 * _settings_game.pf.wait_for_pbs_path * DAY_TICKS) {
4515 /* Show message to player. */
4516 if (_settings_client.gui.lost_vehicle_warn && v->owner == _local_company) {
4517 SetDParam(0, v->index);
4518 AddVehicleAdviceNewsItem(STR_NEWS_TRAIN_IS_STUCK, v->index);
4520 v->wait_counter = 0;
4522 /* Exit if force proceed not pressed, else reset stuck flag anyway. */
4523 if (v->force_proceed == TFP_NONE) return true;
4524 ClrBit(v->flags, VRF_TRAIN_STUCK);
4525 v->wait_counter = 0;
4526 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4530 if (v->current_order.IsType(OT_LEAVESTATION)) {
4531 v->current_order.Free();
4532 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4533 return true;
4536 int j = v->UpdateSpeed();
4538 /* we need to invalidate the widget if we are stopping from 'Stopping 0 km/h' to 'Stopped' */
4539 if (v->cur_speed == 0 && (v->vehstatus & VS_STOPPED)) {
4540 /* If we manually stopped, we're not force-proceeding anymore. */
4541 v->force_proceed = TFP_NONE;
4542 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
4545 int adv_spd = v->GetAdvanceDistance();
4546 if (j < adv_spd) {
4547 /* if the vehicle has speed 0, update the last_speed field. */
4548 if (v->cur_speed == 0) v->SetLastSpeed();
4549 } else {
4550 TrainCheckIfLineEnds(v);
4551 /* Loop until the train has finished moving. */
4552 for (;;) {
4553 j -= adv_spd;
4554 TrainController(v, NULL);
4555 /* Don't continue to move if the train crashed. */
4556 if (CheckTrainCollision(v)) break;
4557 /* Determine distance to next map position */
4558 adv_spd = v->GetAdvanceDistance();
4560 /* No more moving this tick */
4561 if (j < adv_spd || v->cur_speed == 0) break;
4563 OrderType order_type = v->current_order.GetType();
4564 /* Do not skip waypoints (incl. 'via' stations) when passing through at full speed. */
4565 if ((order_type == OT_GOTO_WAYPOINT || order_type == OT_GOTO_STATION) &&
4566 (v->current_order.GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) &&
4567 IsTileType(v->tile, MP_STATION) &&
4568 v->current_order.GetDestination() == GetStationIndex(v->tile)) {
4569 ProcessOrders(v);
4572 v->SetLastSpeed();
4575 for (Train *u = v; u != NULL; u = u->Next()) {
4576 if (!(u->IsDrawn())) continue;
4578 u->UpdateViewport(false, false);
4581 if (v->progress == 0) v->progress = j; // Save unused spd for next time, if TrainController didn't set progress
4583 return true;
4587 * Get running cost for the train consist.
4588 * @return Yearly running costs.
4590 Money Train::GetRunningCost() const
4592 Money cost = 0;
4593 const Train *v = this;
4595 do {
4596 const Engine *e = v->GetEngine();
4597 if (e->u.rail.running_cost_class == INVALID_PRICE) continue;
4599 uint cost_factor = GetVehicleProperty(v, PROP_TRAIN_RUNNING_COST_FACTOR, e->u.rail.running_cost);
4600 if (cost_factor == 0) continue;
4602 /* Halve running cost for multiheaded parts */
4603 if (v->IsMultiheaded()) cost_factor /= 2;
4605 cost += GetPrice(e->u.rail.running_cost_class, cost_factor, e->GetGRF());
4606 } while ((v = v->GetNextVehicle()) != NULL);
4608 return cost;
4612 * Update train vehicle data for a tick.
4613 * @return True if the vehicle still exists, false if it has ceased to exist (front of consists only).
4615 bool Train::Tick()
4617 this->tick_counter++;
4619 if (this->IsFrontEngine()) {
4620 if (!((this->vehstatus & VS_STOPPED) || this->IsChainInDepot()) || this->cur_speed > 0) this->running_ticks++;
4622 this->current_order_time++;
4624 if (!TrainLocoHandler(this, false)) return false;
4626 return TrainLocoHandler(this, true);
4627 } else if (this->IsFreeWagon() && (this->vehstatus & VS_CRASHED)) {
4628 /* Delete flooded standalone wagon chain */
4629 if (++this->crash_anim_pos >= 4400) {
4630 delete this;
4631 return false;
4635 return true;
4639 * Check whether a train needs service, and if so, find a depot or service it.
4640 * @return v %Train to check.
4642 static void CheckIfTrainNeedsService(Train *v)
4644 if (Company::Get(v->owner)->settings.vehicle.servint_trains == 0 || !v->NeedsAutomaticServicing()) return;
4645 if (v->IsChainInDepot()) {
4646 VehicleServiceInDepot(v);
4647 return;
4650 uint max_penalty;
4651 switch (_settings_game.pf.pathfinder_for_trains) {
4652 case VPF_NPF: max_penalty = _settings_game.pf.npf.maximum_go_to_depot_penalty; break;
4653 case VPF_YAPF: max_penalty = _settings_game.pf.yapf.maximum_go_to_depot_penalty; break;
4654 default: NOT_REACHED();
4657 FindDepotData tfdd = FindClosestTrainDepot(v, max_penalty);
4658 /* Only go to the depot if it is not too far out of our way. */
4659 if (tfdd.best_length == UINT_MAX || tfdd.best_length > max_penalty) {
4660 if (v->current_order.IsType(OT_GOTO_DEPOT)) {
4661 /* If we were already heading for a depot but it has
4662 * suddenly moved farther away, we continue our normal
4663 * schedule? */
4664 v->current_order.MakeDummy();
4665 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4667 return;
4670 DepotID depot = GetDepotIndex(tfdd.tile);
4672 if (v->current_order.IsType(OT_GOTO_DEPOT) &&
4673 v->current_order.GetDestination() != depot &&
4674 !Chance16(3, 16)) {
4675 return;
4678 SetBit(v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
4679 v->current_order.MakeGoToDepot(depot, ODTFB_SERVICE);
4680 v->dest_tile = tfdd.tile;
4681 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4684 /** Update day counters of the train vehicle. */
4685 void Train::OnNewDay()
4687 AgeVehicle(this);
4689 if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
4691 if (this->IsFrontEngine()) {
4692 CheckVehicleBreakdown(this);
4694 CheckIfTrainNeedsService(this);
4696 CheckOrders(this);
4698 /* update destination */
4699 if (this->current_order.IsType(OT_GOTO_STATION)) {
4700 TileIndex tile = Station::Get(this->current_order.GetDestination())->train_station.tile;
4701 if (tile != INVALID_TILE) this->dest_tile = tile;
4704 if (this->running_ticks != 0) {
4705 /* running costs */
4706 CommandCost cost(EXPENSES_TRAIN_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR * DAY_TICKS));
4708 this->profit_this_year -= cost.GetCost();
4709 this->running_ticks = 0;
4711 SubtractMoneyFromCompanyFract(this->owner, cost);
4713 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
4714 SetWindowClassesDirty(WC_TRAINS_LIST);
4720 * Get the tracks of the train vehicle.
4721 * @return Current tracks of the vehicle.
4723 Trackdir Train::GetVehicleTrackdir() const
4725 if (this->vehstatus & VS_CRASHED)
4726 return INVALID_TRACKDIR;
4728 if (this->track == TRACK_BIT_DEPOT) {
4729 /* We'll assume the train is facing outwards */
4730 return DiagDirToDiagTrackdir(GetRailDepotDirection(this->tile)); // Train in depot
4733 if (this->track == TRACK_BIT_WORMHOLE) {
4734 /* train in tunnel or on bridge, so just use his direction and assume a diagonal track */
4735 return DiagDirToDiagTrackdir(DirToDiagDir(this->direction));
4738 return TrackDirectionToTrackdir(FindFirstTrack(this->track), this->direction);
4742 /* Get the pixel-width of the image that is used for the train vehicle
4743 * @return: the image width number in pixel
4745 int GetDisplayImageWidth(Train *t, Point *offset)
4747 int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
4748 int vehicle_pitch = 0;
4750 const Engine *e = Engine::Get(t->engine_type);
4751 if (e->grf_prop.grffile != NULL && is_custom_sprite(e->u.rail.image_index)) {
4752 reference_width = e->grf_prop.grffile->traininfo_vehicle_width;
4753 vehicle_pitch = e->grf_prop.grffile->traininfo_vehicle_pitch;
4756 if (offset != NULL) {
4757 offset->x = reference_width / 2;
4758 offset->y = vehicle_pitch;
4760 //printf(" refwid:%d gdiw.cachedvehlen(%d):%d ", reference_width, this->engine_type, this->gcache.cached_veh_length);
4761 return t->gcache.cached_veh_length * reference_width / VEHICLE_LENGTH;
4764 Train* CmdBuildVirtualRailWagon(const Engine *e)
4766 const RailVehicleInfo *rvi = &e->u.rail;
4768 Train *v = new Train();
4770 v->x_pos = 0;
4771 v->y_pos = 0;
4773 v->spritenum = rvi->image_index;
4775 v->engine_type = e->index;
4776 v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
4778 v->direction = DIR_W;
4779 v->tile = 0;//INVALID_TILE;
4781 v->owner = _current_company;
4782 v->track = TRACK_BIT_DEPOT;
4783 v->vehstatus = VS_HIDDEN | VS_DEFPAL;
4785 v->SetWagon();
4786 v->SetFreeWagon();
4788 v->cargo_type = e->GetDefaultCargoType();
4789 v->cargo_cap = rvi->capacity;
4791 v->railtype = rvi->railtype;
4793 v->build_year = _cur_year;
4794 v->sprite_seq.Set(SPR_IMG_QUERY);
4795 v->random_bits = VehicleRandomBits();
4797 v->group_id = DEFAULT_GROUP;
4799 AddArticulatedParts(v);
4801 // Make sure we set EVERYTHING to virtual, even articulated parts.
4802 for (Train* train_part = v; train_part != NULL; train_part = train_part->Next()) {
4803 train_part->SetVirtual();
4806 _new_vehicle_id = v->index;
4808 v->UpdateViewport(true, false);
4810 v->First()->ConsistChanged(CCF_ARRANGE);
4812 CheckConsistencyOfArticulatedVehicle(v);
4814 return v;
4817 Train* CmdBuildVirtualRailVehicle(EngineID eid, bool lax_engine_check, StringID &error)
4819 if (lax_engine_check) {
4820 const Engine *e = Engine::GetIfValid(eid);
4821 if (e == NULL || e->type != VEH_TRAIN) {
4822 error = STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE + VEH_TRAIN;
4823 return NULL;
4826 else {
4827 if (!IsEngineBuildable(eid, VEH_TRAIN, _current_company)) {
4828 error = STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE + VEH_TRAIN;
4829 return NULL;
4833 const Engine* e = Engine::Get(eid);
4834 const RailVehicleInfo *rvi = &e->u.rail;
4836 int num_vehicles = (e->u.rail.railveh_type == RAILVEH_MULTIHEAD ? 2 : 1) + CountArticulatedParts(eid, false);
4837 if (!Train::CanAllocateItem(num_vehicles)) {
4838 error = STR_ERROR_TOO_MANY_VEHICLES_IN_GAME;
4839 return nullptr;
4842 if (rvi->railveh_type == RAILVEH_WAGON)
4843 return CmdBuildVirtualRailWagon(e);
4845 Train *v = new Train();
4847 v->x_pos = 0;
4848 v->y_pos = 0;
4850 v->direction = DIR_W;
4851 v->tile = 0;//INVALID_TILE;
4852 v->owner = _current_company;
4853 v->track = TRACK_BIT_DEPOT;
4854 v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
4855 v->spritenum = rvi->image_index;
4856 v->cargo_type = e->GetDefaultCargoType();
4857 v->cargo_cap = rvi->capacity;
4858 v->last_station_visited = INVALID_STATION;
4860 v->engine_type = e->index;
4861 v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
4863 v->reliability = e->reliability;
4864 v->reliability_spd_dec = e->reliability_spd_dec;
4865 v->max_age = e->GetLifeLengthInDays();
4867 v->railtype = rvi->railtype;
4868 _new_vehicle_id = v->index;
4870 v->sprite_seq.Set(SPR_IMG_QUERY);
4871 v->random_bits = VehicleRandomBits();
4873 v->group_id = DEFAULT_GROUP;
4875 v->SetFrontEngine();
4876 v->SetEngine();
4878 v->UpdateViewport(true, false);
4880 if (rvi->railveh_type == RAILVEH_MULTIHEAD) {
4881 AddRearEngineToMultiheadedTrain(v);
4882 } else {
4883 AddArticulatedParts(v);
4886 // Make sure we set EVERYTHING to virtual, even articulated parts.
4887 for (Train* train_part = v; train_part != NULL; train_part = train_part->Next()) {
4888 train_part->SetVirtual();
4891 v->ConsistChanged(CCF_ARRANGE);
4893 CheckConsistencyOfArticulatedVehicle(v);
4895 return v;
4899 * Build a virtual train vehicle.
4900 * @param tile unused
4901 * @param flags type of operation
4902 * @param p1 the engine ID to build
4903 * @param p2 unused
4904 * @param text unused
4905 * @return the cost of this operation or an error
4907 CommandCost CmdBuildVirtualRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
4909 EngineID eid = p1;
4911 if (!IsEngineBuildable(eid, VEH_TRAIN, _current_company)) {
4912 return_cmd_error(STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE + VEH_TRAIN);
4915 bool should_execute = (flags & DC_EXEC) != 0;
4917 if (should_execute) {
4918 StringID err = INVALID_STRING_ID;
4919 Train* train = CmdBuildVirtualRailVehicle(eid, false, err);
4921 if (train == nullptr) {
4922 return_cmd_error(err);
4926 return CommandCost();
4930 * Replace a vehicle based on a template replacement order.
4931 * @param tile unused
4932 * @param flags type of operation
4933 * @param p1 the ID of the vehicle to replace.
4934 * @param p2 whether the vehicle should stay in the depot.
4935 * @param text unused
4936 * @return the cost of this operation or an error
4938 CommandCost CmdTemplateReplaceVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
4940 VehicleID vehicle_id = p1;
4942 Vehicle* vehicle = Vehicle::GetIfValid(vehicle_id);
4944 if (vehicle == nullptr || vehicle->type != VEH_TRAIN)
4945 return CMD_ERROR;
4947 bool should_execute = (flags & DC_EXEC) != 0;
4949 if (!should_execute)
4950 return CommandCost();
4952 Train* incoming = Train::From(vehicle);
4953 bool stayInDepot = p2 != 0;
4955 Train *new_chain = 0,
4956 *remainder_chain = 0,
4957 *tmp_chain = 0;
4958 TemplateVehicle *tv = GetTemplateVehicleByGroupID(incoming->group_id);
4959 if (tv == nullptr) {
4960 return CMD_ERROR;
4963 CommandCost buy(EXPENSES_NEW_VEHICLES);
4964 CommandCost move_cost(EXPENSES_NEW_VEHICLES);
4965 CommandCost tmp_result(EXPENSES_NEW_VEHICLES);
4968 /* first some tests on necessity and sanity */
4969 if (tv == nullptr)
4970 return buy;
4972 EngineID eid = tv->engine_type;
4974 bool need_replacement = !TrainMatchesTemplate(incoming, tv);
4975 bool need_refit = !TrainMatchesTemplateRefit(incoming, tv);
4976 bool use_refit = tv->refit_as_template;
4978 CargoID store_refit_ct = CT_INVALID;
4979 short store_refit_csubt = 0;
4980 // if a train shall keep its old refit, store the refit setting of its first vehicle
4981 if (!use_refit) {
4982 for (Train *getc = incoming; getc != NULL; getc = getc->GetNextUnit()) {
4983 if (getc->cargo_type != CT_INVALID) {
4984 store_refit_ct = getc->cargo_type;
4985 break;
4990 // TODO: set result status to success/no success before returning
4991 if (!need_replacement) {
4992 if (!need_refit || !use_refit) {
4993 /* before returning, release incoming train first if 2nd param says so */
4994 if (!stayInDepot) incoming->vehstatus &= ~VS_STOPPED;
4995 return buy;
4998 else {
4999 CommandCost buyCost = TestBuyAllTemplateVehiclesInChain(tv, tile);
5000 if (!buyCost.Succeeded() || !CheckCompanyHasMoney(buyCost)) {
5001 if (!stayInDepot) incoming->vehstatus &= ~VS_STOPPED;
5003 if (!buyCost.Succeeded() && buyCost.GetErrorMessage() != INVALID_STRING_ID) {
5004 return buyCost;
5005 } else {
5006 return_cmd_error(STR_ERROR_NOT_ENOUGH_CASH_REQUIRES_CURRENCY);
5011 /* define replacement behavior */
5012 bool reuseDepot = tv->IsSetReuseDepotVehicles();
5013 bool keepRemainders = tv->IsSetKeepRemainingVehicles();
5015 if (need_replacement) {
5016 /// step 1: generate primary for newchain and generate remainder_chain
5017 // 1. primary of incoming might already fit the template
5018 // leave incoming's primary as is and move the rest to a free chain = remainder_chain
5019 // 2. needed primary might be one of incoming's member vehicles
5020 // 3. primary might be available as orphan vehicle in the depot
5021 // 4. we need to buy a new engine for the primary
5022 // all options other than 1. need to make sure to copy incoming's primary's status
5023 if (eid == incoming->engine_type) { // 1
5024 new_chain = incoming;
5025 remainder_chain = incoming->GetNextUnit();
5026 if (remainder_chain)
5027 move_cost.AddCost(CmdMoveRailVehicle(tile, flags, remainder_chain->index | (1 << 20), INVALID_VEHICLE, 0));
5029 else if ((tmp_chain = ChainContainsEngine(eid, incoming)) && tmp_chain != NULL) { // 2
5030 // new_chain is the needed engine, move it to an empty spot in the depot
5031 new_chain = tmp_chain;
5032 move_cost.AddCost(DoCommand(tile, new_chain->index, INVALID_VEHICLE, flags, CMD_MOVE_RAIL_VEHICLE));
5033 remainder_chain = incoming;
5035 else if (reuseDepot && (tmp_chain = DepotContainsEngine(tile, eid, incoming)) && tmp_chain != NULL) { // 3
5036 new_chain = tmp_chain;
5037 move_cost.AddCost(DoCommand(tile, new_chain->index, INVALID_VEHICLE, flags, CMD_MOVE_RAIL_VEHICLE));
5038 remainder_chain = incoming;
5040 else { // 4
5041 tmp_result = DoCommand(tile, eid, 0, flags, CMD_BUILD_VEHICLE);
5042 /* break up in case buying the vehicle didn't succeed */
5043 if (!tmp_result.Succeeded())
5044 return tmp_result;
5045 buy.AddCost(tmp_result);
5046 new_chain = Train::Get(_new_vehicle_id);
5047 /* make sure the newly built engine is not attached to any free wagons inside the depot */
5048 move_cost.AddCost(DoCommand(tile, new_chain->index, INVALID_VEHICLE, flags, CMD_MOVE_RAIL_VEHICLE));
5049 /* prepare the remainder chain */
5050 remainder_chain = incoming;
5052 // If we bought a new engine or reused one from the depot, copy some parameters from the incoming primary engine
5053 if (incoming != new_chain && flags == DC_EXEC) {
5054 CopyHeadSpecificThings(incoming, new_chain, flags);
5055 NeutralizeStatus(incoming);
5058 // additionally, if we don't want to use the template refit, refit as incoming
5059 // the template refit will be set further down, if we use it at all
5060 if (!use_refit) {
5061 uint32 cb = GetCmdRefitVeh(new_chain);
5062 DoCommand(new_chain->tile, new_chain->index, store_refit_ct | store_refit_csubt << 8 | 1 << 16 | (1 << 5), flags, cb);
5067 /// step 2: fill up newchain according to the template
5068 // foreach member of template (after primary):
5069 // 1. needed engine might be within remainder_chain already
5070 // 2. needed engine might be orphaned within the depot (copy status)
5071 // 3. we need to buy (again) (copy status)
5072 TemplateVehicle *cur_tmpl = tv->GetNextUnit();
5073 Train *last_veh = new_chain;
5074 while (cur_tmpl) {
5075 // 1. engine contained in remainder chain
5076 if ((tmp_chain = ChainContainsEngine(cur_tmpl->engine_type, remainder_chain)) && tmp_chain != NULL) {
5077 // advance remainder_chain (if necessary) to not lose track of it
5078 if (tmp_chain == remainder_chain)
5079 remainder_chain = remainder_chain->GetNextUnit();
5080 move_cost.AddCost(CmdMoveRailVehicle(tile, flags, tmp_chain->index, last_veh->index, 0));
5082 // 2. engine contained somewhere else in the depot
5083 else if (reuseDepot && (tmp_chain = DepotContainsEngine(tile, cur_tmpl->engine_type, new_chain)) && tmp_chain != NULL) {
5084 move_cost.AddCost(CmdMoveRailVehicle(tile, flags, tmp_chain->index, last_veh->index, 0));
5086 // 3. must buy new engine
5087 else {
5088 tmp_result = DoCommand(tile, cur_tmpl->engine_type, 0, flags, CMD_BUILD_VEHICLE);
5089 if (!tmp_result.Succeeded()) {
5090 return tmp_result;
5092 buy.AddCost(tmp_result);
5093 tmp_chain = Train::Get(_new_vehicle_id);
5094 move_cost.AddCost(CmdMoveRailVehicle(tile, flags, tmp_chain->index, last_veh->index, 0));
5096 // TODO: is this enough ? might it be that we bought a new wagon here and it now has std refit ?
5097 if (need_refit && flags == DC_EXEC) {
5098 if (use_refit) {
5099 uint32 cb = GetCmdRefitVeh(tmp_chain);
5100 DoCommand(tmp_chain->tile, tmp_chain->index, cur_tmpl->cargo_type | cur_tmpl->cargo_subtype << 8 | 1 << 16 | (1 << 5), flags, cb);
5101 // old
5102 // CopyWagonStatus(cur_tmpl, tmp_chain);
5103 } else {
5104 uint32 cb = GetCmdRefitVeh(tmp_chain);
5105 DoCommand(tmp_chain->tile, tmp_chain->index, store_refit_ct | store_refit_csubt << 8 | 1 << 16 | (1 << 5), flags, cb);
5108 cur_tmpl = cur_tmpl->GetNextUnit();
5109 last_veh = tmp_chain;
5112 /* no replacement done */
5113 else {
5114 new_chain = incoming;
5116 /// step 3: reorder and neutralize the remaining vehicles from incoming
5117 // wagons remaining from remainder_chain should be filled up in as few freewagonchains as possible
5118 // each locos might be left as singular in the depot
5119 // neutralize each remaining engine's status
5121 // refit, only if the template option is set so
5122 if (use_refit && (need_refit || need_replacement)) {
5123 CmdRefitTrainFromTemplate(new_chain, tv, flags);
5126 if (new_chain && remainder_chain)
5127 for (Train *ct = remainder_chain; ct; ct = ct->GetNextUnit())
5128 TransferCargoForTrain(ct, new_chain);
5130 // point incoming to the newly created train so that starting/stopping from the calling function can be done
5131 incoming = new_chain;
5132 if (!stayInDepot && flags == DC_EXEC)
5133 new_chain->vehstatus &= ~VS_STOPPED;
5135 if (remainder_chain && keepRemainders && flags == DC_EXEC)
5136 BreakUpRemainders(remainder_chain);
5137 else if (remainder_chain) {
5138 buy.AddCost(DoCommand(tile, remainder_chain->index | (1 << 20), 0, flags, CMD_SELL_VEHICLE));
5141 /* Redraw main gui for changed statistics */
5142 SetWindowClassesDirty(WC_TEMPLATEGUI_MAIN);
5144 return buy;