Fix #10490: Allow ships to exit depots if another is not moving at the exit point...
[openttd-github.git] / src / train.h
blobae584e78d1c96cce7a9c25c3a1766f559bb1fe5b
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 */
8 /** @file train.h Base for the train class. */
10 #ifndef TRAIN_H
11 #define TRAIN_H
13 #include "core/enum_type.hpp"
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"
22 struct Train;
24 /** Rail vehicle flags. */
25 enum VehicleRailFlags {
26 VRF_REVERSING = 0,
27 VRF_POWEREDWAGON = 3, ///< Wagon is powered.
28 VRF_REVERSE_DIRECTION = 4, ///< Reverse the visible direction of the vehicle.
30 VRF_EL_ENGINE_ALLOWED_NORMAL_RAIL = 6, ///< Electric train engine is allowed to run on normal rail. */
31 VRF_TOGGLE_REVERSE = 7, ///< Used for vehicle var 0xFE bit 8 (toggled each time the train is reversed, accurate for first vehicle only).
32 VRF_TRAIN_STUCK = 8, ///< Train can't get a path reservation.
33 VRF_LEAVING_STATION = 9, ///< Train is just leaving a station.
36 /** Modes for ignoring signals. */
37 enum TrainForceProceeding : byte {
38 TFP_NONE = 0, ///< Normal operation.
39 TFP_STUCK = 1, ///< Proceed till next signal, but ignore being stuck till then. This includes force leaving depots.
40 TFP_SIGNAL = 2, ///< Ignore next signal, after the signal ignore being stuck.
43 /** Flags for Train::ConsistChanged */
44 enum ConsistChangeFlags {
45 CCF_LENGTH = 0x01, ///< Allow vehicles to change length.
46 CCF_CAPACITY = 0x02, ///< Allow vehicles to change capacity.
48 CCF_TRACK = 0, ///< Valid changes while vehicle is driving, and possibly changing tracks.
49 CCF_LOADUNLOAD = 0, ///< Valid changes while vehicle is loading/unloading.
50 CCF_AUTOREFIT = CCF_CAPACITY, ///< Valid changes for autorefitting in stations.
51 CCF_REFIT = CCF_LENGTH | CCF_CAPACITY, ///< Valid changes for refitting in a depot.
52 CCF_ARRANGE = CCF_LENGTH | CCF_CAPACITY, ///< Valid changes for arranging the consist in a depot.
53 CCF_SAVELOAD = CCF_LENGTH, ///< Valid changes when loading a savegame. (Everything that is not stored in the save.)
55 DECLARE_ENUM_AS_BIT_SET(ConsistChangeFlags)
57 byte FreightWagonMult(CargoID cargo);
59 void CheckTrainsLengths();
61 void FreeTrainTrackReservation(const Train *v);
62 bool TryPathReserve(Train *v, bool mark_as_stuck = false, bool first_tile_okay = false);
64 int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *v, int *station_ahead, int *station_length);
66 void GetTrainSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type);
68 bool TrainOnCrossing(TileIndex tile);
69 void NormalizeTrainVehInDepot(const Train *u);
71 /** Variables that are cached to improve performance and such */
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; ///< train can tilt; feature provides a bonus in curves
78 int cached_curve_speed_mod; ///< curve speed modifier of the entire train
80 byte user_def_data; ///< Cached property 0x25. Can be set by Callback 0x36.
82 /* cached max. speed / acceleration data */
83 int cached_max_curve_speed; ///< max consist speed limited by curves
86 /**
87 * 'Train' is either a loco or a wagon.
89 struct Train final : public GroundVehicle<Train, VEH_TRAIN> {
90 TrainCache tcache;
92 /* Link between the two ends of a multiheaded engine */
93 Train *other_multiheaded_part;
95 uint16_t crash_anim_pos; ///< Crash animation counter.
97 uint16_t flags;
98 TrackBits track;
99 TrainForceProceeding force_proceed;
100 RailType railtype;
101 RailTypes compatible_railtypes;
103 /** Ticks waiting in front of a signal, ticks being stuck or a counter for forced proceeding through signals. */
104 uint16_t wait_counter;
106 /** We don't want GCC to zero our struct! It already is zeroed and has an index! */
107 Train() : GroundVehicleBase() {}
108 /** We want to 'destruct' the right class. */
109 virtual ~Train() { this->PreDestructor(); }
111 friend struct GroundVehicle<Train, VEH_TRAIN>; // GroundVehicle needs to use the acceleration functions defined at Train.
113 void MarkDirty() override;
114 void UpdateDeltaXY() override;
115 ExpensesType GetExpenseType(bool income) const override { return income ? EXPENSES_TRAIN_REVENUE : EXPENSES_TRAIN_RUN; }
116 void PlayLeaveStationSound(bool force = false) const override;
117 bool IsPrimaryVehicle() const override { return this->IsFrontEngine(); }
118 void GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const override;
119 int GetDisplaySpeed() const override { return this->gcache.last_speed; }
120 int GetDisplayMaxSpeed() const override { return this->vcache.cached_max_speed; }
121 Money GetRunningCost() const override;
122 int GetCursorImageOffset() const;
123 int GetDisplayImageWidth(Point *offset = nullptr) const;
124 bool IsInDepot() const override { return this->track == TRACK_BIT_DEPOT; }
125 bool Tick() override;
126 void OnNewCalendarDay() override;
127 void OnNewEconomyDay() override;
128 uint Crash(bool flooded = false) override;
129 Trackdir GetVehicleTrackdir() const override;
130 TileIndex GetOrderStationLocation(StationID station) override;
131 ClosestDepot FindClosestDepot() override;
133 void ReserveTrackUnderConsist() const;
135 int GetCurveSpeedLimit() const;
137 void ConsistChanged(ConsistChangeFlags allowed_changes);
139 int UpdateSpeed();
141 void UpdateAcceleration();
143 int GetCurrentMaxSpeed() const override;
146 * Get the next real (non-articulated part and non rear part of dualheaded engine) vehicle in the consist.
147 * @return Next vehicle in the consist.
149 inline Train *GetNextUnit() const
151 Train *v = this->GetNextVehicle();
152 if (v != nullptr && v->IsRearDualheaded()) v = v->GetNextVehicle();
154 return v;
158 * Get the previous real (non-articulated part and non rear part of dualheaded engine) vehicle in the consist.
159 * @return Previous vehicle in the consist.
161 inline Train *GetPrevUnit()
163 Train *v = this->GetPrevVehicle();
164 if (v != nullptr && v->IsRearDualheaded()) v = v->GetPrevVehicle();
166 return v;
170 * Calculate the offset from this vehicle's center to the following center taking the vehicle lengths into account.
171 * @return Offset from center to center.
173 int CalcNextVehicleOffset() const
175 /* For vehicles with odd lengths the part before the center will be one unit
176 * longer than the part after the center. This means we have to round up the
177 * length of the next vehicle but may not round the length of the current
178 * vehicle. */
179 return this->gcache.cached_veh_length / 2 + (this->Next() != nullptr ? this->Next()->gcache.cached_veh_length + 1 : 0) / 2;
182 protected: // These functions should not be called outside acceleration code.
185 * Allows to know the power value that this vehicle will use.
186 * @return Power value from the engine in HP, or zero if the vehicle is not powered.
188 inline uint16_t GetPower() const
190 /* Power is not added for articulated parts */
191 if (!this->IsArticulatedPart() && HasPowerOnRail(this->railtype, GetRailType(this->tile))) {
192 uint16_t power = GetVehicleProperty(this, PROP_TRAIN_POWER, RailVehInfo(this->engine_type)->power);
193 /* Halve power for multiheaded parts */
194 if (this->IsMultiheaded()) power /= 2;
195 return power;
198 return 0;
202 * Returns a value if this articulated part is powered.
203 * @return Power value from the articulated part in HP, or zero if it is not powered.
205 inline uint16_t GetPoweredPartPower(const Train *head) const
207 /* For powered wagons the engine defines the type of engine (i.e. railtype) */
208 if (HasBit(this->flags, VRF_POWEREDWAGON) && HasPowerOnRail(head->railtype, GetRailType(this->tile))) {
209 return RailVehInfo(this->gcache.first_engine)->pow_wag_power;
212 return 0;
216 * Allows to know the weight value that this vehicle will use.
217 * @return Weight value from the engine in tonnes.
219 inline uint16_t GetWeight() const
221 uint16_t weight = CargoSpec::Get(this->cargo_type)->WeightOfNUnitsInTrain(this->cargo.StoredCount());
223 /* Vehicle weight is not added for articulated parts. */
224 if (!this->IsArticulatedPart()) {
225 weight += GetVehicleProperty(this, PROP_TRAIN_WEIGHT, RailVehInfo(this->engine_type)->weight);
228 /* Powered wagons have extra weight added. */
229 if (HasBit(this->flags, VRF_POWEREDWAGON)) {
230 weight += RailVehInfo(this->gcache.first_engine)->pow_wag_weight;
233 return weight;
237 * Calculates the weight value that this vehicle will have when fully loaded with its current cargo.
238 * @return Weight value in tonnes.
240 uint16_t GetMaxWeight() const override;
243 * Allows to know the tractive effort value that this vehicle will use.
244 * @return Tractive effort value from the engine.
246 inline byte GetTractiveEffort() const
248 return GetVehicleProperty(this, PROP_TRAIN_TRACTIVE_EFFORT, RailVehInfo(this->engine_type)->tractive_effort);
252 * Gets the area used for calculating air drag.
253 * @return Area of the engine in m^2.
255 inline byte GetAirDragArea() const
257 /* Air drag is higher in tunnels due to the limited cross-section. */
258 return (this->track == TRACK_BIT_WORMHOLE && this->vehstatus & VS_HIDDEN) ? 28 : 14;
262 * Gets the air drag coefficient of this vehicle.
263 * @return Air drag value from the engine.
265 inline byte GetAirDrag() const
267 return RailVehInfo(this->engine_type)->air_drag;
271 * Checks the current acceleration status of this vehicle.
272 * @return Acceleration status.
274 inline AccelStatus GetAccelerationStatus() const
276 return (this->vehstatus & VS_STOPPED) || HasBit(this->flags, VRF_REVERSING) || HasBit(this->flags, VRF_TRAIN_STUCK) ? AS_BRAKE : AS_ACCEL;
280 * Calculates the current speed of this vehicle.
281 * @return Current speed in km/h-ish.
283 inline uint16_t GetCurrentSpeed() const
285 return this->cur_speed;
289 * Returns the rolling friction coefficient of this vehicle.
290 * @return Rolling friction coefficient in [1e-4].
292 inline uint32_t GetRollingFriction() const
294 /* Rolling friction for steel on steel is between 0.1% and 0.2%.
295 * The friction coefficient increases with speed in a way that
296 * it doubles at 512 km/h, triples at 1024 km/h and so on. */
297 return 15 * (512 + this->GetCurrentSpeed()) / 512;
301 * Allows to know the acceleration type of a vehicle.
302 * @return Acceleration type of the vehicle.
304 inline int GetAccelerationType() const
306 return GetRailTypeInfo(this->railtype)->acceleration_type;
310 * Returns the slope steepness used by this vehicle.
311 * @return Slope steepness used by the vehicle.
313 inline uint32_t GetSlopeSteepness() const
315 return _settings_game.vehicle.train_slope_steepness;
319 * Gets the maximum speed allowed by the track for this vehicle.
320 * @return Maximum speed allowed.
322 inline uint16_t GetMaxTrackSpeed() const
324 return GetRailTypeInfo(GetRailType(this->tile))->max_speed;
328 * Returns the curve speed modifier of this vehicle.
329 * @return Current curve speed modifier, in fixed-point binary representation with 8 fractional bits.
331 inline int GetCurveSpeedModifier() const
333 return GetVehicleProperty(this, PROP_TRAIN_CURVE_SPEED_MOD, RailVehInfo(this->engine_type)->curve_speed_mod, true);
337 * Checks if the vehicle is at a tile that can be sloped.
338 * @return True if the tile can be sloped.
340 inline bool TileMayHaveSlopedTrack() const
342 /* Any track that isn't TRACK_BIT_X or TRACK_BIT_Y cannot be sloped. */
343 return this->track == TRACK_BIT_X || this->track == TRACK_BIT_Y;
347 * Trains can always use the faster algorithm because they
348 * have always the same direction as the track under them.
349 * @return false
351 inline bool HasToUseGetSlopePixelZ()
353 return false;
357 #endif /* TRAIN_H */