AstarData.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using Pathfinding.WindowsStore;
  5. using Pathfinding.Serialization;
  6. #if UNITY_WINRT && !UNITY_EDITOR
  7. //using MarkerMetro.Unity.WinLegacy.IO;
  8. //using MarkerMetro.Unity.WinLegacy.Reflection;
  9. #endif
  10. namespace Pathfinding {
  11. [System.Serializable]
  12. /// <summary>
  13. /// Stores the navigation graphs for the A* Pathfinding System.
  14. ///
  15. /// An instance of this class is assigned to AstarPath.data, from it you can access all graphs loaded through the <see cref="graphs"/> variable.
  16. /// This class also handles a lot of the high level serialization.
  17. /// </summary>
  18. public class AstarData {
  19. /// <summary>Shortcut to AstarPath.active</summary>
  20. public static AstarPath active {
  21. get {
  22. return AstarPath.active;
  23. }
  24. }
  25. #region Fields
  26. /// <summary>
  27. /// Shortcut to the first NavMeshGraph.
  28. /// Updated at scanning time
  29. /// </summary>
  30. public NavMeshGraph navmesh { get; private set; }
  31. #if !ASTAR_NO_GRID_GRAPH
  32. /// <summary>
  33. /// Shortcut to the first GridGraph.
  34. /// Updated at scanning time
  35. /// </summary>
  36. public GridGraph gridGraph { get; private set; }
  37. /// <summary>
  38. /// Shortcut to the first LayerGridGraph.
  39. /// Updated at scanning time.
  40. /// </summary>
  41. public LayerGridGraph layerGridGraph { get; private set; }
  42. #endif
  43. #if !ASTAR_NO_POINT_GRAPH
  44. /// <summary>
  45. /// Shortcut to the first PointGraph.
  46. /// Updated at scanning time
  47. /// </summary>
  48. public PointGraph pointGraph { get; private set; }
  49. #endif
  50. /// <summary>
  51. /// Shortcut to the first RecastGraph.
  52. /// Updated at scanning time.
  53. /// </summary>
  54. public RecastGraph recastGraph { get; private set; }
  55. /// <summary>
  56. /// All supported graph types.
  57. /// Populated through reflection search
  58. /// </summary>
  59. public System.Type[] graphTypes { get; private set; }
  60. #if ASTAR_FAST_NO_EXCEPTIONS || UNITY_WINRT || UNITY_WEBGL
  61. /// <summary>
  62. /// Graph types to use when building with Fast But No Exceptions for iPhone.
  63. /// If you add any custom graph types, you need to add them to this hard-coded list.
  64. /// </summary>
  65. public static readonly System.Type[] DefaultGraphTypes = new System.Type[] {
  66. #if !ASTAR_NO_GRID_GRAPH
  67. typeof(GridGraph),
  68. typeof(LayerGridGraph),
  69. #endif
  70. #if !ASTAR_NO_POINT_GRAPH
  71. typeof(PointGraph),
  72. #endif
  73. typeof(NavMeshGraph),
  74. typeof(RecastGraph),
  75. };
  76. #endif
  77. /// <summary>
  78. /// All graphs this instance holds.
  79. /// This will be filled only after deserialization has completed.
  80. /// May contain null entries if graph have been removed.
  81. /// </summary>
  82. [System.NonSerialized]
  83. public NavGraph[] graphs = new NavGraph[0];
  84. //Serialization Settings
  85. /// <summary>
  86. /// Serialized data for all graphs and settings.
  87. /// Stored as a base64 encoded string because otherwise Unity's Undo system would sometimes corrupt the byte data (because it only stores deltas).
  88. ///
  89. /// This can be accessed as a byte array from the <see cref="data"/> property.
  90. ///
  91. /// Since: 3.6.1
  92. /// </summary>
  93. [SerializeField]
  94. string dataString;
  95. /// <summary>
  96. /// Data from versions from before 3.6.1.
  97. /// Used for handling upgrades
  98. /// Since: 3.6.1
  99. /// </summary>
  100. [SerializeField]
  101. [UnityEngine.Serialization.FormerlySerializedAs("data")]
  102. private byte[] upgradeData;
  103. /// <summary>Serialized data for all graphs and settings</summary>
  104. private byte[] data {
  105. get {
  106. // Handle upgrading from earlier versions than 3.6.1
  107. if (upgradeData != null && upgradeData.Length > 0) {
  108. data = upgradeData;
  109. upgradeData = null;
  110. }
  111. return dataString != null? System.Convert.FromBase64String(dataString) : null;
  112. }
  113. set {
  114. dataString = value != null? System.Convert.ToBase64String(value) : null;
  115. }
  116. }
  117. /// <summary>
  118. /// Serialized data for cached startup.
  119. /// If set, on start the graphs will be deserialized from this file.
  120. /// </summary>
  121. public TextAsset file_cachedStartup;
  122. /// <summary>
  123. /// Serialized data for cached startup.
  124. ///
  125. /// Deprecated: Deprecated since 3.6, AstarData.file_cachedStartup is now used instead
  126. /// </summary>
  127. public byte[] data_cachedStartup;
  128. /// <summary>
  129. /// Should graph-data be cached.
  130. /// Caching the startup means saving the whole graphs - not only the settings - to a file (<see cref="file_cachedStartup)"/> which can
  131. /// be loaded when the game starts. This is usually much faster than scanning the graphs when the game starts. This is configured from the editor under the "Save & Load" tab.
  132. ///
  133. /// See: save-load-graphs (view in online documentation for working links)
  134. /// </summary>
  135. [SerializeField]
  136. public bool cacheStartup;
  137. //End Serialization Settings
  138. List<bool> graphStructureLocked = new List<bool>();
  139. #endregion
  140. public byte[] GetData () {
  141. return data;
  142. }
  143. public void SetData (byte[] data) {
  144. this.data = data;
  145. }
  146. /// <summary>Loads the graphs from memory, will load cached graphs if any exists</summary>
  147. public void Awake () {
  148. graphs = new NavGraph[0];
  149. if (cacheStartup && file_cachedStartup != null) {
  150. LoadFromCache();
  151. } else {
  152. DeserializeGraphs();
  153. }
  154. }
  155. /// <summary>
  156. /// Prevent the graph structure from changing during the time this lock is held.
  157. /// This prevents graphs from being added or removed and also prevents graphs from being serialized or deserialized.
  158. /// This is used when e.g an async scan is happening to ensure that for example a graph that is being scanned is not destroyed.
  159. ///
  160. /// Each call to this method *must* be paired with exactly one call to <see cref="UnlockGraphStructure"/>.
  161. /// The calls may be nested.
  162. /// </summary>
  163. internal void LockGraphStructure (bool allowAddingGraphs = false) {
  164. graphStructureLocked.Add(allowAddingGraphs);
  165. }
  166. /// <summary>
  167. /// Allows the graph structure to change again.
  168. /// See: <see cref="LockGraphStructure"/>
  169. /// </summary>
  170. internal void UnlockGraphStructure () {
  171. if (graphStructureLocked.Count == 0) throw new System.InvalidOperationException();
  172. graphStructureLocked.RemoveAt(graphStructureLocked.Count - 1);
  173. }
  174. PathProcessor.GraphUpdateLock AssertSafe (bool onlyAddingGraph = false) {
  175. if (graphStructureLocked.Count > 0) {
  176. bool allowAdding = true;
  177. for (int i = 0; i < graphStructureLocked.Count; i++) allowAdding &= graphStructureLocked[i];
  178. if (!(onlyAddingGraph && allowAdding)) throw new System.InvalidOperationException("Graphs cannot be added, removed or serialized while the graph structure is locked. This is the case when a graph is currently being scanned and when executing graph updates and work items.\nHowever as a special case, graphs can be added inside work items.");
  179. }
  180. // Pause the pathfinding threads
  181. var graphLock = active.PausePathfinding();
  182. if (!active.IsInsideWorkItem) {
  183. // Make sure all graph updates and other callbacks are done
  184. // Only do this if this code is not being called from a work item itself as that would cause a recursive wait that could never complete.
  185. // There are some valid cases when this can happen. For example it may be necessary to add a new graph inside a work item.
  186. active.FlushWorkItems();
  187. // Paths that are already calculated and waiting to be returned to the Seeker component need to be
  188. // processed immediately as their results usually depend on graphs that currently exist. If this was
  189. // not done then after destroying a graph one could get a path result with destroyed nodes in it.
  190. active.pathReturnQueue.ReturnPaths(false);
  191. }
  192. return graphLock;
  193. }
  194. /// <summary>
  195. /// Calls the callback with every node in all graphs.
  196. /// This is the easiest way to iterate through every existing node.
  197. ///
  198. /// <code>
  199. /// AstarPath.active.data.GetNodes(node => {
  200. /// Debug.Log("I found a node at position " + (Vector3)node.position);
  201. /// });
  202. /// </code>
  203. ///
  204. /// See: <see cref="Pathfinding.NavGraph.GetNodes"/> for getting the nodes of a single graph instead of all.
  205. /// See: graph-updates (view in online documentation for working links)
  206. /// </summary>
  207. public void GetNodes (System.Action<GraphNode> callback) {
  208. for (int i = 0; i < graphs.Length; i++) {
  209. if (graphs[i] != null) graphs[i].GetNodes(callback);
  210. }
  211. }
  212. /// <summary>
  213. /// Updates shortcuts to the first graph of different types.
  214. /// Hard coding references to some graph types is not really a good thing imo. I want to keep it dynamic and flexible.
  215. /// But these references ease the use of the system, so I decided to keep them.
  216. /// </summary>
  217. public void UpdateShortcuts () {
  218. navmesh = (NavMeshGraph)FindGraphOfType(typeof(NavMeshGraph));
  219. #if !ASTAR_NO_GRID_GRAPH
  220. gridGraph = (GridGraph)FindGraphOfType(typeof(GridGraph));
  221. layerGridGraph = (LayerGridGraph)FindGraphOfType(typeof(LayerGridGraph));
  222. #endif
  223. #if !ASTAR_NO_POINT_GRAPH
  224. pointGraph = (PointGraph)FindGraphOfType(typeof(PointGraph));
  225. #endif
  226. recastGraph = (RecastGraph)FindGraphOfType(typeof(RecastGraph));
  227. }
  228. /// <summary>Load from data from <see cref="file_cachedStartup"/></summary>
  229. public void LoadFromCache () {
  230. var graphLock = AssertSafe();
  231. if (file_cachedStartup != null) {
  232. var bytes = file_cachedStartup.bytes;
  233. DeserializeGraphs(bytes);
  234. GraphModifier.TriggerEvent(GraphModifier.EventType.PostCacheLoad);
  235. } else {
  236. Debug.LogError("Can't load from cache since the cache is empty");
  237. }
  238. graphLock.Release();
  239. }
  240. #region Serialization
  241. /// <summary>
  242. /// Serializes all graphs settings to a byte array.
  243. /// See: DeserializeGraphs(byte[])
  244. /// </summary>
  245. public byte[] SerializeGraphs () {
  246. return SerializeGraphs(SerializeSettings.Settings);
  247. }
  248. /// <summary>
  249. /// Serializes all graphs settings and optionally node data to a byte array.
  250. /// See: DeserializeGraphs(byte[])
  251. /// See: Pathfinding.Serialization.SerializeSettings
  252. /// </summary>
  253. public byte[] SerializeGraphs (SerializeSettings settings) {
  254. uint checksum;
  255. return SerializeGraphs(settings, out checksum);
  256. }
  257. /// <summary>
  258. /// Main serializer function.
  259. /// Serializes all graphs to a byte array
  260. /// A similar function exists in the AstarPathEditor.cs script to save additional info
  261. /// </summary>
  262. public byte[] SerializeGraphs (SerializeSettings settings, out uint checksum) {
  263. var graphLock = AssertSafe();
  264. var sr = new AstarSerializer(this, settings, active.gameObject);
  265. sr.OpenSerialize();
  266. sr.SerializeGraphs(graphs);
  267. sr.SerializeExtraInfo();
  268. byte[] bytes = sr.CloseSerialize();
  269. checksum = sr.GetChecksum();
  270. #if ASTARDEBUG
  271. Debug.Log("Got a whole bunch of data, "+bytes.Length+" bytes");
  272. #endif
  273. graphLock.Release();
  274. return bytes;
  275. }
  276. /// <summary>Deserializes graphs from <see cref="data"/></summary>
  277. public void DeserializeGraphs () {
  278. if (data != null) {
  279. DeserializeGraphs(data);
  280. }
  281. }
  282. /// <summary>Destroys all graphs and sets graphs to null</summary>
  283. void ClearGraphs () {
  284. if (graphs == null) return;
  285. for (int i = 0; i < graphs.Length; i++) {
  286. if (graphs[i] != null) {
  287. ((IGraphInternals)graphs[i]).OnDestroy();
  288. graphs[i].active = null;
  289. }
  290. }
  291. graphs = new NavGraph[0];
  292. UpdateShortcuts();
  293. }
  294. public void OnDestroy () {
  295. ClearGraphs();
  296. }
  297. /// <summary>
  298. /// Deserializes graphs from the specified byte array.
  299. /// An error will be logged if deserialization fails.
  300. /// </summary>
  301. public void DeserializeGraphs (byte[] bytes) {
  302. var graphLock = AssertSafe();
  303. ClearGraphs();
  304. DeserializeGraphsAdditive(bytes);
  305. graphLock.Release();
  306. }
  307. /// <summary>
  308. /// Deserializes graphs from the specified byte array additively.
  309. /// An error will be logged if deserialization fails.
  310. /// This function will add loaded graphs to the current ones.
  311. /// </summary>
  312. public void DeserializeGraphsAdditive (byte[] bytes) {
  313. var graphLock = AssertSafe();
  314. try {
  315. if (bytes != null) {
  316. var sr = new AstarSerializer(this, active.gameObject);
  317. if (sr.OpenDeserialize(bytes)) {
  318. DeserializeGraphsPartAdditive(sr);
  319. sr.CloseDeserialize();
  320. } else {
  321. Debug.Log("Invalid data file (cannot read zip).\nThe data is either corrupt or it was saved using a 3.0.x or earlier version of the system");
  322. }
  323. } else {
  324. throw new System.ArgumentNullException("bytes");
  325. }
  326. active.VerifyIntegrity();
  327. } catch (System.Exception e) {
  328. Debug.LogError("Caught exception while deserializing data.\n"+e);
  329. graphs = new NavGraph[0];
  330. }
  331. UpdateShortcuts();
  332. graphLock.Release();
  333. }
  334. /// <summary>Helper function for deserializing graphs</summary>
  335. void DeserializeGraphsPartAdditive (AstarSerializer sr) {
  336. if (graphs == null) graphs = new NavGraph[0];
  337. var gr = new List<NavGraph>(graphs);
  338. // Set an offset so that the deserializer will load
  339. // the graphs with the correct graph indexes
  340. sr.SetGraphIndexOffset(gr.Count);
  341. if (graphTypes == null) FindGraphTypes();
  342. gr.AddRange(sr.DeserializeGraphs(graphTypes));
  343. graphs = gr.ToArray();
  344. sr.DeserializeEditorSettingsCompatibility();
  345. sr.DeserializeExtraInfo();
  346. //Assign correct graph indices.
  347. for (int i = 0; i < graphs.Length; i++) {
  348. if (graphs[i] == null) continue;
  349. graphs[i].GetNodes(node => node.GraphIndex = (uint)i);
  350. }
  351. for (int i = 0; i < graphs.Length; i++) {
  352. for (int j = i+1; j < graphs.Length; j++) {
  353. if (graphs[i] != null && graphs[j] != null && graphs[i].guid == graphs[j].guid) {
  354. Debug.LogWarning("Guid Conflict when importing graphs additively. Imported graph will get a new Guid.\nThis message is (relatively) harmless.");
  355. graphs[i].guid = Pathfinding.Util.Guid.NewGuid();
  356. break;
  357. }
  358. }
  359. }
  360. sr.PostDeserialization();
  361. active.hierarchicalGraph.RecalculateIfNecessary();
  362. }
  363. #endregion
  364. /// <summary>
  365. /// Find all graph types supported in this build.
  366. /// Using reflection, the assembly is searched for types which inherit from NavGraph.
  367. /// </summary>
  368. public void FindGraphTypes () {
  369. #if !ASTAR_FAST_NO_EXCEPTIONS && !UNITY_WINRT && !UNITY_WEBGL
  370. var graphList = new List<System.Type>();
  371. foreach (var assembly in System.AppDomain.CurrentDomain.GetAssemblies()) {
  372. System.Type[] types = null;
  373. try {
  374. types = assembly.GetTypes();
  375. } catch {
  376. // Ignore type load exceptions and things like that.
  377. // We might not be able to read all assemblies for some reason, but hopefully the relevant types exist in the assemblies that we can read
  378. continue;
  379. }
  380. foreach (var type in types) {
  381. #if NETFX_CORE && !UNITY_EDITOR
  382. System.Type baseType = type.GetTypeInfo().BaseType;
  383. #else
  384. var baseType = type.BaseType;
  385. #endif
  386. while (baseType != null) {
  387. if (System.Type.Equals(baseType, typeof(NavGraph))) {
  388. graphList.Add(type);
  389. break;
  390. }
  391. #if NETFX_CORE && !UNITY_EDITOR
  392. baseType = baseType.GetTypeInfo().BaseType;
  393. #else
  394. baseType = baseType.BaseType;
  395. #endif
  396. }
  397. }
  398. }
  399. graphTypes = graphList.ToArray();
  400. #if ASTARDEBUG
  401. Debug.Log("Found "+graphTypes.Length+" graph types");
  402. #endif
  403. #else
  404. graphTypes = DefaultGraphTypes;
  405. #endif
  406. }
  407. #region GraphCreation
  408. /// <summary>
  409. /// Returns: A System.Type which matches the specified type string. If no mathing graph type was found, null is returned
  410. ///
  411. /// Deprecated:
  412. /// </summary>
  413. [System.Obsolete("If really necessary. Use System.Type.GetType instead.")]
  414. public System.Type GetGraphType (string type) {
  415. for (int i = 0; i < graphTypes.Length; i++) {
  416. if (graphTypes[i].Name == type) {
  417. return graphTypes[i];
  418. }
  419. }
  420. return null;
  421. }
  422. /// <summary>
  423. /// Creates a new instance of a graph of type type. If no matching graph type was found, an error is logged and null is returned
  424. /// Returns: The created graph
  425. /// See: <see cref="CreateGraph(System.Type)"/>
  426. ///
  427. /// Deprecated:
  428. /// </summary>
  429. [System.Obsolete("Use CreateGraph(System.Type) instead")]
  430. public NavGraph CreateGraph (string type) {
  431. Debug.Log("Creating Graph of type '"+type+"'");
  432. for (int i = 0; i < graphTypes.Length; i++) {
  433. if (graphTypes[i].Name == type) {
  434. return CreateGraph(graphTypes[i]);
  435. }
  436. }
  437. Debug.LogError("Graph type ("+type+") wasn't found");
  438. return null;
  439. }
  440. /// <summary>
  441. /// Creates a new graph instance of type type
  442. /// See: <see cref="CreateGraph(string)"/>
  443. /// </summary>
  444. internal NavGraph CreateGraph (System.Type type) {
  445. var graph = System.Activator.CreateInstance(type) as NavGraph;
  446. graph.active = active;
  447. return graph;
  448. }
  449. /// <summary>
  450. /// Adds a graph of type type to the <see cref="graphs"/> array
  451. ///
  452. /// Deprecated:
  453. /// </summary>
  454. [System.Obsolete("Use AddGraph(System.Type) instead")]
  455. public NavGraph AddGraph (string type) {
  456. NavGraph graph = null;
  457. for (int i = 0; i < graphTypes.Length; i++) {
  458. if (graphTypes[i].Name == type) {
  459. graph = CreateGraph(graphTypes[i]);
  460. }
  461. }
  462. if (graph == null) {
  463. Debug.LogError("No NavGraph of type '"+type+"' could be found");
  464. return null;
  465. }
  466. AddGraph(graph);
  467. return graph;
  468. }
  469. /// <summary>
  470. /// Adds a graph of type type to the <see cref="graphs"/> array.
  471. /// See: runtime-graphs (view in online documentation for working links)
  472. /// </summary>
  473. public NavGraph AddGraph (System.Type type) {
  474. NavGraph graph = null;
  475. for (int i = 0; i < graphTypes.Length; i++) {
  476. if (System.Type.Equals(graphTypes[i], type)) {
  477. graph = CreateGraph(graphTypes[i]);
  478. }
  479. }
  480. if (graph == null) {
  481. Debug.LogError("No NavGraph of type '"+type+"' could be found, "+graphTypes.Length+" graph types are avaliable");
  482. return null;
  483. }
  484. AddGraph(graph);
  485. return graph;
  486. }
  487. /// <summary>Adds the specified graph to the <see cref="graphs"/> array</summary>
  488. void AddGraph (NavGraph graph) {
  489. // Make sure to not interfere with pathfinding
  490. var graphLock = AssertSafe(true);
  491. // Try to fill in an empty position
  492. bool foundEmpty = false;
  493. for (int i = 0; i < graphs.Length; i++) {
  494. if (graphs[i] == null) {
  495. graphs[i] = graph;
  496. graph.graphIndex = (uint)i;
  497. foundEmpty = true;
  498. break;
  499. }
  500. }
  501. if (!foundEmpty) {
  502. if (graphs != null && graphs.Length >= GraphNode.MaxGraphIndex) {
  503. throw new System.Exception("Graph Count Limit Reached. You cannot have more than " + GraphNode.MaxGraphIndex + " graphs.");
  504. }
  505. // Add a new entry to the list
  506. var graphList = new List<NavGraph>(graphs ?? new NavGraph[0]);
  507. graphList.Add(graph);
  508. graphs = graphList.ToArray();
  509. graph.graphIndex = (uint)(graphs.Length-1);
  510. }
  511. UpdateShortcuts();
  512. graph.active = active;
  513. graphLock.Release();
  514. }
  515. /// <summary>
  516. /// Removes the specified graph from the <see cref="graphs"/> array and Destroys it in a safe manner.
  517. /// To avoid changing graph indices for the other graphs, the graph is simply nulled in the array instead
  518. /// of actually removing it from the array.
  519. /// The empty position will be reused if a new graph is added.
  520. ///
  521. /// Returns: True if the graph was sucessfully removed (i.e it did exist in the <see cref="graphs"/> array). False otherwise.
  522. ///
  523. /// Version: Changed in 3.2.5 to call SafeOnDestroy before removing
  524. /// and nulling it in the array instead of removing the element completely in the <see cref="graphs"/> array.
  525. /// </summary>
  526. public bool RemoveGraph (NavGraph graph) {
  527. // Make sure the pathfinding threads are stopped
  528. // If we don't wait until pathfinding that is potentially running on
  529. // this graph right now we could end up with NullReferenceExceptions
  530. var graphLock = AssertSafe();
  531. ((IGraphInternals)graph).OnDestroy();
  532. graph.active = null;
  533. int i = System.Array.IndexOf(graphs, graph);
  534. if (i != -1) graphs[i] = null;
  535. UpdateShortcuts();
  536. graphLock.Release();
  537. return i != -1;
  538. }
  539. #endregion
  540. #region GraphUtility
  541. /// <summary>
  542. /// Returns the graph which contains the specified node.
  543. /// The graph must be in the <see cref="graphs"/> array.
  544. ///
  545. /// Returns: Returns the graph which contains the node. Null if the graph wasn't found
  546. /// </summary>
  547. public static NavGraph GetGraph (GraphNode node) {
  548. if (node == null) return null;
  549. AstarPath script = AstarPath.active;
  550. if (script == null) return null;
  551. AstarData data = script.data;
  552. if (data == null || data.graphs == null) return null;
  553. uint graphIndex = node.GraphIndex;
  554. if (graphIndex >= data.graphs.Length) {
  555. return null;
  556. }
  557. return data.graphs[(int)graphIndex];
  558. }
  559. /// <summary>Returns the first graph which satisfies the predicate. Returns null if no graph was found.</summary>
  560. public NavGraph FindGraph (System.Func<NavGraph, bool> predicate) {
  561. if (graphs != null) {
  562. for (int i = 0; i < graphs.Length; i++) {
  563. if (graphs[i] != null && predicate(graphs[i])) {
  564. return graphs[i];
  565. }
  566. }
  567. }
  568. return null;
  569. }
  570. /// <summary>Returns the first graph of type type found in the <see cref="graphs"/> array. Returns null if no graph was found.</summary>
  571. public NavGraph FindGraphOfType (System.Type type) {
  572. return FindGraph(graph => System.Type.Equals(graph.GetType(), type));
  573. }
  574. /// <summary>Returns the first graph which inherits from the type type. Returns null if no graph was found.</summary>
  575. public NavGraph FindGraphWhichInheritsFrom (System.Type type) {
  576. return FindGraph(graph => WindowsStoreCompatibility.GetTypeInfo(type).IsAssignableFrom(WindowsStoreCompatibility.GetTypeInfo(graph.GetType())));
  577. }
  578. /// <summary>
  579. /// Loop through this function to get all graphs of type 'type'
  580. /// <code>
  581. /// foreach (GridGraph graph in AstarPath.data.FindGraphsOfType (typeof(GridGraph))) {
  582. /// //Do something with the graph
  583. /// }
  584. /// </code>
  585. /// See: AstarPath.RegisterSafeNodeUpdate
  586. /// </summary>
  587. public IEnumerable FindGraphsOfType (System.Type type) {
  588. if (graphs == null) yield break;
  589. for (int i = 0; i < graphs.Length; i++) {
  590. if (graphs[i] != null && System.Type.Equals(graphs[i].GetType(), type)) {
  591. yield return graphs[i];
  592. }
  593. }
  594. }
  595. /// <summary>
  596. /// All graphs which implements the UpdateableGraph interface
  597. /// <code> foreach (IUpdatableGraph graph in AstarPath.data.GetUpdateableGraphs ()) {
  598. /// //Do something with the graph
  599. /// } </code>
  600. /// See: AstarPath.AddWorkItem
  601. /// See: Pathfinding.IUpdatableGraph
  602. /// </summary>
  603. public IEnumerable GetUpdateableGraphs () {
  604. if (graphs == null) yield break;
  605. for (int i = 0; i < graphs.Length; i++) {
  606. if (graphs[i] is IUpdatableGraph) {
  607. yield return graphs[i];
  608. }
  609. }
  610. }
  611. /// <summary>
  612. /// All graphs which implements the UpdateableGraph interface
  613. /// <code> foreach (IRaycastableGraph graph in AstarPath.data.GetRaycastableGraphs ()) {
  614. /// //Do something with the graph
  615. /// } </code>
  616. /// See: Pathfinding.IRaycastableGraph
  617. /// Deprecated: Deprecated because it is not used by the package internally and the use cases are few. Iterate through the <see cref="graphs"/> array instead.
  618. /// </summary>
  619. [System.Obsolete("Obsolete because it is not used by the package internally and the use cases are few. Iterate through the graphs array instead.")]
  620. public IEnumerable GetRaycastableGraphs () {
  621. if (graphs == null) yield break;
  622. for (int i = 0; i < graphs.Length; i++) {
  623. if (graphs[i] is IRaycastableGraph) {
  624. yield return graphs[i];
  625. }
  626. }
  627. }
  628. /// <summary>Gets the index of the NavGraph in the <see cref="graphs"/> array</summary>
  629. public int GetGraphIndex (NavGraph graph) {
  630. if (graph == null) throw new System.ArgumentNullException("graph");
  631. var index = -1;
  632. if (graphs != null) {
  633. index = System.Array.IndexOf(graphs, graph);
  634. if (index == -1) Debug.LogError("Graph doesn't exist");
  635. }
  636. return index;
  637. }
  638. #endregion
  639. }
  640. }