NavmeshBase.cs 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080
  1. using System.Collections.Generic;
  2. using UnityEngine;
  3. namespace PF {
  4. using System.IO;
  5. using Math = System.Math;
  6. using System.Linq;
  7. /** Returned by graph ray- or linecasts containing info about the hit.
  8. * This is the return value by the #Pathfinding.IRaycastableGraph.Linecast methods.
  9. * Some members will also be initialized even if nothing was hit, see the individual member descriptions for more info.
  10. *
  11. * \shadowimage{linecast.png}
  12. */
  13. public struct GraphHitInfo {
  14. /** Start of the line/ray.
  15. * Note that the point passed to the Linecast method will be clamped to the closest point on the navmesh.
  16. */
  17. public Vector3 origin;
  18. /** Hit point.
  19. * In case no obstacle was hit then this will be set to the endpoint of the line.
  20. */
  21. public Vector3 point;
  22. /** Node which contained the edge which was hit.
  23. * If the linecast did not hit anything then this will be set to the last node along the line's path (the one which contains the endpoint).
  24. *
  25. * For layered grid graphs the linecast will return true (i.e: no free line of sight) if when walking the graph we ended up at X,Z coordinate for the end node
  26. * but the end node was on a different level (e.g the floor below or above in a building). In this case no node edge was really hit so this field will still be null.
  27. */
  28. public GraphNode node;
  29. /** Where the tangent starts. #tangentOrigin and #tangent together actually describes the edge which was hit.
  30. * \shadowimage{linecast_tangent.png}
  31. */
  32. public Vector3 tangentOrigin;
  33. /** Tangent of the edge which was hit.
  34. * \shadowimage{linecast_tangent.png}
  35. */
  36. public Vector3 tangent;
  37. /** Distance from #origin to #point */
  38. public float distance {
  39. get {
  40. return (point-origin).magnitude;
  41. }
  42. }
  43. public GraphHitInfo (Vector3 point) {
  44. tangentOrigin = Vector3.zero;
  45. origin = Vector3.zero;
  46. this.point = point;
  47. node = null;
  48. tangent = Vector3.zero;
  49. }
  50. }
  51. /** Graph which supports the Linecast method */
  52. public interface IRaycastableGraph {
  53. bool Linecast (Vector3 start, Vector3 end);
  54. bool Linecast (Vector3 start, Vector3 end, GraphNode hint);
  55. bool Linecast (Vector3 start, Vector3 end, GraphNode hint, out GraphHitInfo hit);
  56. bool Linecast (Vector3 start, Vector3 end, GraphNode hint, out GraphHitInfo hit, List<GraphNode> trace);
  57. }
  58. /** Graph which has a well defined transformation from graph space to world space */
  59. public interface ITransformedGraph {
  60. GraphTransform transform { get; }
  61. }
  62. /** Base class for RecastGraph and NavMeshGraph */
  63. public abstract class NavmeshBase : NavGraph, INavmesh, INavmeshHolder, ITransformedGraph
  64. , IRaycastableGraph {
  65. #if ASTAR_RECAST_LARGER_TILES
  66. // Larger tiles
  67. public const int VertexIndexMask = 0xFFFFF;
  68. public const int TileIndexMask = 0x7FF;
  69. public const int TileIndexOffset = 20;
  70. #else
  71. // Larger worlds
  72. public const int VertexIndexMask = 0xFFF;
  73. public const int TileIndexMask = 0x7FFFF;
  74. public const int TileIndexOffset = 12;
  75. #endif
  76. /** Size of the bounding box. */
  77. [JsonMember]
  78. public Vector3 forcedBoundsSize = new Vector3(100, 40, 100);
  79. /** Size of a tile in world units along the X axis */
  80. public abstract float TileWorldSizeX { get; }
  81. /** Size of a tile in world units along the Z axis */
  82. public abstract float TileWorldSizeZ { get; }
  83. /** Maximum (vertical) distance between the sides of two nodes for them to be connected across a tile edge.
  84. * When tiles are connected to each other, the nodes sometimes do not line up perfectly
  85. * so some allowance must be made to allow tiles that do not match exactly to be connected with each other.
  86. */
  87. protected abstract float MaxTileConnectionEdgeDistance { get; }
  88. /** Show an outline of the polygons in the Unity Editor */
  89. [JsonMember]
  90. public bool showMeshOutline = true;
  91. /** Show the connections between the polygons in the Unity Editor */
  92. [JsonMember]
  93. public bool showNodeConnections;
  94. /** Show the surface of the navmesh */
  95. [JsonMember]
  96. public bool showMeshSurface;
  97. /** Number of tiles along the X-axis */
  98. public int tileXCount;
  99. /** Number of tiles along the Z-axis */
  100. public int tileZCount;
  101. /** All tiles.
  102. *
  103. * \see #GetTile
  104. */
  105. public NavmeshTile[] tiles;
  106. /** Perform nearest node searches in XZ space only.
  107. * Recomended for single-layered environments. Faster but can be inaccurate esp. in multilayered contexts.
  108. * You should not use this if the graph is rotated since then the XZ plane no longer corresponds to the ground plane.
  109. *
  110. * This can be important on sloped surfaces. See the image below in which the closest point for each blue point is queried for:
  111. * \shadowimage{distanceXZ2.png}
  112. *
  113. * You can also control this using a \link Pathfinding.NNConstraint.distanceXZ field on an NNConstraint object\endlink.
  114. */
  115. [JsonMember]
  116. public bool nearestSearchOnlyXZ;
  117. /** Currently updating tiles in a batch */
  118. bool batchTileUpdate;
  119. /** Determines how the graph transforms graph space to world space.
  120. * \see #CalculateTransform
  121. */
  122. public GraphTransform transform = new GraphTransform(Matrix4x4.identity);
  123. GraphTransform ITransformedGraph.transform { get { return transform; } }
  124. /** \copydoc Pathfinding::NavMeshGraph::recalculateNormals */
  125. protected abstract bool RecalculateNormals { get; }
  126. /** Called when tiles have been completely recalculated.
  127. * This is called after scanning the graph and after
  128. * performing graph updates that completely recalculate tiles
  129. * (not ones that simply modify e.g penalties).
  130. * It is not called after NavmeshCut updates.
  131. */
  132. public System.Action<NavmeshTile[]> OnRecalculatedTiles;
  133. /** Tile at the specified x, z coordinate pair.
  134. * The first tile is at (0,0), the last tile at (tileXCount-1, tileZCount-1).
  135. *
  136. * \snippet MiscSnippets.cs NavmeshBase.GetTile
  137. */
  138. public NavmeshTile GetTile (int x, int z) {
  139. return tiles[x + z * tileXCount];
  140. }
  141. /** Vertex coordinate for the specified vertex index.
  142. *
  143. * \throws IndexOutOfRangeException if the vertex index is invalid.
  144. * \throws NullReferenceException if the tile the vertex is in is not calculated.
  145. *
  146. * \see NavmeshTile.GetVertex
  147. */
  148. public Int3 GetVertex (int index) {
  149. int tileIndex = (index >> TileIndexOffset) & TileIndexMask;
  150. return tiles[tileIndex].GetVertex(index);
  151. }
  152. /** Vertex coordinate in graph space for the specified vertex index */
  153. public Int3 GetVertexInGraphSpace (int index) {
  154. int tileIndex = (index >> TileIndexOffset) & TileIndexMask;
  155. return tiles[tileIndex].GetVertexInGraphSpace(index);
  156. }
  157. /** Tile index from a vertex index */
  158. public static int GetTileIndex (int index) {
  159. return (index >> TileIndexOffset) & TileIndexMask;
  160. }
  161. public int GetVertexArrayIndex (int index) {
  162. return index & VertexIndexMask;
  163. }
  164. /** Tile coordinates from a tile index */
  165. public void GetTileCoordinates (int tileIndex, out int x, out int z) {
  166. //z = System.Math.DivRem (tileIndex, tileXCount, out x);
  167. z = tileIndex/tileXCount;
  168. x = tileIndex - z*tileXCount;
  169. }
  170. /** All tiles.
  171. * \warning Do not modify this array
  172. */
  173. public NavmeshTile[] GetTiles () {
  174. return tiles;
  175. }
  176. /** Returns the tile coordinate which contains the specified \a position.
  177. * It is not necessarily a valid tile (i.e it could be out of bounds).
  178. */
  179. public Int2 GetTileCoordinates (Vector3 position) {
  180. position = transform.InverseTransform(position);
  181. position.x /= TileWorldSizeX;
  182. position.z /= TileWorldSizeZ;
  183. return new Int2((int)position.x, (int)position.z);
  184. }
  185. protected override void OnDestroy () {
  186. base.OnDestroy();
  187. #if !SERVER // 服务端不需要释放
  188. // Cleanup
  189. TriangleMeshNode.SetNavmeshHolder(AstarPath.active.data.GetGraphIndex(this), null);
  190. #endif
  191. if (tiles != null) {
  192. for (int i = 0; i < tiles.Length; i++) {
  193. ObjectPool<BBTree>.Release(ref tiles[i].bbTree);
  194. }
  195. }
  196. }
  197. /** Creates a single new empty tile */
  198. protected NavmeshTile NewEmptyTile (int x, int z) {
  199. return new NavmeshTile {
  200. x = x,
  201. z = z,
  202. w = 1,
  203. d = 1,
  204. verts = new Int3[0],
  205. vertsInGraphSpace = new Int3[0],
  206. tris = new int[0],
  207. nodes = new TriangleMeshNode[0],
  208. bbTree = ObjectPool<BBTree>.Claim(),
  209. graph = this,
  210. };
  211. }
  212. public override void GetNodes (System.Action<GraphNode> action) {
  213. if (tiles == null) return;
  214. for (int i = 0; i < tiles.Length; i++) {
  215. if (tiles[i] == null || tiles[i].x+tiles[i].z*tileXCount != i) continue;
  216. TriangleMeshNode[] nodes = tiles[i].nodes;
  217. if (nodes == null) continue;
  218. for (int j = 0; j < nodes.Length; j++) action(nodes[j]);
  219. }
  220. }
  221. protected void ConnectTileWithNeighbours (NavmeshTile tile, bool onlyUnflagged = false) {
  222. if (tile.w != 1 || tile.d != 1) {
  223. throw new System.ArgumentException("Tile widths or depths other than 1 are not supported. The fields exist mainly for possible future expansions.");
  224. }
  225. // Loop through z and x offsets to adjacent tiles
  226. // _ x _
  227. // x _ x
  228. // _ x _
  229. for (int zo = -1; zo <= 1; zo++) {
  230. var z = tile.z + zo;
  231. if (z < 0 || z >= tileZCount) continue;
  232. for (int xo = -1; xo <= 1; xo++) {
  233. var x = tile.x + xo;
  234. if (x < 0 || x >= tileXCount) continue;
  235. // Ignore diagonals and the tile itself
  236. if ((xo == 0) == (zo == 0)) continue;
  237. var otherTile = tiles[x + z*tileXCount];
  238. if (!onlyUnflagged || !otherTile.flag) {
  239. ConnectTiles(otherTile, tile);
  240. }
  241. }
  242. }
  243. }
  244. static readonly NNConstraint NNConstraintDistanceXZ = new NNConstraint { distanceXZ = true };
  245. public override NNInfoInternal GetNearest (Vector3 position, NNConstraint constraint, GraphNode hint) {
  246. return GetNearestForce(position, constraint != null && constraint.distanceXZ ? NNConstraintDistanceXZ : null);
  247. }
  248. public override NNInfoInternal GetNearestForce (Vector3 position, NNConstraint constraint) {
  249. if (tiles == null) return new NNInfoInternal();
  250. var tileCoords = GetTileCoordinates(position);
  251. // Clamp to graph borders
  252. tileCoords.x = Mathf.Clamp(tileCoords.x, 0, tileXCount-1);
  253. tileCoords.y = Mathf.Clamp(tileCoords.y, 0, tileZCount-1);
  254. int wmax = Math.Max(tileXCount, tileZCount);
  255. var best = new NNInfoInternal();
  256. float bestDistance = float.PositiveInfinity;
  257. bool xzSearch = nearestSearchOnlyXZ || (constraint != null && constraint.distanceXZ);
  258. // Search outwards in a diamond pattern from the closest tile
  259. // 2
  260. // 2 1 2
  261. // 2 1 0 1 2 etc.
  262. // 2 1 2
  263. // 2
  264. for (int w = 0; w < wmax; w++) {
  265. // Stop the loop when we can guarantee that no nodes will be closer than the ones we have already searched
  266. if (bestDistance < (w-2)*Math.Max(TileWorldSizeX, TileWorldSizeX)) break;
  267. int zmax = Math.Min(w+tileCoords.y +1, tileZCount);
  268. for (int z = Math.Max(-w+tileCoords.y, 0); z < zmax; z++) {
  269. // Solve for z such that abs(x-tx) + abs(z-tx) == w
  270. // Delta X coordinate
  271. int originalDx = Math.Abs(w - Math.Abs(z-tileCoords.y));
  272. var dx = originalDx;
  273. // Solution is dx + tx and -dx + tx
  274. // This loop will first check +dx and then -dx
  275. // If dx happens to be zero, then it will not run twice
  276. do {
  277. // Absolute x coordinate
  278. int x = -dx + tileCoords.x;
  279. if (x >= 0 && x < tileXCount) {
  280. NavmeshTile tile = tiles[x + z*tileXCount];
  281. if (tile != null) {
  282. if (xzSearch) {
  283. best = tile.bbTree.QueryClosestXZ(position, constraint, ref bestDistance, best);
  284. } else {
  285. best = tile.bbTree.QueryClosest(position, constraint, ref bestDistance, best);
  286. }
  287. }
  288. }
  289. dx = -dx;
  290. } while (dx != originalDx);
  291. }
  292. }
  293. best.node = best.constrainedNode;
  294. best.constrainedNode = null;
  295. best.clampedPosition = best.constClampedPosition;
  296. return best;
  297. }
  298. /** Fills graph with tiles created by NewEmptyTile */
  299. public void FillWithEmptyTiles () {
  300. for (int z = 0; z < tileZCount; z++) {
  301. for (int x = 0; x < tileXCount; x++) {
  302. tiles[z*tileXCount + x] = NewEmptyTile(x, z);
  303. }
  304. }
  305. }
  306. /** Create connections between all nodes.
  307. * \version Since 3.7.6 the implementation is thread safe
  308. */
  309. public static void CreateNodeConnections (TriangleMeshNode[] nodes) {
  310. List<Connection> connections = ListPool<Connection>.Claim();
  311. var nodeRefs = ObjectPoolSimple<Dictionary<Int2, int> >.Claim();
  312. nodeRefs.Clear();
  313. // Build node neighbours
  314. for (int i = 0; i < nodes.Length; i++) {
  315. TriangleMeshNode node = nodes[i];
  316. int av = node.GetVertexCount();
  317. for (int a = 0; a < av; a++) {
  318. // Recast can in some very special cases generate degenerate triangles which are simply lines
  319. // In that case, duplicate keys might be added and thus an exception will be thrown
  320. // It is safe to ignore the second edge though... I think (only found one case where this happens)
  321. var key = new Int2(node.GetVertexIndex(a), node.GetVertexIndex((a+1) % av));
  322. if (!nodeRefs.ContainsKey(key)) {
  323. nodeRefs.Add(key, i);
  324. }
  325. }
  326. }
  327. for (int i = 0; i < nodes.Length; i++) {
  328. TriangleMeshNode node = nodes[i];
  329. connections.Clear();
  330. int av = node.GetVertexCount();
  331. for (int a = 0; a < av; a++) {
  332. int first = node.GetVertexIndex(a);
  333. int second = node.GetVertexIndex((a+1) % av);
  334. int connNode;
  335. if (nodeRefs.TryGetValue(new Int2(second, first), out connNode)) {
  336. TriangleMeshNode other = nodes[connNode];
  337. int bv = other.GetVertexCount();
  338. for (int b = 0; b < bv; b++) {
  339. /** \todo This will fail on edges which are only partially shared */
  340. if (other.GetVertexIndex(b) == second && other.GetVertexIndex((b+1) % bv) == first) {
  341. connections.Add(new Connection(
  342. other,
  343. (uint)(node.position - other.position).costMagnitude,
  344. (byte)a
  345. ));
  346. break;
  347. }
  348. }
  349. }
  350. }
  351. node.connections = connections.ToArrayFromPool();
  352. }
  353. nodeRefs.Clear();
  354. ObjectPoolSimple<Dictionary<Int2, int> >.Release(ref nodeRefs);
  355. ListPool<Connection>.Release(ref connections);
  356. }
  357. /** Generate connections between the two tiles.
  358. * The tiles must be adjacent.
  359. */
  360. public void ConnectTiles (NavmeshTile tile1, NavmeshTile tile2) {
  361. if (tile1 == null || tile2 == null) return;
  362. if (tile1.nodes == null) throw new System.ArgumentException("tile1 does not contain any nodes");
  363. if (tile2.nodes == null) throw new System.ArgumentException("tile2 does not contain any nodes");
  364. int t1x = Mathf.Clamp(tile2.x, tile1.x, tile1.x+tile1.w-1);
  365. int t2x = Mathf.Clamp(tile1.x, tile2.x, tile2.x+tile2.w-1);
  366. int t1z = Mathf.Clamp(tile2.z, tile1.z, tile1.z+tile1.d-1);
  367. int t2z = Mathf.Clamp(tile1.z, tile2.z, tile2.z+tile2.d-1);
  368. int coord, altcoord;
  369. int t1coord, t2coord;
  370. float tileWorldSize;
  371. // Figure out which side that is shared between the two tiles
  372. // and what coordinate index is fixed along that edge (x or z)
  373. if (t1x == t2x) {
  374. coord = 2;
  375. altcoord = 0;
  376. t1coord = t1z;
  377. t2coord = t2z;
  378. tileWorldSize = TileWorldSizeZ;
  379. } else if (t1z == t2z) {
  380. coord = 0;
  381. altcoord = 2;
  382. t1coord = t1x;
  383. t2coord = t2x;
  384. tileWorldSize = TileWorldSizeX;
  385. } else {
  386. throw new System.ArgumentException("Tiles are not adjacent (neither x or z coordinates match)");
  387. }
  388. if (Math.Abs(t1coord-t2coord) != 1) {
  389. throw new System.ArgumentException("Tiles are not adjacent (tile coordinates must differ by exactly 1. Got '" + t1coord + "' and '" + t2coord + "')");
  390. }
  391. // Midpoint between the two tiles
  392. int midpoint = (int)Math.Round((Math.Max(t1coord, t2coord) * tileWorldSize) * Int3.Precision);
  393. #if ASTARDEBUG
  394. Vector3 v1 = new Vector3(-100, 0, -100);
  395. Vector3 v2 = new Vector3(100, 0, 100);
  396. v1[coord] = midpoint*Int3.PrecisionFactor;
  397. v2[coord] = midpoint*Int3.PrecisionFactor;
  398. Debug.DrawLine(v1, v2, Color.magenta);
  399. #endif
  400. TriangleMeshNode[] nodes1 = tile1.nodes;
  401. TriangleMeshNode[] nodes2 = tile2.nodes;
  402. // Find adjacent nodes on the border between the tiles
  403. for (int i = 0; i < nodes1.Length; i++) {
  404. TriangleMeshNode nodeA = nodes1[i];
  405. int aVertexCount = nodeA.GetVertexCount();
  406. // Loop through all *sides* of the node
  407. for (int a = 0; a < aVertexCount; a++) {
  408. // Vertices that the segment consists of
  409. Int3 aVertex1 = nodeA.GetVertexInGraphSpace(a);
  410. Int3 aVertex2 = nodeA.GetVertexInGraphSpace((a+1) % aVertexCount);
  411. // Check if it is really close to the tile border
  412. if (Math.Abs(aVertex1[coord] - midpoint) < 2 && Math.Abs(aVertex2[coord] - midpoint) < 2) {
  413. int minalt = Math.Min(aVertex1[altcoord], aVertex2[altcoord]);
  414. int maxalt = Math.Max(aVertex1[altcoord], aVertex2[altcoord]);
  415. // Degenerate edge
  416. if (minalt == maxalt) continue;
  417. for (int j = 0; j < nodes2.Length; j++) {
  418. TriangleMeshNode nodeB = nodes2[j];
  419. int bVertexCount = nodeB.GetVertexCount();
  420. for (int b = 0; b < bVertexCount; b++) {
  421. Int3 bVertex1 = nodeB.GetVertexInGraphSpace(b);
  422. Int3 bVertex2 = nodeB.GetVertexInGraphSpace((b+1) % aVertexCount);
  423. if (Math.Abs(bVertex1[coord] - midpoint) < 2 && Math.Abs(bVertex2[coord] - midpoint) < 2) {
  424. int minalt2 = Math.Min(bVertex1[altcoord], bVertex2[altcoord]);
  425. int maxalt2 = Math.Max(bVertex1[altcoord], bVertex2[altcoord]);
  426. // Degenerate edge
  427. if (minalt2 == maxalt2) continue;
  428. if (maxalt > minalt2 && minalt < maxalt2) {
  429. // The two nodes seem to be adjacent
  430. // Test shortest distance between the segments (first test if they are equal since that is much faster and pretty common)
  431. if ((aVertex1 == bVertex1 && aVertex2 == bVertex2) || (aVertex1 == bVertex2 && aVertex2 == bVertex1) ||
  432. VectorMath.SqrDistanceSegmentSegment((Vector3)aVertex1, (Vector3)aVertex2, (Vector3)bVertex1, (Vector3)bVertex2) < MaxTileConnectionEdgeDistance*MaxTileConnectionEdgeDistance) {
  433. uint cost = (uint)(nodeA.position - nodeB.position).costMagnitude;
  434. nodeA.AddConnection(nodeB, cost, a);
  435. nodeB.AddConnection(nodeA, cost, b);
  436. }
  437. }
  438. }
  439. }
  440. }
  441. }
  442. }
  443. }
  444. }
  445. /** Temporary buffer used in #PrepareNodeRecycling */
  446. Dictionary<int, int> nodeRecyclingHashBuffer = new Dictionary<int, int>();
  447. /** Reuse nodes that keep the exact same vertices after a tile replacement.
  448. * The reused nodes will be added to the \a recycledNodeBuffer array at the index corresponding to the
  449. * indices in the triangle array that its vertices uses.
  450. *
  451. * All connections on the reused nodes will be removed except ones that go to other graphs.
  452. * The reused nodes will be removed from the tile by replacing it with a null slot in the node array.
  453. *
  454. * \see #ReplaceTile
  455. */
  456. void PrepareNodeRecycling (int x, int z, Int3[] verts, int[] tris, TriangleMeshNode[] recycledNodeBuffer) {
  457. NavmeshTile tile = GetTile(x, z);
  458. if (tile == null || tile.nodes.Length == 0) return;
  459. var nodes = tile.nodes;
  460. var recycling = nodeRecyclingHashBuffer;
  461. for (int i = 0, j = 0; i < tris.Length; i += 3, j++) {
  462. recycling[verts[tris[i+0]].GetHashCode() + verts[tris[i+1]].GetHashCode() + verts[tris[i+2]].GetHashCode()] = j;
  463. }
  464. var connectionsToKeep = ListPool<Connection>.Claim();
  465. for (int i = 0; i < nodes.Length; i++) {
  466. var node = nodes[i];
  467. Int3 v0, v1, v2;
  468. node.GetVerticesInGraphSpace(out v0, out v1, out v2);
  469. var hash = v0.GetHashCode() + v1.GetHashCode() + v2.GetHashCode();
  470. int newNodeIndex;
  471. if (recycling.TryGetValue(hash, out newNodeIndex)) {
  472. // Technically we should check for a cyclic permutations of the vertices (e.g node a,b,c could become node b,c,a)
  473. // but in almost all cases the vertices will keep the same order. Allocating one or two extra nodes isn't such a big deal.
  474. if (verts[tris[3*newNodeIndex+0]] == v0 && verts[tris[3*newNodeIndex+1]] == v1 && verts[tris[3*newNodeIndex+2]] == v2) {
  475. recycledNodeBuffer[newNodeIndex] = node;
  476. // Remove the node from the tile
  477. nodes[i] = null;
  478. // Only keep connections to nodes on other graphs
  479. // Usually there are no connections to nodes to other graphs and this is faster than removing all connections them one by one
  480. for (int j = 0; j < node.connections.Length; j++) {
  481. if (node.connections[j].node.GraphIndex != node.GraphIndex) {
  482. connectionsToKeep.Add(node.connections[j]);
  483. }
  484. }
  485. ArrayPool<Connection>.Release(ref node.connections, true);
  486. if (connectionsToKeep.Count > 0) {
  487. node.connections = connectionsToKeep.ToArrayFromPool();
  488. connectionsToKeep.Clear();
  489. }
  490. }
  491. }
  492. }
  493. recycling.Clear();
  494. ListPool<Connection>.Release(ref connectionsToKeep);
  495. }
  496. public void CreateNodes (TriangleMeshNode[] buffer, int[] tris, int tileIndex, uint graphIndex) {
  497. if (buffer == null || buffer.Length < tris.Length/3) throw new System.ArgumentException("buffer must be non null and at least as large as tris.Length/3");
  498. // This index will be ORed to the triangle indices
  499. tileIndex <<= TileIndexOffset;
  500. // Create nodes and assign vertex indices
  501. for (int i = 0; i < buffer.Length; i++) {
  502. var node = buffer[i];
  503. // Allow the buffer to be partially filled in already to allow for recycling nodes
  504. if (node == null) node = buffer[i] = new TriangleMeshNode();
  505. // Reset all relevant fields on the node (even on recycled nodes to avoid exposing internal implementation details)
  506. node.Walkable = true;
  507. node.Tag = 0;
  508. node.Penalty = initialPenalty;
  509. node.GraphIndex = graphIndex;
  510. // The vertices stored on the node are composed
  511. // out of the triangle index and the tile index
  512. node.v0 = tris[i*3+0] | tileIndex;
  513. node.v1 = tris[i*3+1] | tileIndex;
  514. node.v2 = tris[i*3+2] | tileIndex;
  515. // Make sure the triangle is clockwise in graph space (it may not be in world space since the graphs can be rotated)
  516. if (RecalculateNormals && !VectorMath.IsClockwiseXZ(node.GetVertexInGraphSpace(0), node.GetVertexInGraphSpace(1), node.GetVertexInGraphSpace(2))) {
  517. Memory.Swap(ref node.v0, ref node.v2);
  518. }
  519. node.UpdatePositionFromVertices();
  520. }
  521. }
  522. /** Returns if there is an obstacle between \a origin and \a end on the graph.
  523. * This is not the same as Physics.Linecast, this function traverses the \b graph and looks for collisions instead of checking for collider intersection.
  524. *
  525. * \astarpro
  526. *
  527. * \shadowimage{linecast.png}
  528. */
  529. public bool Linecast (Vector3 origin, Vector3 end) {
  530. return Linecast(origin, end, GetNearest(origin, NNConstraint.None).node);
  531. }
  532. /** Returns if there is an obstacle between \a origin and \a end on the graph.
  533. * \param [in] origin Point to linecast from
  534. * \param [in] end Point to linecast to
  535. * \param [out] hit Contains info on what was hit, see GraphHitInfo
  536. * \param [in] hint You need to pass the node closest to the start point
  537. *
  538. * This is not the same as Physics.Linecast, this function traverses the \b graph and looks for collisions instead of checking for collider intersection.
  539. * \astarpro
  540. *
  541. * \shadowimage{linecast.png}
  542. */
  543. public bool Linecast (Vector3 origin, Vector3 end, GraphNode hint, out GraphHitInfo hit) {
  544. return Linecast(this, origin, end, hint, out hit, null);
  545. }
  546. /** Returns if there is an obstacle between \a origin and \a end on the graph.
  547. * \param [in] origin Point to linecast from
  548. * \param [in] end Point to linecast to
  549. * \param [in] hint You need to pass the node closest to the start point
  550. *
  551. * This is not the same as Physics.Linecast, this function traverses the \b graph and looks for collisions instead of checking for collider intersection.
  552. * \astarpro
  553. *
  554. * \shadowimage{linecast.png}
  555. */
  556. public bool Linecast (Vector3 origin, Vector3 end, GraphNode hint) {
  557. GraphHitInfo hit;
  558. return Linecast(this, origin, end, hint, out hit, null);
  559. }
  560. /** Returns if there is an obstacle between \a origin and \a end on the graph.
  561. * \param [in] origin Point to linecast from
  562. * \param [in] end Point to linecast to
  563. * \param [out] hit Contains info on what was hit, see GraphHitInfo
  564. * \param [in] hint You need to pass the node closest to the start point
  565. * \param trace If a list is passed, then it will be filled with all nodes the linecast traverses
  566. *
  567. * This is not the same as Physics.Linecast, this function traverses the \b graph and looks for collisions instead of checking for collider intersection.
  568. * \astarpro
  569. *
  570. * \shadowimage{linecast.png}
  571. */
  572. public bool Linecast (Vector3 origin, Vector3 end, GraphNode hint, out GraphHitInfo hit, List<GraphNode> trace) {
  573. return Linecast(this, origin, end, hint, out hit, trace);
  574. }
  575. /** Returns if there is an obstacle between \a origin and \a end on the graph.
  576. * \param [in] graph The graph to perform the search on
  577. * \param [in] origin Point to start from
  578. * \param [in] end Point to linecast to
  579. * \param [out] hit Contains info on what was hit, see GraphHitInfo
  580. * \param [in] hint You need to pass the node closest to the start point, if null, a search for the closest node will be done
  581. *
  582. * This is not the same as Physics.Linecast, this function traverses the \b graph and looks for collisions instead of checking for collider intersection.
  583. * \astarpro
  584. *
  585. * \shadowimage{linecast.png}
  586. */
  587. public static bool Linecast (NavmeshBase graph, Vector3 origin, Vector3 end, GraphNode hint, out GraphHitInfo hit) {
  588. return Linecast(graph, origin, end, hint, out hit, null);
  589. }
  590. /** Cached \link Pathfinding.NNConstraint.None NNConstraint.None\endlink to reduce allocations */
  591. static readonly NNConstraint NNConstraintNone = NNConstraint.None;
  592. /** Used to optimize linecasts by precomputing some values */
  593. static readonly byte[] LinecastShapeEdgeLookup;
  594. static NavmeshBase () {
  595. // Want want to figure out which side of a triangle that a ray exists using.
  596. // There are only 3*3*3 = 27 different options for the [left/right/colinear] options for the 3 vertices of a triangle.
  597. // So we can precompute the result to improve the performance of linecasts.
  598. // For simplicity we reserve 2 bits for each side which means that we have 4*4*4 = 64 entries in the lookup table.
  599. LinecastShapeEdgeLookup = new byte[64];
  600. Side[] sideOfLine = new Side[3];
  601. for (int i = 0; i < LinecastShapeEdgeLookup.Length; i++) {
  602. sideOfLine[0] = (Side)((i >> 0) & 0x3);
  603. sideOfLine[1] = (Side)((i >> 2) & 0x3);
  604. sideOfLine[2] = (Side)((i >> 4) & 0x3);
  605. LinecastShapeEdgeLookup[i] = 0xFF;
  606. // Value 3 is an invalid value. So we just skip it.
  607. if (sideOfLine[0] != (Side)3 && sideOfLine[1] != (Side)3 && sideOfLine[2] != (Side)3) {
  608. // Figure out the side of the triangle that the line exits.
  609. // In case the line passes through one of the vertices of the triangle
  610. // there may be multiple alternatives. In that case pick the edge
  611. // which contains the fewest vertices that lie on the line.
  612. // This prevents a potential infinite loop when a linecast is done colinear
  613. // to the edge of a triangle.
  614. int bestBadness = int.MaxValue;
  615. for (int j = 0; j < 3; j++) {
  616. if ((sideOfLine[j] == Side.Left || sideOfLine[j] == Side.Colinear) && (sideOfLine[(j+1)%3] == Side.Right || sideOfLine[(j+1)%3] == Side.Colinear)) {
  617. var badness = (sideOfLine[j] == Side.Colinear ? 1 : 0) + (sideOfLine[(j+1)%3] == Side.Colinear ? 1 : 0);
  618. if (badness < bestBadness) {
  619. LinecastShapeEdgeLookup[i] = (byte)j;
  620. bestBadness = badness;
  621. }
  622. }
  623. }
  624. }
  625. }
  626. }
  627. /** Returns if there is an obstacle between \a origin and \a end on the graph.
  628. * \param [in] graph The graph to perform the search on
  629. * \param [in] origin Point to start from. This point should be on the navmesh. It will be snapped to the closest point on the navmesh otherwise.
  630. * \param [in] end Point to linecast to
  631. * \param [out] hit Contains info on what was hit, see GraphHitInfo
  632. * \param [in] hint If you already know the node which contains the \a origin point, you may pass it here for slighly improved performance. If null, a search for the closest node will be done.
  633. * \param trace If a list is passed, then it will be filled with all nodes along the line up until it hits an obstacle or reaches the end.
  634. *
  635. * This is not the same as Physics.Linecast, this function traverses the \b graph and looks for collisions instead of checking for collider intersections.
  636. *
  637. * \note This method only makes sense for graphs in which there is a definite 'up' direction. For example it does not make sense for e.g spherical graphs,
  638. * navmeshes in which characters can walk on walls/ceilings or other curved worlds. If you try to use this method on such navmeshes it may output nonsense.
  639. *
  640. * \astarpro
  641. *
  642. * \shadowimage{linecast.png}
  643. */
  644. public static bool Linecast (NavmeshBase graph, Vector3 origin, Vector3 end, GraphNode hint, out GraphHitInfo hit, List<GraphNode> trace) {
  645. hit = new GraphHitInfo();
  646. if (float.IsNaN(origin.x + origin.y + origin.z)) throw new System.ArgumentException("origin is NaN");
  647. if (float.IsNaN(end.x + end.y + end.z)) throw new System.ArgumentException("end is NaN");
  648. var node = hint as TriangleMeshNode;
  649. if (node == null) {
  650. node = graph.GetNearest(origin, NNConstraintNone).node as TriangleMeshNode;
  651. if (node == null) {
  652. #if !SERVER
  653. UnityEngine.Debug.LogError("Could not find a valid node to start from");
  654. #endif
  655. hit.origin = origin;
  656. hit.point = origin;
  657. return true;
  658. }
  659. }
  660. // Snap the origin to the navmesh
  661. var i3originInGraphSpace = node.ClosestPointOnNodeXZInGraphSpace(origin);
  662. hit.origin = graph.transform.Transform((Vector3)i3originInGraphSpace);
  663. if (!node.Walkable) {
  664. hit.node = node;
  665. hit.point = hit.origin;
  666. hit.tangentOrigin = hit.origin;
  667. return true;
  668. }
  669. var endInGraphSpace = graph.transform.InverseTransform(end);
  670. var i3endInGraphSpace = (Int3)endInGraphSpace;
  671. // Fast early out check
  672. if (i3originInGraphSpace == i3endInGraphSpace) {
  673. hit.point = hit.origin;
  674. hit.node = node;
  675. return false;
  676. }
  677. int counter = 0;
  678. while (true) {
  679. counter++;
  680. if (counter > 2000) {
  681. #if !SERVER
  682. UnityEngine.Debug.LogError("Linecast was stuck in infinite loop. Breaking.");
  683. #endif
  684. return true;
  685. }
  686. if (trace != null) trace.Add(node);
  687. Int3 a0, a1, a2;
  688. node.GetVerticesInGraphSpace(out a0, out a1, out a2);
  689. int sideOfLine = (byte)VectorMath.SideXZ(i3originInGraphSpace, i3endInGraphSpace, a0);
  690. sideOfLine |= (byte)VectorMath.SideXZ(i3originInGraphSpace, i3endInGraphSpace, a1) << 2;
  691. sideOfLine |= (byte)VectorMath.SideXZ(i3originInGraphSpace, i3endInGraphSpace, a2) << 4;
  692. // Use a lookup table to figure out which side of this triangle that the ray exits
  693. int shapeEdgeA = (int)LinecastShapeEdgeLookup[sideOfLine];
  694. // The edge consists of the vertex with index 'sharedEdgeA' and the next vertex after that (index '(sharedEdgeA+1)%3')
  695. var sideNodeExit = VectorMath.SideXZ(shapeEdgeA == 0 ? a0 : (shapeEdgeA == 1 ? a1 : a2), shapeEdgeA == 0 ? a1 : (shapeEdgeA == 1 ? a2 : a0), i3endInGraphSpace);
  696. if (sideNodeExit != Side.Left) {
  697. // Ray stops before it leaves the current node.
  698. // The endpoint must be inside the current node.
  699. hit.point = end;
  700. hit.node = node;
  701. return false;
  702. }
  703. if (shapeEdgeA == 0xFF) {
  704. // Line does not intersect node at all?
  705. // This may theoretically happen if the origin was not properly snapped to the inside of the triangle, but is instead a tiny distance outside the node.
  706. #if !SERVER
  707. UnityEngine.Debug.LogError("Line does not intersect node at all");
  708. #endif
  709. hit.node = node;
  710. hit.point = hit.tangentOrigin = hit.origin;
  711. return true;
  712. } else {
  713. bool success = false;
  714. var nodeConnections = node.connections;
  715. for (int i = 0; i < nodeConnections.Length; i++) {
  716. if (nodeConnections[i].shapeEdge == shapeEdgeA) {
  717. // This might be the next node that we enter
  718. var neighbour = nodeConnections[i].node as TriangleMeshNode;
  719. if (neighbour == null || !neighbour.Walkable) continue;
  720. var neighbourConnections = neighbour.connections;
  721. int shapeEdgeB = -1;
  722. for (int j = 0; j < neighbourConnections.Length; j++) {
  723. if (neighbourConnections[j].node == node) {
  724. shapeEdgeB = neighbourConnections[j].shapeEdge;
  725. break;
  726. }
  727. }
  728. if (shapeEdgeB == -1) {
  729. // Connection was mono-directional!
  730. // This shouldn't normally not happen on navmeshes happen on navmeshes (when the shapeEdge matches at least) unless a user has done something strange to the navmesh.
  731. continue;
  732. }
  733. var side1 = VectorMath.SideXZ(i3originInGraphSpace, i3endInGraphSpace, neighbour.GetVertexInGraphSpace(shapeEdgeB));
  734. var side2 = VectorMath.SideXZ(i3originInGraphSpace, i3endInGraphSpace, neighbour.GetVertexInGraphSpace((shapeEdgeB+1) % 3));
  735. // Check if the line enters this edge
  736. success = (side1 == Side.Right || side1 == Side.Colinear) && (side2 == Side.Left || side2 == Side.Colinear);
  737. if (!success) continue;
  738. // Ray has entered the neighbouring node.
  739. // After the first node, it is possible to prove the loop invariant that shapeEdgeA will *never* end up as -1 (checked above)
  740. // Since side = Colinear acts essentially as a wildcard. side1 and side2 can be the most restricted if they are side1=right, side2=left.
  741. // Then when we get to the next node we know that the sideOfLine array is either [*, Right, Left], [Left, *, Right] or [Right, Left, *], where * is unknown.
  742. // We are looking for the sequence [Left, Right] (possibly including Colinear as wildcard). We will always find this sequence regardless of the value of *.
  743. node = neighbour;
  744. break;
  745. }
  746. }
  747. if (!success) {
  748. // Node did not enter any neighbours
  749. // It must have hit the border of the navmesh
  750. var hitEdgeStartInGraphSpace = (Vector3)(shapeEdgeA == 0 ? a0 : (shapeEdgeA == 1 ? a1 : a2));
  751. var hitEdgeEndInGraphSpace = (Vector3)(shapeEdgeA == 0 ? a1 : (shapeEdgeA == 1 ? a2 : a0));
  752. var intersectionInGraphSpace = VectorMath.LineIntersectionPointXZ(hitEdgeStartInGraphSpace, hitEdgeEndInGraphSpace, (Vector3)i3originInGraphSpace, (Vector3)i3endInGraphSpace);
  753. hit.point = graph.transform.Transform(intersectionInGraphSpace);
  754. hit.node = node;
  755. var hitEdgeStart = graph.transform.Transform(hitEdgeStartInGraphSpace);
  756. var hitEdgeEnd = graph.transform.Transform(hitEdgeEndInGraphSpace);
  757. hit.tangent = hitEdgeEnd - hitEdgeStart;
  758. hit.tangentOrigin = hitEdgeStart;
  759. return true;
  760. }
  761. }
  762. }
  763. }
  764. /** Serializes Node Info.
  765. * Should serialize:
  766. * - Base
  767. * - Node Flags
  768. * - Node Penalties
  769. * - Node
  770. * - Node Positions (if applicable)
  771. * - Any other information necessary to load the graph in-game
  772. * All settings marked with json attributes (e.g JsonMember) have already been
  773. * saved as graph settings and do not need to be handled here.
  774. *
  775. * It is not necessary for this implementation to be forward or backwards compatible.
  776. *
  777. * \see
  778. */
  779. protected override void SerializeExtraInfo (GraphSerializationContext ctx) {
  780. BinaryWriter writer = ctx.writer;
  781. if (tiles == null) {
  782. writer.Write(-1);
  783. return;
  784. }
  785. writer.Write(tileXCount);
  786. writer.Write(tileZCount);
  787. for (int z = 0; z < tileZCount; z++) {
  788. for (int x = 0; x < tileXCount; x++) {
  789. NavmeshTile tile = tiles[x + z*tileXCount];
  790. if (tile == null) {
  791. throw new System.Exception("NULL Tile");
  792. //writer.Write (-1);
  793. //continue;
  794. }
  795. writer.Write(tile.x);
  796. writer.Write(tile.z);
  797. if (tile.x != x || tile.z != z) continue;
  798. writer.Write(tile.w);
  799. writer.Write(tile.d);
  800. writer.Write(tile.tris.Length);
  801. for (int i = 0; i < tile.tris.Length; i++) writer.Write(tile.tris[i]);
  802. writer.Write(tile.verts.Length);
  803. for (int i = 0; i < tile.verts.Length; i++) {
  804. ctx.SerializeInt3(tile.verts[i]);
  805. }
  806. writer.Write(tile.vertsInGraphSpace.Length);
  807. for (int i = 0; i < tile.vertsInGraphSpace.Length; i++) {
  808. ctx.SerializeInt3(tile.vertsInGraphSpace[i]);
  809. }
  810. writer.Write(tile.nodes.Length);
  811. for (int i = 0; i < tile.nodes.Length; i++) {
  812. tile.nodes[i].SerializeNode(ctx);
  813. }
  814. }
  815. }
  816. }
  817. public abstract GraphTransform CalculateTransform();
  818. protected override void DeserializeExtraInfo (GraphSerializationContext ctx) {
  819. BinaryReader reader = ctx.reader;
  820. tileXCount = reader.ReadInt32();
  821. if (tileXCount < 0) return;
  822. tileZCount = reader.ReadInt32();
  823. transform = CalculateTransform();
  824. tiles = new NavmeshTile[tileXCount * tileZCount];
  825. //Make sure mesh nodes can reference this graph
  826. TriangleMeshNode.SetNavmeshHolder((int)ctx.graphIndex, this);
  827. for (int z = 0; z < tileZCount; z++) {
  828. for (int x = 0; x < tileXCount; x++) {
  829. int tileIndex = x + z*tileXCount;
  830. int tx = reader.ReadInt32();
  831. if (tx < 0) throw new System.Exception("Invalid tile coordinates (x < 0)");
  832. int tz = reader.ReadInt32();
  833. if (tz < 0) throw new System.Exception("Invalid tile coordinates (z < 0)");
  834. // This is not the origin of a large tile. Refer back to that tile.
  835. if (tx != x || tz != z) {
  836. tiles[tileIndex] = tiles[tz*tileXCount + tx];
  837. continue;
  838. }
  839. var tile = tiles[tileIndex] = new NavmeshTile {
  840. x = tx,
  841. z = tz,
  842. w = reader.ReadInt32(),
  843. d = reader.ReadInt32(),
  844. bbTree = ObjectPool<BBTree>.Claim(),
  845. graph = this,
  846. };
  847. int trisCount = reader.ReadInt32();
  848. if (trisCount % 3 != 0) throw new System.Exception("Corrupt data. Triangle indices count must be divisable by 3. Read " + trisCount);
  849. tile.tris = new int[trisCount];
  850. for (int i = 0; i < tile.tris.Length; i++) tile.tris[i] = reader.ReadInt32();
  851. tile.verts = new Int3[reader.ReadInt32()];
  852. for (int i = 0; i < tile.verts.Length; i++) {
  853. tile.verts[i] = ctx.DeserializeInt3();
  854. }
  855. if (ctx.meta.version.Major >= 4) {
  856. tile.vertsInGraphSpace = new Int3[reader.ReadInt32()];
  857. if (tile.vertsInGraphSpace.Length != tile.verts.Length) throw new System.Exception("Corrupt data. Array lengths did not match");
  858. for (int i = 0; i < tile.verts.Length; i++) {
  859. tile.vertsInGraphSpace[i] = ctx.DeserializeInt3();
  860. }
  861. } else {
  862. // Compatibility
  863. tile.vertsInGraphSpace = new Int3[tile.verts.Length];
  864. tile.verts.CopyTo(tile.vertsInGraphSpace, 0);
  865. transform.InverseTransform(tile.vertsInGraphSpace);
  866. }
  867. int nodeCount = reader.ReadInt32();
  868. tile.nodes = new TriangleMeshNode[nodeCount];
  869. // Prepare for storing in vertex indices
  870. tileIndex <<= TileIndexOffset;
  871. for (int i = 0; i < tile.nodes.Length; i++) {
  872. var node = new TriangleMeshNode();
  873. tile.nodes[i] = node;
  874. node.DeserializeNode(ctx);
  875. node.v0 = tile.tris[i*3+0] | tileIndex;
  876. node.v1 = tile.tris[i*3+1] | tileIndex;
  877. node.v2 = tile.tris[i*3+2] | tileIndex;
  878. node.UpdatePositionFromVertices();
  879. }
  880. tile.bbTree.RebuildFrom(tile.nodes);
  881. }
  882. }
  883. }
  884. protected override void PostDeserialization (GraphSerializationContext ctx) {
  885. // Compatibility
  886. if (ctx.meta.version < AstarSerializer.V4_1_0 && tiles != null) {
  887. Dictionary<TriangleMeshNode, Connection[]> conns = tiles.SelectMany(s => s.nodes).ToDictionary(n => n, n => n.connections ?? new Connection[0]);
  888. // We need to recalculate all connections when upgrading data from earlier than 4.1.0
  889. // as the connections now need information about which edge was used.
  890. // This may remove connections for e.g off-mesh links.
  891. foreach (var tile in tiles) CreateNodeConnections(tile.nodes);
  892. foreach (var tile in tiles) ConnectTileWithNeighbours(tile);
  893. // Restore any connections that were contained in the serialized file but didn't get added by the method calls above
  894. GetNodes(node => {
  895. var triNode = node as TriangleMeshNode;
  896. foreach (var conn in conns[triNode].Where(conn => !triNode.ContainsConnection(conn.node)).ToList()) {
  897. triNode.AddConnection(conn.node, conn.cost, conn.shapeEdge);
  898. }
  899. });
  900. }
  901. // Make sure that the transform is up to date.
  902. // It is assumed that the current graph settings correspond to the correct
  903. // transform as it is not serialized itself.
  904. transform = CalculateTransform();
  905. }
  906. }
  907. }