OpenTTD
train.h
Go to the documentation of this file.
1 /*
2  * This file is part of OpenTTD.
3  * 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.
4  * 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.
5  * 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/>.
6  */
7 
10 #ifndef TRAIN_H
11 #define TRAIN_H
12 
13 #include "core/enum_type.hpp"
14 
15 #include "newgrf_engine.h"
16 #include "cargotype.h"
17 #include "rail.h"
18 #include "engine_base.h"
19 #include "rail_map.h"
20 #include "ground_vehicle.hpp"
21 
22 struct Train;
23 
26  VRF_REVERSING = 0,
29 
34 };
35 
37 enum TrainForceProceeding : byte {
38  TFP_NONE = 0,
39  TFP_STUCK = 1,
40  TFP_SIGNAL = 2,
41 };
42 
45  CCF_LENGTH = 0x01,
46  CCF_CAPACITY = 0x02,
47 
48  CCF_TRACK = 0,
54 };
56 
58 
59 void CheckTrainsLengths();
60 
61 void FreeTrainTrackReservation(const Train *v);
62 bool TryPathReserve(Train *v, bool mark_as_stuck = false, bool first_tile_okay = false);
63 
64 int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *v, int *station_ahead, int *station_length);
65 
66 void GetTrainSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type);
67 
69 struct TrainCache {
70  /* Cached wagon override spritegroup */
71  const struct SpriteGroup *cached_override;
72 
73  /* cached values, recalculated on load and each time a vehicle is added to/removed from the consist. */
74  bool cached_tilt;
75 
77 
78  /* cached max. speed / acceleration data */
80 };
81 
85 struct Train FINAL : public GroundVehicle<Train, VEH_TRAIN> {
86  TrainCache tcache;
87 
88  /* Link between the two ends of a multiheaded engine */
89  Train *other_multiheaded_part;
90 
91  uint16 crash_anim_pos;
92 
93  uint16 flags;
94  TrackBits track;
95  TrainForceProceeding force_proceed;
96  RailType railtype;
97  RailTypes compatible_railtypes;
98 
100  uint16 wait_counter;
101 
105  virtual ~Train() { this->PreDestructor(); }
106 
107  friend struct GroundVehicle<Train, VEH_TRAIN>; // GroundVehicle needs to use the acceleration functions defined at Train.
108 
109  void MarkDirty();
110  void UpdateDeltaXY();
111  ExpensesType GetExpenseType(bool income) const { return income ? EXPENSES_TRAIN_INC : EXPENSES_TRAIN_RUN; }
112  void PlayLeaveStationSound() const;
113  bool IsPrimaryVehicle() const { return this->IsFrontEngine(); }
114  void GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const;
115  int GetDisplaySpeed() const { return this->gcache.last_speed; }
116  int GetDisplayMaxSpeed() const { return this->vcache.cached_max_speed; }
117  Money GetRunningCost() const;
118  int GetDisplayImageWidth(Point *offset = nullptr) const;
119  bool IsInDepot() const { return this->track == TRACK_BIT_DEPOT; }
120  bool Tick();
121  void OnNewDay();
122  uint Crash(bool flooded = false);
124  TileIndex GetOrderStationLocation(StationID station);
125  bool FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse);
126 
127  void ReserveTrackUnderConsist() const;
128 
129  int GetCurveSpeedLimit() const;
130 
131  void ConsistChanged(ConsistChangeFlags allowed_changes);
132 
133  int UpdateSpeed();
134 
135  void UpdateAcceleration();
136 
137  int GetCurrentMaxSpeed() const;
138 
143  inline Train *GetNextUnit() const
144  {
145  Train *v = this->GetNextVehicle();
146  if (v != nullptr && v->IsRearDualheaded()) v = v->GetNextVehicle();
147 
148  return v;
149  }
150 
155  inline Train *GetPrevUnit()
156  {
157  Train *v = this->GetPrevVehicle();
158  if (v != nullptr && v->IsRearDualheaded()) v = v->GetPrevVehicle();
159 
160  return v;
161  }
162 
168  {
169  /* For vehicles with odd lengths the part before the center will be one unit
170  * longer than the part after the center. This means we have to round up the
171  * length of the next vehicle but may not round the length of the current
172  * vehicle. */
173  return this->gcache.cached_veh_length / 2 + (this->Next() != nullptr ? this->Next()->gcache.cached_veh_length + 1 : 0) / 2;
174  }
175 
176 protected: // These functions should not be called outside acceleration code.
177 
182  inline uint16 GetPower() const
183  {
184  /* Power is not added for articulated parts */
185  if (!this->IsArticulatedPart() && HasPowerOnRail(this->railtype, GetRailType(this->tile))) {
186  uint16 power = GetVehicleProperty(this, PROP_TRAIN_POWER, RailVehInfo(this->engine_type)->power);
187  /* Halve power for multiheaded parts */
188  if (this->IsMultiheaded()) power /= 2;
189  return power;
190  }
191 
192  return 0;
193  }
194 
199  inline uint16 GetPoweredPartPower(const Train *head) const
200  {
201  /* For powered wagons the engine defines the type of engine (i.e. railtype) */
202  if (HasBit(this->flags, VRF_POWEREDWAGON) && HasPowerOnRail(head->railtype, GetRailType(this->tile))) {
203  return RailVehInfo(this->gcache.first_engine)->pow_wag_power;
204  }
205 
206  return 0;
207  }
208 
213  inline uint16 GetWeight() const
214  {
215  uint16 weight = (CargoSpec::Get(this->cargo_type)->weight * this->cargo.StoredCount() * FreightWagonMult(this->cargo_type)) / 16;
216 
217  /* Vehicle weight is not added for articulated parts. */
218  if (!this->IsArticulatedPart()) {
219  weight += GetVehicleProperty(this, PROP_TRAIN_WEIGHT, RailVehInfo(this->engine_type)->weight);
220  }
221 
222  /* Powered wagons have extra weight added. */
223  if (HasBit(this->flags, VRF_POWEREDWAGON)) {
224  weight += RailVehInfo(this->gcache.first_engine)->pow_wag_weight;
225  }
226 
227  return weight;
228  }
229 
234  inline byte GetTractiveEffort() const
235  {
236  return GetVehicleProperty(this, PROP_TRAIN_TRACTIVE_EFFORT, RailVehInfo(this->engine_type)->tractive_effort);
237  }
238 
243  inline byte GetAirDragArea() const
244  {
245  /* Air drag is higher in tunnels due to the limited cross-section. */
246  return (this->track == TRACK_BIT_WORMHOLE && this->vehstatus & VS_HIDDEN) ? 28 : 14;
247  }
248 
253  inline byte GetAirDrag() const
254  {
255  return RailVehInfo(this->engine_type)->air_drag;
256  }
257 
263  {
264  return (this->vehstatus & VS_STOPPED) || HasBit(this->flags, VRF_REVERSING) || HasBit(this->flags, VRF_TRAIN_STUCK) ? AS_BRAKE : AS_ACCEL;
265  }
266 
271  inline uint16 GetCurrentSpeed() const
272  {
273  return this->cur_speed;
274  }
275 
280  inline uint32 GetRollingFriction() const
281  {
282  /* Rolling friction for steel on steel is between 0.1% and 0.2%.
283  * The friction coefficient increases with speed in a way that
284  * it doubles at 512 km/h, triples at 1024 km/h and so on. */
285  return 15 * (512 + this->GetCurrentSpeed()) / 512;
286  }
287 
292  inline int GetAccelerationType() const
293  {
294  return GetRailTypeInfo(this->railtype)->acceleration_type;
295  }
296 
301  inline uint32 GetSlopeSteepness() const
302  {
304  }
305 
310  inline uint16 GetMaxTrackSpeed() const
311  {
312  return GetRailTypeInfo(GetRailType(this->tile))->max_speed;
313  }
314 
319  inline bool TileMayHaveSlopedTrack() const
320  {
321  /* Any track that isn't TRACK_BIT_X or TRACK_BIT_Y cannot be sloped. */
322  return this->track == TRACK_BIT_X || this->track == TRACK_BIT_Y;
323  }
324 
331  {
332  return false;
333  }
334 };
335 
336 #endif /* TRAIN_H */
Normal operation.
Definition: train.h:38
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:332
Vehicle is stopped by the player.
Definition: vehicle_base.h:31
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:74
VehicleCargoList cargo
The cargo this vehicle is carrying.
Definition: vehicle_base.h:307
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:79
ExpensesType GetExpenseType(bool income) const
Sets the expense type associated to this vehicle type.
Definition: train.h:111
int CalcNextVehicleOffset() const
Calculate the offset from this vehicle&#39;s center to the following center taking the vehicle lengths in...
Definition: train.h:167
Functions for NewGRF engines.
static const RailtypeInfo * GetRailTypeInfo(RailType railtype)
Returns a pointer to the Railtype information for a given railtype.
Definition: rail.h:304
virtual void MarkDirty()
Marks the vehicles to be redrawn and updates cached variables.
Definition: vehicle_base.h:362
Direction direction
facing
Definition: vehicle_base.h:269
uint8 weight
Weight of a single unit of this cargo type in 1/16 ton (62.5 kg).
Definition: cargotype.h:60
AccelStatus
What is the status of our acceleration?
Train is just leaving a station.
Definition: train.h:33
uint16 GetCurrentSpeed() const
Calculates the current speed of this vehicle.
Definition: train.h:271
ConsistChangeFlags
Flags for Train::ConsistChanged.
Definition: train.h:44
bool TileMayHaveSlopedTrack() const
Checks if the vehicle is at a tile that can be sloped.
Definition: train.h:319
Power in hp (if dualheaded: sum of both vehicles)
void CheckTrainsLengths()
Checks if lengths of all rail vehicles are valid.
Definition: train_cmd.cpp:72
Trackdir
Enumeration for tracks and directions.
Definition: track_type.h:70
Train * GetPrevUnit()
Get the previous real (non-articulated part and non rear part of dualheaded engine) vehicle in the co...
Definition: train.h:155
uint16 cur_speed
current speed
Definition: vehicle_base.h:291
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:143
uint16 wait_counter
Ticks waiting in front of a signal, ticks being stuck or a counter for forced proceeding through sign...
Definition: train.h:100
X-axis track.
Definition: track_type.h:40
Proceed till next signal, but ignore being stuck till then. This includes force leaving depots...
Definition: train.h:39
uint32 GetRollingFriction() const
Returns the rolling friction coefficient of this vehicle.
Definition: train.h:280
virtual void GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const
Gets the sprite to show for the given direction.
Definition: vehicle_base.h:440
int GetDisplayMaxSpeed() const
Gets the maximum speed in km-ish/h that can be sent into SetDParam for string processing.
Definition: train.h:116
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:76
int GetDisplaySpeed() const
Gets the speed in km-ish/h that can be sent into SetDParam for string processing. ...
Definition: train.h:115
byte GetTractiveEffort() const
Allows to know the tractive effort value that this vehicle will use.
Definition: train.h:234
uint16 GetPoweredPartPower(const Train *head) const
Returns a value if this articulated part is powered.
Definition: train.h:199
Tractive effort coefficient in 1/256.
byte vehstatus
Status.
Definition: vehicle_base.h:315
EngineImageType
Visualisation contexts of vehicles and engines.
Definition: vehicle_type.h:85
uint StoredCount() const
Returns sum of cargo on board the vehicle (ie not only reserved).
Definition: cargopacket.h:351
uint16 cached_max_speed
Maximum speed of the consist (minimum of the max speed of all vehicles in the consist).
Definition: vehicle_base.h:121
Ignore next signal, after the signal ignore being stuck.
Definition: train.h:40
Type (helpers) for enums.
bool HasToUseGetSlopePixelZ()
Trains can always use the faster algorithm because they have always the same direction as the track u...
Definition: train.h:330
Variables that are cached to improve performance and such.
Definition: train.h:69
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:292
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:256
uint16 GetMaxTrackSpeed() const
Gets the maximum speed allowed by the track for this vehicle.
Definition: train.h:310
Train()
We don&#39;t want GCC to zero our struct! It already is zeroed and has an index!
Definition: train.h:103
uint16 crash_anim_pos
Crash animation counter.
Definition: train.h:91
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:748
uint16 GetPower() const
Allows to know the power value that this vehicle will use.
Definition: train.h:182
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:301
bool IsArticulatedPart() const
Check if the vehicle is an articulated part of an engine.
Definition: vehicle_base.h:890
AccelStatus GetAccelerationStatus() const
Checks the current acceleration status of this vehicle.
Definition: train.h:262
uint8 acceleration_type
Acceleration type of this rail type.
Definition: rail.h:223
Direction
Defines the 8 directions on the map.
TrainForceProceeding
Modes for ignoring signals.
Definition: train.h:37
Valid changes for arranging the consist in a depot.
Definition: train.h:52
virtual int GetCurrentMaxSpeed() const
Calculates the maximum speed of the vehicle under its current conditions.
Definition: vehicle_base.h:490
CargoID cargo_type
type of cargo this vehicle is carrying
Definition: vehicle_base.h:303
TrackBits
Bitfield corresponding to Track.
Definition: track_type.h:38
bool IsFrontEngine() const
Check if the vehicle is a front engine.
Definition: vehicle_base.h:881
uint16 max_speed
Maximum speed for vehicles travelling on this rail type.
Definition: rail.h:228
TileIndex tile
Current tile index.
Definition: vehicle_base.h:228
virtual void UpdateDeltaXY()
Updates the x and y offsets and the size of the sprite used for this vehicle.
Definition: vehicle_base.h:368
Valid changes for autorefitting in stations.
Definition: train.h:50
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:738
Sprite sequence for a vehicle part.
Definition: vehicle_base.h:128
RailTypes
The different railtypes we support, but then a bitmask of them.
Definition: rail_type.h:46
We want to go faster, if possible of course.
virtual ~Train()
We want to &#39;destruct&#39; the right class.
Definition: train.h:105
Bitflag for a wormhole (used for tunnels)
Definition: track_type.h:55
bool IsPrimaryVehicle() const
Whether this is the primary vehicle in the chain.
Definition: train.h:113
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:85
virtual Money GetRunningCost() const
Gets the running cost of a vehicle.
Definition: vehicle_base.h:496
uint8 train_slope_steepness
Steepness of hills for trains when using realistic acceleration.
Bitflag for a depot.
Definition: track_type.h:56
Wagon is powered.
Definition: train.h:27
uint Crash(bool flooded) override
Common code executed for crashed ground vehicles.
static void OnNewDay()
Runs various procedures that have to be done daily.
Definition: date.cpp:244
Allow vehicles to change length.
Definition: train.h:45
Electric train engine is allowed to run on normal rail. */.
Definition: train.h:30
Base class for engines.
RailType
Enumeration for all possible railtypes.
Definition: rail_type.h:27
Train can&#39;t get a path reservation.
Definition: train.h:32
Running costs trains.
Definition: economy_type.h:151
int cached_max_curve_speed
max consist speed limited by curves
Definition: train.h:79
byte FreightWagonMult(CargoID cargo)
Return the cargo weight multiplier to use for a rail vehicle.
Definition: train_cmd.cpp:65
Used for vehicle var 0xFE bit 8 (toggled each time the train is reversed, accurate for first vehicle ...
Definition: train.h:31
uint16 EngineID
Unique identification number of an engine.
Definition: engine_type.h:21
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo ID.
Definition: cargotype.h:117
uint32 TileIndex
The index/ID of a Tile.
Definition: tile_type.h:78
void FreeTrainTrackReservation(const Train *v)
Free the reserved path in front of a vehicle.
Definition: train_cmd.cpp:2229
uint16 GetWeight() const
Allows to know the weight value that this vehicle will use.
Definition: train.h:213
Valid changes while vehicle is loading/unloading.
Definition: train.h:49
byte GetAirDragArea() const
Gets the area used for calculating air drag.
Definition: train.h:243
Reverse the visible direction of the vehicle.
Definition: train.h:28
T * GetNextVehicle() const
Get the next real (non-articulated part) vehicle in the consist.
Vehicle is not visible.
Definition: vehicle_base.h:30
Types/functions related to cargoes.
Coordinates of a point in 2D.
Valid changes when loading a savegame. (Everything that is not stored in the save.)
Definition: train.h:53
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:552
EngineID engine_type
The type of engine used for this vehicle.
Definition: vehicle_base.h:286
virtual void PlayLeaveStationSound() const
Play the sound associated with leaving the station.
Definition: vehicle_base.h:426
virtual bool Tick()
Calls the tick handler of the vehicle.
Definition: vehicle_base.h:526
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:20
Weight in t (if dualheaded: for each single vehicle)
Base class for all vehicles that move through ground.
VehicleRailFlags
Rail vehicle flags.
Definition: train.h:25
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:253
VehicleCache vcache
Cache of often used vehicle values.
Definition: vehicle_base.h:328
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:2667
Income from trains.
Definition: economy_type.h:156
ExpensesType
Types of expenses.
Definition: economy_type.h:148
Allow vehicles to change capacity.
Definition: train.h:46
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:549
Y-axis track.
Definition: track_type.h:41
Valid changes while vehicle is driving, and possibly changing tracks.
Definition: train.h:48
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:115
Valid changes for refitting in a depot.
Definition: train.h:51
GroundVehicleCache gcache
Cache of often calculated values.
bool IsInDepot() const
Check whether the vehicle is in the depot.
Definition: train.h:119