OpenTTD
npf.cpp
Go to the documentation of this file.
1 /* $Id: npf.cpp 27733 2017-01-15 13:59:46Z frosch $ */
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 #include "../../stdafx.h"
13 #include "../../network/network.h"
14 #include "../../viewport_func.h"
15 #include "../../ship.h"
16 #include "../../roadstop_base.h"
17 #include "../pathfinder_func.h"
18 #include "../pathfinder_type.h"
19 #include "../follow_track.hpp"
20 #include "aystar.h"
21 
22 #include "../../safeguards.h"
23 
24 static const uint NPF_HASH_BITS = 12;
25 /* Do no change below values */
26 static const uint NPF_HASH_SIZE = 1 << NPF_HASH_BITS;
27 static const uint NPF_HASH_HALFBITS = NPF_HASH_BITS / 2;
28 static const uint NPF_HASH_HALFMASK = (1 << NPF_HASH_HALFBITS) - 1;
29 
33  StationID station_index;
34  bool reserve_path;
37  const Vehicle *v;
38 };
39 
42  Owner owner;
43  TransportType type;
44  RailTypes railtypes;
45  RoadTypes roadtypes;
46 };
47 
51  NPF_NODE_FLAGS,
52 };
53 
65 };
66 
73  bool res_okay;
74 };
75 
76 static AyStar _npf_aystar;
77 
78 /* The cost of each trackdir. A diagonal piece is the full NPF_TILE_LENGTH,
79  * the shorter piece is sqrt(2)/2*NPF_TILE_LENGTH =~ 0.7071
80  */
81 #define NPF_STRAIGHT_LENGTH (uint)(NPF_TILE_LENGTH * STRAIGHT_TRACK_LENGTH)
82 static const uint _trackdir_length[TRACKDIR_END] = {
83  NPF_TILE_LENGTH, NPF_TILE_LENGTH, NPF_STRAIGHT_LENGTH, NPF_STRAIGHT_LENGTH, NPF_STRAIGHT_LENGTH, NPF_STRAIGHT_LENGTH,
84  0, 0,
85  NPF_TILE_LENGTH, NPF_TILE_LENGTH, NPF_STRAIGHT_LENGTH, NPF_STRAIGHT_LENGTH, NPF_STRAIGHT_LENGTH, NPF_STRAIGHT_LENGTH
86 };
87 
91 static inline bool NPFGetFlag(const AyStarNode *node, NPFNodeFlag flag)
92 {
93  return HasBit(node->user_data[NPF_NODE_FLAGS], flag);
94 }
95 
99 static inline void NPFSetFlag(AyStarNode *node, NPFNodeFlag flag, bool value)
100 {
101  SB(node->user_data[NPF_NODE_FLAGS], flag, 1, value);
102 }
103 
111 {
112  const uint dx = Delta(TileX(t0), TileX(t1));
113  const uint dy = Delta(TileY(t0), TileY(t1));
114 
115  const uint straightTracks = 2 * min(dx, dy); // The number of straight (not full length) tracks
116  /* OPTIMISATION:
117  * Original: diagTracks = max(dx, dy) - min(dx,dy);
118  * Proof:
119  * (dx+dy) - straightTracks == (min + max) - straightTracks = min + max - 2 * min = max - min */
120  const uint diagTracks = dx + dy - straightTracks; // The number of diagonal (full tile length) tracks.
121 
122  /* Don't factor out NPF_TILE_LENGTH below, this will round values and lose
123  * precision */
124  return diagTracks * NPF_TILE_LENGTH + straightTracks * NPF_TILE_LENGTH * STRAIGHT_TRACK_LENGTH;
125 }
126 
134 static uint NPFHash(uint key1, uint key2)
135 {
136  /* TODO: think of a better hash? */
137  uint part1 = TileX(key1) & NPF_HASH_HALFMASK;
138  uint part2 = TileY(key1) & NPF_HASH_HALFMASK;
139 
140  assert(IsValidTrackdir((Trackdir)key2));
141  assert(IsValidTile(key1));
142  return ((part1 << NPF_HASH_HALFBITS | part2) + (NPF_HASH_SIZE * key2 / TRACKDIR_END)) % NPF_HASH_SIZE;
143 }
144 
145 static int32 NPFCalcZero(AyStar *as, AyStarNode *current, OpenListNode *parent)
146 {
147  return 0;
148 }
149 
150 /* Calculates the heuristic to the target station or tile. For train stations, it
151  * takes into account the direction of approach.
152  */
153 static int32 NPFCalcStationOrTileHeuristic(AyStar *as, AyStarNode *current, OpenListNode *parent)
154 {
155  NPFFindStationOrTileData *fstd = (NPFFindStationOrTileData*)as->user_target;
156  NPFFoundTargetData *ftd = (NPFFoundTargetData*)as->user_path;
157  TileIndex from = current->tile;
158  TileIndex to = fstd->dest_coords;
159  uint dist;
160  AyStarUserData *user = (AyStarUserData *)as->user_data;
161 
162  /* for train-stations, we are going to aim for the closest station tile */
163  if (user->type != TRANSPORT_WATER && fstd->station_index != INVALID_STATION) {
164  to = CalcClosestStationTile(fstd->station_index, from, fstd->station_type);
165  }
166 
167  if (user->type == TRANSPORT_ROAD) {
168  /* Since roads only have diagonal pieces, we use manhattan distance here */
169  dist = DistanceManhattan(from, to) * NPF_TILE_LENGTH;
170  } else {
171  /* Ships and trains can also go diagonal, so the minimum distance is shorter */
172  dist = NPFDistanceTrack(from, to);
173  }
174 
175  DEBUG(npf, 4, "Calculating H for: (%d, %d). Result: %d", TileX(current->tile), TileY(current->tile), dist);
176 
177  if (dist < ftd->best_bird_dist) {
178  ftd->best_bird_dist = dist;
179  ftd->best_trackdir = (Trackdir)current->user_data[NPF_TRACKDIR_CHOICE];
180  }
181  return dist;
182 }
183 
184 
185 /* Fills AyStarNode.user_data[NPF_TRACKDIRCHOICE] with the chosen direction to
186  * get here, either getting it from the current choice or from the parent's
187  * choice */
188 static void NPFFillTrackdirChoice(AyStarNode *current, OpenListNode *parent)
189 {
190  if (parent->path.parent == NULL) {
191  Trackdir trackdir = current->direction;
192  /* This is a first order decision, so we'd better save the
193  * direction we chose */
194  current->user_data[NPF_TRACKDIR_CHOICE] = trackdir;
195  DEBUG(npf, 6, "Saving trackdir: 0x%X", trackdir);
196  } else {
197  /* We've already made the decision, so just save our parent's decision */
198  current->user_data[NPF_TRACKDIR_CHOICE] = parent->path.node.user_data[NPF_TRACKDIR_CHOICE];
199  }
200 }
201 
202 /* Will return the cost of the tunnel. If it is an entry, it will return the
203  * cost of that tile. If the tile is an exit, it will return the tunnel length
204  * including the exit tile. Requires that this is a Tunnel tile */
205 static uint NPFTunnelCost(AyStarNode *current)
206 {
207  DiagDirection exitdir = TrackdirToExitdir(current->direction);
208  TileIndex tile = current->tile;
209  if (GetTunnelBridgeDirection(tile) == ReverseDiagDir(exitdir)) {
210  /* We just popped out if this tunnel, since were
211  * facing the tunnel exit */
212  return NPF_TILE_LENGTH * (GetTunnelBridgeLength(current->tile, GetOtherTunnelEnd(current->tile)) + 1);
213  /* @todo: Penalty for tunnels? */
214  } else {
215  /* We are entering the tunnel, the enter tile is just a
216  * straight track */
217  return NPF_TILE_LENGTH;
218  }
219 }
220 
221 static inline uint NPFBridgeCost(AyStarNode *current)
222 {
223  return NPF_TILE_LENGTH * GetTunnelBridgeLength(current->tile, GetOtherBridgeEnd(current->tile));
224 }
225 
226 static uint NPFSlopeCost(AyStarNode *current)
227 {
228  TileIndex next = current->tile + TileOffsByDiagDir(TrackdirToExitdir(current->direction));
229 
230  /* Get center of tiles */
231  int x1 = TileX(current->tile) * TILE_SIZE + TILE_SIZE / 2;
232  int y1 = TileY(current->tile) * TILE_SIZE + TILE_SIZE / 2;
233  int x2 = TileX(next) * TILE_SIZE + TILE_SIZE / 2;
234  int y2 = TileY(next) * TILE_SIZE + TILE_SIZE / 2;
235 
236  int dx4 = (x2 - x1) / 4;
237  int dy4 = (y2 - y1) / 4;
238 
239  /* Get the height on both sides of the tile edge.
240  * Avoid testing the height on the tile-center. This will fail for halftile-foundations.
241  */
242  int z1 = GetSlopePixelZ(x1 + dx4, y1 + dy4);
243  int z2 = GetSlopePixelZ(x2 - dx4, y2 - dy4);
244 
245  if (z2 - z1 > 1) {
246  /* Slope up */
248  }
249  return 0;
250  /* Should we give a bonus for slope down? Probably not, we
251  * could just subtract that bonus from the penalty, because
252  * there is only one level of steepness... */
253 }
254 
255 static uint NPFReservedTrackCost(AyStarNode *current)
256 {
257  TileIndex tile = current->tile;
258  TrackBits track = TrackToTrackBits(TrackdirToTrack(current->direction));
259  TrackBits res = GetReservedTrackbits(tile);
260 
261  if (NPFGetFlag(current, NPF_FLAG_3RD_SIGNAL) || NPFGetFlag(current, NPF_FLAG_LAST_SIGNAL_BLOCK) || ((res & track) == TRACK_BIT_NONE && !TracksOverlap(res | track))) return 0;
262 
263  if (IsTileType(tile, MP_TUNNELBRIDGE)) {
264  DiagDirection exitdir = TrackdirToExitdir(current->direction);
265  if (GetTunnelBridgeDirection(tile) == ReverseDiagDir(exitdir)) {
267  }
268  }
270 }
271 
276 static void NPFMarkTile(TileIndex tile)
277 {
278 #ifndef NO_DEBUG_MESSAGES
279  if (_debug_npf_level < 1 || _networking) return;
280  switch (GetTileType(tile)) {
281  case MP_RAILWAY:
282  /* DEBUG: mark visited tiles by mowing the grass under them ;-) */
283  if (!IsRailDepot(tile)) {
284  SetRailGroundType(tile, RAIL_GROUND_BARREN);
285  MarkTileDirtyByTile(tile);
286  }
287  break;
288 
289  case MP_ROAD:
290  if (!IsRoadDepot(tile)) {
292  MarkTileDirtyByTile(tile);
293  }
294  break;
295 
296  default:
297  break;
298  }
299 #endif
300 }
301 
302 static int32 NPFWaterPathCost(AyStar *as, AyStarNode *current, OpenListNode *parent)
303 {
304  /* TileIndex tile = current->tile; */
305  int32 cost = 0;
306  Trackdir trackdir = current->direction;
307 
308  cost = _trackdir_length[trackdir]; // Should be different for diagonal tracks
309 
310  if (IsBuoyTile(current->tile) && IsDiagonalTrackdir(trackdir)) {
311  cost += _settings_game.pf.npf.npf_buoy_penalty; // A small penalty for going over buoys
312  }
313 
314  if (current->direction != NextTrackdir((Trackdir)parent->path.node.direction)) {
316  }
317 
318  /* @todo More penalties? */
319 
320  return cost;
321 }
322 
323 /* Determine the cost of this node, for road tracks */
324 static int32 NPFRoadPathCost(AyStar *as, AyStarNode *current, OpenListNode *parent)
325 {
326  TileIndex tile = current->tile;
327  int32 cost = 0;
328 
329  /* Determine base length */
330  switch (GetTileType(tile)) {
331  case MP_TUNNELBRIDGE:
332  cost = IsTunnel(tile) ? NPFTunnelCost(current) : NPFBridgeCost(current);
333  break;
334 
335  case MP_ROAD:
336  cost = NPF_TILE_LENGTH;
337  /* Increase the cost for level crossings */
339  break;
340 
341  case MP_STATION: {
342  cost = NPF_TILE_LENGTH;
343  const RoadStop *rs = RoadStop::GetByTile(tile, GetRoadStopType(tile));
344  if (IsDriveThroughStopTile(tile)) {
345  /* Increase the cost for drive-through road stops */
347  DiagDirection dir = TrackdirToExitdir(current->direction);
349  /* When we're the first road stop in a 'queue' of them we increase
350  * cost based on the fill percentage of the whole queue. */
351  const RoadStop::Entry *entry = rs->GetEntry(dir);
353  }
354  } else {
355  /* Increase cost for filled road stops */
356  cost += _settings_game.pf.npf.npf_road_bay_occupied_penalty * (!rs->IsFreeBay(0) + !rs->IsFreeBay(1)) / 2;
357  }
358  break;
359  }
360 
361  default:
362  break;
363  }
364 
365  /* Determine extra costs */
366 
367  /* Check for slope */
368  cost += NPFSlopeCost(current);
369 
370  /* Check for turns. Road vehicles only really drive diagonal, turns are
371  * represented by non-diagonal tracks */
372  if (!IsDiagonalTrackdir(current->direction)) {
374  }
375 
376  NPFMarkTile(tile);
377  DEBUG(npf, 4, "Calculating G for: (%d, %d). Result: %d", TileX(current->tile), TileY(current->tile), cost);
378  return cost;
379 }
380 
381 
382 /* Determine the cost of this node, for railway tracks */
383 static int32 NPFRailPathCost(AyStar *as, AyStarNode *current, OpenListNode *parent)
384 {
385  TileIndex tile = current->tile;
386  Trackdir trackdir = current->direction;
387  int32 cost = 0;
388  /* HACK: We create a OpenListNode manually, so we can call EndNodeCheck */
389  OpenListNode new_node;
390 
391  /* Determine base length */
392  switch (GetTileType(tile)) {
393  case MP_TUNNELBRIDGE:
394  cost = IsTunnel(tile) ? NPFTunnelCost(current) : NPFBridgeCost(current);
395  break;
396 
397  case MP_RAILWAY:
398  cost = _trackdir_length[trackdir]; // Should be different for diagonal tracks
399  break;
400 
401  case MP_ROAD: // Railway crossing
402  cost = NPF_TILE_LENGTH;
403  break;
404 
405  case MP_STATION:
406  /* We give a station tile a penalty. Logically we would only want to give
407  * station tiles that are not our destination this penalty. This would
408  * discourage trains to drive through busy stations. But, we can just
409  * give any station tile a penalty, because every possible route will get
410  * this penalty exactly once, on its end tile (if it's a station) and it
411  * will therefore not make a difference. */
413 
414  if (IsRailWaypoint(tile)) {
415  NPFFindStationOrTileData *fstd = (NPFFindStationOrTileData*)as->user_target;
416  if (fstd->v->current_order.IsType(OT_GOTO_WAYPOINT) && GetStationIndex(tile) == fstd->v->current_order.GetDestination()) {
417  /* This waypoint is our destination; maybe this isn't an unreserved
418  * one, so check that and if so see that as the last signal being
419  * red. This way waypoints near stations should work better. */
420  const Train *train = Train::From(fstd->v);
421  CFollowTrackRail ft(train);
422  TileIndex t = tile;
423  Trackdir td = trackdir;
424  while (ft.Follow(t, td)) {
425  assert(t != ft.m_new_tile);
426  t = ft.m_new_tile;
427  if (KillFirstBit(ft.m_new_td_bits) != TRACKDIR_BIT_NONE) {
428  /* We encountered a junction; it's going to be too complex to
429  * handle this perfectly, so just bail out. There is no simple
430  * free path, so try the other possibilities. */
431  td = INVALID_TRACKDIR;
432  break;
433  }
434  td = RemoveFirstTrackdir(&ft.m_new_td_bits);
435  /* If this is a safe waiting position we're done searching for it */
436  if (IsSafeWaitingPosition(train, t, td, true, _settings_game.pf.forbid_90_deg)) break;
437  }
438  if (td == INVALID_TRACKDIR ||
439  !IsSafeWaitingPosition(train, t, td, true, _settings_game.pf.forbid_90_deg) ||
442  }
443  }
444  }
445  break;
446 
447  default:
448  break;
449  }
450 
451  /* Determine extra costs */
452 
453  /* Check for signals */
454  if (IsTileType(tile, MP_RAILWAY)) {
455  if (HasSignalOnTrackdir(tile, trackdir)) {
456  SignalType sigtype = GetSignalType(tile, TrackdirToTrack(trackdir));
457  /* Ordinary track with signals */
458  if (GetSignalStateByTrackdir(tile, trackdir) == SIGNAL_STATE_RED) {
459  /* Signal facing us is red */
460  if (!NPFGetFlag(current, NPF_FLAG_SEEN_SIGNAL)) {
461  /* Penalize the first signal we
462  * encounter, if it is red */
463 
464  /* Is this a presignal exit or combo? */
465  if (!IsPbsSignal(sigtype)) {
466  if (sigtype == SIGTYPE_EXIT || sigtype == SIGTYPE_COMBO) {
467  /* Penalise exit and combo signals differently (heavier) */
469  } else {
471  }
472  }
473  }
474  /* Record the state of this signal. Path signals are assumed to
475  * be green as the signal state of them has no meaning for this. */
476  NPFSetFlag(current, NPF_FLAG_LAST_SIGNAL_RED, !IsPbsSignal(sigtype));
477  } else {
478  /* Record the state of this signal */
479  NPFSetFlag(current, NPF_FLAG_LAST_SIGNAL_RED, false);
480  }
481  if (NPFGetFlag(current, NPF_FLAG_SEEN_SIGNAL)) {
482  if (NPFGetFlag(current, NPF_FLAG_2ND_SIGNAL)) {
483  NPFSetFlag(current, NPF_FLAG_3RD_SIGNAL, true);
484  } else {
485  NPFSetFlag(current, NPF_FLAG_2ND_SIGNAL, true);
486  }
487  } else {
488  NPFSetFlag(current, NPF_FLAG_SEEN_SIGNAL, true);
489  }
490  NPFSetFlag(current, NPF_FLAG_LAST_SIGNAL_BLOCK, !IsPbsSignal(sigtype));
491  }
492 
493  if (HasPbsSignalOnTrackdir(tile, ReverseTrackdir(trackdir)) && !NPFGetFlag(current, NPF_FLAG_3RD_SIGNAL)) {
495  }
496  }
497 
498  /* Penalise the tile if it is a target tile and the last signal was
499  * red */
500  /* HACK: We create a new_node here so we can call EndNodeCheck. Ugly as hell
501  * of course... */
502  new_node.path.node = *current;
503  if (as->EndNodeCheck(as, &new_node) == AYSTAR_FOUND_END_NODE && NPFGetFlag(current, NPF_FLAG_LAST_SIGNAL_RED)) {
505  }
506 
507  /* Check for slope */
508  cost += NPFSlopeCost(current);
509 
510  /* Check for turns */
511  if (current->direction != NextTrackdir((Trackdir)parent->path.node.direction)) {
513  }
514  /* TODO, with realistic acceleration, also the amount of straight track between
515  * curves should be taken into account, as this affects the speed limit. */
516 
517  /* Check for reverse in depot */
518  if (IsRailDepotTile(tile) && as->EndNodeCheck(as, &new_node) != AYSTAR_FOUND_END_NODE) {
519  /* Penalise any depot tile that is not the last tile in the path. This
520  * _should_ penalise every occurrence of reversing in a depot (and only
521  * that) */
523  }
524 
525  /* Check for occupied track */
526  cost += NPFReservedTrackCost(current);
527 
528  NPFMarkTile(tile);
529  DEBUG(npf, 4, "Calculating G for: (%d, %d). Result: %d", TileX(current->tile), TileY(current->tile), cost);
530  return cost;
531 }
532 
533 /* Will find any depot */
534 static int32 NPFFindDepot(AyStar *as, OpenListNode *current)
535 {
536  AyStarUserData *user = (AyStarUserData *)as->user_data;
537  /* It's not worth caching the result with NPF_FLAG_IS_TARGET here as below,
538  * since checking the cache not that much faster than the actual check */
539  return IsDepotTypeTile(current->path.node.tile, user->type) ?
541 }
542 
544 static int32 NPFFindSafeTile(AyStar *as, OpenListNode *current)
545 {
546  const Train *v = Train::From(((NPFFindStationOrTileData *)as->user_target)->v);
547 
548  return (IsSafeWaitingPosition(v, current->path.node.tile, current->path.node.direction, true, _settings_game.pf.forbid_90_deg) &&
549  IsWaitingPositionFree(v, current->path.node.tile, current->path.node.direction, _settings_game.pf.forbid_90_deg)) ?
551 }
552 
553 /* Will find a station identified using the NPFFindStationOrTileData */
554 static int32 NPFFindStationOrTile(AyStar *as, OpenListNode *current)
555 {
556  NPFFindStationOrTileData *fstd = (NPFFindStationOrTileData*)as->user_target;
557  AyStarNode *node = &current->path.node;
558  TileIndex tile = node->tile;
559 
560  if (fstd->station_index == INVALID_STATION && tile == fstd->dest_coords) return AYSTAR_FOUND_END_NODE;
561 
562  if (IsTileType(tile, MP_STATION) && GetStationIndex(tile) == fstd->station_index) {
563  if (fstd->v->type == VEH_TRAIN) return AYSTAR_FOUND_END_NODE;
564 
565  assert(fstd->v->type == VEH_ROAD);
566  /* Only if it is a valid station *and* we can stop there */
567  if (GetStationType(tile) == fstd->station_type && (fstd->not_articulated || IsDriveThroughStopTile(tile))) return AYSTAR_FOUND_END_NODE;
568  }
569  return AYSTAR_DONE;
570 }
571 
579 static const PathNode *FindSafePosition(PathNode *path, const Train *v)
580 {
581  /* If there is no signal, reserve the whole path. */
582  PathNode *sig = path;
583 
584  for (; path->parent != NULL; path = path->parent) {
585  if (IsSafeWaitingPosition(v, path->node.tile, path->node.direction, true, _settings_game.pf.forbid_90_deg)) {
586  sig = path;
587  }
588  }
589 
590  return sig;
591 }
592 
596 static void ClearPathReservation(const PathNode *start, const PathNode *end)
597 {
598  bool first_run = true;
599  for (; start != end; start = start->parent) {
600  if (IsRailStationTile(start->node.tile) && first_run) {
601  SetRailStationPlatformReservation(start->node.tile, TrackdirToExitdir(start->node.direction), false);
602  } else {
603  UnreserveRailTrack(start->node.tile, TrackdirToTrack(start->node.direction));
604  }
605  first_run = false;
606  }
607 }
608 
615 static void NPFSaveTargetData(AyStar *as, OpenListNode *current)
616 {
617  AyStarUserData *user = (AyStarUserData *)as->user_data;
618  NPFFoundTargetData *ftd = (NPFFoundTargetData*)as->user_path;
619  ftd->best_trackdir = (Trackdir)current->path.node.user_data[NPF_TRACKDIR_CHOICE];
620  ftd->best_path_dist = current->g;
621  ftd->best_bird_dist = 0;
622  ftd->node = current->path.node;
623  ftd->res_okay = false;
624 
625  if (as->user_target != NULL && ((NPFFindStationOrTileData*)as->user_target)->reserve_path && user->type == TRANSPORT_RAIL) {
626  /* Path reservation is requested. */
627  const Train *v = Train::From(((NPFFindStationOrTileData *)as->user_target)->v);
628 
629  const PathNode *target = FindSafePosition(&current->path, v);
630  ftd->node = target->node;
631 
632  /* If the target is a station skip to platform end. */
633  if (IsRailStationTile(target->node.tile)) {
634  DiagDirection dir = TrackdirToExitdir(target->node.direction);
635  uint len = Station::GetByTile(target->node.tile)->GetPlatformLength(target->node.tile, dir);
636  TileIndex end_tile = TILE_ADD(target->node.tile, (len - 1) * TileOffsByDiagDir(dir));
637 
638  /* Update only end tile, trackdir of a station stays the same. */
639  ftd->node.tile = end_tile;
640  if (!IsWaitingPositionFree(v, end_tile, target->node.direction, _settings_game.pf.forbid_90_deg)) return;
641  SetRailStationPlatformReservation(target->node.tile, dir, true);
642  SetRailStationReservation(target->node.tile, false);
643  } else {
644  if (!IsWaitingPositionFree(v, target->node.tile, target->node.direction, _settings_game.pf.forbid_90_deg)) return;
645  }
646 
647  for (const PathNode *cur = target; cur->parent != NULL; cur = cur->parent) {
648  if (!TryReserveRailTrack(cur->node.tile, TrackdirToTrack(cur->node.direction))) {
649  /* Reservation failed, undo. */
650  ClearPathReservation(target, cur);
651  return;
652  }
653  }
654 
655  ftd->res_okay = true;
656  }
657 }
658 
668 static bool CanEnterTileOwnerCheck(Owner owner, TileIndex tile, DiagDirection enterdir)
669 {
670  if (IsTileType(tile, MP_RAILWAY) || // Rail tile (also rail depot)
671  HasStationTileRail(tile) || // Rail station tile/waypoint
672  IsRoadDepotTile(tile) || // Road depot tile
673  IsStandardRoadStopTile(tile)) { // Road station tile (but not drive-through stops)
674  return IsTileOwner(tile, owner); // You need to own these tiles entirely to use them
675  }
676 
677  switch (GetTileType(tile)) {
678  case MP_ROAD:
679  /* rail-road crossing : are we looking at the railway part? */
680  if (IsLevelCrossing(tile) &&
681  DiagDirToAxis(enterdir) != GetCrossingRoadAxis(tile)) {
682  return IsTileOwner(tile, owner); // Railway needs owner check, while the street is public
683  }
684  break;
685 
686  case MP_TUNNELBRIDGE:
688  return IsTileOwner(tile, owner);
689  }
690  break;
691 
692  default:
693  break;
694  }
695 
696  return true; // no need to check
697 }
698 
699 
704 {
705  assert(IsDepotTypeTile(tile, type));
706 
707  switch (type) {
708  case TRANSPORT_RAIL: return GetRailDepotDirection(tile);
709  case TRANSPORT_ROAD: return GetRoadDepotDirection(tile);
710  case TRANSPORT_WATER: return GetShipDepotDirection(tile);
711  default: return INVALID_DIAGDIR; // Not reached
712  }
713 }
714 
717 {
718  if (IsNormalRoadTile(tile)) {
719  RoadBits rb = GetRoadBits(tile, ROADTYPE_TRAM);
720  switch (rb) {
721  case ROAD_NW: return DIAGDIR_NW;
722  case ROAD_SW: return DIAGDIR_SW;
723  case ROAD_SE: return DIAGDIR_SE;
724  case ROAD_NE: return DIAGDIR_NE;
725  default: break;
726  }
727  }
728  return INVALID_DIAGDIR;
729 }
730 
741 static DiagDirection GetTileSingleEntry(TileIndex tile, TransportType type, uint subtype)
742 {
743  if (type != TRANSPORT_WATER && IsDepotTypeTile(tile, type)) return GetDepotDirection(tile, type);
744 
745  if (type == TRANSPORT_ROAD) {
746  if (IsStandardRoadStopTile(tile)) return GetRoadStopDir(tile);
747  if (HasBit(subtype, ROADTYPE_TRAM)) return GetSingleTramBit(tile);
748  }
749 
750  return INVALID_DIAGDIR;
751 }
752 
762 static inline bool ForceReverse(TileIndex tile, DiagDirection dir, TransportType type, uint subtype)
763 {
764  DiagDirection single_entry = GetTileSingleEntry(tile, type, subtype);
765  return single_entry != INVALID_DIAGDIR && single_entry != dir;
766 }
767 
776 static bool CanEnterTile(TileIndex tile, DiagDirection dir, AyStarUserData *user)
777 {
778  /* Check tunnel entries and bridge ramps */
779  if (IsTileType(tile, MP_TUNNELBRIDGE) && GetTunnelBridgeDirection(tile) != dir) return false;
780 
781  /* Test ownership */
782  if (!CanEnterTileOwnerCheck(user->owner, tile, dir)) return false;
783 
784  /* check correct rail type (mono, maglev, etc) */
785  if (user->type == TRANSPORT_RAIL) {
786  RailType rail_type = GetTileRailType(tile);
787  if (!HasBit(user->railtypes, rail_type)) return false;
788  }
789 
790  /* Depots, standard roadstops and single tram bits can only be entered from one direction */
791  DiagDirection single_entry = GetTileSingleEntry(tile, user->type, user->roadtypes);
792  if (single_entry != INVALID_DIAGDIR && single_entry != ReverseDiagDir(dir)) return false;
793 
794  return true;
795 }
796 
808 static TrackdirBits GetDriveableTrackdirBits(TileIndex dst_tile, Trackdir src_trackdir, TransportType type, uint subtype)
809 {
810  TrackdirBits trackdirbits = TrackStatusToTrackdirBits(GetTileTrackStatus(dst_tile, type, subtype));
811 
812  if (trackdirbits == 0 && type == TRANSPORT_ROAD && HasBit(subtype, ROADTYPE_TRAM)) {
813  /* GetTileTrackStatus() returns 0 for single tram bits.
814  * As we cannot change it there (easily) without breaking something, change it here */
815  switch (GetSingleTramBit(dst_tile)) {
816  case DIAGDIR_NE:
817  case DIAGDIR_SW:
818  trackdirbits = TRACKDIR_BIT_X_NE | TRACKDIR_BIT_X_SW;
819  break;
820 
821  case DIAGDIR_NW:
822  case DIAGDIR_SE:
823  trackdirbits = TRACKDIR_BIT_Y_NW | TRACKDIR_BIT_Y_SE;
824  break;
825 
826  default: break;
827  }
828  }
829 
830  DEBUG(npf, 4, "Next node: (%d, %d) [%d], possible trackdirs: 0x%X", TileX(dst_tile), TileY(dst_tile), dst_tile, trackdirbits);
831 
832  /* Select only trackdirs we can reach from our current trackdir */
833  trackdirbits &= TrackdirReachesTrackdirs(src_trackdir);
834 
835  /* Filter out trackdirs that would make 90 deg turns for trains */
836  if (_settings_game.pf.forbid_90_deg && (type == TRANSPORT_RAIL || type == TRANSPORT_WATER)) trackdirbits &= ~TrackdirCrossesTrackdirs(src_trackdir);
837 
838  DEBUG(npf, 6, "After filtering: (%d, %d), possible trackdirs: 0x%X", TileX(dst_tile), TileY(dst_tile), trackdirbits);
839 
840  return trackdirbits;
841 }
842 
843 
844 /* Will just follow the results of GetTileTrackStatus concerning where we can
845  * go and where not. Uses AyStar.user_data[NPF_TYPE] as the transport type and
846  * an argument to GetTileTrackStatus. Will skip tunnels, meaning that the
847  * entry and exit are neighbours. Will fill
848  * AyStarNode.user_data[NPF_TRACKDIR_CHOICE] with an appropriate value, and
849  * copy AyStarNode.user_data[NPF_NODE_FLAGS] from the parent */
850 static void NPFFollowTrack(AyStar *aystar, OpenListNode *current)
851 {
852  AyStarUserData *user = (AyStarUserData *)aystar->user_data;
853  /* We leave src_tile on track src_trackdir in direction src_exitdir */
854  Trackdir src_trackdir = current->path.node.direction;
855  TileIndex src_tile = current->path.node.tile;
856  DiagDirection src_exitdir = TrackdirToExitdir(src_trackdir);
857 
858  /* Is src_tile valid, and can be used?
859  * When choosing track on a junction src_tile is the tile neighboured to the junction wrt. exitdir.
860  * But we must not check the validity of this move, as src_tile is totally unrelated to the move, if a roadvehicle reversed on a junction. */
861  bool ignore_src_tile = (current->path.parent == NULL && NPFGetFlag(&current->path.node, NPF_FLAG_IGNORE_START_TILE));
862 
863  /* Information about the vehicle: TransportType (road/rail/water) and SubType (compatible rail/road types) */
864  TransportType type = user->type;
865  uint subtype = user->roadtypes;
866 
867  /* Initialize to 0, so we can jump out (return) somewhere an have no neighbours */
868  aystar->num_neighbours = 0;
869  DEBUG(npf, 4, "Expanding: (%d, %d, %d) [%d]", TileX(src_tile), TileY(src_tile), src_trackdir, src_tile);
870 
871  /* We want to determine the tile we arrive, and which choices we have there */
872  TileIndex dst_tile;
873  TrackdirBits trackdirbits;
874 
875  /* Find dest tile */
876  if (ignore_src_tile) {
877  /* Do not perform any checks that involve src_tile */
878  dst_tile = src_tile + TileOffsByDiagDir(src_exitdir);
879  trackdirbits = GetDriveableTrackdirBits(dst_tile, src_trackdir, type, subtype);
880  } else if (IsTileType(src_tile, MP_TUNNELBRIDGE) && GetTunnelBridgeDirection(src_tile) == src_exitdir) {
881  /* We drive through the wormhole and arrive on the other side */
882  dst_tile = GetOtherTunnelBridgeEnd(src_tile);
883  trackdirbits = TrackdirToTrackdirBits(src_trackdir);
884  } else if (ForceReverse(src_tile, src_exitdir, type, subtype)) {
885  /* We can only reverse on this tile */
886  dst_tile = src_tile;
887  src_trackdir = ReverseTrackdir(src_trackdir);
888  trackdirbits = TrackdirToTrackdirBits(src_trackdir);
889  } else {
890  /* We leave src_tile in src_exitdir and reach dst_tile */
891  dst_tile = AddTileIndexDiffCWrap(src_tile, TileIndexDiffCByDiagDir(src_exitdir));
892 
893  if (dst_tile != INVALID_TILE && !CanEnterTile(dst_tile, src_exitdir, user)) dst_tile = INVALID_TILE;
894 
895  if (dst_tile == INVALID_TILE) {
896  /* We cannot enter the next tile. Road vehicles can reverse, others reach dead end */
897  if (type != TRANSPORT_ROAD || HasBit(subtype, ROADTYPE_TRAM)) return;
898 
899  dst_tile = src_tile;
900  src_trackdir = ReverseTrackdir(src_trackdir);
901  }
902 
903  trackdirbits = GetDriveableTrackdirBits(dst_tile, src_trackdir, type, subtype);
904 
905  if (trackdirbits == 0) {
906  /* We cannot enter the next tile. Road vehicles can reverse, others reach dead end */
907  if (type != TRANSPORT_ROAD || HasBit(subtype, ROADTYPE_TRAM)) return;
908 
909  dst_tile = src_tile;
910  src_trackdir = ReverseTrackdir(src_trackdir);
911 
912  trackdirbits = GetDriveableTrackdirBits(dst_tile, src_trackdir, type, subtype);
913  }
914  }
915 
916  if (NPFGetFlag(&current->path.node, NPF_FLAG_IGNORE_RESERVED)) {
917  /* Mask out any reserved tracks. */
918  TrackBits reserved = GetReservedTrackbits(dst_tile);
919  trackdirbits &= ~TrackBitsToTrackdirBits(reserved);
920 
921  Track t;
922  FOR_EACH_SET_TRACK(t, TrackdirBitsToTrackBits(trackdirbits)) {
923  if (TracksOverlap(reserved | TrackToTrackBits(t))) trackdirbits &= ~TrackToTrackdirBits(t);
924  }
925  }
926 
927  /* Enumerate possible track */
928  uint i = 0;
929  while (trackdirbits != 0) {
930  Trackdir dst_trackdir = RemoveFirstTrackdir(&trackdirbits);
931  DEBUG(npf, 5, "Expanded into trackdir: %d, remaining trackdirs: 0x%X", dst_trackdir, trackdirbits);
932 
933  /* Tile with signals? */
934  if (IsTileType(dst_tile, MP_RAILWAY) && GetRailTileType(dst_tile) == RAIL_TILE_SIGNALS) {
935  if (HasSignalOnTrackdir(dst_tile, ReverseTrackdir(dst_trackdir)) && !HasSignalOnTrackdir(dst_tile, dst_trackdir) && IsOnewaySignal(dst_tile, TrackdirToTrack(dst_trackdir))) {
936  /* If there's a one-way signal not pointing towards us, stop going in this direction. */
937  break;
938  }
939  }
940  {
941  /* We've found ourselves a neighbour :-) */
942  AyStarNode *neighbour = &aystar->neighbours[i];
943  neighbour->tile = dst_tile;
944  neighbour->direction = dst_trackdir;
945  /* Save user data */
946  neighbour->user_data[NPF_NODE_FLAGS] = current->path.node.user_data[NPF_NODE_FLAGS];
947  NPFFillTrackdirChoice(neighbour, current);
948  }
949  i++;
950  }
951  aystar->num_neighbours = i;
952 }
953 
954 /*
955  * Plan a route to the specified target (which is checked by target_proc),
956  * from start1 and if not NULL, from start2 as well. The type of transport we
957  * are checking is in type. reverse_penalty is applied to all routes that
958  * originate from the second start node.
959  * When we are looking for one specific target (optionally multiple tiles), we
960  * should use a good heuristic to perform aystar search. When we search for
961  * multiple targets that are spread around, we should perform a breadth first
962  * search by specifiying CalcZero as our heuristic.
963  */
964 static NPFFoundTargetData NPFRouteInternal(AyStarNode *start1, bool ignore_start_tile1, AyStarNode *start2, bool ignore_start_tile2, NPFFindStationOrTileData *target, AyStar_EndNodeCheck target_proc, AyStar_CalculateH heuristic_proc, AyStarUserData *user, uint reverse_penalty)
965 {
966  int r;
967  NPFFoundTargetData result;
968 
969  /* Initialize procs */
970  _npf_aystar.CalculateH = heuristic_proc;
971  _npf_aystar.EndNodeCheck = target_proc;
972  _npf_aystar.FoundEndNode = NPFSaveTargetData;
973  _npf_aystar.GetNeighbours = NPFFollowTrack;
974  switch (user->type) {
975  default: NOT_REACHED();
976  case TRANSPORT_RAIL: _npf_aystar.CalculateG = NPFRailPathCost; break;
977  case TRANSPORT_ROAD: _npf_aystar.CalculateG = NPFRoadPathCost; break;
978  case TRANSPORT_WATER: _npf_aystar.CalculateG = NPFWaterPathCost; break;
979  }
980 
981  /* Initialize Start Node(s) */
982  start1->user_data[NPF_TRACKDIR_CHOICE] = INVALID_TRACKDIR;
983  start1->user_data[NPF_NODE_FLAGS] = 0;
984  NPFSetFlag(start1, NPF_FLAG_IGNORE_START_TILE, ignore_start_tile1);
985  _npf_aystar.AddStartNode(start1, 0);
986  if (start2 != NULL) {
987  start2->user_data[NPF_TRACKDIR_CHOICE] = INVALID_TRACKDIR;
988  start2->user_data[NPF_NODE_FLAGS] = 0;
989  NPFSetFlag(start2, NPF_FLAG_IGNORE_START_TILE, ignore_start_tile2);
990  NPFSetFlag(start2, NPF_FLAG_REVERSE, true);
991  _npf_aystar.AddStartNode(start2, reverse_penalty);
992  }
993 
994  /* Initialize result */
995  result.best_bird_dist = UINT_MAX;
996  result.best_path_dist = UINT_MAX;
998  result.node.tile = INVALID_TILE;
999  result.res_okay = false;
1000  _npf_aystar.user_path = &result;
1001 
1002  /* Initialize target */
1003  _npf_aystar.user_target = target;
1004 
1005  /* Initialize user_data */
1006  _npf_aystar.user_data = user;
1007 
1008  /* GO! */
1009  r = _npf_aystar.Main();
1010  assert(r != AYSTAR_STILL_BUSY);
1011 
1012  if (result.best_bird_dist != 0) {
1013  if (target != NULL) {
1014  DEBUG(npf, 1, "Could not find route to tile 0x%X from 0x%X.", target->dest_coords, start1->tile);
1015  } else {
1016  /* Assumption: target == NULL, so we are looking for a depot */
1017  DEBUG(npf, 1, "Could not find route to a depot from tile 0x%X.", start1->tile);
1018  }
1019 
1020  }
1021  return result;
1022 }
1023 
1024 /* Will search as below, but with two start nodes, the second being the
1025  * reverse. Look at the NPF_FLAG_REVERSE flag in the result node to see which
1026  * direction was taken (NPFGetFlag(result.node, NPF_FLAG_REVERSE)) */
1027 static NPFFoundTargetData NPFRouteToStationOrTileTwoWay(TileIndex tile1, Trackdir trackdir1, bool ignore_start_tile1, TileIndex tile2, Trackdir trackdir2, bool ignore_start_tile2, NPFFindStationOrTileData *target, AyStarUserData *user)
1028 {
1029  AyStarNode start1;
1030  AyStarNode start2;
1031 
1032  start1.tile = tile1;
1033  start2.tile = tile2;
1034  /* We set this in case the target is also the start tile, we will just
1035  * return a not found then */
1036  start1.user_data[NPF_TRACKDIR_CHOICE] = INVALID_TRACKDIR;
1037  start1.direction = trackdir1;
1038  start2.direction = trackdir2;
1039  start2.user_data[NPF_TRACKDIR_CHOICE] = INVALID_TRACKDIR;
1040 
1041  return NPFRouteInternal(&start1, ignore_start_tile1, (IsValidTile(tile2) ? &start2 : NULL), ignore_start_tile2, target, NPFFindStationOrTile, NPFCalcStationOrTileHeuristic, user, 0);
1042 }
1043 
1044 /* Will search from the given tile and direction, for a route to the given
1045  * station for the given transport type. See the declaration of
1046  * NPFFoundTargetData above for the meaning of the result. */
1047 static NPFFoundTargetData NPFRouteToStationOrTile(TileIndex tile, Trackdir trackdir, bool ignore_start_tile, NPFFindStationOrTileData *target, AyStarUserData *user)
1048 {
1049  return NPFRouteToStationOrTileTwoWay(tile, trackdir, ignore_start_tile, INVALID_TILE, INVALID_TRACKDIR, false, target, user);
1050 }
1051 
1052 /* Search using breadth first. Good for little track choice and inaccurate
1053  * heuristic, such as railway/road with two start nodes, the second being the reverse. Call
1054  * NPFGetFlag(result.node, NPF_FLAG_REVERSE) to see from which node the path
1055  * originated. All paths from the second node will have the given
1056  * reverse_penalty applied (NPF_TILE_LENGTH is the equivalent of one full
1057  * tile).
1058  */
1059 static NPFFoundTargetData NPFRouteToDepotBreadthFirstTwoWay(TileIndex tile1, Trackdir trackdir1, bool ignore_start_tile1, TileIndex tile2, Trackdir trackdir2, bool ignore_start_tile2, NPFFindStationOrTileData *target, AyStarUserData *user, uint reverse_penalty)
1060 {
1061  AyStarNode start1;
1062  AyStarNode start2;
1063 
1064  start1.tile = tile1;
1065  start2.tile = tile2;
1066  /* We set this in case the target is also the start tile, we will just
1067  * return a not found then */
1068  start1.user_data[NPF_TRACKDIR_CHOICE] = INVALID_TRACKDIR;
1069  start1.direction = trackdir1;
1070  start2.direction = trackdir2;
1071  start2.user_data[NPF_TRACKDIR_CHOICE] = INVALID_TRACKDIR;
1072 
1073  /* perform a breadth first search. Target is NULL,
1074  * since we are just looking for any depot...*/
1075  return NPFRouteInternal(&start1, ignore_start_tile1, (IsValidTile(tile2) ? &start2 : NULL), ignore_start_tile2, target, NPFFindDepot, NPFCalcZero, user, reverse_penalty);
1076 }
1077 
1078 void InitializeNPF()
1079 {
1080  static bool first_init = true;
1081  if (first_init) {
1082  first_init = false;
1083  _npf_aystar.Init(NPFHash, NPF_HASH_SIZE);
1084  } else {
1085  _npf_aystar.Clear();
1086  }
1087  _npf_aystar.loops_per_tick = 0;
1088  _npf_aystar.max_path_cost = 0;
1089  //_npf_aystar.max_search_nodes = 0;
1090  /* We will limit the number of nodes for now, until we have a better
1091  * solution to really fix performance */
1093 }
1094 
1095 static void NPFFillWithOrderData(NPFFindStationOrTileData *fstd, const Vehicle *v, bool reserve_path = false)
1096 {
1097  /* Ships don't really reach their stations, but the tile in front. So don't
1098  * save the station id for ships. For roadvehs we don't store it either,
1099  * because multistop depends on vehicles actually reaching the exact
1100  * dest_tile, not just any stop of that station.
1101  * So only for train orders to stations we fill fstd->station_index, for all
1102  * others only dest_coords */
1103  if (v->type != VEH_SHIP && (v->current_order.IsType(OT_GOTO_STATION) || v->current_order.IsType(OT_GOTO_WAYPOINT))) {
1104  assert(v->IsGroundVehicle());
1106  fstd->station_type = (v->type == VEH_TRAIN) ? (v->current_order.IsType(OT_GOTO_STATION) ? STATION_RAIL : STATION_WAYPOINT) : (RoadVehicle::From(v)->IsBus() ? STATION_BUS : STATION_TRUCK);
1108  /* Let's take the closest tile of the station as our target for vehicles */
1110  } else {
1111  fstd->dest_coords = v->dest_tile;
1112  fstd->station_index = INVALID_STATION;
1113  }
1114  fstd->reserve_path = reserve_path;
1115  fstd->v = v;
1116 }
1117 
1118 /*** Road vehicles ***/
1119 
1121 {
1122  Trackdir trackdir = v->GetVehicleTrackdir();
1123 
1124  AyStarUserData user = { v->owner, TRANSPORT_ROAD, INVALID_RAILTYPES, v->compatible_roadtypes };
1125  NPFFoundTargetData ftd = NPFRouteToDepotBreadthFirstTwoWay(v->tile, trackdir, false, v->tile, ReverseTrackdir(trackdir), false, NULL, &user, 0);
1126 
1127  if (ftd.best_bird_dist != 0) return FindDepotData();
1128 
1129  /* Found target */
1130  /* Our caller expects a number of tiles, so we just approximate that
1131  * number by this. It might not be completely what we want, but it will
1132  * work for now :-) We can possibly change this when the old pathfinder
1133  * is removed. */
1134  return FindDepotData(ftd.node.tile, ftd.best_path_dist);
1135 }
1136 
1137 Trackdir NPFRoadVehicleChooseTrack(const RoadVehicle *v, TileIndex tile, DiagDirection enterdir, TrackdirBits trackdirs, bool &path_found)
1138 {
1140 
1141  NPFFillWithOrderData(&fstd, v);
1142  Trackdir trackdir = DiagDirToDiagTrackdir(enterdir);
1143 
1144  AyStarUserData user = { v->owner, TRANSPORT_ROAD, INVALID_RAILTYPES, v->compatible_roadtypes };
1145  NPFFoundTargetData ftd = NPFRouteToStationOrTile(tile - TileOffsByDiagDir(enterdir), trackdir, true, &fstd, &user);
1146  if (ftd.best_trackdir == INVALID_TRACKDIR) {
1147  /* We are already at our target. Just do something
1148  * @todo: maybe display error?
1149  * @todo: go straight ahead if possible? */
1150  path_found = true;
1151  return (Trackdir)FindFirstBit2x64(trackdirs);
1152  }
1153 
1154  /* If ftd.best_bird_dist is 0, we found our target and ftd.best_trackdir contains
1155  * the direction we need to take to get there, if ftd.best_bird_dist is not 0,
1156  * we did not find our target, but ftd.best_trackdir contains the direction leading
1157  * to the tile closest to our target. */
1158  path_found = (ftd.best_bird_dist == 0);
1159  return ftd.best_trackdir;
1160 }
1161 
1162 /*** Ships ***/
1163 
1164 Track NPFShipChooseTrack(const Ship *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found)
1165 {
1167  Trackdir trackdir = v->GetVehicleTrackdir();
1168  assert(trackdir != INVALID_TRACKDIR); // Check that we are not in a depot
1169 
1170  NPFFillWithOrderData(&fstd, v);
1171 
1173  NPFFoundTargetData ftd = NPFRouteToStationOrTile(tile - TileOffsByDiagDir(enterdir), trackdir, true, &fstd, &user);
1174 
1175  /* If ftd.best_bird_dist is 0, we found our target and ftd.best_trackdir contains
1176  * the direction we need to take to get there, if ftd.best_bird_dist is not 0,
1177  * we did not find our target, but ftd.best_trackdir contains the direction leading
1178  * to the tile closest to our target. */
1179  path_found = (ftd.best_bird_dist == 0);
1180  if (ftd.best_trackdir == 0xff) return INVALID_TRACK;
1181  return TrackdirToTrack(ftd.best_trackdir);
1182 }
1183 
1185 {
1187  NPFFoundTargetData ftd;
1188 
1189  NPFFillWithOrderData(&fstd, v);
1190 
1191  Trackdir trackdir = v->GetVehicleTrackdir();
1192  Trackdir trackdir_rev = ReverseTrackdir(trackdir);
1193  assert(trackdir != INVALID_TRACKDIR);
1194  assert(trackdir_rev != INVALID_TRACKDIR);
1195 
1197  ftd = NPFRouteToStationOrTileTwoWay(v->tile, trackdir, false, v->tile, trackdir_rev, false, &fstd, &user);
1198  /* If we didn't find anything, just keep on going straight ahead, otherwise take the reverse flag */
1199  return ftd.best_bird_dist == 0 && NPFGetFlag(&ftd.node, NPF_FLAG_REVERSE);
1200 }
1201 
1202 /*** Trains ***/
1203 
1205 {
1206  const Train *last = v->Last();
1207  Trackdir trackdir = v->GetVehicleTrackdir();
1208  Trackdir trackdir_rev = ReverseTrackdir(last->GetVehicleTrackdir());
1210  fstd.v = v;
1211  fstd.reserve_path = false;
1212 
1213  assert(trackdir != INVALID_TRACKDIR);
1214  AyStarUserData user = { v->owner, TRANSPORT_RAIL, v->compatible_railtypes, ROADTYPES_NONE };
1215  NPFFoundTargetData ftd = NPFRouteToDepotBreadthFirstTwoWay(v->tile, trackdir, false, last->tile, trackdir_rev, false, &fstd, &user, NPF_INFINITE_PENALTY);
1216  if (ftd.best_bird_dist != 0) return FindDepotData();
1217 
1218  /* Found target */
1219  /* Our caller expects a number of tiles, so we just approximate that
1220  * number by this. It might not be completely what we want, but it will
1221  * work for now :-) We can possibly change this when the old pathfinder
1222  * is removed. */
1223  return FindDepotData(ftd.node.tile, ftd.best_path_dist, NPFGetFlag(&ftd.node, NPF_FLAG_REVERSE));
1224 }
1225 
1226 bool NPFTrainFindNearestSafeTile(const Train *v, TileIndex tile, Trackdir trackdir, bool override_railtype)
1227 {
1228  assert(v->type == VEH_TRAIN);
1229 
1231  fstd.v = v;
1232  fstd.reserve_path = true;
1233 
1234  AyStarNode start1;
1235  start1.tile = tile;
1236  /* We set this in case the target is also the start tile, we will just
1237  * return a not found then */
1238  start1.user_data[NPF_TRACKDIR_CHOICE] = INVALID_TRACKDIR;
1239  start1.direction = trackdir;
1240  NPFSetFlag(&start1, NPF_FLAG_IGNORE_RESERVED, true);
1241 
1242  RailTypes railtypes = v->compatible_railtypes;
1243  if (override_railtype) railtypes |= GetRailTypeInfo(v->railtype)->compatible_railtypes;
1244 
1245  /* perform a breadth first search. Target is NULL,
1246  * since we are just looking for any safe tile...*/
1247  AyStarUserData user = { v->owner, TRANSPORT_RAIL, railtypes, ROADTYPES_NONE };
1248  return NPFRouteInternal(&start1, true, NULL, false, &fstd, NPFFindSafeTile, NPFCalcZero, &user, 0).res_okay;
1249 }
1250 
1252 {
1254  NPFFoundTargetData ftd;
1255  const Train *last = v->Last();
1256 
1257  NPFFillWithOrderData(&fstd, v);
1258 
1259  Trackdir trackdir = v->GetVehicleTrackdir();
1260  Trackdir trackdir_rev = ReverseTrackdir(last->GetVehicleTrackdir());
1261  assert(trackdir != INVALID_TRACKDIR);
1262  assert(trackdir_rev != INVALID_TRACKDIR);
1263 
1264  AyStarUserData user = { v->owner, TRANSPORT_RAIL, v->compatible_railtypes, ROADTYPES_NONE };
1265  ftd = NPFRouteToStationOrTileTwoWay(v->tile, trackdir, false, last->tile, trackdir_rev, false, &fstd, &user);
1266  /* If we didn't find anything, just keep on going straight ahead, otherwise take the reverse flag */
1267  return ftd.best_bird_dist == 0 && NPFGetFlag(&ftd.node, NPF_FLAG_REVERSE);
1268 }
1269 
1270 Track NPFTrainChooseTrack(const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found, bool reserve_track, struct PBSTileInfo *target)
1271 {
1273  NPFFillWithOrderData(&fstd, v, reserve_track);
1274 
1275  PBSTileInfo origin = FollowTrainReservation(v);
1276  assert(IsValidTrackdir(origin.trackdir));
1277 
1278  AyStarUserData user = { v->owner, TRANSPORT_RAIL, v->compatible_railtypes, ROADTYPES_NONE };
1279  NPFFoundTargetData ftd = NPFRouteToStationOrTile(origin.tile, origin.trackdir, true, &fstd, &user);
1280 
1281  if (target != NULL) {
1282  target->tile = ftd.node.tile;
1283  target->trackdir = (Trackdir)ftd.node.direction;
1284  target->okay = ftd.res_okay;
1285  }
1286 
1287  if (ftd.best_trackdir == INVALID_TRACKDIR) {
1288  /* We are already at our target. Just do something
1289  * @todo maybe display error?
1290  * @todo: go straight ahead if possible? */
1291  path_found = true;
1292  return FindFirstTrack(tracks);
1293  }
1294 
1295  /* If ftd.best_bird_dist is 0, we found our target and ftd.best_trackdir contains
1296  * the direction we need to take to get there, if ftd.best_bird_dist is not 0,
1297  * we did not find our target, but ftd.best_trackdir contains the direction leading
1298  * to the tile closest to our target. */
1299  path_found = (ftd.best_bird_dist == 0);
1300  /* Discard enterdir information, making it a normal track */
1301  return TrackdirToTrack(ftd.best_trackdir);
1302 }