TriangleMeshNode.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. namespace PF {
  2. /** Interface for something that holds a triangle based navmesh */
  3. public interface INavmeshHolder : ITransformedGraph, INavmesh {
  4. /** Position of vertex number i in the world */
  5. Int3 GetVertex (int i);
  6. /** Position of vertex number i in coordinates local to the graph.
  7. * The up direction is always the +Y axis for these coordinates.
  8. */
  9. Int3 GetVertexInGraphSpace (int i);
  10. int GetVertexArrayIndex (int index);
  11. /** Transforms coordinates from graph space to world space */
  12. void GetTileCoordinates (int tileIndex, out int x, out int z);
  13. }
  14. /** Node represented by a triangle */
  15. public class TriangleMeshNode : MeshNode {
  16. /** Internal vertex index for the first vertex */
  17. public int v0;
  18. /** Internal vertex index for the second vertex */
  19. public int v1;
  20. /** Internal vertex index for the third vertex */
  21. public int v2;
  22. /** Holds INavmeshHolder references for all graph indices to be able to access them in a performant manner */
  23. protected static INavmeshHolder[] _navmeshHolders = new INavmeshHolder[0];
  24. /** Used for synchronised access to the #_navmeshHolders array */
  25. protected static readonly System.Object lockObject = new System.Object();
  26. public static INavmeshHolder GetNavmeshHolder (uint graphIndex) {
  27. return _navmeshHolders[(int)graphIndex];
  28. }
  29. /** Sets the internal navmesh holder for a given graph index.
  30. * \warning Internal method
  31. */
  32. public static void SetNavmeshHolder (int graphIndex, INavmeshHolder graph) {
  33. // We need to lock to make sure that
  34. // the resize operation is thread safe
  35. lock (lockObject) {
  36. if (graphIndex >= _navmeshHolders.Length) {
  37. var gg = new INavmeshHolder[graphIndex+1];
  38. _navmeshHolders.CopyTo(gg, 0);
  39. _navmeshHolders = gg;
  40. }
  41. _navmeshHolders[graphIndex] = graph;
  42. }
  43. }
  44. /** Set the position of this node to the average of its 3 vertices */
  45. public void UpdatePositionFromVertices () {
  46. Int3 a, b, c;
  47. GetVertices(out a, out b, out c);
  48. position = (a + b + c) * 0.333333f;
  49. }
  50. /** Return a number identifying a vertex.
  51. * This number does not necessarily need to be a index in an array but two different vertices (in the same graph) should
  52. * not have the same vertex numbers.
  53. */
  54. public int GetVertexIndex (int i) {
  55. return i == 0 ? v0 : (i == 1 ? v1 : v2);
  56. }
  57. /** Return a number specifying an index in the source vertex array.
  58. * The vertex array can for example be contained in a recast tile, or be a navmesh graph, that is graph dependant.
  59. * This is slower than GetVertexIndex, if you only need to compare vertices, use GetVertexIndex.
  60. */
  61. public int GetVertexArrayIndex (int i) {
  62. return GetNavmeshHolder(GraphIndex).GetVertexArrayIndex(i == 0 ? v0 : (i == 1 ? v1 : v2));
  63. }
  64. /** Returns all 3 vertices of this node in world space */
  65. public void GetVertices (out Int3 v0, out Int3 v1, out Int3 v2) {
  66. // Get the object holding the vertex data for this node
  67. // This is usually a graph or a recast graph tile
  68. var holder = GetNavmeshHolder(GraphIndex);
  69. v0 = holder.GetVertex(this.v0);
  70. v1 = holder.GetVertex(this.v1);
  71. v2 = holder.GetVertex(this.v2);
  72. }
  73. /** Returns all 3 vertices of this node in graph space */
  74. public void GetVerticesInGraphSpace (out Int3 v0, out Int3 v1, out Int3 v2) {
  75. // Get the object holding the vertex data for this node
  76. // This is usually a graph or a recast graph tile
  77. var holder = GetNavmeshHolder(GraphIndex);
  78. v0 = holder.GetVertexInGraphSpace(this.v0);
  79. v1 = holder.GetVertexInGraphSpace(this.v1);
  80. v2 = holder.GetVertexInGraphSpace(this.v2);
  81. }
  82. public override Int3 GetVertex (int i) {
  83. return GetNavmeshHolder(GraphIndex).GetVertex(GetVertexIndex(i));
  84. }
  85. public Int3 GetVertexInGraphSpace (int i) {
  86. return GetNavmeshHolder(GraphIndex).GetVertexInGraphSpace(GetVertexIndex(i));
  87. }
  88. public override int GetVertexCount () {
  89. // A triangle has 3 vertices
  90. return 3;
  91. }
  92. public override Vector3 ClosestPointOnNode (Vector3 p) {
  93. Int3 a, b, c;
  94. GetVertices(out a, out b, out c);
  95. return Polygon.ClosestPointOnTriangle((Vector3)a, (Vector3)b, (Vector3)c, p);
  96. }
  97. /** Closest point on the node when seen from above.
  98. * This method is mostly for internal use as the #Pathfinding.NavmeshBase.Linecast methods use it.
  99. *
  100. * - The returned point is the closest one on the node to \a p when seen from above (relative to the graph).
  101. * This is important mostly for sloped surfaces.
  102. * - The returned point is an Int3 point in graph space.
  103. * - It is guaranteed to be inside the node, so if you call #ContainsPointInGraphSpace with the return value from this method the result is guaranteed to be true.
  104. *
  105. * This method is slower than e.g #ClosestPointOnNode or #ClosestPointOnNodeXZ.
  106. * However they do not have the same guarantees as this method has.
  107. */
  108. internal Int3 ClosestPointOnNodeXZInGraphSpace (Vector3 p) {
  109. // Get the vertices that make up the triangle
  110. Int3 a, b, c;
  111. GetVerticesInGraphSpace(out a, out b, out c);
  112. // Convert p to graph space
  113. p = GetNavmeshHolder(GraphIndex).transform.InverseTransform(p);
  114. // Find the closest point on the triangle to p when looking at the triangle from above (relative to the graph)
  115. var closest = Polygon.ClosestPointOnTriangleXZ((Vector3)a, (Vector3)b, (Vector3)c, p);
  116. // Make sure the point is actually inside the node
  117. var i3closest = (Int3)closest;
  118. if (ContainsPointInGraphSpace(i3closest)) {
  119. // Common case
  120. return i3closest;
  121. } else {
  122. // Annoying...
  123. // The closest point when converted from floating point coordinates to integer coordinates
  124. // is not actually inside the node. It needs to be inside the node for some methods
  125. // (like for example Linecast) to work properly.
  126. // Try the 8 integer coordinates around the closest point
  127. // and check if any one of them are completely inside the node.
  128. // This will most likely succeed as it should be very close.
  129. for (int dx = -1; dx <= 1; dx++) {
  130. for (int dz = -1; dz <= 1; dz++) {
  131. if ((dx != 0 || dz != 0)) {
  132. var candidate = new Int3(i3closest.x + dx, i3closest.y, i3closest.z + dz);
  133. if (ContainsPointInGraphSpace(candidate)) return candidate;
  134. }
  135. }
  136. }
  137. // Happens veery rarely.
  138. // Pick the closest vertex of the triangle.
  139. // The vertex is guaranteed to be inside the triangle.
  140. var da = (a - i3closest).sqrMagnitudeLong;
  141. var db = (b - i3closest).sqrMagnitudeLong;
  142. var dc = (c - i3closest).sqrMagnitudeLong;
  143. return da < db ? (da < dc ? a : c) : (db < dc ? b : c);
  144. }
  145. }
  146. public override Vector3 ClosestPointOnNodeXZ (Vector3 p) {
  147. // Get all 3 vertices for this node
  148. Int3 tp1, tp2, tp3;
  149. GetVertices(out tp1, out tp2, out tp3);
  150. return Polygon.ClosestPointOnTriangleXZ((Vector3)tp1, (Vector3)tp2, (Vector3)tp3, p);
  151. }
  152. public override bool ContainsPoint (Vector3 p) {
  153. return ContainsPointInGraphSpace((Int3)GetNavmeshHolder(GraphIndex).transform.InverseTransform(p));
  154. }
  155. public override bool ContainsPointInGraphSpace (Int3 p) {
  156. // Get all 3 vertices for this node
  157. Int3 a, b, c;
  158. GetVerticesInGraphSpace(out a, out b, out c);
  159. if ((long)(b.x - a.x) * (long)(p.z - a.z) - (long)(p.x - a.x) * (long)(b.z - a.z) > 0) return false;
  160. if ((long)(c.x - b.x) * (long)(p.z - b.z) - (long)(p.x - b.x) * (long)(c.z - b.z) > 0) return false;
  161. if ((long)(a.x - c.x) * (long)(p.z - c.z) - (long)(p.x - c.x) * (long)(a.z - c.z) > 0) return false;
  162. return true;
  163. // Equivalent code, but the above code is faster
  164. //return Polygon.IsClockwiseMargin (a,b, p) && Polygon.IsClockwiseMargin (b,c, p) && Polygon.IsClockwiseMargin (c,a, p);
  165. //return Polygon.ContainsPoint(g.GetVertex(v0),g.GetVertex(v1),g.GetVertex(v2),p);
  166. }
  167. public override void UpdateRecursiveG (Path path, PathNode pathNode, PathHandler handler) {
  168. pathNode.UpdateG(path);
  169. handler.heap.Add(pathNode);
  170. if (connections == null) return;
  171. for (int i = 0; i < connections.Length; i++) {
  172. GraphNode other = connections[i].node;
  173. PathNode otherPN = handler.GetPathNode(other);
  174. if (otherPN.parent == pathNode && otherPN.pathID == handler.PathID) other.UpdateRecursiveG(path, otherPN, handler);
  175. }
  176. }
  177. public override void Open (Path path, PathNode pathNode, PathHandler handler) {
  178. if (connections == null) return;
  179. // Flag2 indicates if this node needs special treatment
  180. // with regard to connection costs
  181. bool flag2 = pathNode.flag2;
  182. // Loop through all connections
  183. for (int i = connections.Length-1; i >= 0; i--) {
  184. var conn = connections[i];
  185. var other = conn.node;
  186. // Make sure we can traverse the neighbour
  187. if (path.CanTraverse(conn.node)) {
  188. PathNode pathOther = handler.GetPathNode(conn.node);
  189. // Fast path out, worth it for triangle mesh nodes since they usually have degree 2 or 3
  190. if (pathOther == pathNode.parent) {
  191. continue;
  192. }
  193. uint cost = conn.cost;
  194. if (flag2 || pathOther.flag2) {
  195. // Get special connection cost from the path
  196. // This is used by the start and end nodes
  197. cost = path.GetConnectionSpecialCost(this, conn.node, cost);
  198. }
  199. // Test if we have seen the other node before
  200. if (pathOther.pathID != handler.PathID) {
  201. // We have not seen the other node before
  202. // So the path from the start through this node to the other node
  203. // must be the shortest one so far
  204. // Might not be assigned
  205. pathOther.node = conn.node;
  206. pathOther.parent = pathNode;
  207. pathOther.pathID = handler.PathID;
  208. pathOther.cost = cost;
  209. pathOther.H = path.CalculateHScore(other);
  210. pathOther.UpdateG(path);
  211. handler.heap.Add(pathOther);
  212. } else {
  213. // If not we can test if the path from this node to the other one is a better one than the one already used
  214. if (pathNode.G + cost + path.GetTraversalCost(other) < pathOther.G) {
  215. pathOther.cost = cost;
  216. pathOther.parent = pathNode;
  217. other.UpdateRecursiveG(path, pathOther, handler);
  218. }
  219. }
  220. }
  221. }
  222. }
  223. /** Returns the edge which is shared with \a other.
  224. * If no edge is shared, -1 is returned.
  225. * If there is a connection with the other node, but the connection is not marked as using a particular edge of the shape of the node
  226. * then 0xFF will be returned.
  227. *
  228. * The vertices in the edge can be retrieved using
  229. * \code
  230. * var edge = node.SharedEdge(other);
  231. * var a = node.GetVertex(edge);
  232. * var b = node.GetVertex((edge+1) % node.GetVertexCount());
  233. * \endcode
  234. *
  235. * \see #GetPortal which also handles edges that are shared over tile borders and some types of node links
  236. */
  237. public int SharedEdge (GraphNode other) {
  238. var edge = -1;
  239. for (int i = 0; i < connections.Length; i++) {
  240. if (connections[i].node == other) edge = connections[i].shapeEdge;
  241. }
  242. return edge;
  243. }
  244. public override bool GetPortal (GraphNode toNode, System.Collections.Generic.List<Vector3> left, System.Collections.Generic.List<Vector3> right, bool backwards) {
  245. int aIndex, bIndex;
  246. return GetPortal(toNode, left, right, backwards, out aIndex, out bIndex);
  247. }
  248. public bool GetPortal (GraphNode toNode, System.Collections.Generic.List<Vector3> left, System.Collections.Generic.List<Vector3> right, bool backwards, out int aIndex, out int bIndex) {
  249. aIndex = -1;
  250. bIndex = -1;
  251. //If the nodes are in different graphs, this function has no idea on how to find a shared edge.
  252. if (backwards || toNode.GraphIndex != GraphIndex) return false;
  253. // Since the nodes are in the same graph, they are both TriangleMeshNodes
  254. // So we don't need to care about other types of nodes
  255. var toTriNode = toNode as TriangleMeshNode;
  256. var edge = SharedEdge(toTriNode);
  257. // A connection was found, but it specifically didn't use an edge
  258. if (edge == 0xFF) return false;
  259. // No connection was found between the nodes
  260. // Check if there is a node link that connects them
  261. if (edge == -1) {
  262. return false;
  263. }
  264. aIndex = edge;
  265. bIndex = (edge + 1) % GetVertexCount();
  266. // Get the vertices of the shared edge for the first node
  267. Int3 v1a = GetVertex(edge);
  268. Int3 v1b = GetVertex((edge+1) % GetVertexCount());
  269. // Get tile indices
  270. int tileIndex1 = (GetVertexIndex(0) >> NavmeshBase.TileIndexOffset) & NavmeshBase.TileIndexMask;
  271. int tileIndex2 = (toTriNode.GetVertexIndex(0) >> NavmeshBase.TileIndexOffset) & NavmeshBase.TileIndexMask;
  272. if (tileIndex1 != tileIndex2) {
  273. // When the nodes are in different tiles, the edges might not be completely identical
  274. // so another technique is needed.
  275. // Get the tile coordinates, from them we can figure out which edge is going to be shared
  276. int x1, x2, z1, z2, coord;
  277. INavmeshHolder nm = GetNavmeshHolder(GraphIndex);
  278. nm.GetTileCoordinates(tileIndex1, out x1, out z1);
  279. nm.GetTileCoordinates(tileIndex2, out x2, out z2);
  280. if (System.Math.Abs(x1-x2) == 1) coord = 2;
  281. else if (System.Math.Abs(z1-z2) == 1) coord = 0;
  282. else return false; // Tiles are not adjacent. This is likely a custom connection between two nodes.
  283. var otherEdge = toTriNode.SharedEdge(this);
  284. // A connection was found, but it specifically didn't use an edge. This is odd since the connection in the other direction did use an edge
  285. if (otherEdge == 0xFF) throw new System.Exception("Connection used edge in one direction, but not in the other direction. Has the wrong overload of AddConnection been used?");
  286. // If it is -1 then it must be a one-way connection. Fall back to using the whole edge
  287. if (otherEdge != -1) {
  288. // When the nodes are in different tiles, they might not share exactly the same edge
  289. // so we clamp the portal to the segment of the edges which they both have.
  290. int mincoord = System.Math.Min(v1a[coord], v1b[coord]);
  291. int maxcoord = System.Math.Max(v1a[coord], v1b[coord]);
  292. // Get the vertices of the shared edge for the second node
  293. Int3 v2a = toTriNode.GetVertex(otherEdge);
  294. Int3 v2b = toTriNode.GetVertex((otherEdge+1) % toTriNode.GetVertexCount());
  295. mincoord = System.Math.Max(mincoord, System.Math.Min(v2a[coord], v2b[coord]));
  296. maxcoord = System.Math.Min(maxcoord, System.Math.Max(v2a[coord], v2b[coord]));
  297. if (v1a[coord] < v1b[coord]) {
  298. v1a[coord] = mincoord;
  299. v1b[coord] = maxcoord;
  300. } else {
  301. v1a[coord] = maxcoord;
  302. v1b[coord] = mincoord;
  303. }
  304. }
  305. }
  306. if (left != null) {
  307. // All triangles should be laid out in clockwise order so v1b is the rightmost vertex (seen from this node)
  308. left.Add((Vector3)v1a);
  309. right.Add((Vector3)v1b);
  310. }
  311. return true;
  312. }
  313. /** \todo This is the area in XZ space, use full 3D space for higher correctness maybe? */
  314. public override float SurfaceArea () {
  315. var holder = GetNavmeshHolder(GraphIndex);
  316. return System.Math.Abs(VectorMath.SignedTriangleAreaTimes2XZ(holder.GetVertex(v0), holder.GetVertex(v1), holder.GetVertex(v2))) * 0.5f;
  317. }
  318. public override void SerializeNode (GraphSerializationContext ctx) {
  319. base.SerializeNode(ctx);
  320. ctx.writer.Write(v0);
  321. ctx.writer.Write(v1);
  322. ctx.writer.Write(v2);
  323. }
  324. public override void DeserializeNode (GraphSerializationContext ctx) {
  325. base.DeserializeNode(ctx);
  326. v0 = ctx.reader.ReadInt32();
  327. v1 = ctx.reader.ReadInt32();
  328. v2 = ctx.reader.ReadInt32();
  329. }
  330. }
  331. }