AstarPathEditor.cs 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392
  1. using UnityEngine;
  2. using UnityEditor;
  3. using System.Collections.Generic;
  4. using System.Reflection;
  5. namespace Pathfinding {
  6. [CustomEditor(typeof(AstarPath))]
  7. public class AstarPathEditor : Editor {
  8. /// <summary>List of all graph editors available (e.g GridGraphEditor)</summary>
  9. static Dictionary<string, CustomGraphEditorAttribute> graphEditorTypes = new Dictionary<string, CustomGraphEditorAttribute>();
  10. /// <summary>
  11. /// Holds node counts for each graph to avoid calculating it every frame.
  12. /// Only used for visualization purposes
  13. /// </summary>
  14. static Dictionary<NavGraph, KeyValuePair<float, KeyValuePair<int, int> > > graphNodeCounts;
  15. /// <summary>List of all graph editors for the graphs</summary>
  16. GraphEditor[] graphEditors;
  17. System.Type[] graphTypes {
  18. get {
  19. return script.data.graphTypes;
  20. }
  21. }
  22. static int lastUndoGroup = -1000;
  23. /// <summary>Used to make sure correct behaviour when handling undos</summary>
  24. static uint ignoredChecksum;
  25. const string scriptsFolder = "Assets/AstarPathfindingProject";
  26. #region SectionFlags
  27. static bool showSettings;
  28. static bool customAreaColorsOpen;
  29. static bool editTags;
  30. static FadeArea settingsArea;
  31. static FadeArea colorSettingsArea;
  32. static FadeArea editorSettingsArea;
  33. static FadeArea aboutArea;
  34. static FadeArea optimizationSettingsArea;
  35. static FadeArea serializationSettingsArea;
  36. static FadeArea tagsArea;
  37. static FadeArea graphsArea;
  38. static FadeArea addGraphsArea;
  39. static FadeArea alwaysVisibleArea;
  40. #endregion
  41. /// <summary>AstarPath instance that is being inspected</summary>
  42. public AstarPath script { get; private set; }
  43. #region Styles
  44. static bool stylesLoaded;
  45. public static GUISkin astarSkin { get; private set; }
  46. static GUIStyle level0AreaStyle, level0LabelStyle;
  47. static GUIStyle level1AreaStyle, level1LabelStyle;
  48. static GUIStyle graphDeleteButtonStyle, graphInfoButtonStyle, graphGizmoButtonStyle, graphEditNameButtonStyle;
  49. public static GUIStyle helpBox { get; private set; }
  50. public static GUIStyle thinHelpBox { get; private set; }
  51. #endregion
  52. /// <summary>Enables editor stuff. Loads graphs, reads settings and sets everything up</summary>
  53. public void OnEnable () {
  54. script = target as AstarPath;
  55. // Make sure all references are set up to avoid NullReferenceExceptions
  56. script.ConfigureReferencesInternal();
  57. Undo.undoRedoPerformed += OnUndoRedoPerformed;
  58. // Search the assembly for graph types and graph editors
  59. if (graphEditorTypes == null || graphEditorTypes.Count == 0)
  60. FindGraphTypes();
  61. try {
  62. GetAstarEditorSettings();
  63. } catch (System.Exception e) {
  64. Debug.LogException(e);
  65. }
  66. LoadStyles();
  67. // Load graphs only when not playing, or in extreme cases, when data.graphs is null
  68. if ((!Application.isPlaying && (script.data == null || script.data.graphs == null || script.data.graphs.Length == 0)) || script.data.graphs == null) {
  69. LoadGraphs();
  70. }
  71. CreateFadeAreas();
  72. }
  73. void CreateFadeAreas () {
  74. if (settingsArea == null) {
  75. aboutArea = new FadeArea(false, this, level0AreaStyle, level0LabelStyle);
  76. optimizationSettingsArea = new FadeArea(false, this, level0AreaStyle, level0LabelStyle);
  77. graphsArea = new FadeArea(false, this, level0AreaStyle, level0LabelStyle);
  78. serializationSettingsArea = new FadeArea(false, this, level0AreaStyle, level0LabelStyle);
  79. settingsArea = new FadeArea(showSettings, this, level0AreaStyle, level0LabelStyle);
  80. addGraphsArea = new FadeArea(false, this, level1AreaStyle, level1LabelStyle);
  81. colorSettingsArea = new FadeArea(false, this, level1AreaStyle, level1LabelStyle);
  82. editorSettingsArea = new FadeArea(false, this, level1AreaStyle, level1LabelStyle);
  83. alwaysVisibleArea = new FadeArea(true, this, level1AreaStyle, level1LabelStyle);
  84. tagsArea = new FadeArea(editTags, this, level1AreaStyle, level1LabelStyle);
  85. }
  86. }
  87. /// <summary>Cleans up editor stuff</summary>
  88. public void OnDisable () {
  89. Undo.undoRedoPerformed -= OnUndoRedoPerformed;
  90. if (target == null) {
  91. return;
  92. }
  93. SetAstarEditorSettings();
  94. CheckGraphEditors();
  95. SaveGraphsAndUndo();
  96. }
  97. /// <summary>Reads settings frome EditorPrefs</summary>
  98. void GetAstarEditorSettings () {
  99. FadeArea.fancyEffects = EditorPrefs.GetBool("EditorGUILayoutx.fancyEffects", true);
  100. }
  101. void SetAstarEditorSettings () {
  102. EditorPrefs.SetBool("EditorGUILayoutx.fancyEffects", FadeArea.fancyEffects);
  103. }
  104. /// <summary>Checks if JS support is enabled. This is done by checking if the directory 'Assets/AstarPathfindingEditor/Editor' exists</summary>
  105. static bool IsJsEnabled () {
  106. return System.IO.Directory.Exists(Application.dataPath+"/AstarPathfindingEditor/Editor");
  107. }
  108. /// <summary>
  109. /// Enables JS support.
  110. /// This is done by restructuring folders in the project.
  111. /// See: javascript (view in online documentation for working links)
  112. /// </summary>
  113. static void EnableJs () {
  114. // Path to the project folder (with /Assets at the end)
  115. string projectPath = Application.dataPath;
  116. if (projectPath.EndsWith("/Assets")) {
  117. projectPath = projectPath.Remove(projectPath.Length-("Assets".Length));
  118. }
  119. if (!System.IO.Directory.Exists(projectPath + scriptsFolder)) {
  120. string error = "Could not enable Js support. AstarPathfindingProject folder did not exist in the default location.\n" +
  121. "If you get this message and the AstarPathfindingProject is not at the root of your Assets folder (i.e at Assets/AstarPathfindingProject)" +
  122. " then you should move it to the root";
  123. Debug.LogError(error);
  124. EditorUtility.DisplayDialog("Could not enable Js support", error, "ok");
  125. return;
  126. }
  127. if (!System.IO.Directory.Exists(Application.dataPath+"/AstarPathfindingEditor")) {
  128. System.IO.Directory.CreateDirectory(Application.dataPath+"/AstarPathfindingEditor");
  129. AssetDatabase.Refresh();
  130. }
  131. if (!System.IO.Directory.Exists(Application.dataPath+"/Plugins")) {
  132. System.IO.Directory.CreateDirectory(Application.dataPath+"/Plugins");
  133. AssetDatabase.Refresh();
  134. }
  135. AssetDatabase.MoveAsset(scriptsFolder + "/Editor", "Assets/AstarPathfindingEditor/Editor");
  136. AssetDatabase.MoveAsset(scriptsFolder, "Assets/Plugins/AstarPathfindingProject");
  137. AssetDatabase.Refresh();
  138. }
  139. /// <summary>Disables JS support if it was enabled. This is done by restructuring folders in the project</summary>
  140. static void DisableJs () {
  141. if (System.IO.Directory.Exists(Application.dataPath+"/Plugins/AstarPathfindingProject")) {
  142. string error = AssetDatabase.MoveAsset("Assets/Plugins/AstarPathfindingProject", scriptsFolder);
  143. if (error != "") {
  144. Debug.LogError("Couldn't disable Js - "+error);
  145. } else {
  146. try {
  147. System.IO.Directory.Delete(Application.dataPath+"/Plugins");
  148. } catch (System.Exception) {}
  149. }
  150. } else {
  151. Debug.LogWarning("Could not disable JS - Could not find directory '"+Application.dataPath+"/Plugins/AstarPathfindingProject'");
  152. }
  153. if (System.IO.Directory.Exists(Application.dataPath+"/AstarPathfindingEditor/Editor")) {
  154. string error = AssetDatabase.MoveAsset("Assets/AstarPathfindingEditor/Editor", scriptsFolder + "/Editor");
  155. if (error != "") {
  156. Debug.LogError("Couldn't disable Js - "+error);
  157. } else {
  158. try {
  159. System.IO.Directory.Delete(Application.dataPath+"/AstarPathfindingEditor");
  160. } catch (System.Exception) {}
  161. }
  162. } else {
  163. Debug.LogWarning("Could not disable JS - Could not find directory '"+Application.dataPath+"/AstarPathfindingEditor/Editor'");
  164. }
  165. AssetDatabase.Refresh();
  166. }
  167. /// <summary>
  168. /// Repaints Scene View.
  169. /// Warning: Uses Undocumented Unity Calls (should be safe for Unity 3.x though)
  170. /// </summary>
  171. void RepaintSceneView () {
  172. if (!Application.isPlaying || EditorApplication.isPaused) SceneView.RepaintAll();
  173. }
  174. /// <summary>Tell Unity that we want to use the whole inspector width</summary>
  175. public override bool UseDefaultMargins () {
  176. return false;
  177. }
  178. public override void OnInspectorGUI () {
  179. // Do some loading and checking
  180. if (!LoadStyles()) {
  181. EditorGUILayout.HelpBox("The GUISkin 'AstarEditorSkin.guiskin' in the folder "+EditorResourceHelper.editorAssets+"/ was not found or some custom styles in it does not exist.\n"+
  182. "This file is required for the A* Pathfinding Project editor.\n\n"+
  183. "If you are trying to add A* to a new project, please do not copy the files outside Unity, "+
  184. "export them as a UnityPackage and import them to this project or download the package from the Asset Store"+
  185. "or the 'scripts only' package from the A* Pathfinding Project website.\n\n\n"+
  186. "Skin loading is done in the AstarPathEditor.cs --> LoadStyles method", MessageType.Error);
  187. return;
  188. }
  189. #if ASTAR_ATAVISM
  190. EditorGUILayout.HelpBox("This is a special version of the A* Pathfinding Project for Atavism. This version only supports scanning recast graphs and exporting them, but no pathfinding during runtime.", MessageType.Info);
  191. #endif
  192. EditorGUI.BeginChangeCheck();
  193. Undo.RecordObject(script, "A* inspector");
  194. CheckGraphEditors();
  195. // End loading and checking
  196. EditorGUI.indentLevel = 1;
  197. // Apparently these can sometimes get eaten by unity components
  198. // so I catch them here for later use
  199. EventType storedEventType = Event.current.type;
  200. string storedEventCommand = Event.current.commandName;
  201. DrawMainArea();
  202. GUILayout.Space(5);
  203. if (GUILayout.Button(new GUIContent("Scan", "Recalculate all graphs. Shortcut cmd+alt+s ( ctrl+alt+s on windows )"))) {
  204. MenuScan();
  205. }
  206. #if ProfileAstar
  207. if (GUILayout.Button("Log Profiles")) {
  208. AstarProfiler.PrintResults();
  209. AstarProfiler.PrintFastResults();
  210. AstarProfiler.Reset();
  211. }
  212. #endif
  213. // Handle undo
  214. SaveGraphsAndUndo(storedEventType, storedEventCommand);
  215. if (EditorGUI.EndChangeCheck()) {
  216. RepaintSceneView();
  217. EditorUtility.SetDirty(script);
  218. }
  219. }
  220. /// <summary>
  221. /// Loads GUISkin and sets up styles.
  222. /// See: EditorResourceHelper.LocateEditorAssets
  223. /// Returns: True if all styles were found, false if there was an error somewhere
  224. /// </summary>
  225. static bool LoadStyles () {
  226. if (stylesLoaded) return true;
  227. // Dummy styles in case the loading fails
  228. var inspectorSkin = EditorGUIUtility.GetBuiltinSkin(EditorSkin.Inspector);
  229. if (!EditorResourceHelper.LocateEditorAssets()) {
  230. return false;
  231. }
  232. var skinPath = EditorResourceHelper.editorAssets + "/AstarEditorSkin" + (EditorGUIUtility.isProSkin ? "Dark" : "Light") + ".guiskin";
  233. astarSkin = AssetDatabase.LoadAssetAtPath(skinPath, typeof(GUISkin)) as GUISkin;
  234. if (astarSkin != null) {
  235. astarSkin.button = inspectorSkin.button;
  236. } else {
  237. Debug.LogWarning("Could not load editor skin at '" + skinPath + "'");
  238. return false;
  239. }
  240. level0AreaStyle = astarSkin.FindStyle("PixelBox");
  241. // If the first style is null, then the rest are likely corrupted as well
  242. // Probably due to the user not copying meta files
  243. if (level0AreaStyle == null) {
  244. return false;
  245. }
  246. level1LabelStyle = astarSkin.FindStyle("BoxHeader");
  247. level0LabelStyle = astarSkin.FindStyle("TopBoxHeader");
  248. level1AreaStyle = astarSkin.FindStyle("PixelBox3");
  249. graphDeleteButtonStyle = astarSkin.FindStyle("PixelButton");
  250. graphInfoButtonStyle = astarSkin.FindStyle("InfoButton");
  251. graphGizmoButtonStyle = astarSkin.FindStyle("GizmoButton");
  252. graphEditNameButtonStyle = astarSkin.FindStyle("EditButton");
  253. helpBox = inspectorSkin.FindStyle("HelpBox") ?? inspectorSkin.box;
  254. thinHelpBox = new GUIStyle(helpBox);
  255. thinHelpBox.stretchWidth = false;
  256. thinHelpBox.clipping = TextClipping.Overflow;
  257. thinHelpBox.overflow.bottom += 2;
  258. stylesLoaded = true;
  259. return true;
  260. }
  261. /// <summary>Draws the main area in the inspector</summary>
  262. void DrawMainArea () {
  263. CheckGraphEditors();
  264. graphsArea.Begin();
  265. graphsArea.Header("Graphs", ref script.showGraphs);
  266. if (graphsArea.BeginFade()) {
  267. bool anyNonNull = false;
  268. for (int i = 0; i < script.graphs.Length; i++) {
  269. if (script.graphs[i] != null) {
  270. anyNonNull = true;
  271. DrawGraph(graphEditors[i]);
  272. }
  273. }
  274. // Draw the Add Graph button
  275. addGraphsArea.Begin();
  276. addGraphsArea.open |= !anyNonNull;
  277. addGraphsArea.Header("Add New Graph");
  278. if (addGraphsArea.BeginFade()) {
  279. if (graphTypes == null) script.data.FindGraphTypes();
  280. for (int i = 0; i < graphTypes.Length; i++) {
  281. if (graphEditorTypes.ContainsKey(graphTypes[i].Name)) {
  282. if (GUILayout.Button(graphEditorTypes[graphTypes[i].Name].displayName)) {
  283. addGraphsArea.open = false;
  284. AddGraph(graphTypes[i]);
  285. }
  286. } else if (!graphTypes[i].Name.Contains("Base")) {
  287. EditorGUI.BeginDisabledGroup(true);
  288. GUILayout.Label(graphTypes[i].Name + " (no editor found)", "Button");
  289. EditorGUI.EndDisabledGroup();
  290. }
  291. }
  292. }
  293. addGraphsArea.End();
  294. }
  295. graphsArea.End();
  296. DrawSettings();
  297. DrawSerializationSettings();
  298. DrawOptimizationSettings();
  299. DrawAboutArea();
  300. bool showNavGraphs = EditorGUILayout.Toggle("Show Graphs", script.showNavGraphs);
  301. if (script.showNavGraphs != showNavGraphs) {
  302. script.showNavGraphs = showNavGraphs;
  303. RepaintSceneView();
  304. }
  305. }
  306. /// <summary>Draws optimizations settings.</summary>
  307. void DrawOptimizationSettings () {
  308. optimizationSettingsArea.Begin();
  309. optimizationSettingsArea.Header("Optimization");
  310. if (optimizationSettingsArea.BeginFade()) {
  311. GUIUtilityx.PushTint(Color.Lerp(Color.yellow, Color.white, 0.5F));
  312. if (GUILayout.Button("Optimizations is an A* Pathfinding Project Pro only feature\nThe Pro version can be bought on the A* Pathfinding Project homepage, click here for info", helpBox)) {
  313. Application.OpenURL(AstarUpdateChecker.GetURL("astarpro"));
  314. }
  315. GUIUtilityx.PopTint();
  316. }
  317. optimizationSettingsArea.End();
  318. }
  319. /// <summary>
  320. /// Returns a version with all fields fully defined.
  321. /// This is used because by default new Version(3,0,0) > new Version(3,0).
  322. /// This is not the desired behaviour so we make sure that all fields are defined here
  323. /// </summary>
  324. public static System.Version FullyDefinedVersion (System.Version v) {
  325. return new System.Version(Mathf.Max(v.Major, 0), Mathf.Max(v.Minor, 0), Mathf.Max(v.Build, 0), Mathf.Max(v.Revision, 0));
  326. }
  327. void DrawAboutArea () {
  328. aboutArea.Begin();
  329. GUILayout.BeginHorizontal();
  330. if (GUILayout.Button("About", level0LabelStyle)) {
  331. aboutArea.open = !aboutArea.open;
  332. GUI.changed = true;
  333. }
  334. #if !ASTAR_ATAVISM
  335. System.Version newVersion = AstarUpdateChecker.latestVersion;
  336. bool beta = false;
  337. // Check if either the latest release version or the latest beta version is newer than this version
  338. if (FullyDefinedVersion(AstarUpdateChecker.latestVersion) > FullyDefinedVersion(AstarPath.Version) || FullyDefinedVersion(AstarUpdateChecker.latestBetaVersion) > FullyDefinedVersion(AstarPath.Version)) {
  339. if (FullyDefinedVersion(AstarUpdateChecker.latestVersion) <= FullyDefinedVersion(AstarPath.Version)) {
  340. newVersion = AstarUpdateChecker.latestBetaVersion;
  341. beta = true;
  342. }
  343. }
  344. // Check if the latest version is newer than this version
  345. if (FullyDefinedVersion(newVersion) > FullyDefinedVersion(AstarPath.Version)) {
  346. GUIUtilityx.PushTint(Color.green);
  347. if (GUILayout.Button((beta ? "Beta" : "New") + " Version Available! "+newVersion, thinHelpBox, GUILayout.Height(15))) {
  348. Application.OpenURL(AstarUpdateChecker.GetURL("download"));
  349. }
  350. GUIUtilityx.PopTint();
  351. GUILayout.Space(20);
  352. }
  353. #endif
  354. GUILayout.EndHorizontal();
  355. if (aboutArea.BeginFade()) {
  356. GUILayout.Label("The A* Pathfinding Project was made by Aron Granberg\nYour current version is "+AstarPath.Version);
  357. #if !ASTAR_ATAVISM
  358. if (FullyDefinedVersion(newVersion) > FullyDefinedVersion(AstarPath.Version)) {
  359. EditorGUILayout.HelpBox("A new "+(beta ? "beta " : "")+"version of the A* Pathfinding Project is available, the new version is "+
  360. newVersion, MessageType.Info);
  361. if (GUILayout.Button("What's new?")) {
  362. Application.OpenURL(AstarUpdateChecker.GetURL(beta ? "beta_changelog" : "changelog"));
  363. }
  364. if (GUILayout.Button("Click here to find out more")) {
  365. Application.OpenURL(AstarUpdateChecker.GetURL("findoutmore"));
  366. }
  367. GUIUtilityx.PushTint(new Color(0.3F, 0.9F, 0.3F));
  368. if (GUILayout.Button("Download new version")) {
  369. Application.OpenURL(AstarUpdateChecker.GetURL("download"));
  370. }
  371. GUIUtilityx.PopTint();
  372. }
  373. #endif
  374. if (GUILayout.Button(new GUIContent("Documentation", "Open the documentation for the A* Pathfinding Project"))) {
  375. Application.OpenURL(AstarUpdateChecker.GetURL("documentation"));
  376. }
  377. if (GUILayout.Button(new GUIContent("Project Homepage", "Open the homepage for the A* Pathfinding Project"))) {
  378. Application.OpenURL(AstarUpdateChecker.GetURL("homepage"));
  379. }
  380. }
  381. aboutArea.End();
  382. }
  383. /// <summary>Graph editor which has its 'name' field focused</summary>
  384. GraphEditor graphNameFocused;
  385. void DrawGraphHeader (GraphEditor graphEditor) {
  386. var graph = graphEditor.target;
  387. // Graph guid, just used to get a unique value
  388. string graphGUIDString = graph.guid.ToString();
  389. GUILayout.BeginHorizontal();
  390. if (graphNameFocused == graphEditor) {
  391. GUI.SetNextControlName(graphGUIDString);
  392. graph.name = GUILayout.TextField(graph.name ?? "", level1LabelStyle, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(false));
  393. // Mark the name field as deselected when it has been deselected or when the user presses Return or Escape
  394. if ((Event.current.type == EventType.Repaint && GUI.GetNameOfFocusedControl() != graphGUIDString) || (Event.current.type == EventType.KeyUp && (Event.current.keyCode == KeyCode.Return || Event.current.keyCode == KeyCode.Escape))) {
  395. if (Event.current.type == EventType.KeyUp) Event.current.Use();
  396. graphNameFocused = null;
  397. }
  398. } else {
  399. // If the graph name text field is not focused and the graph name is empty, then fill it in
  400. if (graph.name == null || graph.name == "") graph.name = graphEditorTypes[graph.GetType().Name].displayName;
  401. if (GUILayout.Button(graph.name, level1LabelStyle)) {
  402. graphEditor.fadeArea.open = graph.open = !graph.open;
  403. if (!graph.open) {
  404. graph.infoScreenOpen = false;
  405. }
  406. RepaintSceneView();
  407. }
  408. }
  409. if (script.prioritizeGraphs) {
  410. var moveUp = GUILayout.Button(new GUIContent("Up", "Increase the graph priority"), GUILayout.Width(40));
  411. var moveDown = GUILayout.Button(new GUIContent("Down", "Decrease the graph priority"), GUILayout.Width(40));
  412. if (moveUp || moveDown) {
  413. int index = script.data.GetGraphIndex(graph);
  414. int next;
  415. if (moveUp) {
  416. // Find the previous non null graph
  417. next = index-1;
  418. for (; next >= 0; next--) if (script.graphs[next] != null) break;
  419. } else {
  420. // Find the next non null graph
  421. next = index+1;
  422. for (; next < script.graphs.Length; next++) if (script.graphs[next] != null) break;
  423. }
  424. if (next >= 0 && next < script.graphs.Length) {
  425. NavGraph tmp = script.graphs[next];
  426. script.graphs[next] = graph;
  427. script.graphs[index] = tmp;
  428. GraphEditor tmpEditor = graphEditors[next];
  429. graphEditors[next] = graphEditors[index];
  430. graphEditors[index] = tmpEditor;
  431. }
  432. CheckGraphEditors();
  433. Repaint();
  434. }
  435. }
  436. // The OnInspectorGUI method ensures that the scene view is repainted when gizmos are toggled on or off by checking for EndChangeCheck
  437. graph.drawGizmos = GUILayout.Toggle(graph.drawGizmos, new GUIContent("Draw Gizmos", "Draw Gizmos"), graphGizmoButtonStyle);
  438. if (GUILayout.Button(new GUIContent("", "Edit Name"), graphEditNameButtonStyle)) {
  439. graphNameFocused = graphEditor;
  440. GUI.FocusControl(graphGUIDString);
  441. }
  442. if (GUILayout.Toggle(graph.infoScreenOpen, new GUIContent("Info", "Info"), graphInfoButtonStyle)) {
  443. if (!graph.infoScreenOpen) {
  444. graphEditor.infoFadeArea.open = graph.infoScreenOpen = true;
  445. graphEditor.fadeArea.open = graph.open = true;
  446. }
  447. } else {
  448. graphEditor.infoFadeArea.open = graph.infoScreenOpen = false;
  449. }
  450. if (GUILayout.Button(new GUIContent("Delete", "Delete"), graphDeleteButtonStyle)) {
  451. RemoveGraph(graph);
  452. }
  453. GUILayout.EndHorizontal();
  454. }
  455. void DrawGraphInfoArea (GraphEditor graphEditor) {
  456. graphEditor.infoFadeArea.Begin();
  457. if (graphEditor.infoFadeArea.BeginFade()) {
  458. bool anyNodesNull = false;
  459. int total = 0;
  460. int numWalkable = 0;
  461. // Calculate number of nodes in the graph
  462. KeyValuePair<float, KeyValuePair<int, int> > pair;
  463. graphNodeCounts = graphNodeCounts ?? new Dictionary<NavGraph, KeyValuePair<float, KeyValuePair<int, int> > >();
  464. if (!graphNodeCounts.TryGetValue(graphEditor.target, out pair) || (Time.realtimeSinceStartup-pair.Key) > 2) {
  465. graphEditor.target.GetNodes(node => {
  466. if (node == null) {
  467. anyNodesNull = true;
  468. } else {
  469. total++;
  470. if (node.Walkable) numWalkable++;
  471. }
  472. });
  473. pair = new KeyValuePair<float, KeyValuePair<int, int> >(Time.realtimeSinceStartup, new KeyValuePair<int, int>(total, numWalkable));
  474. graphNodeCounts[graphEditor.target] = pair;
  475. }
  476. total = pair.Value.Key;
  477. numWalkable = pair.Value.Value;
  478. EditorGUI.indentLevel++;
  479. if (anyNodesNull) {
  480. Debug.LogError("Some nodes in the graph are null. Please report this error.");
  481. }
  482. EditorGUILayout.LabelField("Nodes", total.ToString());
  483. EditorGUILayout.LabelField("Walkable", numWalkable.ToString());
  484. EditorGUILayout.LabelField("Unwalkable", (total-numWalkable).ToString());
  485. if (total == 0) EditorGUILayout.HelpBox("The number of nodes in the graph is zero. The graph might not be scanned", MessageType.Info);
  486. EditorGUI.indentLevel--;
  487. }
  488. graphEditor.infoFadeArea.End();
  489. }
  490. /// <summary>Draws the inspector for the given graph with the given graph editor</summary>
  491. void DrawGraph (GraphEditor graphEditor) {
  492. graphEditor.fadeArea.Begin();
  493. DrawGraphHeader(graphEditor);
  494. if (graphEditor.fadeArea.BeginFade()) {
  495. DrawGraphInfoArea(graphEditor);
  496. graphEditor.OnInspectorGUI(graphEditor.target);
  497. graphEditor.OnBaseInspectorGUI(graphEditor.target);
  498. }
  499. graphEditor.fadeArea.End();
  500. }
  501. public void OnSceneGUI () {
  502. script = target as AstarPath;
  503. // OnSceneGUI may be called from EditorUtility.DisplayProgressBar
  504. // which is called repeatedly while the graphs are scanned in the
  505. // editor. However running the OnSceneGUI method while the graphs
  506. // are being scanned is a bad idea since it can interfere with
  507. // scanning, especially by serializing changes
  508. if (script.isScanning) {
  509. return;
  510. }
  511. script.ConfigureReferencesInternal();
  512. EditorGUI.BeginChangeCheck();
  513. if (!LoadStyles()) return;
  514. // Some GUI controls might change this to Used, so we need to grab it here
  515. EventType et = Event.current.type;
  516. CheckGraphEditors();
  517. for (int i = 0; i < script.graphs.Length; i++) {
  518. NavGraph graph = script.graphs[i];
  519. if (graph != null) {
  520. graphEditors[i].OnSceneGUI(graph);
  521. }
  522. }
  523. SaveGraphsAndUndo(et);
  524. if (EditorGUI.EndChangeCheck()) {
  525. EditorUtility.SetDirty(target);
  526. }
  527. }
  528. TextAsset SaveGraphData (byte[] bytes, TextAsset target = null) {
  529. string projectPath = System.IO.Path.GetDirectoryName(Application.dataPath) + "/";
  530. string path;
  531. if (target != null) {
  532. path = AssetDatabase.GetAssetPath(target);
  533. } else {
  534. // Find a valid file name
  535. int i = 0;
  536. do {
  537. path = "Assets/GraphCaches/GraphCache" + (i == 0 ? "" : i.ToString()) + ".bytes";
  538. i++;
  539. } while (System.IO.File.Exists(projectPath+path));
  540. }
  541. string fullPath = projectPath + path;
  542. System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(fullPath));
  543. var fileInfo = new System.IO.FileInfo(fullPath);
  544. // Make sure we can write to the file
  545. if (fileInfo.Exists && fileInfo.IsReadOnly)
  546. fileInfo.IsReadOnly = false;
  547. System.IO.File.WriteAllBytes(fullPath, bytes);
  548. AssetDatabase.Refresh();
  549. return AssetDatabase.LoadAssetAtPath<TextAsset>(path);
  550. }
  551. void DrawSerializationSettings () {
  552. serializationSettingsArea.Begin();
  553. GUILayout.BeginHorizontal();
  554. if (GUILayout.Button("Save & Load", level0LabelStyle)) {
  555. serializationSettingsArea.open = !serializationSettingsArea.open;
  556. }
  557. if (script.data.cacheStartup && script.data.file_cachedStartup != null) {
  558. GUIUtilityx.PushTint(Color.yellow);
  559. GUILayout.Label("Startup cached", thinHelpBox, GUILayout.Height(15));
  560. GUILayout.Space(20);
  561. GUIUtilityx.PopTint();
  562. }
  563. GUILayout.EndHorizontal();
  564. // This displays the serialization settings
  565. if (serializationSettingsArea.BeginFade()) {
  566. script.data.cacheStartup = EditorGUILayout.Toggle(new GUIContent("Cache startup", "If enabled, will cache the graphs so they don't have to be scanned at startup"), script.data.cacheStartup);
  567. script.data.file_cachedStartup = EditorGUILayout.ObjectField(script.data.file_cachedStartup, typeof(TextAsset), false) as TextAsset;
  568. if (script.data.cacheStartup && script.data.file_cachedStartup == null) {
  569. EditorGUILayout.HelpBox("No cache has been generated", MessageType.Error);
  570. }
  571. if (script.data.cacheStartup && script.data.file_cachedStartup != null) {
  572. EditorGUILayout.HelpBox("All graph settings will be replaced with the ones from the cache when the game starts", MessageType.Info);
  573. }
  574. GUILayout.BeginHorizontal();
  575. if (GUILayout.Button("Generate cache")) {
  576. var serializationSettings = new Pathfinding.Serialization.SerializeSettings();
  577. serializationSettings.nodes = true;
  578. if (EditorUtility.DisplayDialog("Scan before generating cache?", "Do you want to scan the graphs before saving the cache.\n" +
  579. "If the graphs have not been scanned then the cache may not contain node data and then the graphs will have to be scanned at startup anyway.", "Scan", "Don't scan")) {
  580. MenuScan();
  581. }
  582. // Save graphs
  583. var bytes = script.data.SerializeGraphs(serializationSettings);
  584. // Store it in a file
  585. script.data.file_cachedStartup = SaveGraphData(bytes, script.data.file_cachedStartup);
  586. script.data.cacheStartup = true;
  587. }
  588. if (GUILayout.Button("Load from cache")) {
  589. if (EditorUtility.DisplayDialog("Are you sure you want to load from cache?", "Are you sure you want to load graphs from the cache, this will replace your current graphs?", "Yes", "Cancel")) {
  590. script.data.LoadFromCache();
  591. }
  592. }
  593. GUILayout.EndHorizontal();
  594. if (script.data.data_cachedStartup != null && script.data.data_cachedStartup.Length > 0) {
  595. EditorGUILayout.HelpBox("Storing the cached starup data on the AstarPath object has been deprecated. It is now stored " +
  596. "in a separate file.", MessageType.Error);
  597. if (GUILayout.Button("Transfer cache data to separate file")) {
  598. script.data.file_cachedStartup = SaveGraphData(script.data.data_cachedStartup);
  599. script.data.data_cachedStartup = null;
  600. }
  601. }
  602. GUILayout.Space(5);
  603. GUILayout.BeginHorizontal();
  604. if (GUILayout.Button("Save to file")) {
  605. string path = EditorUtility.SaveFilePanel("Save Graphs", "", "graph.bytes", "bytes");
  606. if (path != "") {
  607. var serializationSettings = Pathfinding.Serialization.SerializeSettings.Settings;
  608. if (EditorUtility.DisplayDialog("Include node data?", "Do you want to include node data in the save file. " +
  609. "If node data is included the graph can be restored completely without having to scan it first.", "Include node data", "Only settings")) {
  610. serializationSettings.nodes = true;
  611. }
  612. if (serializationSettings.nodes && EditorUtility.DisplayDialog("Scan before saving?", "Do you want to scan the graphs before saving? " +
  613. "\nNot scanning can cause node data to be omitted from the file if the graph is not yet scanned.", "Scan", "Don't scan")) {
  614. MenuScan();
  615. }
  616. uint checksum;
  617. var bytes = SerializeGraphs(serializationSettings, out checksum);
  618. Pathfinding.Serialization.AstarSerializer.SaveToFile(path, bytes);
  619. EditorUtility.DisplayDialog("Done Saving", "Done saving graph data.", "Ok");
  620. }
  621. }
  622. if (GUILayout.Button("Load from file")) {
  623. string path = EditorUtility.OpenFilePanel("Load Graphs", "", "");
  624. if (path != "") {
  625. try {
  626. byte[] bytes = Pathfinding.Serialization.AstarSerializer.LoadFromFile(path);
  627. DeserializeGraphs(bytes);
  628. } catch (System.Exception e) {
  629. Debug.LogError("Could not load from file at '"+path+"'\n"+e);
  630. }
  631. }
  632. }
  633. GUILayout.EndHorizontal();
  634. }
  635. serializationSettingsArea.End();
  636. }
  637. void DrawSettings () {
  638. settingsArea.Begin();
  639. settingsArea.Header("Settings", ref showSettings);
  640. if (settingsArea.BeginFade()) {
  641. DrawPathfindingSettings();
  642. DrawDebugSettings();
  643. DrawColorSettings();
  644. DrawTagSettings();
  645. DrawEditorSettings();
  646. }
  647. settingsArea.End();
  648. }
  649. void DrawPathfindingSettings () {
  650. alwaysVisibleArea.Begin();
  651. alwaysVisibleArea.HeaderLabel("Pathfinding");
  652. alwaysVisibleArea.BeginFade();
  653. #if !ASTAR_ATAVISM
  654. EditorGUI.BeginDisabledGroup(Application.isPlaying);
  655. script.threadCount = (ThreadCount)EditorGUILayout.EnumPopup(new GUIContent("Thread Count", "Number of threads to run the pathfinding in (if any). More threads " +
  656. "can boost performance on multi core systems. \n" +
  657. "Use None for debugging or if you dont use pathfinding that much.\n " +
  658. "See docs for more info"), script.threadCount);
  659. EditorGUI.EndDisabledGroup();
  660. int threads = AstarPath.CalculateThreadCount(script.threadCount);
  661. if (threads > 0) EditorGUILayout.HelpBox("Using " + threads +" thread(s)" + (script.threadCount < 0 ? " on your machine" : "") + ".\n" +
  662. "The free version of the A* Pathfinding Project is limited to at most one thread.", MessageType.None);
  663. else EditorGUILayout.HelpBox("Using a single coroutine (no threads)" + (script.threadCount < 0 ? " on your machine" : ""), MessageType.None);
  664. if (script.threadCount == ThreadCount.None) {
  665. script.maxFrameTime = EditorGUILayout.FloatField(new GUIContent("Max Frame Time", "Max number of milliseconds to use for path calculation per frame"), script.maxFrameTime);
  666. } else {
  667. script.maxFrameTime = 10;
  668. }
  669. script.maxNearestNodeDistance = EditorGUILayout.FloatField(new GUIContent("Max Nearest Node Distance",
  670. "Normally, if the nearest node to e.g the start point of a path was not walkable" +
  671. " a search will be done for the nearest node which is walkble. This is the maximum distance (world units) which it will search"),
  672. script.maxNearestNodeDistance);
  673. script.heuristic = (Heuristic)EditorGUILayout.EnumPopup("Heuristic", script.heuristic);
  674. if (script.heuristic == Heuristic.Manhattan || script.heuristic == Heuristic.Euclidean || script.heuristic == Heuristic.DiagonalManhattan) {
  675. EditorGUI.indentLevel++;
  676. script.heuristicScale = EditorGUILayout.FloatField("Heuristic Scale", script.heuristicScale);
  677. EditorGUI.indentLevel--;
  678. }
  679. GUILayout.Label(new GUIContent("Advanced"), EditorStyles.boldLabel);
  680. DrawHeuristicOptimizationSettings();
  681. script.batchGraphUpdates = EditorGUILayout.Toggle(new GUIContent("Batch Graph Updates", "Limit graph updates to only run every x seconds. Can have positive impact on performance if many graph updates are done"), script.batchGraphUpdates);
  682. if (script.batchGraphUpdates) {
  683. EditorGUI.indentLevel++;
  684. script.graphUpdateBatchingInterval = EditorGUILayout.FloatField(new GUIContent("Update Interval (s)", "Minimum number of seconds between each batch of graph updates"), script.graphUpdateBatchingInterval);
  685. EditorGUI.indentLevel--;
  686. }
  687. // Only show if there is actually a navmesh/recast graph in the scene
  688. // to help reduce clutter for other users.
  689. if (script.data.FindGraphWhichInheritsFrom(typeof(NavmeshBase)) != null) {
  690. script.navmeshUpdates.updateInterval = EditorGUILayout.FloatField(new GUIContent("Navmesh Cutting Update Interval (s)", "How often to check if any navmesh cut has changed."), script.navmeshUpdates.updateInterval);
  691. }
  692. script.prioritizeGraphs = EditorGUILayout.Toggle(new GUIContent("Prioritize Graphs", "Normally, the system will search for the closest node in all graphs and choose the closest one" +
  693. "but if Prioritize Graphs is enabled, the first graph which has a node closer than Priority Limit will be chosen and additional search (e.g for the closest WALKABLE node) will be carried out on that graph only"),
  694. script.prioritizeGraphs);
  695. if (script.prioritizeGraphs) {
  696. EditorGUI.indentLevel++;
  697. script.prioritizeGraphsLimit = EditorGUILayout.FloatField("Priority Limit", script.prioritizeGraphsLimit);
  698. EditorGUI.indentLevel--;
  699. }
  700. script.fullGetNearestSearch = EditorGUILayout.Toggle(new GUIContent("Full Get Nearest Node Search", "Forces more accurate searches on all graphs. " +
  701. "Normally only the closest graph in the initial fast check will perform additional searches, " +
  702. "if this is toggled, all graphs will do additional searches. Slower, but more accurate"), script.fullGetNearestSearch);
  703. #endif
  704. script.scanOnStartup = EditorGUILayout.Toggle(new GUIContent("Scan on Awake", "Scan all graphs on Awake. If this is false, you must call AstarPath.active.Scan () yourself. Useful if you want to make changes to the graphs with code."), script.scanOnStartup);
  705. alwaysVisibleArea.End();
  706. }
  707. void DrawHeuristicOptimizationSettings () {
  708. // Pro only feature
  709. }
  710. /// <summary>Opens the A* Inspector and shows the section for editing tags</summary>
  711. public static void EditTags () {
  712. AstarPath astar = GameObject.FindObjectOfType<AstarPath>();
  713. if (astar != null) {
  714. editTags = true;
  715. showSettings = true;
  716. Selection.activeGameObject = astar.gameObject;
  717. } else {
  718. Debug.LogWarning("No AstarPath component in the scene");
  719. }
  720. }
  721. void DrawTagSettings () {
  722. tagsArea.Begin();
  723. tagsArea.Header("Tag Names", ref editTags);
  724. if (tagsArea.BeginFade()) {
  725. string[] tagNames = script.GetTagNames();
  726. for (int i = 0; i < tagNames.Length; i++) {
  727. tagNames[i] = EditorGUILayout.TextField(new GUIContent("Tag "+i, "Name for tag "+i), tagNames[i]);
  728. if (tagNames[i] == "") tagNames[i] = ""+i;
  729. }
  730. }
  731. tagsArea.End();
  732. }
  733. void DrawEditorSettings () {
  734. editorSettingsArea.Begin();
  735. editorSettingsArea.Header("Editor");
  736. if (editorSettingsArea.BeginFade()) {
  737. FadeArea.fancyEffects = EditorGUILayout.Toggle("Smooth Transitions", FadeArea.fancyEffects);
  738. if (IsJsEnabled()) {
  739. if (GUILayout.Button(new GUIContent("Disable Js Support", "Revert to only enable pathfinding calls from C#"))) {
  740. DisableJs();
  741. }
  742. } else {
  743. if (GUILayout.Button(new GUIContent("Enable Js Support", "Folders can be restructured to enable pathfinding calls from Js instead of just from C#"))) {
  744. EnableJs();
  745. }
  746. }
  747. }
  748. editorSettingsArea.End();
  749. }
  750. static void DrawColorSlider (ref float left, ref float right, bool editable) {
  751. GUILayout.BeginHorizontal();
  752. GUILayout.Space(20);
  753. GUILayout.BeginVertical();
  754. GUILayout.Box("", astarSkin.GetStyle("ColorInterpolationBox"));
  755. GUILayout.BeginHorizontal();
  756. if (editable) {
  757. left = EditorGUILayout.IntField((int)left);
  758. } else {
  759. GUILayout.Label(left.ToString("0"));
  760. }
  761. GUILayout.FlexibleSpace();
  762. if (editable) {
  763. right = EditorGUILayout.IntField((int)right);
  764. } else {
  765. GUILayout.Label(right.ToString("0"));
  766. }
  767. GUILayout.EndHorizontal();
  768. GUILayout.EndVertical();
  769. GUILayout.Space(4);
  770. GUILayout.EndHorizontal();
  771. }
  772. void DrawDebugSettings () {
  773. alwaysVisibleArea.Begin();
  774. alwaysVisibleArea.HeaderLabel("Debug");
  775. alwaysVisibleArea.BeginFade();
  776. script.logPathResults = (PathLog)EditorGUILayout.EnumPopup("Path Logging", script.logPathResults);
  777. script.debugMode = (GraphDebugMode)EditorGUILayout.EnumPopup("Graph Coloring", script.debugMode);
  778. if (script.debugMode == GraphDebugMode.SolidColor) {
  779. EditorGUI.BeginChangeCheck();
  780. script.colorSettings._SolidColor = EditorGUILayout.ColorField(new GUIContent("Color", "Color used for the graph when 'Graph Coloring'='Solid Color'"), script.colorSettings._SolidColor);
  781. if (EditorGUI.EndChangeCheck()) {
  782. script.colorSettings.PushToStatic(script);
  783. }
  784. }
  785. if (script.debugMode == GraphDebugMode.G || script.debugMode == GraphDebugMode.H || script.debugMode == GraphDebugMode.F || script.debugMode == GraphDebugMode.Penalty) {
  786. script.manualDebugFloorRoof = !EditorGUILayout.Toggle("Automatic Limits", !script.manualDebugFloorRoof);
  787. DrawColorSlider(ref script.debugFloor, ref script.debugRoof, script.manualDebugFloorRoof);
  788. }
  789. script.showSearchTree = EditorGUILayout.Toggle("Show Search Tree", script.showSearchTree);
  790. if (script.showSearchTree) {
  791. EditorGUILayout.HelpBox("Show Search Tree is enabled, you may see rendering glitches in the graph rendering" +
  792. " while the game is running. This is nothing to worry about and is simply due to the paths being calculated at the same time as the gizmos" +
  793. " are being rendered. You can pause the game to see an accurate rendering.", MessageType.Info);
  794. }
  795. script.showUnwalkableNodes = EditorGUILayout.Toggle("Show Unwalkable Nodes", script.showUnwalkableNodes);
  796. if (script.showUnwalkableNodes) {
  797. EditorGUI.indentLevel++;
  798. script.unwalkableNodeDebugSize = EditorGUILayout.FloatField("Size", script.unwalkableNodeDebugSize);
  799. EditorGUI.indentLevel--;
  800. }
  801. alwaysVisibleArea.End();
  802. }
  803. void DrawColorSettings () {
  804. colorSettingsArea.Begin();
  805. colorSettingsArea.Header("Colors");
  806. if (colorSettingsArea.BeginFade()) {
  807. // Make sure the object is not null
  808. AstarColor colors = script.colorSettings = script.colorSettings ?? new AstarColor();
  809. colors._SolidColor = EditorGUILayout.ColorField(new GUIContent("Solid Color", "Color used for the graph when 'Graph Coloring'='Solid Color'"), colors._SolidColor);
  810. colors._UnwalkableNode = EditorGUILayout.ColorField("Unwalkable Node", colors._UnwalkableNode);
  811. colors._BoundsHandles = EditorGUILayout.ColorField("Bounds Handles", colors._BoundsHandles);
  812. colors._ConnectionLowLerp = EditorGUILayout.ColorField("Connection Gradient (low)", colors._ConnectionLowLerp);
  813. colors._ConnectionHighLerp = EditorGUILayout.ColorField("Connection Gradient (high)", colors._ConnectionHighLerp);
  814. colors._MeshEdgeColor = EditorGUILayout.ColorField("Mesh Edge", colors._MeshEdgeColor);
  815. if (EditorResourceHelper.GizmoSurfaceMaterial != null && EditorResourceHelper.GizmoLineMaterial != null) {
  816. EditorGUI.BeginChangeCheck();
  817. var col1 = EditorResourceHelper.GizmoSurfaceMaterial.color;
  818. col1.a = EditorGUILayout.Slider("Navmesh Surface Opacity", col1.a, 0, 1);
  819. var col2 = EditorResourceHelper.GizmoLineMaterial.color;
  820. col2.a = EditorGUILayout.Slider("Navmesh Outline Opacity", col2.a, 0, 1);
  821. var fade = EditorResourceHelper.GizmoSurfaceMaterial.GetColor("_FadeColor");
  822. fade.a = EditorGUILayout.Slider("Opacity Behind Objects", fade.a, 0, 1);
  823. if (EditorGUI.EndChangeCheck()) {
  824. Undo.RecordObjects(new [] { EditorResourceHelper.GizmoSurfaceMaterial, EditorResourceHelper.GizmoLineMaterial }, "Change navmesh transparency");
  825. EditorResourceHelper.GizmoSurfaceMaterial.color = col1;
  826. EditorResourceHelper.GizmoLineMaterial.color = col2;
  827. EditorResourceHelper.GizmoSurfaceMaterial.SetColor("_FadeColor", fade);
  828. EditorResourceHelper.GizmoLineMaterial.SetColor("_FadeColor", fade * new Color(1, 1, 1, 0.7f));
  829. }
  830. }
  831. colors._AreaColors = colors._AreaColors ?? new Color[0];
  832. // Custom Area Colors
  833. customAreaColorsOpen = EditorGUILayout.Foldout(customAreaColorsOpen, "Custom Area Colors");
  834. if (customAreaColorsOpen) {
  835. EditorGUI.indentLevel += 2;
  836. for (int i = 0; i < colors._AreaColors.Length; i++) {
  837. GUILayout.BeginHorizontal();
  838. colors._AreaColors[i] = EditorGUILayout.ColorField("Area "+i+(i == 0 ? " (not used usually)" : ""), colors._AreaColors[i]);
  839. if (GUILayout.Button(new GUIContent("", "Reset to the default color"), astarSkin.FindStyle("SmallReset"), GUILayout.Width(20))) {
  840. colors._AreaColors[i] = AstarMath.IntToColor(i, 1F);
  841. }
  842. GUILayout.EndHorizontal();
  843. }
  844. GUILayout.BeginHorizontal();
  845. EditorGUI.BeginDisabledGroup(colors._AreaColors.Length > 255);
  846. if (GUILayout.Button("Add New")) {
  847. var newcols = new Color[colors._AreaColors.Length+1];
  848. colors._AreaColors.CopyTo(newcols, 0);
  849. newcols[newcols.Length-1] = AstarMath.IntToColor(newcols.Length-1, 1F);
  850. colors._AreaColors = newcols;
  851. }
  852. EditorGUI.EndDisabledGroup();
  853. EditorGUI.BeginDisabledGroup(colors._AreaColors.Length == 0);
  854. if (GUILayout.Button("Remove last") && colors._AreaColors.Length > 0) {
  855. var newcols = new Color[colors._AreaColors.Length-1];
  856. for (int i = 0; i < colors._AreaColors.Length-1; i++) {
  857. newcols[i] = colors._AreaColors[i];
  858. }
  859. colors._AreaColors = newcols;
  860. }
  861. EditorGUI.EndDisabledGroup();
  862. GUILayout.EndHorizontal();
  863. EditorGUI.indentLevel -= 2;
  864. }
  865. if (GUI.changed) {
  866. colors.PushToStatic(script);
  867. }
  868. }
  869. colorSettingsArea.End();
  870. }
  871. /// <summary>Make sure every graph has a graph editor</summary>
  872. void CheckGraphEditors (bool forceRebuild = false) {
  873. if (forceRebuild || graphEditors == null || script.graphs == null || script.graphs.Length != graphEditors.Length) {
  874. if (script.data.graphs == null) {
  875. script.data.graphs = new NavGraph[0];
  876. }
  877. graphEditors = new GraphEditor[script.graphs.Length];
  878. for (int i = 0; i < script.graphs.Length; i++) {
  879. NavGraph graph = script.graphs[i];
  880. if (graph == null) continue;
  881. if (graph.guid == new Pathfinding.Util.Guid()) {
  882. graph.guid = Pathfinding.Util.Guid.NewGuid();
  883. }
  884. graphEditors[i] = CreateGraphEditor(graph);
  885. }
  886. } else {
  887. for (int i = 0; i < script.graphs.Length; i++) {
  888. if (script.graphs[i] == null) continue;
  889. if (graphEditors[i] == null || graphEditorTypes[script.graphs[i].GetType().Name].editorType != graphEditors[i].GetType()) {
  890. CheckGraphEditors(true);
  891. return;
  892. }
  893. if (script.graphs[i].guid == new Pathfinding.Util.Guid()) {
  894. script.graphs[i].guid = Pathfinding.Util.Guid.NewGuid();
  895. }
  896. graphEditors[i].target = script.graphs[i];
  897. }
  898. }
  899. }
  900. void RemoveGraph (NavGraph graph) {
  901. script.data.RemoveGraph(graph);
  902. CheckGraphEditors(true);
  903. GUI.changed = true;
  904. Repaint();
  905. }
  906. void AddGraph (System.Type type) {
  907. script.data.AddGraph(type);
  908. CheckGraphEditors();
  909. GUI.changed = true;
  910. }
  911. /// <summary>Creates a GraphEditor for a graph</summary>
  912. GraphEditor CreateGraphEditor (NavGraph graph) {
  913. var graphType = graph.GetType().Name;
  914. GraphEditor result;
  915. if (graphEditorTypes.ContainsKey(graphType)) {
  916. result = System.Activator.CreateInstance(graphEditorTypes[graphType].editorType) as GraphEditor;
  917. } else {
  918. Debug.LogError("Couldn't find an editor for the graph type '" + graphType + "' There are " + graphEditorTypes.Count + " available graph editors");
  919. result = new GraphEditor();
  920. }
  921. result.editor = this;
  922. result.fadeArea = new FadeArea(graph.open, this, level1AreaStyle, level1LabelStyle);
  923. result.infoFadeArea = new FadeArea(graph.infoScreenOpen, this, null, null);
  924. result.target = graph;
  925. result.OnEnable();
  926. return result;
  927. }
  928. bool HandleUndo () {
  929. // The user has tried to undo something, apply that
  930. if (script.data.GetData() == null) {
  931. script.data.SetData(new byte[0]);
  932. } else {
  933. LoadGraphs();
  934. return true;
  935. }
  936. return false;
  937. }
  938. /// <summary>Hashes the contents of a byte array</summary>
  939. static int ByteArrayHash (byte[] arr) {
  940. if (arr == null) return -1;
  941. int hash = -1;
  942. for (int i = 0; i < arr.Length; i++) {
  943. hash ^= (arr[i]^i)*3221;
  944. }
  945. return hash;
  946. }
  947. void SerializeIfDataChanged () {
  948. uint checksum;
  949. byte[] bytes = SerializeGraphs(out checksum);
  950. int byteHash = ByteArrayHash(bytes);
  951. int dataHash = ByteArrayHash(script.data.GetData());
  952. //Check if the data is different than the previous data, use checksums
  953. bool isDifferent = checksum != ignoredChecksum && dataHash != byteHash;
  954. //Only save undo if the data was different from the last saved undo
  955. if (isDifferent) {
  956. //Assign the new data
  957. script.data.SetData(bytes);
  958. EditorUtility.SetDirty(script);
  959. Undo.IncrementCurrentGroup();
  960. Undo.RegisterCompleteObjectUndo(script, "A* Graph Settings");
  961. }
  962. }
  963. /// <summary>Called when an undo or redo operation has been performed</summary>
  964. void OnUndoRedoPerformed () {
  965. if (!this) return;
  966. uint checksum;
  967. byte[] bytes = SerializeGraphs(out checksum);
  968. //Check if the data is different than the previous data, use checksums
  969. bool isDifferent = ByteArrayHash(script.data.GetData()) != ByteArrayHash(bytes);
  970. if (isDifferent) {
  971. HandleUndo();
  972. }
  973. CheckGraphEditors();
  974. // Deserializing a graph does not necessarily yield the same hash as the data loaded from
  975. // this is (probably) because editor settings are not saved all the time
  976. // so we explicitly ignore the new hash
  977. SerializeGraphs(out checksum);
  978. ignoredChecksum = checksum;
  979. }
  980. public void SaveGraphsAndUndo (EventType et = EventType.Used, string eventCommand = "") {
  981. // Serialize the settings of the graphs
  982. // Dont process undo events in editor, we don't want to reset graphs
  983. // Also don't do this if the graph is being updated as serializing the graph
  984. // might interfere with that (in particular it might unblock the path queue)
  985. if (Application.isPlaying || script.isScanning || script.IsAnyWorkItemInProgress) {
  986. return;
  987. }
  988. if ((Undo.GetCurrentGroup() != lastUndoGroup || et == EventType.MouseUp) && eventCommand != "UndoRedoPerformed") {
  989. SerializeIfDataChanged();
  990. lastUndoGroup = Undo.GetCurrentGroup();
  991. }
  992. if (Event.current == null || script.data.GetData() == null) {
  993. SerializeIfDataChanged();
  994. return;
  995. }
  996. }
  997. /// <summary>Load graphs from serialized data</summary>
  998. public void LoadGraphs () {
  999. DeserializeGraphs();
  1000. }
  1001. public byte[] SerializeGraphs (out uint checksum) {
  1002. var settings = Pathfinding.Serialization.SerializeSettings.Settings;
  1003. settings.editorSettings = true;
  1004. return SerializeGraphs(settings, out checksum);
  1005. }
  1006. public byte[] SerializeGraphs (Pathfinding.Serialization.SerializeSettings settings, out uint checksum) {
  1007. byte[] bytes = null;
  1008. uint tmpChecksum = 0;
  1009. // Serialize all graph editors
  1010. var output = new System.Text.StringBuilder();
  1011. for (int i = 0; i < graphEditors.Length; i++) {
  1012. if (graphEditors[i] == null) continue;
  1013. output.Length = 0;
  1014. Pathfinding.Serialization.TinyJsonSerializer.Serialize(graphEditors[i], output);
  1015. (graphEditors[i].target as IGraphInternals).SerializedEditorSettings = output.ToString();
  1016. }
  1017. // Serialize all graphs (including serialized editor data)
  1018. bytes = script.data.SerializeGraphs(settings, out tmpChecksum);
  1019. // Make sure the above work item is executed immediately
  1020. AstarPath.active.FlushWorkItems();
  1021. checksum = tmpChecksum;
  1022. return bytes;
  1023. }
  1024. void DeserializeGraphs () {
  1025. if (script.data.GetData() == null || script.data.GetData().Length == 0) {
  1026. script.data.graphs = new NavGraph[0];
  1027. } else {
  1028. DeserializeGraphs(script.data.GetData());
  1029. }
  1030. }
  1031. void DeserializeGraphs (byte[] bytes) {
  1032. try {
  1033. script.data.DeserializeGraphs(bytes);
  1034. // Make sure every graph has a graph editor
  1035. CheckGraphEditors();
  1036. // Deserialize editor settings
  1037. for (int i = 0; i < graphEditors.Length; i++) {
  1038. var data = (graphEditors[i].target as IGraphInternals).SerializedEditorSettings;
  1039. if (data != null) Pathfinding.Serialization.TinyJsonDeserializer.Deserialize(data, graphEditors[i].GetType(), graphEditors[i]);
  1040. }
  1041. } catch (System.Exception e) {
  1042. Debug.LogError("Failed to deserialize graphs");
  1043. Debug.LogException(e);
  1044. script.data.SetData(null);
  1045. }
  1046. }
  1047. [MenuItem("Edit/Pathfinding/Scan All Graphs %&s")]
  1048. public static void MenuScan () {
  1049. if (AstarPath.active == null) {
  1050. AstarPath.active = FindObjectOfType<AstarPath>();
  1051. if (AstarPath.active == null) {
  1052. return;
  1053. }
  1054. }
  1055. if (!Application.isPlaying && (AstarPath.active.data.graphs == null || AstarPath.active.data.graphTypes == null)) {
  1056. EditorUtility.DisplayProgressBar("Scanning", "Deserializing", 0);
  1057. AstarPath.active.data.DeserializeGraphs();
  1058. }
  1059. try {
  1060. var lastMessageTime = Time.realtimeSinceStartup;
  1061. foreach (var p in AstarPath.active.ScanAsync()) {
  1062. // Displaying the progress bar is pretty slow, so don't do it too often
  1063. if (Time.realtimeSinceStartup - lastMessageTime > 0.2f) {
  1064. // Display a progress bar of the scan
  1065. UnityEditor.EditorUtility.DisplayProgressBar("Scanning", p.description, p.progress);
  1066. lastMessageTime = Time.realtimeSinceStartup;
  1067. }
  1068. }
  1069. } catch (System.Exception e) {
  1070. Debug.LogError("There was an error generating the graphs:\n"+e+"\n\nIf you think this is a bug, please contact me on forum.arongranberg.com (post a new thread)\n");
  1071. EditorUtility.DisplayDialog("Error Generating Graphs", "There was an error when generating graphs, check the console for more info", "Ok");
  1072. throw e;
  1073. } finally {
  1074. EditorUtility.ClearProgressBar();
  1075. }
  1076. }
  1077. /// <summary>Searches in the current assembly for GraphEditor and NavGraph types</summary>
  1078. void FindGraphTypes () {
  1079. graphEditorTypes = new Dictionary<string, CustomGraphEditorAttribute>();
  1080. var graphList = new List<System.Type>();
  1081. foreach (var assembly in System.AppDomain.CurrentDomain.GetAssemblies()) {
  1082. System.Type[] types = assembly.GetTypes();
  1083. // Iterate through the assembly for classes which inherit from GraphEditor
  1084. foreach (var type in types) {
  1085. System.Type baseType = type.BaseType;
  1086. while (!System.Type.Equals(baseType, null)) {
  1087. if (System.Type.Equals(baseType, typeof(GraphEditor))) {
  1088. System.Object[] att = type.GetCustomAttributes(false);
  1089. // Loop through the attributes for the CustomGraphEditorAttribute attribute
  1090. foreach (System.Object attribute in att) {
  1091. var cge = attribute as CustomGraphEditorAttribute;
  1092. if (cge != null && !System.Type.Equals(cge.graphType, null)) {
  1093. cge.editorType = type;
  1094. graphList.Add(cge.graphType);
  1095. graphEditorTypes.Add(cge.graphType.Name, cge);
  1096. }
  1097. }
  1098. break;
  1099. }
  1100. baseType = baseType.BaseType;
  1101. }
  1102. }
  1103. }
  1104. // Make sure graph types (not graph editor types) are also up to date
  1105. script.data.FindGraphTypes();
  1106. }
  1107. }
  1108. }