Go to the documentation of this file.
1 /* $Id: train.h 27811 2017-03-20 17:49:44Z peter1138 $ */
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 <>.
8  */
12 #ifndef TRAIN_H
13 #define TRAIN_H
15 #include "core/enum_type.hpp"
17 #include "newgrf_engine.h"
18 #include "cargotype.h"
19 #include "rail.h"
20 #include "engine_base.h"
21 #include "rail_map.h"
22 #include "ground_vehicle.hpp"
24 struct Train;
36 };
40  TFP_NONE = 0,
41  TFP_STUCK = 1,
42  TFP_SIGNAL = 2,
43 };
48  CCF_LENGTH = 0x01,
49  CCF_CAPACITY = 0x02,
51  CCF_TRACK = 0,
57 };
62 void CheckTrainsLengths();
64 void FreeTrainTrackReservation(const Train *v);
65 bool TryPathReserve(Train *v, bool mark_as_stuck = false, bool first_tile_okay = false);
67 int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *v, int *station_ahead, int *station_length);
69 void GetTrainSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type);
72 struct TrainCache {
73  /* Cached wagon override spritegroup */
74  const struct SpriteGroup *cached_override;
76  /* cached values, recalculated on load and each time a vehicle is added to/removed from the consist. */
77  bool cached_tilt;
81  /* cached max. speed / acceleration data */
83 };
88 struct Train FINAL : public GroundVehicle<Train, VEH_TRAIN> {
89  TrainCache tcache;
91  /* Link between the two ends of a multiheaded engine */
92  Train *other_multiheaded_part;
94  uint16 crash_anim_pos;
96  uint16 flags;
97  TrackBitsByte track;
98  TrainForceProceedingByte force_proceed;
99  RailTypeByte railtype;
100  RailTypes compatible_railtypes;
103  uint16 wait_counter;
108  virtual ~Train() { this->PreDestructor(); }
110  friend struct GroundVehicle<Train, VEH_TRAIN>; // GroundVehicle needs to use the acceleration functions defined at Train.
112  void MarkDirty();
114  ExpensesType GetExpenseType(bool income) const { return income ? EXPENSES_TRAIN_INC : EXPENSES_TRAIN_RUN; }
115  void PlayLeaveStationSound() const;
116  bool IsPrimaryVehicle() const { return this->IsFrontEngine(); }
117  void GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const;
118  int GetDisplaySpeed() const { return this->gcache.last_speed; }
119  int GetDisplayMaxSpeed() const { return this->vcache.cached_max_speed; }
120  Money GetRunningCost() const;
121  int GetDisplayImageWidth(Point *offset = NULL) const;
122  bool IsInDepot() const { return this->track == TRACK_BIT_DEPOT; }
123  bool Tick();
124  void OnNewDay();
125  uint Crash(bool flooded = false);
127  TileIndex GetOrderStationLocation(StationID station);
128  bool FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse);
130  void ReserveTrackUnderConsist() const;
132  int GetCurveSpeedLimit() const;
134  void ConsistChanged(ConsistChangeFlags allowed_changes);
136  int UpdateSpeed();
138  void UpdateAcceleration();
140  int GetCurrentMaxSpeed() const;
146  inline Train *GetNextUnit() const
147  {
148  Train *v = this->GetNextVehicle();
149  if (v != NULL && v->IsRearDualheaded()) v = v->GetNextVehicle();
151  return v;
152  }
158  inline Train *GetPrevUnit()
159  {
160  Train *v = this->GetPrevVehicle();
161  if (v != NULL && v->IsRearDualheaded()) v = v->GetPrevVehicle();
163  return v;
164  }
171  {
172  /* For vehicles with odd lengths the part before the center will be one unit
173  * longer than the part after the center. This means we have to round up the
174  * length of the next vehicle but may not round the length of the current
175  * vehicle. */
176  return this->gcache.cached_veh_length / 2 + (this->Next() != NULL ? this->Next()->gcache.cached_veh_length + 1 : 0) / 2;
177  }
179 protected: // These functions should not be called outside acceleration code.
185  inline uint16 GetPower() const
186  {
187  /* Power is not added for articulated parts */
188  if (!this->IsArticulatedPart() && HasPowerOnRail(this->railtype, GetRailType(this->tile))) {
189  uint16 power = GetVehicleProperty(this, PROP_TRAIN_POWER, RailVehInfo(this->engine_type)->power);
190  /* Halve power for multiheaded parts */
191  if (this->IsMultiheaded()) power /= 2;
192  return power;
193  }
195  return 0;
196  }
202  inline uint16 GetPoweredPartPower(const Train *head) const
203  {
204  /* For powered wagons the engine defines the type of engine (i.e. railtype) */
205  if (HasBit(this->flags, VRF_POWEREDWAGON) && HasPowerOnRail(head->railtype, GetRailType(this->tile))) {
206  return RailVehInfo(this->gcache.first_engine)->pow_wag_power;
207  }
209  return 0;
210  }
216  inline uint16 GetWeight() const
217  {
218  uint16 weight = (CargoSpec::Get(this->cargo_type)->weight * this->cargo.StoredCount() * FreightWagonMult(this->cargo_type)) / 16;
220  /* Vehicle weight is not added for articulated parts. */
221  if (!this->IsArticulatedPart()) {
222  weight += GetVehicleProperty(this, PROP_TRAIN_WEIGHT, RailVehInfo(this->engine_type)->weight);
223  }
225  /* Powered wagons have extra weight added. */
226  if (HasBit(this->flags, VRF_POWEREDWAGON)) {
227  weight += RailVehInfo(this->gcache.first_engine)->pow_wag_weight;
228  }
230  return weight;
231  }
237  inline byte GetTractiveEffort() const
238  {
239  return GetVehicleProperty(this, PROP_TRAIN_TRACTIVE_EFFORT, RailVehInfo(this->engine_type)->tractive_effort);
240  }
246  inline byte GetAirDragArea() const
247  {
248  /* Air drag is higher in tunnels due to the limited cross-section. */
249  return (this->track == TRACK_BIT_WORMHOLE && this->vehstatus & VS_HIDDEN) ? 28 : 14;
250  }
256  inline byte GetAirDrag() const
257  {
258  return RailVehInfo(this->engine_type)->air_drag;
259  }
266  {
267  return (this->vehstatus & VS_STOPPED) || HasBit(this->flags, VRF_REVERSING) || HasBit(this->flags, VRF_TRAIN_STUCK) ? AS_BRAKE : AS_ACCEL;
268  }
274  inline uint16 GetCurrentSpeed() const
275  {
276  return this->cur_speed;
277  }
283  inline uint32 GetRollingFriction() const
284  {
285  /* Rolling friction for steel on steel is between 0.1% and 0.2%.
286  * The friction coefficient increases with speed in a way that
287  * it doubles at 512 km/h, triples at 1024 km/h and so on. */
288  return 15 * (512 + this->GetCurrentSpeed()) / 512;
289  }
295  inline int GetAccelerationType() const
296  {
297  return GetRailTypeInfo(this->railtype)->acceleration_type;
298  }
304  inline uint32 GetSlopeSteepness() const
305  {
307  }
313  inline uint16 GetMaxTrackSpeed() const
314  {
315  return GetRailTypeInfo(GetRailType(this->tile))->max_speed;
316  }
322  inline bool TileMayHaveSlopedTrack() const
323  {
324  /* Any track that isn't TRACK_BIT_X or TRACK_BIT_Y cannot be sloped. */
325  return this->track == TRACK_BIT_X || this->track == TRACK_BIT_Y;
326  }
334  {
335  return false;
336  }
337 };
339 #define FOR_ALL_TRAINS(var) FOR_ALL_VEHICLES_OF_TYPE(Train, var)
341 #endif /* TRAIN_H */
VehicleSettings vehicle
options for vehicles
static bool HasPowerOnRail(RailType enginetype, RailType tiletype)
Checks if an engine of the given RailType got power on a tile with a given RailType.
Definition: rail.h:324
Vehicle is stopped by the player.
Definition: vehicle_base.h:33
DECLARE_ENUM_AS_BIT_SET(GenderEthnicity) enum CompanyManagerFaceVariable
Bitgroups of the CompanyManagerFace variable.
bool cached_tilt
train can tilt; feature provides a bonus in curves
Definition: train.h:77
VehicleCargoList cargo
The cargo this vehicle is carrying.
Definition: vehicle_base.h:309
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:77
ExpensesType GetExpenseType(bool income) const
Sets the expense type associated to this vehicle type.
Definition: train.h:114
int CalcNextVehicleOffset() const
Calculate the offset from this vehicle&#39;s center to the following center taking the vehicle lengths in...
Definition: train.h:170
Functions for NewGRF engines.
static const RailtypeInfo * GetRailTypeInfo(RailType railtype)
Returns a pointer to the Railtype information for a given railtype.
Definition: rail.h:296
The different roadtypes we support, but then a bitmask of them.
Definition: rail_type.h:52
virtual void MarkDirty()
Marks the vehicles to be redrawn and updates cached variables.
Definition: vehicle_base.h:364
uint8 weight
Weight of a single unit of this cargo type in 1/16 ton (62.5 kg).
Definition: cargotype.h:61
What is the status of our acceleration?
DirectionByte direction
Definition: vehicle_base.h:271
Train is just leaving a station.
Definition: train.h:35
uint16 GetCurrentSpeed() const
Calculates the current speed of this vehicle.
Definition: train.h:274
Flags for Train::ConsistChanged.
Definition: train.h:47
bool TileMayHaveSlopedTrack() const
Checks if the vehicle is at a tile that can be sloped.
Definition: train.h:322
Power in hp (if dualheaded: sum of both vehicles)
void CheckTrainsLengths()
Checks if lengths of all rail vehicles are valid.
Definition: train_cmd.cpp:94
Modes for ignoring signals.
Definition: train.h:39
Train * GetPrevUnit()
Get the previous real (non-articulated part and non rear part of dualheaded engine) vehicle in the co...
Definition: train.h:158
uint16 cur_speed
current speed
Definition: vehicle_base.h:293
Rail specific functions.
Train * GetNextUnit() const
Get the next real (non-articulated part and non rear part of dualheaded engine) vehicle in the consis...
Definition: train.h:146
uint16 wait_counter
Ticks waiting in front of a signal, ticks being stuck or a counter for forced proceeding through sign...
Definition: train.h:103
uint32 GetRollingFriction() const
Returns the rolling friction coefficient of this vehicle.
Definition: train.h:283
virtual void GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const
Gets the sprite to show for the given direction.
Definition: vehicle_base.h:443
int GetDisplayMaxSpeed() const
Gets the maximum speed in km-ish/h that can be sent into SetDParam for string processing.
Definition: train.h:119
bool IsMultiheaded() const
Check if the vehicle is a multiheaded engine.
byte user_def_data
Cached property 0x25. Can be set by Callback 0x36.
Definition: train.h:79
int GetDisplaySpeed() const
Gets the speed in km-ish/h that can be sent into SetDParam for string processing. ...
Definition: train.h:118
byte GetTractiveEffort() const
Allows to know the tractive effort value that this vehicle will use.
Definition: train.h:237
uint16 GetPoweredPartPower(const Train *head) const
Returns a value if this articulated part is powered.
Definition: train.h:202
Tractive effort coefficient in 1/256.
byte vehstatus
Definition: vehicle_base.h:317
Visualisation contexts of vehicles and engines.
Definition: vehicle_type.h:87
uint StoredCount() const
Returns sum of cargo on board the vehicle (ie not only reserved).
Definition: cargopacket.h:366
uint16 cached_max_speed
Maximum speed of the consist (minimum of the max speed of all vehicles in the consist).
Definition: vehicle_base.h:123
Type (helpers) for enums.
Running costs trains.
Definition: economy_type.h:153
Defines the 8 directions on the map.
bool HasToUseGetSlopePixelZ()
Trains can always use the faster algorithm because they have always the same direction as the track u...
Definition: train.h:333
Variables that are cached to improve performance and such.
Definition: train.h:72
EngineID first_engine
Cached EngineID of the front vehicle. INVALID_ENGINE for the front vehicle itself.
int GetAccelerationType() const
Allows to know the acceleration type of a vehicle.
Definition: train.h:295
int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *v, int *station_ahead, int *station_length)
Get the stop location of (the center) of the front vehicle of a train at a platform of a station...
Definition: train_cmd.cpp:279
uint16 GetMaxTrackSpeed() const
Gets the maximum speed allowed by the track for this vehicle.
Definition: train.h:313
We don&#39;t want GCC to zero our struct! It already is zeroed and has an index!
Definition: train.h:106
Normal operation.
Definition: train.h:40
uint16 crash_anim_pos
Crash animation counter.
Definition: train.h:94
X-axis track.
Definition: track_type.h:43
virtual bool FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
Find the closest depot for this vehicle and tell us the location, DestinationID and whether we should...
Definition: vehicle_base.h:751
uint16 GetPower() const
Allows to know the power value that this vehicle will use.
Definition: train.h:185
We want to stop.
T * Next() const
Get next vehicle in the chain.
uint32 GetSlopeSteepness() const
Returns the slope steepness used by this vehicle.
Definition: train.h:304
bool IsArticulatedPart() const
Check if the vehicle is an articulated part of an engine.
Definition: vehicle_base.h:891
AccelStatus GetAccelerationStatus() const
Checks the current acceleration status of this vehicle.
Definition: train.h:265
uint8 acceleration_type
Acceleration type of this rail type.
Definition: rail.h:215
Enumeration for tracks and directions.
Definition: track_type.h:74
Valid changes for arranging the consist in a depot.
Definition: train.h:55
virtual int GetCurrentMaxSpeed() const
Calculates the maximum speed of the vehicle under its current conditions.
Definition: vehicle_base.h:493
CargoID cargo_type
type of cargo this vehicle is carrying
Definition: vehicle_base.h:305
bool IsFrontEngine() const
Check if the vehicle is a front engine.
Definition: vehicle_base.h:882
uint16 max_speed
Maximum speed for vehicles travelling on this rail type.
Definition: rail.h:220
TileIndex tile
Current tile index.
Definition: vehicle_base.h:230
Types of expenses.
Definition: economy_type.h:150
Valid changes for autorefitting in stations.
Definition: train.h:53
bool IsRearDualheaded() const
Tell if we are dealing with the rear end of a multiheaded engine.
virtual TileIndex GetOrderStationLocation(StationID station)
Determine the location for the station where the vehicle goes to next.
Definition: vehicle_base.h:741
Sprite sequence for a vehicle part.
Definition: vehicle_base.h:130
We want to go faster, if possible of course.
virtual ~Train()
We want to &#39;destruct&#39; the right class.
Definition: train.h:108
bool IsPrimaryVehicle() const
Whether this is the primary vehicle in the chain.
Definition: train.h:116
uint16 last_speed
The last speed we did display, so we only have to redraw when this changes.
&#39;Train&#39; is either a loco or a wagon.
Definition: train.h:88
virtual Money GetRunningCost() const
Gets the running cost of a vehicle.
Definition: vehicle_base.h:499
uint8 train_slope_steepness
Steepness of hills for trains when using realistic acceleration.
Wagon is powered.
Definition: train.h:29
Bitflag for a wormhole (used for tunnels)
Definition: track_type.h:58
static void OnNewDay()
Runs various procedures that have to be done daily.
Definition: date.cpp:255
Allow vehicles to change length.
Definition: train.h:48
Electric train engine is allowed to run on normal rail. */.
Definition: train.h:32
Base class for engines.
Train can&#39;t get a path reservation.
Definition: train.h:34
int cached_max_curve_speed
max consist speed limited by curves
Definition: train.h:82
byte FreightWagonMult(CargoID cargo)
Return the cargo weight multiplier to use for a rail vehicle.
Definition: train_cmd.cpp:87
Used for vehicle var 0xFE bit 8 (toggled each time the train is reversed, accurate for first vehicle ...
Definition: train.h:33
uint16 EngineID
Unique identification number of an engine.
Definition: engine_type.h:22
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo ID.
Definition: cargotype.h:118
uint32 TileIndex
The index/ID of a Tile.
Definition: tile_type.h:80
Bitflag for a depot.
Definition: track_type.h:59
void FreeTrainTrackReservation(const Train *v)
Free the reserved path in front of a vehicle.
Definition: train_cmd.cpp:2258
uint16 GetWeight() const
Allows to know the weight value that this vehicle will use.
Definition: train.h:216
virtual void UpdateDeltaXY(Direction direction)
Updates the x and y offsets and the size of the sprite used for this vehicle.
Definition: vehicle_base.h:371
Valid changes while vehicle is loading/unloading.
Definition: train.h:52
byte GetAirDragArea() const
Gets the area used for calculating air drag.
Definition: train.h:246
Reverse the visible direction of the vehicle.
Definition: train.h:30
T * GetNextVehicle() const
Get the next real (non-articulated part) vehicle in the consist.
Vehicle is not visible.
Definition: vehicle_base.h:32
Types/functions related to cargoes.
Coordinates of a point in 2D.
Proceed till next signal, but ignore being stuck till then. This includes force leaving depots...
Definition: train.h:41
Income from trains.
Definition: economy_type.h:158
Ignore next signal, after the signal ignore being stuck.
Definition: train.h:42
Valid changes when loading a savegame. (Everything that is not stored in the save.)
Definition: train.h:56
uint8 cached_veh_length
Length of this vehicle in units of 1/VEHICLE_LENGTH of normal length. It is cached because this can b...
virtual Trackdir GetVehicleTrackdir() const
Returns the Trackdir on which the vehicle is currently located.
Definition: vehicle_base.h:555
EngineID engine_type
The type of engine used for this vehicle.
Definition: vehicle_base.h:288
virtual void PlayLeaveStationSound() const
Play the sound associated with leaving the station.
Definition: vehicle_base.h:429
virtual bool Tick()
Calls the tick handler of the vehicle.
Definition: vehicle_base.h:529
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
byte CargoID
Cargo slots to indicate a cargo type within a game.
Definition: cargo_type.h:22
Weight in t (if dualheaded: for each single vehicle)
uint Crash(bool flooded)
Common code executed for crashed ground vehicles.
Base class for all vehicles that move through ground.
Rail vehicle flags.
Definition: train.h:27
T * GetPrevVehicle() const
Get the previous real (non-articulated part) vehicle in the consist.
byte GetAirDrag() const
Gets the air drag coefficient of this vehicle.
Definition: train.h:256
VehicleCache vcache
Cache of often used vehicle values.
Definition: vehicle_base.h:330
bool TryPathReserve(Train *v, bool mark_as_stuck=false, bool first_tile_okay=false)
Try to reserve a path to a safe position.
Definition: train_cmd.cpp:2696
Allow vehicles to change capacity.
Definition: train.h:49
void GetTrainSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
Get the size of the sprite of a train sprite heading west, or both heads (used for lists)...
Definition: train_cmd.cpp:572
Valid changes while vehicle is driving, and possibly changing tracks.
Definition: train.h:51
Base class and functions for all vehicles that move through ground.
Hides the direct accesses to the map array with map accessors.
static RailType GetRailType(TileIndex t)
Gets the rail type of the given tile.
Definition: rail_map.h:116
Y-axis track.
Definition: track_type.h:44
Valid changes for refitting in a depot.
Definition: train.h:54
GroundVehicleCache gcache
Cache of often calculated values.
bool IsInDepot() const
Check whether the vehicle is in the depot.
Definition: train.h:122