OpenTTD
train.h
Go to the documentation of this file.
1 /* $Id$ */
2 
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  */
9 
12 #ifndef TRAIN_H
13 #define TRAIN_H
14 
15 #include "core/enum_type.hpp"
16 
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"
23 
24 struct Train;
25 
28  VRF_REVERSING = 0,
31 
36 };
37 
39 enum TrainForceProceeding : byte {
40  TFP_NONE = 0,
41  TFP_STUCK = 1,
42  TFP_SIGNAL = 2,
43 };
44 
47  CCF_LENGTH = 0x01,
48  CCF_CAPACITY = 0x02,
49 
50  CCF_TRACK = 0,
56 };
58 
60 
61 void CheckTrainsLengths();
62 
63 void FreeTrainTrackReservation(const Train *v);
64 bool TryPathReserve(Train *v, bool mark_as_stuck = false, bool first_tile_okay = false);
65 
66 int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *v, int *station_ahead, int *station_length);
67 
68 void GetTrainSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type);
69 
71 struct TrainCache {
72  /* Cached wagon override spritegroup */
73  const struct SpriteGroup *cached_override;
74 
75  /* cached values, recalculated on load and each time a vehicle is added to/removed from the consist. */
76  bool cached_tilt;
77 
79 
80  /* cached max. speed / acceleration data */
82 };
83 
87 struct Train FINAL : public GroundVehicle<Train, VEH_TRAIN> {
88  TrainCache tcache;
89 
90  /* Link between the two ends of a multiheaded engine */
91  Train *other_multiheaded_part;
92 
93  uint16 crash_anim_pos;
94 
95  uint16 flags;
96  TrackBits track;
97  TrainForceProceeding force_proceed;
98  RailType railtype;
99  RailTypes compatible_railtypes;
100 
102  uint16 wait_counter;
103 
107  virtual ~Train() { this->PreDestructor(); }
108 
109  friend struct GroundVehicle<Train, VEH_TRAIN>; // GroundVehicle needs to use the acceleration functions defined at Train.
110 
111  void MarkDirty();
112  void UpdateDeltaXY();
113  ExpensesType GetExpenseType(bool income) const { return income ? EXPENSES_TRAIN_INC : EXPENSES_TRAIN_RUN; }
114  void PlayLeaveStationSound() const;
115  bool IsPrimaryVehicle() const { return this->IsFrontEngine(); }
116  void GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const;
117  int GetDisplaySpeed() const { return this->gcache.last_speed; }
118  int GetDisplayMaxSpeed() const { return this->vcache.cached_max_speed; }
119  Money GetRunningCost() const;
120  int GetDisplayImageWidth(Point *offset = nullptr) const;
121  bool IsInDepot() const { return this->track == TRACK_BIT_DEPOT; }
122  bool Tick();
123  void OnNewDay();
124  uint Crash(bool flooded = false);
126  TileIndex GetOrderStationLocation(StationID station);
127  bool FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse);
128 
129  void ReserveTrackUnderConsist() const;
130 
131  int GetCurveSpeedLimit() const;
132 
133  void ConsistChanged(ConsistChangeFlags allowed_changes);
134 
135  int UpdateSpeed();
136 
137  void UpdateAcceleration();
138 
139  int GetCurrentMaxSpeed() const;
140 
145  inline Train *GetNextUnit() const
146  {
147  Train *v = this->GetNextVehicle();
148  if (v != nullptr && v->IsRearDualheaded()) v = v->GetNextVehicle();
149 
150  return v;
151  }
152 
157  inline Train *GetPrevUnit()
158  {
159  Train *v = this->GetPrevVehicle();
160  if (v != nullptr && v->IsRearDualheaded()) v = v->GetPrevVehicle();
161 
162  return v;
163  }
164 
170  {
171  /* For vehicles with odd lengths the part before the center will be one unit
172  * longer than the part after the center. This means we have to round up the
173  * length of the next vehicle but may not round the length of the current
174  * vehicle. */
175  return this->gcache.cached_veh_length / 2 + (this->Next() != nullptr ? this->Next()->gcache.cached_veh_length + 1 : 0) / 2;
176  }
177 
178 protected: // These functions should not be called outside acceleration code.
179 
184  inline uint16 GetPower() const
185  {
186  /* Power is not added for articulated parts */
187  if (!this->IsArticulatedPart() && HasPowerOnRail(this->railtype, GetRailType(this->tile))) {
188  uint16 power = GetVehicleProperty(this, PROP_TRAIN_POWER, RailVehInfo(this->engine_type)->power);
189  /* Halve power for multiheaded parts */
190  if (this->IsMultiheaded()) power /= 2;
191  return power;
192  }
193 
194  return 0;
195  }
196 
201  inline uint16 GetPoweredPartPower(const Train *head) const
202  {
203  /* For powered wagons the engine defines the type of engine (i.e. railtype) */
204  if (HasBit(this->flags, VRF_POWEREDWAGON) && HasPowerOnRail(head->railtype, GetRailType(this->tile))) {
205  return RailVehInfo(this->gcache.first_engine)->pow_wag_power;
206  }
207 
208  return 0;
209  }
210 
215  inline uint16 GetWeight() const
216  {
217  uint16 weight = (CargoSpec::Get(this->cargo_type)->weight * this->cargo.StoredCount() * FreightWagonMult(this->cargo_type)) / 16;
218 
219  /* Vehicle weight is not added for articulated parts. */
220  if (!this->IsArticulatedPart()) {
221  weight += GetVehicleProperty(this, PROP_TRAIN_WEIGHT, RailVehInfo(this->engine_type)->weight);
222  }
223 
224  /* Powered wagons have extra weight added. */
225  if (HasBit(this->flags, VRF_POWEREDWAGON)) {
226  weight += RailVehInfo(this->gcache.first_engine)->pow_wag_weight;
227  }
228 
229  return weight;
230  }
231 
236  inline byte GetTractiveEffort() const
237  {
238  return GetVehicleProperty(this, PROP_TRAIN_TRACTIVE_EFFORT, RailVehInfo(this->engine_type)->tractive_effort);
239  }
240 
245  inline byte GetAirDragArea() const
246  {
247  /* Air drag is higher in tunnels due to the limited cross-section. */
248  return (this->track == TRACK_BIT_WORMHOLE && this->vehstatus & VS_HIDDEN) ? 28 : 14;
249  }
250 
255  inline byte GetAirDrag() const
256  {
257  return RailVehInfo(this->engine_type)->air_drag;
258  }
259 
265  {
266  return (this->vehstatus & VS_STOPPED) || HasBit(this->flags, VRF_REVERSING) || HasBit(this->flags, VRF_TRAIN_STUCK) ? AS_BRAKE : AS_ACCEL;
267  }
268 
273  inline uint16 GetCurrentSpeed() const
274  {
275  return this->cur_speed;
276  }
277 
282  inline uint32 GetRollingFriction() const
283  {
284  /* Rolling friction for steel on steel is between 0.1% and 0.2%.
285  * The friction coefficient increases with speed in a way that
286  * it doubles at 512 km/h, triples at 1024 km/h and so on. */
287  return 15 * (512 + this->GetCurrentSpeed()) / 512;
288  }
289 
294  inline int GetAccelerationType() const
295  {
296  return GetRailTypeInfo(this->railtype)->acceleration_type;
297  }
298 
303  inline uint32 GetSlopeSteepness() const
304  {
306  }
307 
312  inline uint16 GetMaxTrackSpeed() const
313  {
314  return GetRailTypeInfo(GetRailType(this->tile))->max_speed;
315  }
316 
321  inline bool TileMayHaveSlopedTrack() const
322  {
323  /* Any track that isn't TRACK_BIT_X or TRACK_BIT_Y cannot be sloped. */
324  return this->track == TRACK_BIT_X || this->track == TRACK_BIT_Y;
325  }
326 
333  {
334  return false;
335  }
336 };
337 
338 #define FOR_ALL_TRAINS(var) FOR_ALL_VEHICLES_OF_TYPE(Train, var)
339 
340 #endif /* TRAIN_H */
Normal operation.
Definition: train.h:40
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:334
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:76
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:81
ExpensesType GetExpenseType(bool income) const
Sets the expense type associated to this vehicle type.
Definition: train.h:113
int CalcNextVehicleOffset() const
Calculate the offset from this vehicle&#39;s center to the following center taking the vehicle lengths in...
Definition: train.h:169
Functions for NewGRF engines.
static const RailtypeInfo * GetRailTypeInfo(RailType railtype)
Returns a pointer to the Railtype information for a given railtype.
Definition: rail.h:306
virtual void MarkDirty()
Marks the vehicles to be redrawn and updates cached variables.
Definition: vehicle_base.h:364
Direction direction
facing
Definition: vehicle_base.h:271
uint8 weight
Weight of a single unit of this cargo type in 1/16 ton (62.5 kg).
Definition: cargotype.h:62
AccelStatus
What is the status of our acceleration?
Train is just leaving a station.
Definition: train.h:35
uint16 GetCurrentSpeed() const
Calculates the current speed of this vehicle.
Definition: train.h:273
ConsistChangeFlags
Flags for Train::ConsistChanged.
Definition: train.h:46
bool TileMayHaveSlopedTrack() const
Checks if the vehicle is at a tile that can be sloped.
Definition: train.h:321
Power in hp (if dualheaded: sum of both vehicles)
void CheckTrainsLengths()
Checks if lengths of all rail vehicles are valid.
Definition: train_cmd.cpp:74
Trackdir
Enumeration for tracks and directions.
Definition: track_type.h:72
Train * GetPrevUnit()
Get the previous real (non-articulated part and non rear part of dualheaded engine) vehicle in the co...
Definition: train.h:157
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:145
uint16 wait_counter
Ticks waiting in front of a signal, ticks being stuck or a counter for forced proceeding through sign...
Definition: train.h:102
X-axis track.
Definition: track_type.h:42
Proceed till next signal, but ignore being stuck till then. This includes force leaving depots...
Definition: train.h:41
uint32 GetRollingFriction() const
Returns the rolling friction coefficient of this vehicle.
Definition: train.h:282
virtual void GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const
Gets the sprite to show for the given direction.
Definition: vehicle_base.h:442
int GetDisplayMaxSpeed() const
Gets the maximum speed in km-ish/h that can be sent into SetDParam for string processing.
Definition: train.h:118
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:78
int GetDisplaySpeed() const
Gets the speed in km-ish/h that can be sent into SetDParam for string processing. ...
Definition: train.h:117
byte GetTractiveEffort() const
Allows to know the tractive effort value that this vehicle will use.
Definition: train.h:236
uint16 GetPoweredPartPower(const Train *head) const
Returns a value if this articulated part is powered.
Definition: train.h:201
Tractive effort coefficient in 1/256.
byte vehstatus
Status.
Definition: vehicle_base.h:317
EngineImageType
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
Ignore next signal, after the signal ignore being stuck.
Definition: train.h:42
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:332
Variables that are cached to improve performance and such.
Definition: train.h:71
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:294
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:259
uint16 GetMaxTrackSpeed() const
Gets the maximum speed allowed by the track for this vehicle.
Definition: train.h:312
Train()
We don&#39;t want GCC to zero our struct! It already is zeroed and has an index!
Definition: train.h:105
uint16 crash_anim_pos
Crash animation counter.
Definition: train.h:93
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:750
uint16 GetPower() const
Allows to know the power value that this vehicle will use.
Definition: train.h:184
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:303
bool IsArticulatedPart() const
Check if the vehicle is an articulated part of an engine.
Definition: vehicle_base.h:892
AccelStatus GetAccelerationStatus() const
Checks the current acceleration status of this vehicle.
Definition: train.h:264
uint8 acceleration_type
Acceleration type of this rail type.
Definition: rail.h:225
Direction
Defines the 8 directions on the map.
TrainForceProceeding
Modes for ignoring signals.
Definition: train.h:39
Valid changes for arranging the consist in a depot.
Definition: train.h:54
virtual int GetCurrentMaxSpeed() const
Calculates the maximum speed of the vehicle under its current conditions.
Definition: vehicle_base.h:492
CargoID cargo_type
type of cargo this vehicle is carrying
Definition: vehicle_base.h:305
TrackBits
Bitfield corresponding to Track.
Definition: track_type.h:40
bool IsFrontEngine() const
Check if the vehicle is a front engine.
Definition: vehicle_base.h:883
uint16 max_speed
Maximum speed for vehicles travelling on this rail type.
Definition: rail.h:230
TileIndex tile
Current tile index.
Definition: vehicle_base.h:230
virtual void UpdateDeltaXY()
Updates the x and y offsets and the size of the sprite used for this vehicle.
Definition: vehicle_base.h:370
Valid changes for autorefitting in stations.
Definition: train.h:52
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:740
Sprite sequence for a vehicle part.
Definition: vehicle_base.h:130
RailTypes
The different railtypes we support, but then a bitmask of them.
Definition: rail_type.h:52
We want to go faster, if possible of course.
virtual ~Train()
We want to &#39;destruct&#39; the right class.
Definition: train.h:107
Bitflag for a wormhole (used for tunnels)
Definition: track_type.h:57
bool IsPrimaryVehicle() const
Whether this is the primary vehicle in the chain.
Definition: train.h:115
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:87
virtual Money GetRunningCost() const
Gets the running cost of a vehicle.
Definition: vehicle_base.h:498
uint8 train_slope_steepness
Steepness of hills for trains when using realistic acceleration.
Bitflag for a depot.
Definition: track_type.h:58
Wagon is powered.
Definition: train.h:29
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:249
Allow vehicles to change length.
Definition: train.h:47
Electric train engine is allowed to run on normal rail. */.
Definition: train.h:32
Base class for engines.
RailType
Enumeration for all possible railtypes.
Definition: rail_type.h:29
Train can&#39;t get a path reservation.
Definition: train.h:34
Running costs trains.
Definition: economy_type.h:153
int cached_max_curve_speed
max consist speed limited by curves
Definition: train.h:81
byte FreightWagonMult(CargoID cargo)
Return the cargo weight multiplier to use for a rail vehicle.
Definition: train_cmd.cpp:67
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:23
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo ID.
Definition: cargotype.h:119
uint32 TileIndex
The index/ID of a Tile.
Definition: tile_type.h:80
void FreeTrainTrackReservation(const Train *v)
Free the reserved path in front of a vehicle.
Definition: train_cmd.cpp:2235
uint16 GetWeight() const
Allows to know the weight value that this vehicle will use.
Definition: train.h:215
Valid changes while vehicle is loading/unloading.
Definition: train.h:51
byte GetAirDragArea() const
Gets the area used for calculating air drag.
Definition: train.h:245
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.
Valid changes when loading a savegame. (Everything that is not stored in the save.)
Definition: train.h:55
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:554
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:428
virtual bool Tick()
Calls the tick handler of the vehicle.
Definition: vehicle_base.h:528
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)
Base class for all vehicles that move through ground.
VehicleRailFlags
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:255
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:2673
Income from trains.
Definition: economy_type.h:158
ExpensesType
Types of expenses.
Definition: economy_type.h:150
Allow vehicles to change capacity.
Definition: train.h:48
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:552
Y-axis track.
Definition: track_type.h:43
Valid changes while vehicle is driving, and possibly changing tracks.
Definition: train.h:50
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:117
Valid changes for refitting in a depot.
Definition: train.h:53
GroundVehicleCache gcache
Cache of often calculated values.
bool IsInDepot() const
Check whether the vehicle is in the depot.
Definition: train.h:121