# train_cmd.cpp File Reference

Handling of trains. More...

`#include "stdafx.h"`
`#include "gui.h"`
`#include "articulated_vehicles.h"`
`#include "command_func.h"`
`#include "npf.h"`
`#include "news_func.h"`
`#include "engine_func.h"`
`#include "engine_base.h"`
`#include "company_func.h"`
`#include "depot_base.h"`
`#include "vehicle_gui.h"`
`#include "train.h"`
`#include "newgrf_engine.h"`
`#include "newgrf_sound.h"`
`#include "newgrf_text.h"`
`#include "yapf/follow_track.hpp"`
`#include "group.h"`
`#include "table/sprites.h"`
`#include "strings_func.h"`
`#include "functions.h"`
`#include "window_func.h"`
`#include "vehicle_func.h"`
`#include "sound_func.h"`
`#include "variables.h"`
`#include "autoreplace_gui.h"`
`#include "gfx_func.h"`
`#include "ai/ai.hpp"`
`#include "newgrf_station.h"`
`#include "effectvehicle_func.h"`
`#include "gamelog.h"`
`#include "network/network.h"`
`#include "table/strings.h"`
`#include "table/train_cmd.h"`

Go to the source code of this file.

## Data Structures

struct | TrainFindDepotData
struct | TrainTrackFollowerData
| Check for station tiles. More...
class | VehicleOrderSaver
| This class will save the current order of a vehicle and restore it on destruction. More...
struct | RailtypeSlowdownParams
struct | TrainCollideChecker

## Defines

#define | MKIT(a, b, c, d) ((a & 0xFF) << 24) | ((b & 0xFF) << 16) | ((c & 0xFF) << 8) | ((d & 0xFF) << 0)

## Enumerations

enum | AccelType { AM_ACCEL, AM_BRAKE }

## Functions

