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 
8 /** @file rail.h Rail specific functions. */
9 
10 #ifndef RAIL_H
11 #define RAIL_H
12 
13 #include "rail_type.h"
14 #include "track_type.h"
15 #include "gfx_type.h"
16 #include "core/bitmath_func.hpp"
17 #include "economy_func.h"
18 #include "slope_type.h"
19 #include "strings_type.h"
20 #include "date_type.h"
21 #include "signal_type.h"
22 #include "settings_type.h"
23 
24 /** Railtype flags. */
25 enum RailTypeFlags {
26 	RTF_CATENARY          = 0,                           ///< Bit number for drawing a catenary.
27 	RTF_NO_LEVEL_CROSSING = 1,                           ///< Bit number for disallowing level crossings.
28 	RTF_HIDDEN            = 2,                           ///< Bit number for hiding from selection.
29 	RTF_NO_SPRITE_COMBINE = 3,                           ///< Bit number for using non-combined junctions.
30 	RTF_ALLOW_90DEG       = 4,                           ///< Bit number for always allowed 90 degree turns, regardless of setting.
31 	RTF_DISALLOW_90DEG    = 5,                           ///< Bit number for never allowed 90 degree turns, regardless of setting.
32 
33 	RTFB_NONE              = 0,                          ///< All flags cleared.
34 	RTFB_CATENARY          = 1 << RTF_CATENARY,          ///< Value for drawing a catenary.
35 	RTFB_NO_LEVEL_CROSSING = 1 << RTF_NO_LEVEL_CROSSING, ///< Value for disallowing level crossings.
36 	RTFB_HIDDEN            = 1 << RTF_HIDDEN,            ///< Value for hiding from selection.
37 	RTFB_NO_SPRITE_COMBINE = 1 << RTF_NO_SPRITE_COMBINE, ///< Value for using non-combined junctions.
38 	RTFB_ALLOW_90DEG       = 1 << RTF_ALLOW_90DEG,       ///< Value for always allowed 90 degree turns, regardless of setting.
39 	RTFB_DISALLOW_90DEG    = 1 << RTF_DISALLOW_90DEG,    ///< Value for never allowed 90 degree turns, regardless of setting.
40 };
41 DECLARE_ENUM_AS_BIT_SET(RailTypeFlags)
42 
43 struct SpriteGroup;
44 
45 /** Sprite groups for a railtype. */
46 enum RailTypeSpriteGroup {
47 	RTSG_CURSORS,     ///< Cursor and toolbar icon images
48 	RTSG_OVERLAY,     ///< Images for overlaying track
49 	RTSG_GROUND,      ///< Main group of ground images
50 	RTSG_TUNNEL,      ///< Main group of ground images for snow or desert
51 	RTSG_WIRES,       ///< Catenary wires
52 	RTSG_PYLONS,      ///< Catenary pylons
53 	RTSG_BRIDGE,      ///< Bridge surface images
54 	RTSG_CROSSING,    ///< Level crossing overlay images
55 	RTSG_DEPOT,       ///< Depot images
56 	RTSG_FENCES,      ///< Fence images
57 	RTSG_TUNNEL_PORTAL, ///< Tunnel portal overlay
58 	RTSG_SIGNALS,     ///< Signal images
59 	RTSG_GROUND_COMPLETE, ///< Complete ground images
60 	RTSG_END,
61 };
62 
63 /**
64  * Offsets for sprites within an overlay/underlay set.
65  * These are the same for overlay and underlay sprites.
66  */
67 enum RailTrackOffset {
68 	RTO_X,            ///< Piece of rail in X direction
69 	RTO_Y,            ///< Piece of rail in Y direction
70 	RTO_N,            ///< Piece of rail in northern corner
71 	RTO_S,            ///< Piece of rail in southern corner
72 	RTO_E,            ///< Piece of rail in eastern corner
73 	RTO_W,            ///< Piece of rail in western corner
74 	RTO_SLOPE_NE,     ///< Piece of rail on slope with north-east raised
75 	RTO_SLOPE_SE,     ///< Piece of rail on slope with south-east raised
76 	RTO_SLOPE_SW,     ///< Piece of rail on slope with south-west raised
77 	RTO_SLOPE_NW,     ///< Piece of rail on slope with north-west raised
78 	RTO_CROSSING_XY,  ///< Crossing of X and Y rail, with ballast
79 	RTO_JUNCTION_SW,  ///< Ballast for junction 'pointing' SW
80 	RTO_JUNCTION_NE,  ///< Ballast for junction 'pointing' NE
81 	RTO_JUNCTION_SE,  ///< Ballast for junction 'pointing' SE
82 	RTO_JUNCTION_NW,  ///< Ballast for junction 'pointing' NW
83 	RTO_JUNCTION_NSEW,///< Ballast for full junction
84 };
85 
86 /**
87  * Offsets for sprites within a bridge surface overlay set.
88  */
89 enum RailTrackBridgeOffset {
90 	RTBO_X,     ///< Piece of rail in X direction
91 	RTBO_Y,     ///< Piece of rail in Y direction
92 	RTBO_SLOPE, ///< Sloped rail pieces, in order NE, SE, SW, NW
93 };
94 
95 /**
96  * Offsets from base sprite for fence sprites. These are in the order of
97  *  the sprites in the original data files.
98  */
99 enum RailFenceOffset {
100 	RFO_FLAT_X_NW,     //!< Slope FLAT, Track X,     Fence NW
101 	RFO_FLAT_Y_NE,     //!< Slope FLAT, Track Y,     Fence NE
102 	RFO_FLAT_LEFT,     //!< Slope FLAT, Track LEFT,  Fence E
103 	RFO_FLAT_UPPER,    //!< Slope FLAT, Track UPPER, Fence S
104 	RFO_SLOPE_SW_NW,   //!< Slope SW,   Track X,     Fence NW
105 	RFO_SLOPE_SE_NE,   //!< Slope SE,   Track Y,     Fence NE
106 	RFO_SLOPE_NE_NW,   //!< Slope NE,   Track X,     Fence NW
107 	RFO_SLOPE_NW_NE,   //!< Slope NW,   Track Y,     Fence NE
108 	RFO_FLAT_X_SE,     //!< Slope FLAT, Track X,     Fence SE
109 	RFO_FLAT_Y_SW,     //!< Slope FLAT, Track Y,     Fence SW
110 	RFO_FLAT_RIGHT,    //!< Slope FLAT, Track RIGHT, Fence W
111 	RFO_FLAT_LOWER,    //!< Slope FLAT, Track LOWER, Fence N
112 	RFO_SLOPE_SW_SE,   //!< Slope SW,   Track X,     Fence SE
113 	RFO_SLOPE_SE_SW,   //!< Slope SE,   Track Y,     Fence SW
114 	RFO_SLOPE_NE_SE,   //!< Slope NE,   Track X,     Fence SE
115 	RFO_SLOPE_NW_SW,   //!< Slope NW,   Track Y,     Fence SW
116 };
117 
118 /** List of rail type labels. */
119 typedef std::vector<RailTypeLabel> RailTypeLabelList;
120 
121 /**
122  * This struct contains all the info that is needed to draw and construct tracks.
123  */
124 class RailtypeInfo {
125 public:
126 	/**
127 	 * Struct containing the main sprites. @note not all sprites are listed, but only
128 	 *  the ones used directly in the code
129 	 */
130 	struct {
131 		SpriteID track_y;      ///< single piece of rail in Y direction, with ground
132 		SpriteID track_ns;     ///< two pieces of rail in North and South corner (East-West direction)
133 		SpriteID ground;       ///< ground sprite for a 3-way switch
134 		SpriteID single_x;     ///< single piece of rail in X direction, without ground
135 		SpriteID single_y;     ///< single piece of rail in Y direction, without ground
136 		SpriteID single_n;     ///< single piece of rail in the northern corner
137 		SpriteID single_s;     ///< single piece of rail in the southern corner
138 		SpriteID single_e;     ///< single piece of rail in the eastern corner
139 		SpriteID single_w;     ///< single piece of rail in the western corner
140 		SpriteID single_sloped;///< single piece of rail for slopes
141 		SpriteID crossing;     ///< level crossing, rail in X direction
142 		SpriteID tunnel;       ///< tunnel sprites base
143 	} base_sprites;
144 
145 	/**
146 	 * struct containing the sprites for the rail GUI. @note only sprites referred to
147 	 * directly in the code are listed
148 	 */
149 	struct {
150 		SpriteID build_ns_rail;      ///< button for building single rail in N-S direction
151 		SpriteID build_x_rail;       ///< button for building single rail in X direction
152 		SpriteID build_ew_rail;      ///< button for building single rail in E-W direction
153 		SpriteID build_y_rail;       ///< button for building single rail in Y direction
154 		SpriteID auto_rail;          ///< button for the autorail construction
155 		SpriteID build_depot;        ///< button for building depots
156 		SpriteID build_tunnel;       ///< button for building a tunnel
157 		SpriteID convert_rail;       ///< button for converting rail
158 		SpriteID signals[SIGTYPE_END][2][2]; ///< signal GUI sprites (type, variant, state)
159 	} gui_sprites;
160 
161 	struct {
162 		CursorID rail_ns;    ///< Cursor for building rail in N-S direction
163 		CursorID rail_swne;  ///< Cursor for building rail in X direction
164 		CursorID rail_ew;    ///< Cursor for building rail in E-W direction
165 		CursorID rail_nwse;  ///< Cursor for building rail in Y direction
166 		CursorID autorail;   ///< Cursor for autorail tool
167 		CursorID depot;      ///< Cursor for building a depot
168 		CursorID tunnel;     ///< Cursor for building a tunnel
169 		CursorID convert;    ///< Cursor for converting track
170 	} cursor;                    ///< Cursors associated with the rail type.
171 
172 	struct {
173 		StringID name;            ///< Name of this rail type.
174 		StringID toolbar_caption; ///< Caption in the construction toolbar GUI for this rail type.
175 		StringID menu_text;       ///< Name of this rail type in the main toolbar dropdown.
176 		StringID build_caption;   ///< Caption of the build vehicle GUI for this rail type.
177 		StringID replace_text;    ///< Text used in the autoreplace GUI.
178 		StringID new_loco;        ///< Name of an engine for this type of rail in the engine preview GUI.
179 	} strings;                        ///< Strings associated with the rail type.
180 
181 	/** sprite number difference between a piece of track on a snowy ground and the corresponding one on normal ground */
182 	SpriteID snow_offset;
183 
184 	/** bitmask to the OTHER railtypes on which an engine of THIS railtype generates power */
185 	RailTypes powered_railtypes;
186 
187 	/** bitmask to the OTHER railtypes on which an engine of THIS railtype can physically travel */
188 	RailTypes compatible_railtypes;
189 
190 	/**
191 	 * Bridge offset
192 	 */
193 	SpriteID bridge_offset;
194 
195 	/**
196 	 * Original railtype number to use when drawing non-newgrf railtypes, or when drawing stations.
197 	 */
198 	byte fallback_railtype;
199 
200 	/**
201 	 * Multiplier for curve maximum speed advantage
202 	 */
203 	byte curve_speed;
204 
205 	/**
206 	 * Bit mask of rail type flags
207 	 */
208 	RailTypeFlags flags;
209 
210 	/**
211 	 * Cost multiplier for building this rail type
212 	 */
213 	uint16 cost_multiplier;
214 
215 	/**
216 	 * Cost multiplier for maintenance of this rail type
217 	 */
218 	uint16 maintenance_multiplier;
219 
220 	/**
221 	 * Acceleration type of this rail type
222 	 */
223 	uint8 acceleration_type;
224 
225 	/**
226 	 * Maximum speed for vehicles travelling on this rail type
227 	 */
228 	uint16 max_speed;
229 
230 	/**
231 	 * Unique 32 bit rail type identifier
232 	 */
233 	RailTypeLabel label;
234 
235 	/**
236 	 * Rail type labels this type provides in addition to the main label.
237 	 */
238 	RailTypeLabelList alternate_labels;
239 
240 	/**
241 	 * Colour on mini-map
242 	 */
243 	byte map_colour;
244 
245 	/**
246 	 * Introduction date.
247 	 * When #INVALID_DATE or a vehicle using this railtype gets introduced earlier,
248 	 * the vehicle's introduction date will be used instead for this railtype.
249 	 * The introduction at this date is furthermore limited by the
250 	 * #introduction_required_railtypes.
251 	 */
252 	Date introduction_date;
253 
254 	/**
255 	 * Bitmask of railtypes that are required for this railtype to be introduced
256 	 * at a given #introduction_date.
257 	 */
258 	RailTypes introduction_required_railtypes;
259 
260 	/**
261 	 * Bitmask of which other railtypes are introduced when this railtype is introduced.
262 	 */
263 	RailTypes introduces_railtypes;
264 
265 	/**
266 	 * The sorting order of this railtype for the toolbar dropdown.
267 	 */
268 	byte sorting_order;
269 
270 	/**
271 	 * NewGRF providing the Action3 for the railtype. nullptr if not available.
272 	 */
273 	const GRFFile *grffile[RTSG_END];
274 
275 	/**
276 	 * Sprite groups for resolving sprites
277 	 */
278 	const SpriteGroup *group[RTSG_END];
279 
UsesOverlay()280 	inline bool UsesOverlay() const
281 	{
282 		return this->group[RTSG_GROUND] != nullptr;
283 	}
284 
285 	/**
286 	 * Offset between the current railtype and normal rail. This means that:<p>
287 	 * 1) All the sprites in a railset MUST be in the same order. This order
288 	 *    is determined by normal rail. Check sprites 1005 and following for this order<p>
289 	 * 2) The position where the railtype is loaded must always be the same, otherwise
290 	 *    the offset will fail.
291 	 */
GetRailtypeSpriteOffset()292 	inline uint GetRailtypeSpriteOffset() const
293 	{
294 		return 82 * this->fallback_railtype;
295 	}
296 };
297 
298 
299 /**
300  * Returns a pointer to the Railtype information for a given railtype
301  * @param railtype the rail type which the information is requested for
302  * @return The pointer to the RailtypeInfo
303  */
GetRailTypeInfo(RailType railtype)304 static inline const RailtypeInfo *GetRailTypeInfo(RailType railtype)
305 {
306 	extern RailtypeInfo _railtypes[RAILTYPE_END];
307 	assert(railtype < RAILTYPE_END);
308 	return &_railtypes[railtype];
309 }
310 
311 /**
312  * Checks if an engine of the given RailType can drive on a tile with a given
313  * RailType. This would normally just be an equality check, but for electric
314  * rails (which also support non-electric engines).
315  * @return Whether the engine can drive on this tile.
316  * @param  enginetype The RailType of the engine we are considering.
317  * @param  tiletype   The RailType of the tile we are considering.
318  */
IsCompatibleRail(RailType enginetype,RailType tiletype)319 static inline bool IsCompatibleRail(RailType enginetype, RailType tiletype)
320 {
321 	return HasBit(GetRailTypeInfo(enginetype)->compatible_railtypes, tiletype);
322 }
323 
324 /**
325  * Checks if an engine of the given RailType got power on a tile with a given
326  * RailType. This would normally just be an equality check, but for electric
327  * rails (which also support non-electric engines).
328  * @return Whether the engine got power on this tile.
329  * @param  enginetype The RailType of the engine we are considering.
330  * @param  tiletype   The RailType of the tile we are considering.
331  */
HasPowerOnRail(RailType enginetype,RailType tiletype)332 static inline bool HasPowerOnRail(RailType enginetype, RailType tiletype)
333 {
334 	return HasBit(GetRailTypeInfo(enginetype)->powered_railtypes, tiletype);
335 }
336 
337 /**
338  * Test if a RailType disallows build of level crossings.
339  * @param rt The RailType to check.
340  * @return Whether level crossings are not allowed.
341  */
RailNoLevelCrossings(RailType rt)342 static inline bool RailNoLevelCrossings(RailType rt)
343 {
344 	return HasBit(GetRailTypeInfo(rt)->flags, RTF_NO_LEVEL_CROSSING);
345 }
346 
347 /**
348  * Test if 90 degree turns are disallowed between two railtypes.
349  * @param rt1 First railtype to test for.
350  * @param rt2 Second railtype to test for.
351  * @param def Default value to use if the rail type doesn't specify anything.
352  * @return True if 90 degree turns are disallowed between the two rail types.
353  */
354 static inline bool Rail90DegTurnDisallowed(RailType rt1, RailType rt2, bool def = _settings_game.pf.forbid_90_deg)
355 {
356 	if (rt1 == INVALID_RAILTYPE || rt2 == INVALID_RAILTYPE) return def;
357 
358 	const RailtypeInfo *rti1 = GetRailTypeInfo(rt1);
359 	const RailtypeInfo *rti2 = GetRailTypeInfo(rt2);
360 
361 	bool rt1_90deg = HasBit(rti1->flags, RTF_DISALLOW_90DEG) || (!HasBit(rti1->flags, RTF_ALLOW_90DEG) && def);
362 	bool rt2_90deg = HasBit(rti2->flags, RTF_DISALLOW_90DEG) || (!HasBit(rti2->flags, RTF_ALLOW_90DEG) && def);
363 
364 	return rt1_90deg || rt2_90deg;
365 }
366 
367 /**
368  * Returns the cost of building the specified railtype.
369  * @param railtype The railtype being built.
370  * @return The cost multiplier.
371  */
RailBuildCost(RailType railtype)372 static inline Money RailBuildCost(RailType railtype)
373 {
374 	assert(railtype < RAILTYPE_END);
375 	return (_price[PR_BUILD_RAIL] * GetRailTypeInfo(railtype)->cost_multiplier) >> 3;
376 }
377 
378 /**
379  * Returns the 'cost' of clearing the specified railtype.
380  * @param railtype The railtype being removed.
381  * @return The cost.
382  */
RailClearCost(RailType railtype)383 static inline Money RailClearCost(RailType railtype)
384 {
385 	/* Clearing rail in fact earns money, but if the build cost is set
386 	 * very low then a loophole exists where money can be made.
387 	 * In this case we limit the removal earnings to 3/4s of the build
388 	 * cost.
389 	 */
390 	assert(railtype < RAILTYPE_END);
391 	return std::max(_price[PR_CLEAR_RAIL], -RailBuildCost(railtype) * 3 / 4);
392 }
393 
394 /**
395  * Calculates the cost of rail conversion
396  * @param from The railtype we are converting from
397  * @param to   The railtype we are converting to
398  * @return Cost per TrackBit
399  */
RailConvertCost(RailType from,RailType to)400 static inline Money RailConvertCost(RailType from, RailType to)
401 {
402 	/* Get the costs for removing and building anew
403 	 * A conversion can never be more costly */
404 	Money rebuildcost = RailBuildCost(to) + RailClearCost(from);
405 
406 	/* Conversion between somewhat compatible railtypes:
407 	 * Pay 1/8 of the target rail cost (labour costs) and additionally any difference in the
408 	 * build costs, if the target type is more expensive (material upgrade costs).
409 	 * Upgrade can never be more expensive than re-building. */
410 	if (HasPowerOnRail(from, to) || HasPowerOnRail(to, from)) {
411 		Money upgradecost = RailBuildCost(to) / 8 + std::max((Money)0, RailBuildCost(to) - RailBuildCost(from));
412 		return std::min(upgradecost, rebuildcost);
413 	}
414 
415 	/* make the price the same as remove + build new type for rail types
416 	 * which are not compatible in any way */
417 	return rebuildcost;
418 }
419 
420 /**
421  * Calculates the maintenance cost of a number of track bits.
422  * @param railtype The railtype to get the cost of.
423  * @param num Number of track bits of this railtype.
424  * @param total_num Total number of track bits of all railtypes.
425  * @return Total cost.
426  */
RailMaintenanceCost(RailType railtype,uint32 num,uint32 total_num)427 static inline Money RailMaintenanceCost(RailType railtype, uint32 num, uint32 total_num)
428 {
429 	assert(railtype < RAILTYPE_END);
430 	return (_price[PR_INFRASTRUCTURE_RAIL] * GetRailTypeInfo(railtype)->maintenance_multiplier * num * (1 + IntSqrt(total_num))) >> 11; // 4 bits fraction for the multiplier and 7 bits scaling.
431 }
432 
433 /**
434  * Calculates the maintenance cost of a number of signals.
435  * @param num Number of signals.
436  * @return Total cost.
437  */
SignalMaintenanceCost(uint32 num)438 static inline Money SignalMaintenanceCost(uint32 num)
439 {
440 	return (_price[PR_INFRASTRUCTURE_RAIL] * 15 * num * (1 + IntSqrt(num))) >> 8; // 1 bit fraction for the multiplier and 7 bits scaling.
441 }
442 
443 void DrawTrainDepotSprite(int x, int y, int image, RailType railtype);
444 int TicksToLeaveDepot(const Train *v);
445 
446 Foundation GetRailFoundation(Slope tileh, TrackBits bits);
447 
448 
449 bool HasRailtypeAvail(const CompanyID company, const RailType railtype);
450 bool HasAnyRailtypesAvail(const CompanyID company);
451 bool ValParamRailtype(const RailType rail);
452 
453 RailTypes AddDateIntroducedRailTypes(RailTypes current, Date date);
454 
455 RailTypes GetCompanyRailtypes(CompanyID company, bool introduces = true);
456 RailTypes GetRailTypes(bool introduces);
457 
458 RailType GetRailTypeByLabel(RailTypeLabel label, bool allow_alternate_labels = true);
459 
460 void ResetRailTypes();
461 void InitRailTypes();
462 RailType AllocateRailType(RailTypeLabel label);
463 
464 extern std::vector<RailType> _sorted_railtypes;
465 extern RailTypes _railtypes_hidden_mask;
466 
467 #endif /* RAIL_H */
468