Codechange: Use null pointer literal instead of the NULL macro
[openttd-github.git] / src / pathfinder / follow_track.hpp
blob999f7f94de9ae2822ff86fc69bfb640a756c49e0
1 /* $Id$ */
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 */
10 /** @file follow_track.hpp Template function for track followers */
12 #ifndef FOLLOW_TRACK_HPP
13 #define FOLLOW_TRACK_HPP
15 #include "../pbs.h"
16 #include "../roadveh.h"
17 #include "../station_base.h"
18 #include "../train.h"
19 #include "../tunnelbridge.h"
20 #include "../tunnelbridge_map.h"
21 #include "../depot_map.h"
22 #include "pf_performance_timer.hpp"
24 /**
25 * Track follower helper template class (can serve pathfinders and vehicle
26 * controllers). See 6 different typedefs below for 3 different transport
27 * types w/ or w/o 90-deg turns allowed
29 template <TransportType Ttr_type_, typename VehicleType, bool T90deg_turns_allowed_ = true, bool Tmask_reserved_tracks = false>
30 struct CFollowTrackT
32 enum ErrorCode {
33 EC_NONE,
34 EC_OWNER,
35 EC_RAIL_TYPE,
36 EC_90DEG,
37 EC_NO_WAY,
38 EC_RESERVED,
41 const VehicleType *m_veh; ///< moving vehicle
42 Owner m_veh_owner; ///< owner of the vehicle
43 TileIndex m_old_tile; ///< the origin (vehicle moved from) before move
44 Trackdir m_old_td; ///< the trackdir (the vehicle was on) before move
45 TileIndex m_new_tile; ///< the new tile (the vehicle has entered)
46 TrackdirBits m_new_td_bits; ///< the new set of available trackdirs
47 DiagDirection m_exitdir; ///< exit direction (leaving the old tile)
48 bool m_is_tunnel; ///< last turn passed tunnel
49 bool m_is_bridge; ///< last turn passed bridge ramp
50 bool m_is_station; ///< last turn passed station
51 int m_tiles_skipped; ///< number of skipped tunnel or station tiles
52 ErrorCode m_err;
53 CPerformanceTimer *m_pPerf;
54 RailTypes m_railtypes;
56 inline CFollowTrackT(const VehicleType *v = nullptr, RailTypes railtype_override = INVALID_RAILTYPES, CPerformanceTimer *pPerf = nullptr)
58 Init(v, railtype_override, pPerf);
61 inline CFollowTrackT(Owner o, RailTypes railtype_override = INVALID_RAILTYPES, CPerformanceTimer *pPerf = nullptr)
63 m_veh = nullptr;
64 Init(o, railtype_override, pPerf);
67 inline void Init(const VehicleType *v, RailTypes railtype_override, CPerformanceTimer *pPerf)
69 assert(!IsRailTT() || (v != nullptr && v->type == VEH_TRAIN));
70 m_veh = v;
71 Init(v != nullptr ? v->owner : INVALID_OWNER, IsRailTT() && railtype_override == INVALID_RAILTYPES ? Train::From(v)->compatible_railtypes : railtype_override, pPerf);
74 inline void Init(Owner o, RailTypes railtype_override, CPerformanceTimer *pPerf)
76 assert(!IsRoadTT() || m_veh != nullptr);
77 assert(!IsRailTT() || railtype_override != INVALID_RAILTYPES);
78 m_veh_owner = o;
79 m_pPerf = pPerf;
80 /* don't worry, all is inlined so compiler should remove unnecessary initializations */
81 m_old_tile = INVALID_TILE;
82 m_old_td = INVALID_TRACKDIR;
83 m_new_tile = INVALID_TILE;
84 m_new_td_bits = TRACKDIR_BIT_NONE;
85 m_exitdir = INVALID_DIAGDIR;
86 m_is_station = m_is_bridge = m_is_tunnel = false;
87 m_tiles_skipped = 0;
88 m_err = EC_NONE;
89 m_railtypes = railtype_override;
92 inline static TransportType TT() { return Ttr_type_; }
93 inline static bool IsWaterTT() { return TT() == TRANSPORT_WATER; }
94 inline static bool IsRailTT() { return TT() == TRANSPORT_RAIL; }
95 inline bool IsTram() { return IsRoadTT() && HasBit(RoadVehicle::From(m_veh)->compatible_roadtypes, ROADTYPE_TRAM); }
96 inline static bool IsRoadTT() { return TT() == TRANSPORT_ROAD; }
97 inline static bool Allow90degTurns() { return T90deg_turns_allowed_; }
98 inline static bool DoTrackMasking() { return Tmask_reserved_tracks; }
100 /** Tests if a tile is a road tile with a single tramtrack (tram can reverse) */
101 inline DiagDirection GetSingleTramBit(TileIndex tile)
103 assert(IsTram()); // this function shouldn't be called in other cases
105 if (IsNormalRoadTile(tile)) {
106 RoadBits rb = GetRoadBits(tile, ROADTYPE_TRAM);
107 switch (rb) {
108 case ROAD_NW: return DIAGDIR_NW;
109 case ROAD_SW: return DIAGDIR_SW;
110 case ROAD_SE: return DIAGDIR_SE;
111 case ROAD_NE: return DIAGDIR_NE;
112 default: break;
115 return INVALID_DIAGDIR;
119 * main follower routine. Fills all members and return true on success.
120 * Otherwise returns false if track can't be followed.
122 inline bool Follow(TileIndex old_tile, Trackdir old_td)
124 m_old_tile = old_tile;
125 m_old_td = old_td;
126 m_err = EC_NONE;
127 assert(
128 ((TrackStatusToTrackdirBits(
129 GetTileTrackStatus(m_old_tile, TT(), (IsRoadTT() && m_veh != nullptr) ? RoadVehicle::From(m_veh)->compatible_roadtypes : 0)
130 ) & TrackdirToTrackdirBits(m_old_td)) != 0) ||
131 (IsTram() && GetSingleTramBit(m_old_tile) != INVALID_DIAGDIR) // Disable the assertion for single tram bits
133 m_exitdir = TrackdirToExitdir(m_old_td);
134 if (ForcedReverse()) return true;
135 if (!CanExitOldTile()) return false;
136 FollowTileExit();
137 if (!QueryNewTileTrackStatus()) return TryReverse();
138 m_new_td_bits &= DiagdirReachesTrackdirs(m_exitdir);
139 if (m_new_td_bits == TRACKDIR_BIT_NONE || !CanEnterNewTile()) {
140 /* In case we can't enter the next tile, but are
141 * a normal road vehicle, then we can actually
142 * try to reverse as this is the end of the road.
143 * Trams can only turn on the appropriate bits in
144 * which case reaching this would mean a dead end
145 * near a building and in that case there would
146 * a "false" QueryNewTileTrackStatus result and
147 * as such reversing is already tried. The fact
148 * that function failed can have to do with a
149 * missing road bit, or inability to connect the
150 * different bits due to slopes. */
151 if (IsRoadTT() && !IsTram() && TryReverse()) return true;
153 /* CanEnterNewTile already set a reason.
154 * Do NOT overwrite it (important for example for EC_RAIL_TYPE).
155 * Only set a reason if CanEnterNewTile was not called */
156 if (m_new_td_bits == TRACKDIR_BIT_NONE) m_err = EC_NO_WAY;
158 return false;
160 if ((!IsRailTT() && !Allow90degTurns()) || (IsRailTT() && Rail90DegTurnDisallowed(GetTileRailType(m_old_tile), GetTileRailType(m_new_tile), !Allow90degTurns()))) {
161 m_new_td_bits &= (TrackdirBits)~(int)TrackdirCrossesTrackdirs(m_old_td);
162 if (m_new_td_bits == TRACKDIR_BIT_NONE) {
163 m_err = EC_90DEG;
164 return false;
167 return true;
170 inline bool MaskReservedTracks()
172 if (!DoTrackMasking()) return true;
174 if (m_is_station) {
175 /* Check skipped station tiles as well. */
176 TileIndexDiff diff = TileOffsByDiagDir(m_exitdir);
177 for (TileIndex tile = m_new_tile - diff * m_tiles_skipped; tile != m_new_tile; tile += diff) {
178 if (HasStationReservation(tile)) {
179 m_new_td_bits = TRACKDIR_BIT_NONE;
180 m_err = EC_RESERVED;
181 return false;
186 TrackBits reserved = GetReservedTrackbits(m_new_tile);
187 /* Mask already reserved trackdirs. */
188 m_new_td_bits &= ~TrackBitsToTrackdirBits(reserved);
189 /* Mask out all trackdirs that conflict with the reservation. */
190 Track t;
191 FOR_EACH_SET_TRACK(t, TrackdirBitsToTrackBits(m_new_td_bits)) {
192 if (TracksOverlap(reserved | TrackToTrackBits(t))) m_new_td_bits &= ~TrackToTrackdirBits(t);
194 if (m_new_td_bits == TRACKDIR_BIT_NONE) {
195 m_err = EC_RESERVED;
196 return false;
198 return true;
201 protected:
202 /** Follow the m_exitdir from m_old_tile and fill m_new_tile and m_tiles_skipped */
203 inline void FollowTileExit()
205 m_is_station = m_is_bridge = m_is_tunnel = false;
206 m_tiles_skipped = 0;
208 /* extra handling for tunnels and bridges in our direction */
209 if (IsTileType(m_old_tile, MP_TUNNELBRIDGE)) {
210 DiagDirection enterdir = GetTunnelBridgeDirection(m_old_tile);
211 if (enterdir == m_exitdir) {
212 /* we are entering the tunnel / bridge */
213 if (IsTunnel(m_old_tile)) {
214 m_is_tunnel = true;
215 m_new_tile = GetOtherTunnelEnd(m_old_tile);
216 } else { // IsBridge(m_old_tile)
217 m_is_bridge = true;
218 m_new_tile = GetOtherBridgeEnd(m_old_tile);
220 m_tiles_skipped = GetTunnelBridgeLength(m_new_tile, m_old_tile);
221 return;
223 assert(ReverseDiagDir(enterdir) == m_exitdir);
226 /* normal or station tile, do one step */
227 m_new_tile = TileAddByDiagDir(m_old_tile, m_exitdir);
229 /* special handling for stations */
230 if (IsRailTT() && HasStationTileRail(m_new_tile)) {
231 m_is_station = true;
232 } else if (IsRoadTT() && IsRoadStopTile(m_new_tile)) {
233 m_is_station = true;
237 /** stores track status (available trackdirs) for the new tile into m_new_td_bits */
238 inline bool QueryNewTileTrackStatus()
240 CPerfStart perf(*m_pPerf);
241 if (IsRailTT() && IsPlainRailTile(m_new_tile)) {
242 m_new_td_bits = (TrackdirBits)(GetTrackBits(m_new_tile) * 0x101);
243 } else {
244 m_new_td_bits = TrackStatusToTrackdirBits(GetTileTrackStatus(m_new_tile, TT(), IsRoadTT() ? RoadVehicle::From(m_veh)->compatible_roadtypes : 0));
246 if (IsTram() && m_new_td_bits == TRACKDIR_BIT_NONE) {
247 /* GetTileTrackStatus() returns 0 for single tram bits.
248 * As we cannot change it there (easily) without breaking something, change it here */
249 switch (GetSingleTramBit(m_new_tile)) {
250 case DIAGDIR_NE:
251 case DIAGDIR_SW:
252 m_new_td_bits = TRACKDIR_BIT_X_NE | TRACKDIR_BIT_X_SW;
253 break;
255 case DIAGDIR_NW:
256 case DIAGDIR_SE:
257 m_new_td_bits = TRACKDIR_BIT_Y_NW | TRACKDIR_BIT_Y_SE;
258 break;
260 default: break;
264 return (m_new_td_bits != TRACKDIR_BIT_NONE);
267 /** return true if we can leave m_old_tile in m_exitdir */
268 inline bool CanExitOldTile()
270 /* road stop can be left at one direction only unless it's a drive-through stop */
271 if (IsRoadTT() && IsStandardRoadStopTile(m_old_tile)) {
272 DiagDirection exitdir = GetRoadStopDir(m_old_tile);
273 if (exitdir != m_exitdir) {
274 m_err = EC_NO_WAY;
275 return false;
279 /* single tram bits can only be left in one direction */
280 if (IsTram()) {
281 DiagDirection single_tram = GetSingleTramBit(m_old_tile);
282 if (single_tram != INVALID_DIAGDIR && single_tram != m_exitdir) {
283 m_err = EC_NO_WAY;
284 return false;
288 /* road depots can be also left in one direction only */
289 if (IsRoadTT() && IsDepotTypeTile(m_old_tile, TT())) {
290 DiagDirection exitdir = GetRoadDepotDirection(m_old_tile);
291 if (exitdir != m_exitdir) {
292 m_err = EC_NO_WAY;
293 return false;
296 return true;
299 /** return true if we can enter m_new_tile from m_exitdir */
300 inline bool CanEnterNewTile()
302 if (IsRoadTT() && IsStandardRoadStopTile(m_new_tile)) {
303 /* road stop can be entered from one direction only unless it's a drive-through stop */
304 DiagDirection exitdir = GetRoadStopDir(m_new_tile);
305 if (ReverseDiagDir(exitdir) != m_exitdir) {
306 m_err = EC_NO_WAY;
307 return false;
311 /* single tram bits can only be entered from one direction */
312 if (IsTram()) {
313 DiagDirection single_tram = GetSingleTramBit(m_new_tile);
314 if (single_tram != INVALID_DIAGDIR && single_tram != ReverseDiagDir(m_exitdir)) {
315 m_err = EC_NO_WAY;
316 return false;
320 /* road and rail depots can also be entered from one direction only */
321 if (IsRoadTT() && IsDepotTypeTile(m_new_tile, TT())) {
322 DiagDirection exitdir = GetRoadDepotDirection(m_new_tile);
323 if (ReverseDiagDir(exitdir) != m_exitdir) {
324 m_err = EC_NO_WAY;
325 return false;
327 /* don't try to enter other company's depots */
328 if (GetTileOwner(m_new_tile) != m_veh_owner) {
329 m_err = EC_OWNER;
330 return false;
333 if (IsRailTT() && IsDepotTypeTile(m_new_tile, TT())) {
334 DiagDirection exitdir = GetRailDepotDirection(m_new_tile);
335 if (ReverseDiagDir(exitdir) != m_exitdir) {
336 m_err = EC_NO_WAY;
337 return false;
341 /* rail transport is possible only on tiles with the same owner as vehicle */
342 if (IsRailTT() && GetTileOwner(m_new_tile) != m_veh_owner) {
343 /* different owner */
344 m_err = EC_NO_WAY;
345 return false;
348 /* rail transport is possible only on compatible rail types */
349 if (IsRailTT()) {
350 RailType rail_type = GetTileRailType(m_new_tile);
351 if (!HasBit(m_railtypes, rail_type)) {
352 /* incompatible rail type */
353 m_err = EC_RAIL_TYPE;
354 return false;
358 /* tunnel holes and bridge ramps can be entered only from proper direction */
359 if (IsTileType(m_new_tile, MP_TUNNELBRIDGE)) {
360 if (IsTunnel(m_new_tile)) {
361 if (!m_is_tunnel) {
362 DiagDirection tunnel_enterdir = GetTunnelBridgeDirection(m_new_tile);
363 if (tunnel_enterdir != m_exitdir) {
364 m_err = EC_NO_WAY;
365 return false;
368 } else { // IsBridge(m_new_tile)
369 if (!m_is_bridge) {
370 DiagDirection ramp_enderdir = GetTunnelBridgeDirection(m_new_tile);
371 if (ramp_enderdir != m_exitdir) {
372 m_err = EC_NO_WAY;
373 return false;
379 /* special handling for rail stations - get to the end of platform */
380 if (IsRailTT() && m_is_station) {
381 /* entered railway station
382 * get platform length */
383 uint length = BaseStation::GetByTile(m_new_tile)->GetPlatformLength(m_new_tile, TrackdirToExitdir(m_old_td));
384 /* how big step we must do to get to the last platform tile; */
385 m_tiles_skipped = length - 1;
386 /* move to the platform end */
387 TileIndexDiff diff = TileOffsByDiagDir(m_exitdir);
388 diff *= m_tiles_skipped;
389 m_new_tile = TILE_ADD(m_new_tile, diff);
390 return true;
393 return true;
396 /** return true if we must reverse (in depots and single tram bits) */
397 inline bool ForcedReverse()
399 /* rail and road depots cause reversing */
400 if (!IsWaterTT() && IsDepotTypeTile(m_old_tile, TT())) {
401 DiagDirection exitdir = IsRailTT() ? GetRailDepotDirection(m_old_tile) : GetRoadDepotDirection(m_old_tile);
402 if (exitdir != m_exitdir) {
403 /* reverse */
404 m_new_tile = m_old_tile;
405 m_new_td_bits = TrackdirToTrackdirBits(ReverseTrackdir(m_old_td));
406 m_exitdir = exitdir;
407 m_tiles_skipped = 0;
408 m_is_tunnel = m_is_bridge = m_is_station = false;
409 return true;
413 /* Single tram bits and standard road stops cause reversing. */
414 if (IsRoadTT() && ((IsTram() && GetSingleTramBit(m_old_tile) == ReverseDiagDir(m_exitdir)) ||
415 (IsStandardRoadStopTile(m_old_tile) && GetRoadStopDir(m_old_tile) == ReverseDiagDir(m_exitdir)))) {
416 /* reverse */
417 m_new_tile = m_old_tile;
418 m_new_td_bits = TrackdirToTrackdirBits(ReverseTrackdir(m_old_td));
419 m_exitdir = ReverseDiagDir(m_exitdir);
420 m_tiles_skipped = 0;
421 m_is_tunnel = m_is_bridge = m_is_station = false;
422 return true;
425 return false;
428 /** return true if we successfully reversed at end of road/track */
429 inline bool TryReverse()
431 if (IsRoadTT() && !IsTram()) {
432 /* if we reached the end of road, we can reverse the RV and continue moving */
433 m_exitdir = ReverseDiagDir(m_exitdir);
434 /* new tile will be the same as old one */
435 m_new_tile = m_old_tile;
436 /* set new trackdir bits to all reachable trackdirs */
437 QueryNewTileTrackStatus();
438 m_new_td_bits &= DiagdirReachesTrackdirs(m_exitdir);
439 if (m_new_td_bits != TRACKDIR_BIT_NONE) {
440 /* we have some trackdirs reachable after reversal */
441 return true;
444 m_err = EC_NO_WAY;
445 return false;
448 public:
449 /** Helper for pathfinders - get min/max speed on the m_old_tile/m_old_td */
450 int GetSpeedLimit(int *pmin_speed = nullptr) const
452 int min_speed = 0;
453 int max_speed = INT_MAX; // no limit
455 /* Check for on-bridge speed limit */
456 if (!IsWaterTT() && IsBridgeTile(m_old_tile)) {
457 int spd = GetBridgeSpec(GetBridgeType(m_old_tile))->speed;
458 if (IsRoadTT()) spd *= 2;
459 if (max_speed > spd) max_speed = spd;
461 /* Check for speed limit imposed by railtype */
462 if (IsRailTT()) {
463 uint16 rail_speed = GetRailTypeInfo(GetRailType(m_old_tile))->max_speed;
464 if (rail_speed > 0) max_speed = min(max_speed, rail_speed);
467 /* if min speed was requested, return it */
468 if (pmin_speed != nullptr) *pmin_speed = min_speed;
469 return max_speed;
473 typedef CFollowTrackT<TRANSPORT_WATER, Ship, true > CFollowTrackWater;
474 typedef CFollowTrackT<TRANSPORT_ROAD, RoadVehicle, true > CFollowTrackRoad;
475 typedef CFollowTrackT<TRANSPORT_RAIL, Train, true > CFollowTrackRail;
477 typedef CFollowTrackT<TRANSPORT_RAIL, Train, false> CFollowTrackRailNo90;
479 typedef CFollowTrackT<TRANSPORT_RAIL, Train, true, true > CFollowTrackFreeRail;
480 typedef CFollowTrackT<TRANSPORT_RAIL, Train, false, true > CFollowTrackFreeRailNo90;
482 #endif /* FOLLOW_TRACK_HPP */