-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGraphGridNeighborsService.cs
86 lines (76 loc) · 2.71 KB
/
GraphGridNeighborsService.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEngine;
namespace AStar
{
/// <summary>
/// Service for finding neighbor nodes on grid-graph
/// </summary>
public class GraphGridNeighborsService : IGraphNeighborsService
{
/// <summary>
/// Directions, where needs find neighbors
/// </summary>
public Vector2Int[] Directions { get; set; } = new[]
{
new Vector2Int(1, 0),
new Vector2Int(1, -1),
new Vector2Int(0, -1),
new Vector2Int(-1, -1),
new Vector2Int(-1, 0),
new Vector2Int(-1, 1),
new Vector2Int(0, 1),
new Vector2Int(1, 1),
};
/// <summary>
/// Maximum cost value of transition on graph. if transition more or equal than the value,
/// destination node is not reachable, or not is neighbor.
/// </summary>
private float MaxCost { get; set; }
/// <param name="maxCost"> threshold value of cost after which neighbor node is not reachable </param>
public GraphGridNeighborsService(float maxCost)
{
MaxCost = maxCost;
}
/// <summary>
/// Find reachable neighbour for node. Result stored in neighbors
/// </summary>
public void GetNeighbors(IGraph graph, Vector2Int node, IList<Vector2Int> neighbors)
{
if (graph == null)
{
throw new ArgumentNullException(nameof(graph));
}
if (neighbors == null)
{
throw new ArgumentNullException(nameof(neighbors));
}
if (!IsValidNode(graph, node))
{
throw new ArgumentException("node not in graph bounds", nameof(node));
}
neighbors.Clear();
for (var index = 0; index < Directions.Length; index++)
{
var direction = Directions[index];
var nextNodeAddr = node + direction;
if (!IsValidNode(graph, nextNodeAddr))
{
continue;
}
var cost = graph.GetTransition(node, nextNodeAddr);
if (cost >= MaxCost)
{
continue;
}
neighbors.Add(nextNodeAddr);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private bool IsValidNode(IGraph graph, Vector2Int node)
{
return node.x >= 0 && node.y >= 0 && node.x < graph.Width && node.y < graph.Height;
}
}
}