-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMatrixFullGraph.cs
102 lines (86 loc) · 3.12 KB
/
MatrixFullGraph.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
using System;
using UnityEngine;
namespace AStar
{
/// <summary>
/// Graph representation using full linked transition matrix
/// </summary>
public class MatrixFullGraph : IGraph
{
/// <summary>
/// Transition matrix of graph
/// </summary>
public readonly float[,] Matrix;
/// <summary>
/// Graph horizontal node count
/// </summary>
public int Width { get; private set; }
/// <summary>
/// Graph vertical node count
/// </summary>
public int Height { get; private set; }
public MatrixFullGraph(int height, int width, float defaultCost = 0f)
{
if(height <= 0)
{
throw new ArgumentException("height should be more than zero", nameof(height));
}
if(width <= 0)
{
throw new ArgumentException("value should be more than zero", nameof(width));
}
Width = width;
Height = height;
var nodeCount = height * width;
Matrix = new float[nodeCount, nodeCount];
for (var y = 0; y < nodeCount; y++)
{
for (var x = 0; x < nodeCount; x++)
{
Matrix[x, y] = defaultCost;
}
}
}
/// <summary>
/// Get a transition cost from one point to second
/// </summary>
/// <param name="from"> first node address </param>
/// <param name="to"> second node address </param>
/// <returns> cost of a transition </returns>
public float GetTransition(Vector2Int from, Vector2Int to)
{
AssertNodeAddress(from, nameof(from));
AssertNodeAddress(to, nameof(to));
return Matrix[MapToFlat(from), MapToFlat(to)];
}
/// <summary>
/// Set or rewrite a transition cost from one point to second
/// </summary>
/// <param name="from"> first node address </param>
/// <param name="to"> second node address </param>
public void SetTransition(Vector2Int from, Vector2Int to, float cost)
{
AssertNodeAddress(from, nameof(from));
AssertNodeAddress(to, nameof(to));
Matrix[MapToFlat(from), MapToFlat(to)] = cost;
}
/// <summary>
/// Convert vector node address to flat representation
/// </summary>
private int MapToFlat(Vector2Int vector) => vector.y * Width + vector.x;
/// <summary>
/// Assert an node address
/// </summary>
private void AssertNodeAddress(Vector2Int vector, string name)
{
if (vector.x < 0 || vector.y < 0)
{
throw new ArgumentException("value should be more or equal than zero", name);
}
if (vector.x >= Width || vector.y >= Height)
{
throw new ArgumentException("value should be less than graph bounds", name);
}
}
}
}