11namespace NetRts . Engine ;
22
33/// <summary>
4- /// 8-directional A* over the tile grid. Diagonal steps cost the same as straight ones
5- /// (Chebyshev metric) but may not cut the corner of a blocked tile.
4+ /// How units move over the tile grid: in 8 directions, diagonal steps costing the same as straight ones
5+ /// (Chebyshev metric) but never cutting the corner of a blocked tile. <see cref="PathSearch"/> plans routes .
66/// </summary>
77internal static class Pathfinder
88{
9- private static readonly ( int Dx , int Dy ) [ ] Directions =
9+ internal static readonly ( int Dx , int Dy ) [ ] Directions =
1010 [
1111 ( 0 , - 1 ) , ( 1 , 0 ) , ( 0 , 1 ) , ( - 1 , 0 ) ,
1212 ( 1 , - 1 ) , ( 1 , 1 ) , ( - 1 , 1 ) , ( - 1 , - 1 ) ,
@@ -31,49 +31,167 @@ public static IEnumerable<Point> Neighbors(Point p, Func<int, int, bool> passabl
3131 yield return new Point ( nx , ny ) ;
3232 }
3333 }
34+ }
35+
36+ /// <summary>
37+ /// One match's A* searches over its grid of blocked tiles (call <see cref="BlockedChanged"/> when it changes).
38+ /// The working arrays are reused from search to search, so a short search costs what it explores, not the
39+ /// size of the map.
40+ /// </summary>
41+ internal sealed class PathSearch ( int width , int height , bool [ ] blocked )
42+ {
43+ private readonly int [ ] _cost = new int [ width * height ] ;
44+ private readonly int [ ] _cameFrom = new int [ width * height ] ;
45+ private readonly int [ ] _seen = new int [ width * height ] ; // the search that last touched each tile; _cost is stale otherwise
46+ private readonly PriorityQueue < int , ( int F , int H , int Seq ) > _open = new ( ) ;
47+ private int _search ;
48+
49+ // Regions: which tiles can reach which (-1 for blocked ones).
50+ private readonly int [ ] _region = new int [ width * height ] ;
51+ private readonly Queue < int > _fill = new ( ) ;
52+ private bool _regionsStale = true ;
53+
54+ private bool Passable ( int x , int y ) => ( uint ) x < ( uint ) width && ( uint ) y < ( uint ) height && ! blocked [ y * width + x ] ;
55+
56+ private int CostAt ( int i ) => _seen [ i ] == _search ? _cost [ i ] : int . MaxValue ;
57+
58+ private static int Heuristic ( int x , int y , Point target , int range ) =>
59+ Math . Max ( 0 , Math . Max ( Math . Abs ( x - target . X ) , Math . Abs ( y - target . Y ) ) - range ) ;
60+
61+ public void BlockedChanged ( ) => _regionsStale = true ;
62+
63+ /// <summary>
64+ /// Whether any tile reachable from <paramref name="start"/> is nearer the goal than it is: exactly when
65+ /// <see cref="Find"/> returns a path, since the search ends on the nearest tile it reaches and the start
66+ /// wins a tie. Much cheaper than finding out by searching. A start on a blocked tile has no region, so
67+ /// the answer there is yes: search and see.
68+ /// </summary>
69+ public bool CanGetCloser ( Point start , Point target , int range ) =>
70+ Heuristic ( start . X , start . Y , target , range ) > ( Nearest ( start , target , range ) ?? 0 ) ;
71+
72+ /// <summary>
73+ /// How near the goal (in <see cref="Heuristic"/> terms: 0 is within range) the nearest tile reachable from
74+ /// <paramref name="start"/> is; null when <paramref name="start"/> is blocked and so has no region.
75+ /// </summary>
76+ private int ? Nearest ( Point start , Point target , int range )
77+ {
78+ var s = start . Y * width + start . X ;
79+ if ( blocked [ s ] )
80+ {
81+ return null ;
82+ }
83+
84+ if ( _regionsStale )
85+ {
86+ Relabel ( ) ;
87+ }
88+
89+ // Ring by ring out from the target: the first ring with a tile of the start's region is the nearest.
90+ // The start's own ring has one, so this ends.
91+ var region = _region [ s ] ;
92+ for ( var r = 0 ; ; r ++ )
93+ {
94+ for ( var d = - r ; d <= r ; d ++ )
95+ {
96+ if ( InRegion ( target . X + d , target . Y - r , region ) || InRegion ( target . X + d , target . Y + r , region )
97+ || InRegion ( target . X - r , target . Y + d , region ) || InRegion ( target . X + r , target . Y + d , region ) )
98+ {
99+ return Math . Max ( 0 , r - range ) ;
100+ }
101+ }
102+ }
103+ }
104+
105+ private bool InRegion ( int x , int y , int region ) =>
106+ ( uint ) x < ( uint ) width && ( uint ) y < ( uint ) height && _region [ y * width + x ] == region ;
107+
108+ /// <summary>Flood-fills the regions, moving the way <see cref="Find"/> does.</summary>
109+ private void Relabel ( )
110+ {
111+ Array . Fill ( _region , - 1 ) ;
112+ var next = 0 ;
113+ for ( var first = 0 ; first < _region . Length ; first ++ )
114+ {
115+ if ( blocked [ first ] || _region [ first ] >= 0 )
116+ {
117+ continue ;
118+ }
119+
120+ _region [ first ] = next ;
121+ _fill . Enqueue ( first ) ;
122+ while ( _fill . TryDequeue ( out var current ) )
123+ {
124+ var ( x , y ) = ( current % width , current / width ) ;
125+ foreach ( var ( dx , dy ) in Pathfinder . Directions )
126+ {
127+ var n = ( y + dy ) * width + x + dx ;
128+ if ( CanStep ( x , y , dx , dy ) && _region [ n ] < 0 )
129+ {
130+ _region [ n ] = next ;
131+ _fill . Enqueue ( n ) ;
132+ }
133+ }
134+ }
135+
136+ next ++ ;
137+ }
138+
139+ _regionsStale = false ;
140+ }
141+
142+ /// <summary>Pathfinder.Neighbors' rule: onto a passable tile, without cutting the corner of a blocked one.</summary>
143+ private bool CanStep ( int x , int y , int dx , int dy ) =>
144+ Passable ( x + dx , y + dy ) && ( dx == 0 || dy == 0 || ( Passable ( x + dx , y ) && Passable ( x , y + dy ) ) ) ;
34145
35146 /// <summary>
36147 /// Finds a path from <paramref name="start"/> to any passable tile within Chebyshev
37148 /// <paramref name="range"/> of <paramref name="target"/>. If no such tile is reachable the
38149 /// path leads to the reachable tile closest to the target. The start tile is not included;
39150 /// an empty list means "already as close as possible".
40151 /// </summary>
41- public static List < Point > FindPath ( int width , int height , Func < int , int , bool > passable , Point start , Point target , int range )
152+ public List < Point > Find ( Point start , Point target , int range )
42153 {
43- int Heuristic ( Point p ) => Math . Max ( 0 , p . Chebyshev ( target ) - range ) ;
154+ int Heuristic ( int x , int y ) => PathSearch . Heuristic ( x , y , target , range ) ;
44155
45- if ( Heuristic ( start ) == 0 )
156+ if ( Heuristic ( start . X , start . Y ) == 0 )
46157 {
47158 return [ ] ;
48159 }
49160
50- var size = width * height ;
51- var cameFrom = new int [ size ] ;
52- var cost = new int [ size ] ;
53- Array . Fill ( cost , int . MaxValue ) ;
54- Array . Fill ( cameFrom , - 1 ) ;
161+ // Tiles come off the queue nearest-first by cost so far plus distance left, so the first one as near as
162+ // this region gets is the one the search would end on anyway: stop there rather than search it all.
163+ var nearest = Nearest ( start , target , range ) ?? 0 ;
164+
165+ if ( ++ _search == int . MaxValue )
166+ {
167+ Array . Clear ( _seen ) ;
168+ _search = 1 ;
169+ }
55170
171+ var size = width * height ;
56172 var startIndex = start . Y * width + start . X ;
57- cost [ startIndex ] = 0 ;
173+ _seen [ startIndex ] = _search ;
174+ _cost [ startIndex ] = 0 ;
58175
59- var open = new PriorityQueue < int , ( int F , int H , int Seq ) > ( ) ;
176+ _open . Clear ( ) ;
60177 var seq = 0 ;
61- open . Enqueue ( startIndex , ( Heuristic ( start ) , Heuristic ( start ) , seq ++ ) ) ;
178+ var startH = Heuristic ( start . X , start . Y ) ;
179+ _open . Enqueue ( startIndex , ( startH , startH , seq ++ ) ) ;
62180
63181 var bestIndex = startIndex ;
64- var bestH = Heuristic ( start ) ;
182+ var bestH = startH ;
65183 var bestCost = 0 ;
66184 var expansions = 0 ;
67185
68- while ( open . TryDequeue ( out var current , out var priority ) )
186+ while ( _open . TryDequeue ( out var current , out var priority ) )
69187 {
70- var g = cost [ current ] ;
188+ var g = _cost [ current ] ;
71189 if ( priority . F - priority . H != g )
72190 {
73191 continue ; // stale queue entry
74192 }
75193
76- var p = new Point ( current % width , current / width ) ;
194+ var ( x , y ) = ( current % width , current / width ) ;
77195 var h = priority . H ;
78196 if ( h < bestH || ( h == bestH && g < bestCost ) )
79197 {
@@ -82,29 +200,36 @@ public static List<Point> FindPath(int width, int height, Func<int, int, bool> p
82200 bestCost = g ;
83201 }
84202
85- if ( h == 0 || ++ expansions > size )
203+ if ( h <= nearest || ++ expansions > size )
86204 {
87205 break ;
88206 }
89207
90- foreach ( var n in Neighbors ( p , passable ) )
208+ foreach ( var ( dx , dy ) in Pathfinder . Directions ) // Pathfinder.Neighbors' order
91209 {
92- var ni = n . Y * width + n . X ;
210+ var ( nx , ny ) = ( x + dx , y + dy ) ;
211+ if ( ! CanStep ( x , y , dx , dy ) )
212+ {
213+ continue ;
214+ }
215+
216+ var ni = ny * width + nx ;
93217 var ng = g + 1 ;
94- if ( ng >= cost [ ni ] )
218+ if ( ng >= CostAt ( ni ) )
95219 {
96220 continue ;
97221 }
98222
99- cost [ ni ] = ng ;
100- cameFrom [ ni ] = current ;
101- var nh = Heuristic ( n ) ;
102- open . Enqueue ( ni , ( ng + nh , nh , seq ++ ) ) ;
223+ _seen [ ni ] = _search ;
224+ _cost [ ni ] = ng ;
225+ _cameFrom [ ni ] = current ;
226+ var nh = Heuristic ( nx , ny ) ;
227+ _open . Enqueue ( ni , ( ng + nh , nh , seq ++ ) ) ;
103228 }
104229 }
105230
106231 var path = new List < Point > ( ) ;
107- for ( var i = bestIndex ; i != startIndex ; i = cameFrom [ i ] )
232+ for ( var i = bestIndex ; i != startIndex ; i = _cameFrom [ i ] )
108233 {
109234 path . Add ( new Point ( i % width , i / width ) ) ;
110235 }
0 commit comments