static Track | ChooseTrainTrack (Vehicle *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck)
static bool | TrainCheckIfLineEnds (Vehicle *v)
| Checks for line end.
static void | TrainController (Vehicle *v, Vehicle *nomove)
static TileIndex | TrainApproachingCrossingTile (const Vehicle *v)
| Determines whether train is approaching a rail-road crossing (thus making it barred).
static void | CheckIfTrainNeedsService (Vehicle *v)
static void | CheckNextTrainTile (Vehicle *v)
| Check if the train is on the last reserved tile and try to extend the path then.
static DiagDirection | TrainExitDir (Direction direction, TrackBits track)
| Determine the side in which the train will leave the tile.
byte | FreightWagonMult (CargoID cargo)
| Return the cargo weight multiplier to use for a rail vehicle.
void | TrainPowerChanged (Vehicle *v)
| Recalculates the cached total power of a train.
static void | TrainCargoChanged (Vehicle *v)
| Recalculates the cached weight of a train and its vehicles.
static void | RailVehicleLengthChanged (const Vehicle *u)
| Logs a bug in GRF and shows a warning message if this is for the first time this happened.
void | CheckTrainsLengths ()
| Checks if lengths of all rail vehicles are valid.
void | TrainConsistChanged (Vehicle *v, bool same_length)
| Recalculates the cached stuff of a train.
static int | GetTrainAcceleration (Vehicle *v, bool mode)
| new acceleration
void | UpdateTrainAcceleration (Vehicle *v)
static SpriteID | GetRailIcon (EngineID engine, bool rear_head, int &y)
void | DrawTrainEngine (int x, int y, EngineID engine, SpriteID pal)
static CommandCost | CmdBuildRailWagon (EngineID engine, TileIndex tile, DoCommandFlag flags)
static void | NormalizeTrainVehInDepot (const Vehicle *u)
| Move all free vehicles in the depot to the train.
static void | AddRearEngineToMultiheadedTrain (Vehicle *v, Vehicle *u, bool building)
CommandCost | CmdBuildRailVehicle (TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
| Build a railroad vehicle.
int | CheckTrainInDepot (const Vehicle *v, bool needs_to_be_stopped)
int | CheckTrainStoppedInDepot (const Vehicle *v)
bool | CheckTrainIsInsideDepot (const Vehicle *v)
static Vehicle * | UnlinkWagon (Vehicle *v, Vehicle *first)
| Unlink a rail wagon from the consist.
static Vehicle * | FindGoodVehiclePos (const Vehicle *src)
static void | AddWagonToConsist (Vehicle *v, Vehicle *dest)
static void | NormaliseTrainConsist (Vehicle *v)
CommandCost | CmdMoveRailVehicle (TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
| Move a rail vehicle around inside the depot.
CommandCost | CmdSellRailWagon (TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
| Sell a (single) train wagon/engine.
static void | SetLastSpeed (Vehicle *v, int spd)
static void | MarkTrainAsStuck (Vehicle *v)
| Mark a train as stuck and stop it if it isn't stopped right now.
static void | SwapTrainFlags (uint16 *swap_flag1, uint16 *swap_flag2)
static void | ReverseTrainSwapVeh (Vehicle *v, int l, int r)
static Vehicle * | TrainOnTileEnum (Vehicle *v, void *)
| Check if the vehicle is a train.
static Vehicle * | TrainApproachingCrossingEnum (Vehicle *v, void *data)
| Checks if a train is approaching a rail-road crossing.
static bool | TrainApproachingCrossing (TileIndex tile)
| Finds a vehicle approaching rail-road crossing.
void | UpdateLevelCrossing (TileIndex tile, bool sound)
| Sets correct crossing state.
static void | MaybeBarCrossingWithSound (TileIndex tile)
| Bars crossing and plays ding-ding sound if not barred already.
static void | AdvanceWagonsBeforeSwap (Vehicle *v)
| Advances wagons for train reversing, needed for variable length wagons.
static void | AdvanceWagonsAfterSwap (Vehicle *v)
| Advances wagons for train reversing, needed for variable length wagons.
static void | ReverseTrainDirection (Vehicle *v)
CommandCost | CmdReverseTrainDirection (TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
| Reverse train.
CommandCost | CmdForceTrainProceed (TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
| Force a train through a red signal.
CommandCost | CmdRefitRailVehicle (TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
| Refits a train to the specified cargo type.
static bool | NtpCallbFindDepot (TileIndex tile, TrainFindDepotData *tfdd, int track, uint length)
static TrainFindDepotData | FindClosestTrainDepot (Vehicle *v, int max_distance)
| returns the tile of a depot to goto to.
CommandCost | CmdSendTrainToDepot (TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
| Send a train to a depot.
void | OnTick_Train ()
static void | HandleLocomotiveSmokeCloud (const Vehicle *v)
static bool | CheckTrainStayInDepot (Vehicle *v)
static void | ClearPathReservation (const Vehicle *v, TileIndex tile, Trackdir track_dir)
| Clear the reservation of a tile that was just left by a wagon on track_dir.
void | FreeTrainTrackReservation (const Vehicle *v, TileIndex origin, Trackdir orig_td)
| Free the reserved path in front of a vehicle.
static bool | NtpCallbFindStation (TileIndex tile, TrainTrackFollowerData *ttfd, Trackdir track, uint length)
static void | FillWithStationData (TrainTrackFollowerData *fd, const Vehicle *v)
static Track | DoTrainPathfind (Vehicle *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool *path_not_found, bool do_track_reservation, PBSTileInfo *dest)
| Perform pathfinding for a train.
static PBSTileInfo | ExtendTrainReservation (const Vehicle *v, TrackBits *new_tracks, DiagDirection *enterdir)
| Extend a train path as far as possible.
static bool | TryReserveSafeTrack (const Vehicle *v, TileIndex tile, Trackdir td, bool override_tailtype)
| Try to reserve any path to a safe tile, ignoring the vehicle's destination.
bool | TryPathReserve (Vehicle *v, bool mark_as_stuck, bool first_tile_okay)
| Try to reserve a path to a safe position.
static bool | CheckReverseTrain (Vehicle *v)
static int | UpdateTrainSpeed (Vehicle *v)
| This function looks at the vehicle and updates it's speed (cur_speed and subspeed) variables.
static void | TrainEnterStation (Vehicle *v, StationID station)
static byte | AfterSetTrainPos (Vehicle *v, bool new_tile)
static Direction | GetNewVehicleDirectionByTile (TileIndex new_tile, TileIndex old_tile)
static int | GetDirectionToVehicle (const Vehicle *v, int x, int y)
static bool | CheckCompatibleRail (const Vehicle *v, TileIndex tile)
static void | AffectSpeedByDirChange (Vehicle *v, Direction new_dir)
| Modify the speed of the vehicle due to a turn.
static void | AffectSpeedByZChange (Vehicle *v, byte old_z)
| Modify the speed of the vehicle due to a change in altitude.
static bool | TrainMovedChangeSignals (TileIndex tile, DiagDirection dir)
static void | SetVehicleCrashed (Vehicle *v)
static uint | CountPassengersInTrain (const Vehicle *v)
static uint | TrainCrashed (Vehicle *v)
| Marks train as crashed and creates an AI event.
static Vehicle * | FindTrainCollideEnum (Vehicle *v, void *data)
static bool | CheckTrainCollision (Vehicle *v)
| Checks whether the specified train has a collision with another vehicle.
static Vehicle * | CheckVehicleAtSignal (Vehicle *v, void *data)
static Vehicle * | CollectTrackbitsFromCrashedVehiclesEnum (Vehicle *v, void *data)
| Collect trackbits of all crashed train vehicles on a tile.
static void | DeleteLastWagon (Vehicle *v)
| Deletes/Clears the last wagon of a crashed train.
static void | ChangeTrainDirRandomly (Vehicle *v)
static void | HandleCrashedTrain (Vehicle *v)
static void | HandleBrokenTrain (Vehicle *v)
static bool | TrainApproachingLineEnd (Vehicle *v, bool signal)
| Train is approaching line end, slow down and possibly reverse.
static bool | TrainCanLeaveTile (const Vehicle *v)
| Determines whether train would like to leave the tile.
static void | TrainLocoHandler (Vehicle *v, bool mode)
void | InitializeTrains ()

## Variables

static const byte | _vehicle_initial_x_fract [4] = {10, 8, 4, 8}
static const byte | _vehicle_initial_y_fract [4] = { 8, 4, 8, 10}
static const int8 | _vehicle_smoke_pos [8]
static const byte | _initial_tile_subcoord [6][4][3]
static const byte | _search_directions [6][4]
static const byte | _pick_track_table [6] = {1, 3, 2, 2, 0, 0}
static const Direction | _new_vehicle_direction_table [11]
static const RailtypeSlowdownParams | _railtype_slowdown []
static const uint16 | _breakdown_speeds [16]
| Maximum speeds for train that is broken down or approaching line end.

## Detailed Description

Handling of trains.

Definition in file train_cmd.cpp.

## Function Documentation

static void AdvanceWagonsAfterSwap | ( | Vehicle * | v | ) | `[static]`

Advances wagons for train reversing, needed for variable length wagons.

This one is called after the train is reversed.

Parameters:

  | v | First vehicle in chain

Definition at line 1764 of file train_cmd.cpp.

References GetRailDepotTrack(), TicksToLeaveDepot(), TRACK_BIT_DEPOT, and TrackToTrackBits().

static void AdvanceWagonsBeforeSwap | ( | Vehicle * | v | ) | `[static]`

Advances wagons for train reversing, needed for variable length wagons.

This one is called before the train is reversed.

Parameters:

  | v | First vehicle in chain

Definition at line 1736 of file train_cmd.cpp.

static void CheckNextTrainTile | ( | Vehicle * | v | ) | `[static]`

Check if the train is on the last reserved tile and try to extend the path then.

Definition at line 2314 of file train_cmd.cpp.

References _settings_game, FindFirstTrackdir(), CFollowTrackT< Ttr_type_, T90deg_turns_allowed_, Tmask_reserved_tracks >::Follow(), PathfinderSettings::forbid_90_deg, GetSignalStateByTrackdir(), GetStationIndex(), GetVehicleTrackdir(), HasPbsSignalOnTrackdir(), HasReservedTracks(), HasSignalOnTrackdir(), IsTileType(), KillFirstBit(), CFollowTrackT< Ttr_type_, T90deg_turns_allowed_, Tmask_reserved_tracks >::m_exitdir, CFollowTrackT< Ttr_type_, T90deg_turns_allowed_, Tmask_reserved_tracks >::m_new_td_bits, CFollowTrackT< Ttr_type_, T90deg_turns_allowed_, Tmask_reserved_tracks >::m_new_tile, CFollowTrackT< Ttr_type_, T90deg_turns_allowed_, Tmask_reserved_tracks >::m_old_td, MP_RAILWAY, PathfinderSettings::path_backoff_interval, PathfinderSettings::pathfinder_for_trains, GameSettings::pf, SIGNAL_STATE_RED, TRACK_BIT_DEPOT, TrackCrossesTracks(), TRACKDIR_BIT_NONE, TrackdirBitsToTrackBits(), TrackdirToTrack(), and VPF_NTP.

static bool CheckTrainCollision | ( | Vehicle * | v | ) | `[static]`

Checks whether the specified train has a collision with another vehicle.

If so, destroys this vehicle, and the other vehicle if its subtype has TS_Front. Reports the incident in a flashy news item, modifies station ratings and plays a sound.

Definition at line 3592 of file train_cmd.cpp.

References AddNewsItem(), FindVehicleOnPos(), FindVehicleOnPosXY(), GetOtherTunnelBridgeEnd(), NS_ACCIDENT_VEHICLE, TRACK_BIT_DEPOT, and TRACK_BIT_WORMHOLE.

void CheckTrainsLengths | ( |  | ) |

Checks if lengths of all rail vehicles are valid.

If not, shows an error message.

Definition at line 186 of file train_cmd.cpp.

References abs(), INVALID_STRING_ID, max(), TicksToLeaveDepot(), and TRACK_BIT_DEPOT.

Referenced by InitializeWindowsAndCaches(), and ReloadNewGRFData().

static void ClearPathReservation | ( | const Vehicle * | v,
|  | TileIndex | tile,
|  | Trackdir | track_dir |
| ) |  |  | `[static]`

Clear the reservation of a tile that was just left by a wagon on track_dir.

Definition at line 2427 of file train_cmd.cpp.

References _settings_client, GetOtherTunnelBridgeEnd(), GetTunnelBridgeDirection(), ClientSettings::gui, HasVehicleOnTunnelBridge(), IsTileType(), MarkTileDirtyByTile(), MP_TUNNELBRIDGE, ReverseDiagDir(), SetRailwayStationPlatformReservation(), SetTunnelBridgeReservation(), GUISettings::show_track_reservation, TileAddByDiagDir(), TrackdirToExitdir(), TrackdirToTrack(), and UnreserveRailTrack().

CommandCost CmdBuildRailVehicle | ( | TileIndex | tile,
|  | DoCommandFlag | flags,
|  | uint32 | p1,
|  | uint32 | p2,
|  | const char * | text |
| ) |  |  |

Build a railroad vehicle.

Parameters:

  | tile | tile of the depot where rail-vehicle is built
  | flags | type of operation
  | p1 | engine type id
  | p2 | bit 1 prevents any free cars from being added to the train

Definition at line 725 of file train_cmd.cpp.

References _cur_year, _date, _settings_game, AllocaM, CheckConsistencyOfArticulatedVehicle(), CMD_ERROR, CmdBuildRailWagon(), DAYS_IN_LEAP_YEAR, DC_AUTOREPLACE, DC_EXEC, DC_QUERY_COST, DEFAULT_GROUP, DiagDirToDir(), ENGINE_EXCLUSIVE_PREVIEW, GetRailDepotDirection(), GetRailType(), HasBit(), HasPowerOnRail(), InvalidateAutoreplaceWindow(), InvalidateWindow(), InvalidateWindowClassesData(), InvalidateWindowData(), IsEngineBuildable(), IsRailDepotTile(), IsTileOwner(), VehicleSettings::max_trains, NormalizeTrainVehInDepot(), RAILVEH_MULTIHEAD, RAILVEH_WAGON, return_cmd_error, VehicleSettings::servint_trains, SetBit(), SetFrontEngine(), SetMultiheaded(), SetTrainEngine(), TILE_SIZE, TileX(), TileY(), TRACK_BIT_DEPOT, Train::Train(), TrainConsistChanged(), UpdateTrainGroupID(), GameSettings::vehicle, VehicleMove(), and VehicleRandomBits().

static CommandCost CmdBuildRailWagon | ( | EngineID | engine,
|  | TileIndex | tile,
|  | DoCommandFlag | flags |
| ) |  |  | `[static]`

do not connect new wagon with crashed/flooded consists

Definition at line 573 of file train_cmd.cpp.

References _cur_year, AllocaM, CheckConsistencyOfArticulatedVehicle(), CMD_ERROR, DC_EXEC, DC_QUERY_COST, DEFAULT_GROUP, DiagDirToDir(), GetRailDepotDirection(), GetRailType(), HASBITS, InvalidateAutoreplaceWindow(), InvalidateWindow(), InvalidateWindowData(), IsCompatibleRail(), IsFreeWagon(), return_cmd_error, SetFreeWagon(), SetTrainWagon(), TILE_SIZE, TileX(), TileY(), TRACK_BIT_DEPOT, Train::Train(), TrainConsistChanged(), UpdateTrainGroupID(), VehicleMove(), and VehicleRandomBits().

Referenced by CmdBuildRailVehicle().

CommandCost CmdForceTrainProceed | ( | TileIndex | tile,
|  | DoCommandFlag | flags,
|  | uint32 | p1,
|  | uint32 | p2,
|  | const char * | text |
| ) |  |  |

Force a train through a red signal.

Parameters:

  | tile | unused
  | flags | type of operation
  | p1 | train to ignore the red signal
  | p2 | unused

Definition at line 1966 of file train_cmd.cpp.

References CMD_ERROR, DC_EXEC, and IsValidVehicleID().

CommandCost CmdMoveRailVehicle | ( | TileIndex | tile,
|  | DoCommandFlag | flags,
|  | uint32 | p1,
|  | uint32 | p2,
|  | const char * | text |
| ) |  |  |

Move a rail vehicle around inside the depot.

Parameters:

  | tile | unused
  | flags | type of operation Note: DC_AUTOREPLACE is set when autoreplace tries to undo its modifications or moves vehicles to temporary locations inside the depot.

  p1

  various bitstuffed elements
  - p1 (bit 0 - 15) source vehicle index
  - p1 (bit 16 - 31) what wagon to put the source wagon AFTER, XXX - INVALID_VEHICLE to make a new line

  | p2 | (bit 0) move all vehicles following the source vehicle

Definition at line 993 of file train_cmd.cpp.

References _settings_game, CALLBACK_FAILED, CBID_TRAIN_ALLOW_WAGON_ATTACH, ClearFreeWagon(), ClearFrontEngine(), CMD_ERROR, CmdMoveRailVehicle(), DC_AUTOREPLACE, DC_EXEC, DEFAULT_GROUP, DeleteVehicleOrders(), DeleteWindowById(), error, GB(), GetEngineGRFID(), GetGRFStringID(), GetLastEnginePart(), GetNextUnit(), GetNextVehicle(), GetVehicleCallbackParent(), HasBit(), HASBITS, InvalidateWindow(), InvalidateWindowClassesData(), InvalidateWindowData(), InvalidateWindowWidget(), IsArticulatedPart(), IsFreeWagon(), IsFrontEngine(), IsRearDualheaded(), IsTrainEngine(), IsValidVehicleID(), VehicleSettings::mammoth_trains, VehicleSettings::max_trains, RemoveVehicleFromGroup(), return_cmd_error, SetFreeWagon(), SetFrontEngine(), SetTrainGroupID(), TrainConsistChanged(), UnlinkWagon(), UpdateTrainGroupID(), and GameSettings::vehicle.

Referenced by CmdMoveRailVehicle().

CommandCost CmdRefitRailVehicle | ( | TileIndex | tile,
|  | DoCommandFlag | flags,
|  | uint32 | p1,
|  | uint32 | p2,
|  | const char * | text |
| ) |  |  |

Refits a train to the specified cargo type.

Parameters:

  | tile | unused
  | flags | type of operation

  p1

  vehicle ID of the train to refit param p2 various bitstuffed elements
  - p2 = (bit 0-7) - the new cargo type to refit to
  - p2 = (bit 8-15) - the new cargo subtype to refit to
  - p2 = (bit 16) - refit only this vehicle

Returns:
  cost of refit or error

Definition at line 1989 of file train_cmd.cpp.

References CommandCost::AddCost(), CALLBACK_FAILED, CanRefitTo(), CBID_VEHICLE_REFIT_CAPACITY, CBM_VEHICLE_REFIT_CAPACITY, CMD_ERROR, DC_EXEC, GB(), GetRefitCost(), GetVehicleCallback(), HasBit(), InvalidateWindow(), InvalidateWindowClassesData(), IsValidVehicleID(), return_cmd_error, and TrainConsistChanged().

CommandCost CmdReverseTrainDirection | ( | TileIndex | tile,
|  | DoCommandFlag | flags,
|  | uint32 | p1,
|  | uint32 | p2,
|  | const char * | text |
| ) |  |  |

Reverse train.

Parameters:

  | tile | unused
  | flags | type of operation
  | p1 | train to reverse
  | p2 | if true, reverse a unit in a train (needs to be in a depot)

Definition at line 1905 of file train_cmd.cpp.

References _settings_game, CBM_VEHICLE_ARTIC_ENGINE, CMD_ERROR, DC_EXEC, GetStationIndex(), HasBit(), InvalidateWindow(), IsMultiheaded(), IsTileType(), IsValidVehicleID(), MP_STATION, return_cmd_error, ToggleBit(), VehicleSettings::train_acceleration_model, and GameSettings::vehicle.

CommandCost CmdSellRailWagon | ( | TileIndex | tile,
|  | DoCommandFlag | flags,
|  | uint32 | p1,
|  | uint32 | p2,
|  | const char * | text |
| ) |  |  |

Sell a (single) train wagon/engine.

Parameters:

  | tile | unused
  | flags | type of operation
  | p1 | the wagon/engine index

  p2

  the selling mode
  - p2 = 0: only sell the single dragged wagon/engine (and any belonging rear-engines)
  - p2 = 1: sell the vehicle and all vehicles following it in the chain if the wagon is dragged, don't delete the possibly belonging rear-engine to some front

Definition at line 1348 of file train_cmd.cpp.

References CommandCost::AddCost(), CMD_ERROR, CMD_MOVE_RAIL_VEHICLE, DC_EXEC, DEFAULT_GROUP, DeleteVehicleOrders(), DeleteWindowById(), DoCommand(), CommandCost::Failed(), GetNextVehicle(), HASBITS, InvalidateWindow(), InvalidateWindowClassesData(), IsArticulatedPart(), IsFrontEngine(), IsMultiheaded(), IsRearDualheaded(), IsTrainEngine(), IsValidVehicleID(), return_cmd_error, SetFrontEngine(), ShowVehicleViewWindow(), TrainConsistChanged(), UnlinkWagon(), and UpdateTrainGroupID().

CommandCost CmdSendTrainToDepot | ( | TileIndex | tile,
|  | DoCommandFlag | flags,
|  | uint32 | p1,
|  | uint32 | p2,
|  | const char * | text |
| ) |  |  |

Send a train to a depot.

Parameters:

  | tile | unused
  | flags | type of operation
  | p1 | train to send to the depot

  p2

  various bitmasked elements
  - p2 bit 0-3 - DEPOT_ flags (see vehicle.h)
  - p2 bit 8-10 - VLW flag (for mass goto depot)

Definition at line 2193 of file train_cmd.cpp.

References CMD_ERROR, DEPOT_MASS_SEND, DEPOT_SERVICE, IsValidVehicleID(), and SendAllVehiclesToDepot().

static Vehicle* CollectTrackbitsFromCrashedVehiclesEnum | ( | Vehicle * | v,
|  | void * | data |
| ) |  |  | `[static]`

Collect trackbits of all crashed train vehicles on a tile.

Parameters:

  | v | Vehicle passed from Find/HasVehicleOnPos()
  | data | trackdirbits for the result

Returns:
  NULL to iterate over all vehicles on the tile.

Definition at line 3900 of file train_cmd.cpp.

References DiagDirToDiagTrackBits(), GetTunnelBridgeDirection(), and TRACK_BIT_WORMHOLE.

Referenced by DeleteLastWagon().

static void DeleteLastWagon | ( | Vehicle * | v | ) | `[static]`

Deletes/Clears the last wagon of a crashed train.

It takes the engine of the train, then goes to the last wagon and deletes that. Each call to this function will remove the last wagon of a crashed train. If this wagon was on a crossing, or inside a tunnel/bridge, recalculate the signals as they might need updating

Parameters:

  | v | the Vehicle of which last wagon is to be removed

Definition at line 3923 of file train_cmd.cpp.

References CollectTrackbitsFromCrashedVehiclesEnum(), DiagDirToDiagTrackBits(), FindVehicleOnPos(), GetTunnelBridgeDirection(), HasBit(), HasReservedTracks(), INVALID_DIAGDIR, InvalidateWindow(), IsRailDepotTile(), IsTileType(), MP_TUNNELBRIDGE, SetSignalsOnBothDir(), TRACK_BEGIN, TRACK_BIT_DEPOT, TRACK_BIT_NONE, TRACK_BIT_WORMHOLE, TRACK_END, TRACK_X, TRACK_Y, TrackBitsToTrack(), TrainConsistChanged(), TryReserveRailTrack(), UnreserveRailTrack(), UpdateLevelCrossing(), and UpdateSignalsOnSegment().

static Track DoTrainPathfind | ( | Vehicle * | v,
|  | TileIndex | tile,
|  | DiagDirection | enterdir,
|  | TrackBits | tracks,
|  | bool * | path_not_found,
|  | bool | do_track_reservation,
|  | PBSTileInfo * | dest |
| ) |  |  | `[static]`

Perform pathfinding for a train.

Parameters:

  | v | The train
  | tile | The tile the train is about to enter
  | enterdir | Diagonal direction the train is coming from
  | tracks | Usable tracks on the new tile
  | path_not_found | [out] Set to false if the pathfinder couldn't find a way to the destination
  | do_track_reservation | Path reservation is requested
  | dest | [out] State and destination of the requested path

Returns:
  The best track the train should follow

Definition at line 2586 of file train_cmd.cpp.

References _settings_game, TrainTrackFollowerData::best_bird_dist, TrainTrackFollowerData::best_track, TrainTrackFollowerData::best_track_dist, FindFirstTrack(), FollowTrainReservation(), INVALID_TRACKDIR, IsValidTrackdir(), NewTrainPathfind(), NpfBeginInterval(), NpfEndInterval(), PBSTileInfo::okay, PathfinderSettings::pathfinder_for_trains, GameSettings::pf, PBSTileInfo::tile, TileOffsByDiagDir(), PBSTileInfo::trackdir, TrackdirToTrack(), TRANSPORT_RAIL, VPF_NPF, VPF_NTP, VPF_YAPF, and YapfChooseRailTrack().

static PBSTileInfo ExtendTrainReservation | ( | const Vehicle * | v,
|  | TrackBits * | new_tracks,
|  | DiagDirection * | enterdir |
| ) |  |  | `[static]`

Extend a train path as far as possible.

Stops on encountering a safe tile, another reservation or a track choice.

Returns:
  INVALID_TILE indicates that the reservation failed.

Definition at line 2687 of file train_cmd.cpp.

References _settings_game, FindFirstTrackdir(), CFollowTrackT< Ttr_type_, T90deg_turns_allowed_, Tmask_reserved_tracks >::Follow(), FollowTrainReservation(), PathfinderSettings::forbid_90_deg, HasOnewaySignalBlockingTrackdir(), HasReservedTracks(), IsPlainRail(), IsSafeWaitingPosition(), IsTileType(), IsWaitingPositionFree(), KillFirstBit(), CFollowTrackT< Ttr_type_, T90deg_turns_allowed_, Tmask_reserved_tracks >::m_err, CFollowTrackT< Ttr_type_, T90deg_turns_allowed_, Tmask_reserved_tracks >::m_exitdir, CFollowTrackT< Ttr_type_, T90deg_turns_allowed_, Tmask_reserved_tracks >::m_is_station, CFollowTrackT< Ttr_type_, T90deg_turns_allowed_, Tmask_reserved_tracks >::m_new_td_bits, CFollowTrackT< Ttr_type_, T90deg_turns_allowed_, Tmask_reserved_tracks >::m_new_tile, CFollowTrackT< Ttr_type_, T90deg_turns_allowed_, Tmask_reserved_tracks >::m_old_td, CFollowTrackT< Ttr_type_, T90deg_turns_allowed_, Tmask_reserved_tracks >::m_old_tile, CFollowTrackT< Ttr_type_, T90deg_turns_allowed_, Tmask_reserved_tracks >::m_tiles_skipped, MP_RAILWAY, PathfinderSettings::pathfinder_for_trains, GameSettings::pf, PBSTileInfo::tile, TileOffsByDiagDir(), PBSTileInfo::trackdir, TRACKDIR_BIT_NONE, TrackdirBitsToTrackBits(), TrackdirCrossesTrackdirs(), TrackdirReachesTrackdirs(), TrackdirToTrack(), TryReserveRailTrack(), UnreserveRailTrack(), and VPF_NTP.

static TrainFindDepotData FindClosestTrainDepot | ( | Vehicle * | v,
|  | int | max_distance |
| ) |  |  | `[static]`

returns the tile of a depot to goto to.

The given vehicle must not be crashed!

Definition at line 2105 of file train_cmd.cpp.

References _settings_game, FollowTrainReservation(), GetVehicleTrackdir(), HasReservedTracks(), INVALID_TRACKDIR, IsRailDepotTile(), NewTrainPathfind(), NPF_FLAG_REVERSE, NPF_INFINITE_PENALTY, NPFGetFlag(), PathfinderSettings::pathfinder_for_trains, GameSettings::pf, PathfinderSettings::reserve_paths, ReverseDir(), ReverseTrackdir(), PBSTileInfo::tile, TrainExitDir(), TRANSPORT_RAIL, VPF_NPF, VPF_NTP, VPF_YAPF, and YapfFindNearestRailDepotTwoWay().

void FreeTrainTrackReservation | ( | const Vehicle * | v,
|  | TileIndex | origin,
|  | Trackdir | orig_td |
| ) |  |  |

Free the reserved path in front of a vehicle.

Definition at line 2461 of file train_cmd.cpp.

References ClearPathReservation(), RailtypeInfo::compatible_railtypes, CFollowTrackT< Ttr_type_, T90deg_turns_allowed_, Tmask_reserved_tracks >::Follow(), GetRailTypeInfo(), GetReservedTrackbits(), GetSignalStateByTrackdir(), GetStationIndex(), GetVehicleTrackdir(), HasPbsSignalOnTrackdir(), HasSignalOnTrackdir(), INVALID_TILE, INVALID_TRACKDIR, IsFrontEngine(), IsOnewaySignal(), IsTileType(), IsValidTrackdir(), CFollowTrackT< Ttr_type_, T90deg_turns_allowed_, Tmask_reserved_tracks >::m_is_bridge, CFollowTrackT< Ttr_type_, T90deg_turns_allowed_, Tmask_reserved_tracks >::m_is_station, CFollowTrackT< Ttr_type_, T90deg_turns_allowed_, Tmask_reserved_tracks >::m_is_tunnel, CFollowTrackT< Ttr_type_, T90deg_turns_allowed_, Tmask_reserved_tracks >::m_new_td_bits, CFollowTrackT< Ttr_type_, T90deg_turns_allowed_, Tmask_reserved_tracks >::m_new_tile, MarkTileDirtyByTile(), MP_RAILWAY, MP_TUNNELBRIDGE, RemoveFirstTrackdir(), ReverseTrackdir(), SetSignalStateByTrackdir(), SIGNAL_STATE_RED, TrackBitsToTrackdirBits(), TRACKDIR_BIT_NONE, TrackdirToTrack(), TracksOverlap(), TrackToTrackBits(), and UnreserveRailTrack().

Referenced by CmdBuildRailroadStation(), CmdBuildSingleSignal(), CmdConvertRail(), CmdRemoveFromRailroadStation(), CmdRemoveSingleRail(), and RemoveTrainWaypoint().

byte FreightWagonMult | ( | CargoID | cargo | ) |

Return the cargo weight multiplier to use for a rail vehicle.

Parameters:

  | cargo | Cargo type to get multiplier for

Returns:
  Cargo weight multiplier

Definition at line 77 of file train_cmd.cpp.

References _settings_game, VehicleSettings::freight_trains, and GameSettings::vehicle.

Referenced by TrainCargoChanged().

static void MarkTrainAsStuck | ( | Vehicle * | v | ) | `[static]`

Mark a train as stuck and stop it if it isn't stopped right now.

Definition at line 1548 of file train_cmd.cpp.

References HasBit(), InvalidateWindowWidget(), and SetBit().

Referenced by TryPathReserve().

static void MaybeBarCrossingWithSound | ( | TileIndex | tile | ) | `[inline, static]`

Bars crossing and plays ding-ding sound if not barred already.

Parameters:

  | tile | tile with crossing

Precondition:
  tile is a rail-road crossing

Definition at line 1721 of file train_cmd.cpp.

References MarkTileDirtyByTile().

Referenced by TrainCheckIfLineEnds().

static void RailVehicleLengthChanged | ( | const Vehicle * | u | ) | `[static]`

Logs a bug in GRF and shows a warning message if this is for the first time this happened.

Parameters:

  | u | first vehicle of chain

Definition at line 174 of file train_cmd.cpp.

References GamelogGRFBugReverse(), GBUG_VEH_LENGTH, GRFConfig::grf_bugs, HasBit(), and ShowNewGrfVehicleError().

Referenced by TrainConsistChanged().

static bool TrainApproachingCrossing | ( | TileIndex | tile | ) | `[static]`

Finds a vehicle approaching rail-road crossing.

Parameters:

  | tile | tile to test

Returns:
  true if a vehicle is approaching the crossing

Precondition:
  tile is a rail-road crossing

Definition at line 1677 of file train_cmd.cpp.

References AxisToDiagDir(), HasVehicleOnPos(), ReverseDiagDir(), TileOffsByDiagDir(), and TrainApproachingCrossingEnum().

Referenced by UpdateLevelCrossing().

static Vehicle* TrainApproachingCrossingEnum | ( | Vehicle * | v,
|  | void * | data |
| ) |  |  | `[static]`

Checks if a train is approaching a rail-road crossing.

Parameters:

  | v | vehicle on tile
  | data | tile with crossing we are testing

Returns:
  v if it is approaching a crossing, NULL otherwise

Definition at line 1658 of file train_cmd.cpp.

References IsFrontEngine(), and TrainApproachingCrossingTile().

Referenced by TrainApproachingCrossing().

static TileIndex TrainApproachingCrossingTile | ( | const Vehicle * | v | ) | `[static]`

Determines whether train is approaching a rail-road crossing (thus making it barred).

Parameters:

  | v | front engine of train

Returns:
  TileIndex of crossing the train is approaching, else INVALID_TILE

Precondition:
  v in non-crashed front engine

Definition at line 4155 of file train_cmd.cpp.

References DiagDirToAxis(), INVALID_TILE, IsFrontEngine(), TileOffsByDiagDir(), TrainCanLeaveTile(), and TrainExitDir().

Referenced by TrainApproachingCrossingEnum().

static bool TrainApproachingLineEnd | ( | Vehicle * | v,
|  | bool | signal |
| ) |  |  | `[static]`

Train is approaching line end, slow down and possibly reverse.

Parameters:

  | v | front train engine
  | signal | not line end, just a red signal

Returns:
  true iff we did NOT have to reverse

Definition at line 4084 of file train_cmd.cpp.

References DIR_E, DIR_N, DIR_NE, DIR_NW, DIR_S, DIR_SE, DIR_W, and TILE_SIZE.

Referenced by TrainCheckIfLineEnds().

static bool TrainCanLeaveTile | ( | const Vehicle * | v | ) | `[static]`

Determines whether train would like to leave the tile.

Parameters:

  | v | train to test

Returns:
  true iff vehicle is NOT entering or inside a depot or tunnel/bridge

Definition at line 4125 of file train_cmd.cpp.

References DiagDirToDir(), GetRailDepotDirection(), GetTunnelBridgeDirection(), IsRailDepotTile(), IsTileType(), MP_TUNNELBRIDGE, ReverseDiagDir(), TRACK_BIT_DEPOT, and TRACK_BIT_WORMHOLE.

Referenced by TrainApproachingCrossingTile(), and TrainCheckIfLineEnds().

static void TrainCargoChanged | ( | Vehicle * | v | ) | `[static]`

Recalculates the cached weight of a train and its vehicles.

Should be called each time the cargo on the consist changes.

Parameters:

  | v | First vehicle of the consist.

Definition at line 137 of file train_cmd.cpp.

References FreightWagonMult(), HasBit(), IsArticulatedPart(), and TrainPowerChanged().

Referenced by TrainConsistChanged().

static bool TrainCheckIfLineEnds | ( | Vehicle * | v | ) | `[static]`

Checks for line end.

Also, bars crossing at next tile if needed

Parameters:

  | v | vehicle we are checking

Returns:
  true iff we did NOT have to reverse

Definition at line 4181 of file train_cmd.cpp.

References _settings_game, DiagdirReachesTrackdirs(), FindFirstTrack(), PathfinderSettings::forbid_90_deg, GB(), GetTileTrackStatus(), MaybeBarCrossingWithSound(), PathfinderSettings::pathfinder_for_trains, GameSettings::pf, ReverseDiagDir(), TileOffsByDiagDir(), TRACK_BIT_NONE, TrackCrossesTracks(), TrackdirBitsToTrackBits(), TrackStatusToRedSignals(), TrackStatusToTrackdirBits(), TrainApproachingLineEnd(), TrainCanLeaveTile(), TrainExitDir(), TRANSPORT_RAIL, and VPF_NTP.

void TrainConsistChanged | ( | Vehicle * | v,
|  | bool | same_length |
| ) |  |  |

Recalculates the cached stuff of a train.

Should be called each time a vehicle is added to/removed from the chain, and when the game is loaded. Note: this needs to be called too for 'wagon chains' (in the depot, without an engine)

Parameters:

  | v | First vehicle of the chain.
  | same_length | should length of vehicles stay the same?

Definition at line 216 of file train_cmd.cpp.

References _settings_game, CALLBACK_FAILED, CBID_TRAIN_WAGON_POWER, CBID_VEHICLE_LENGTH, CBM_TRAIN_WAGON_POWER, CBM_VEHICLE_LENGTH, Clamp(), ClrBit(), EF_RAIL_TILTS, GB(), GetRailTypeInfo(), GetVehicleCallback(), HasBit(), InvalidateWindow(), IsArticulatedPart(), IsFreeWagon(), IsFrontEngine(), IsTrainEngine(), IsTrainWagon(), min(), RailtypeInfo::powered_railtypes, RAILTYPE_RAIL, RAILTYPES_NONE, RAILTYPES_RAIL, RAILVEH_WAGON, RailVehicleLengthChanged(), SetBit(), TrainCargoChanged(), UsesWagonOverride(), GameSettings::vehicle, and VehicleSettings::wagon_speed_limits.

Referenced by AfterLoadVehicles(), CmdBuildRailVehicle(), CmdBuildRailWagon(), CmdMoveRailVehicle(), CmdRefitRailVehicle(), CmdSellRailWagon(), DeleteLastWagon(), StateGameLoop(), and TransferCargo().

static uint TrainCrashed | ( | Vehicle * | v | ) | `[static]`

Marks train as crashed and creates an AI event.

Doesn't do anything if the train is crashed already.

Parameters:

  | v | first vehicle of chain

Returns:
  number of victims (including 2 drivers; zero if train was already crashed)

Definition at line 3528 of file train_cmd.cpp.

References AIEventVehicleCrashed::CRASH_TRAIN.

static DiagDirection TrainExitDir | ( | Direction | direction,
|  | TrackBits | track |
| ) |  |  | `[inline, static]`

Determine the side in which the train will leave the tile.

Parameters:

  | direction | vehicle direction
  | track | vehicle track bits

Returns:
  side of tile the train will leave

Definition at line 58 of file train_cmd.cpp.

References ChangeDiagDir(), DIAGDIR_END, DIAGDIRDIFF_90LEFT, DirToDiagDir(), HasBit(), TRACK_BIT_LEFT, TRACK_BIT_LOWER, TRACK_BIT_RIGHT, and TRACK_BIT_UPPER.

Referenced by FindClosestTrainDepot(), TrainApproachingCrossingTile(), TrainCheckIfLineEnds(), and TryPathReserve().

static Vehicle* TrainOnTileEnum | ( | Vehicle * | v,
|  | void * |  |
| ) |  |  | `[static]`

Check if the vehicle is a train.

Parameters:

  | v | vehicle on tile

Returns:
  v if it is a train, NULL otherwise

Definition at line 1646 of file train_cmd.cpp.

void TrainPowerChanged | ( | Vehicle * | v | ) |

Recalculates the cached total power of a train.

Should be called when the consist is changed

Parameters:

  | v | First vehicle of the consist.

Definition at line 88 of file train_cmd.cpp.

References GetRailType(), HasBit(), HasPowerOnRail(), InvalidateWindow(), InvalidateWindowWidget(), IsArticulatedPart(), and IsMultiheaded().

Referenced by SettingsDisableElrail(), TrainCargoChanged(), and UpdateTrainPowerProc().

bool TryPathReserve | ( | Vehicle * | v,
|  | bool | mark_as_stuck,
|  | bool | first_tile_okay |
| ) |  |  |

Try to reserve a path to a safe position.

Parameters:

  | v | The vehicle
  | mark_as_stuck | Should the train be marked as stuck on a failed reservation?
  | first_tile_okay | True if no path should be reserved if the current tile is a safe position.

Returns:
  True if a path could be reserved.

Definition at line 3048 of file train_cmd.cpp.

References _settings_client, _settings_game, ClrBit(), DiagdirReachesTrackdirs(), DiagdirReachesTracks(), FindFirstTrackdir(), FollowTrainReservation(), PathfinderSettings::forbid_90_deg, GetDepotWaypointReservation(), GetRailDepotDirection(), GetReservedTrackbits(), GetTileTrackStatus(), ClientSettings::gui, HasBit(), HasReservedTracks(), HasSignalOnTrackdir(), InvalidateWindowWidget(), IsFrontEngine(), IsTileType(), MarkTileDirtyByTile(), MarkTrainAsStuck(), MP_RAILWAY, PBSTileInfo::okay, PathfinderSettings::pathfinder_for_trains, GameSettings::pf, ReverseTrackdir(), SetDepotWaypointReservation(), GUISettings::show_track_reservation, PBSTileInfo::tile, TileAddByDiagDir(), TRACK_BIT_DEPOT, TrackBitsToTrackdirBits(), TrackCrossesTracks(), PBSTileInfo::trackdir, TrackdirBitsToTrackBits(), TrackdirToExitdir(), TrackdirToTrack(), TrackStatusToTrackdirBits(), TrainExitDir(), TRANSPORT_RAIL, and VPF_NTP.

Referenced by CmdBuildRailroadStation(), CmdBuildSingleSignal(), CmdConvertRail(), CmdRemoveFromRailroadStation(), CmdRemoveSingleRail(), CmdRemoveSingleSignal(), and RemoveTrainWaypoint().

static bool TryReserveSafeTrack | ( | const Vehicle * | v,
|  | TileIndex | tile,
|  | Trackdir | td,
|  | bool | override_tailtype |
| ) |  |  | `[static]`

Try to reserve any path to a safe tile, ignoring the vehicle's destination.

Safe tiles are tiles in front of a signal, depots and station tiles at end of line.

Parameters:

  | v | The vehicle.
  | tile | The tile the search should start from.
  | td | The trackdir the search should start from.
  | override_tailtype | Whether all physically compatible railtypes should be followed.

Returns:
  True if a path to a safe stopping tile could be reserved.

Definition at line 2780 of file train_cmd.cpp.

References _settings_game, NPFRouteToSafeTile(), PathfinderSettings::pathfinder_for_trains, GameSettings::pf, VPF_YAPF, and YapfRailFindNearestSafeTile().

static Vehicle* UnlinkWagon | ( | Vehicle * | v,
|  | Vehicle * | first |
| ) |  |  | `[static]`

Unlink a rail wagon from the consist.

Parameters:

  | v | Vehicle to remove.
  | first | The first vehicle of the consist.

Returns:
  The first vehicle of the consist.

Definition at line 901 of file train_cmd.cpp.

References GetLastEnginePart(), GetNextVehicle(), IsTrainWagon(), and SetFreeWagon().

Referenced by CmdMoveRailVehicle(), and CmdSellRailWagon().

void UpdateLevelCrossing | ( | TileIndex | tile,
|  | bool | sound |
| ) |  |  |

Sets correct crossing state.

Parameters:

  | tile | tile to update
  | sound | should we play sound?

Precondition:
  tile is a rail-road crossing

Definition at line 1699 of file train_cmd.cpp.

References GetCrossingReservation(), HasVehicleOnPos(), MarkTileDirtyByTile(), TrainApproachingCrossing(), and TrainOnTileEnum().

Referenced by CmdBuildRoad(), CmdBuildSingleRail(), DeleteLastWagon(), and UnreserveRailTrack().

static int UpdateTrainSpeed | ( | Vehicle * | v | ) | `[static]`

This function looks at the vehicle and updates it's speed (cur_speed and subspeed) variables.

Furthermore, it returns the distance that the train can drive this tick. This distance is expressed as 256 * n, where n is the number of straight (long) tracks the train can traverse. This means that moving along a straight track costs 256 "speed" and a diagonal track costs 192 "speed".

Parameters:

  | v | The vehicle to update the speed of.

Returns:
  distance to drive.

Definition at line 3268 of file train_cmd.cpp.

References _settings_game, Clamp(), GetTrainAcceleration(), HasBit(), VehicleSettings::train_acceleration_model, and GameSettings::vehicle.

## Variable Documentation

const uint16 _breakdown_speeds[16]`[static]`

Initial value:

     {
      225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
    }

Maximum speeds for train that is broken down or approaching line end.

Definition at line 4072 of file train_cmd.cpp.

const byte _initial_tile_subcoord[6][4][3]`[static]`

Initial value:

     {
    {{ 15, 8, 1 }, { 0, 0, 0 }, { 0, 8, 5 }, { 0,  0, 0 }},
    {{  0, 0, 0 }, { 8, 0, 3 }, { 0, 0, 0 }, { 8, 15, 7 }},
    {{  0, 0, 0 }, { 7, 0, 2 }, { 0, 7, 6 }, { 0,  0, 0 }},
    {{ 15, 8, 2 }, { 0, 0, 0 }, { 0, 0, 0 }, { 8, 15, 6 }},
    {{ 15, 7, 0 }, { 8, 0, 4 }, { 0, 0, 0 }, { 0,  0, 0 }},
    {{  0, 0, 0 }, { 0, 0, 0 }, { 0, 8, 4 }, { 7, 15, 0 }},
    }

Definition at line 2554 of file train_cmd.cpp.

const Direction _new_vehicle_direction_table[11]`[static]`

Initial value:

     {
      DIR_N , DIR_NW, DIR_W , INVALID_DIR,
      DIR_NE, DIR_N , DIR_SW, INVALID_DIR,
      DIR_E , DIR_SE, DIR_S
    }

Definition at line 3368 of file train_cmd.cpp.

const RailtypeSlowdownParams _railtype_slowdown[]`[static]`

Initial value:

     {

      {256 / 4, 256 / 2, 256 / 4, 2},
      {256 / 4, 256 / 2, 256 / 4, 2},
      {256 / 4, 256 / 2, 256 / 4, 2},
      {0,       256 / 2, 256 / 4, 2},
    }

Definition at line 3420 of file train_cmd.cpp.

const byte _search_directions[6][4]`[static]`

Initial value:

     {
      { 0, 9, 2, 9 },
      { 9, 1, 9, 3 },
      { 9, 0, 3, 9 },
      { 1, 9, 9, 2 },
      { 3, 2, 9, 9 },
      { 9, 9, 1, 0 },
    }

Definition at line 2563 of file train_cmd.cpp.

const int8 _vehicle_smoke_pos[8]`[static]`

Initial value:

     {
      1, 1, 1, 0, -1, -1, -1, 0
    }

Definition at line 2216 of file train_cmd.cpp.