12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427 |
- using UnityEngine;
- using UnityEditor;
- using System.Collections.Generic;
- using System.Reflection;
- namespace Pathfinding {
- [CustomEditor(typeof(AstarPath))]
- public class AstarPathEditor : Editor {
-
- static Dictionary<string, CustomGraphEditorAttribute> graphEditorTypes = new Dictionary<string, CustomGraphEditorAttribute>();
-
-
-
-
- static Dictionary<NavGraph, KeyValuePair<float, KeyValuePair<int, int> > > graphNodeCounts;
-
- GraphEditor[] graphEditors;
- System.Type[] graphTypes {
- get {
- return script.data.graphTypes;
- }
- }
- static int lastUndoGroup = -1000;
-
- static uint ignoredChecksum;
- const string scriptsFolder = "Assets/AstarPathfindingProject";
- #region SectionFlags
- static bool showSettings;
- static bool customAreaColorsOpen;
- static bool editTags;
- FadeArea settingsArea;
- FadeArea colorSettingsArea;
- FadeArea editorSettingsArea;
- FadeArea aboutArea;
- FadeArea optimizationSettingsArea;
- FadeArea serializationSettingsArea;
- FadeArea tagsArea;
- FadeArea graphsArea;
- FadeArea addGraphsArea;
- FadeArea alwaysVisibleArea;
- #endregion
-
- public AstarPath script { get; private set; }
- #region Styles
- static bool stylesLoaded;
- public static GUISkin astarSkin { get; private set; }
- static GUIStyle level0AreaStyle, level0LabelStyle;
- static GUIStyle level1AreaStyle, level1LabelStyle;
- static GUIStyle graphDeleteButtonStyle, graphInfoButtonStyle, graphGizmoButtonStyle, graphEditNameButtonStyle;
- public static GUIStyle helpBox { get; private set; }
- public static GUIStyle thinHelpBox { get; private set; }
- #endregion
-
- List<OptimizationHandler.DefineDefinition> defines;
-
- public void OnEnable () {
- script = target as AstarPath;
-
- script.ConfigureReferencesInternal();
- Undo.undoRedoPerformed += OnUndoRedoPerformed;
-
- if (graphEditorTypes == null || graphEditorTypes.Count == 0)
- FindGraphTypes();
- try {
- GetAstarEditorSettings();
- } catch (System.Exception e) {
- Debug.LogException(e);
- }
- LoadStyles();
-
- if ((!Application.isPlaying && (script.data == null || script.data.graphs == null || script.data.graphs.Length == 0)) || script.data.graphs == null) {
- LoadGraphs();
- }
- CreateFadeAreas();
- }
- void CreateFadeAreas () {
- if (settingsArea == null) {
- aboutArea = new FadeArea(false, this, level0AreaStyle, level0LabelStyle);
- optimizationSettingsArea = new FadeArea(false, this, level0AreaStyle, level0LabelStyle);
- graphsArea = new FadeArea(false, this, level0AreaStyle, level0LabelStyle);
- serializationSettingsArea = new FadeArea(false, this, level0AreaStyle, level0LabelStyle);
- settingsArea = new FadeArea(showSettings, this, level0AreaStyle, level0LabelStyle);
- addGraphsArea = new FadeArea(false, this, level1AreaStyle, level1LabelStyle);
- colorSettingsArea = new FadeArea(false, this, level1AreaStyle, level1LabelStyle);
- editorSettingsArea = new FadeArea(false, this, level1AreaStyle, level1LabelStyle);
- alwaysVisibleArea = new FadeArea(true, this, level1AreaStyle, level1LabelStyle);
- tagsArea = new FadeArea(editTags, this, level1AreaStyle, level1LabelStyle);
- }
- }
-
- public void OnDisable () {
- Undo.undoRedoPerformed -= OnUndoRedoPerformed;
- if (target == null) {
- return;
- }
- SetAstarEditorSettings();
- CheckGraphEditors();
- SaveGraphsAndUndo();
- script = null;
- }
-
- void GetAstarEditorSettings () {
- FadeArea.fancyEffects = EditorPrefs.GetBool("EditorGUILayoutx.fancyEffects", true);
- }
- void SetAstarEditorSettings () {
- EditorPrefs.SetBool("EditorGUILayoutx.fancyEffects", FadeArea.fancyEffects);
- }
-
-
-
-
- void RepaintSceneView () {
- if (!Application.isPlaying || EditorApplication.isPaused) SceneView.RepaintAll();
- }
-
- public override bool UseDefaultMargins () {
- return false;
- }
- public override void OnInspectorGUI () {
-
- if (!LoadStyles()) {
- EditorGUILayout.HelpBox("The GUISkin 'AstarEditorSkin.guiskin' in the folder "+EditorResourceHelper.editorAssets+"/ was not found or some custom styles in it does not exist.\n"+
- "This file is required for the A* Pathfinding Project editor.\n\n"+
- "If you are trying to add A* to a new project, please do not copy the files outside Unity, "+
- "export them as a UnityPackage and import them to this project or download the package from the Asset Store"+
- "or the 'scripts only' package from the A* Pathfinding Project website.\n\n\n"+
- "Skin loading is done in the AstarPathEditor.cs --> LoadStyles method", MessageType.Error);
- return;
- }
- #if UNITY_2020_1_OR_NEWER
- if (UnityEditor.EditorSettings.enterPlayModeOptionsEnabled && (UnityEditor.EditorSettings.enterPlayModeOptions & EnterPlayModeOptions.DisableSceneReload) != 0) {
- EditorGUILayout.HelpBox("The enter play mode option 'Scene Reload' must be enabled. This package does not support it being disabled. Disabling domain reload is supported however.", MessageType.Error);
- if (GUILayout.Button("Enable the Scene Reload option")) {
- UnityEditor.EditorSettings.enterPlayModeOptions &= ~EnterPlayModeOptions.DisableSceneReload;
- }
- EditorGUILayout.Separator();
- }
- #endif
- #if ASTAR_ATAVISM
- 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);
- #endif
- EditorGUI.BeginChangeCheck();
- Undo.RecordObject(script, "A* inspector");
- CheckGraphEditors();
-
- EditorGUI.indentLevel = 1;
-
-
- EventType storedEventType = Event.current.type;
- string storedEventCommand = Event.current.commandName;
- DrawMainArea();
- GUILayout.Space(5);
- if (GUILayout.Button(new GUIContent("Scan", "Recalculate all graphs. Shortcut cmd+alt+s ( ctrl+alt+s on windows )"))) {
- MenuScan();
- }
- #if ProfileAstar
- if (GUILayout.Button("Log Profiles")) {
- AstarProfiler.PrintResults();
- AstarProfiler.PrintFastResults();
- AstarProfiler.Reset();
- }
- #endif
-
- SaveGraphsAndUndo(storedEventType, storedEventCommand);
- if (EditorGUI.EndChangeCheck()) {
- RepaintSceneView();
- EditorUtility.SetDirty(script);
- }
- }
-
-
-
-
-
- static bool LoadStyles () {
- if (stylesLoaded) return true;
-
- var inspectorSkin = EditorGUIUtility.GetBuiltinSkin(EditorSkin.Inspector);
- if (!EditorResourceHelper.LocateEditorAssets()) {
- return false;
- }
- var skinPath = EditorResourceHelper.editorAssets + "/AstarEditorSkin" + (EditorGUIUtility.isProSkin ? "Dark" : "Light") + ".guiskin";
- astarSkin = AssetDatabase.LoadAssetAtPath(skinPath, typeof(GUISkin)) as GUISkin;
- if (astarSkin != null) {
- astarSkin.button = inspectorSkin.button;
- } else {
- Debug.LogWarning("Could not load editor skin at '" + skinPath + "'");
- return false;
- }
- level0AreaStyle = astarSkin.FindStyle("PixelBox");
-
-
- if (level0AreaStyle == null) {
- return false;
- }
- level1LabelStyle = astarSkin.FindStyle("BoxHeader");
- level0LabelStyle = astarSkin.FindStyle("TopBoxHeader");
- level1AreaStyle = astarSkin.FindStyle("PixelBox3");
- graphDeleteButtonStyle = astarSkin.FindStyle("PixelButton");
- graphInfoButtonStyle = astarSkin.FindStyle("InfoButton");
- graphGizmoButtonStyle = astarSkin.FindStyle("GizmoButton");
- graphEditNameButtonStyle = astarSkin.FindStyle("EditButton");
- helpBox = inspectorSkin.FindStyle("HelpBox") ?? inspectorSkin.box;
- thinHelpBox = new GUIStyle(helpBox);
- thinHelpBox.stretchWidth = false;
- thinHelpBox.clipping = TextClipping.Overflow;
- thinHelpBox.overflow.bottom += 2;
- stylesLoaded = true;
- return true;
- }
-
- void DrawMainArea () {
- CheckGraphEditors();
- graphsArea.Begin();
- graphsArea.Header("Graphs", ref script.showGraphs);
- if (graphsArea.BeginFade()) {
- bool anyNonNull = false;
- for (int i = 0; i < script.graphs.Length; i++) {
- if (script.graphs[i] != null) {
- anyNonNull = true;
- DrawGraph(graphEditors[i]);
- }
- }
-
- addGraphsArea.Begin();
- addGraphsArea.open |= !anyNonNull;
- addGraphsArea.Header("Add New Graph");
- if (addGraphsArea.BeginFade()) {
- if (graphTypes == null) script.data.FindGraphTypes();
- for (int i = 0; i < graphTypes.Length; i++) {
- if (graphEditorTypes.ContainsKey(graphTypes[i].Name)) {
- if (GUILayout.Button(graphEditorTypes[graphTypes[i].Name].displayName)) {
- addGraphsArea.open = false;
- AddGraph(graphTypes[i]);
- }
- } else if (!graphTypes[i].Name.Contains("Base")) {
- EditorGUI.BeginDisabledGroup(true);
- GUILayout.Label(graphTypes[i].Name + " (no editor found)", "Button");
- EditorGUI.EndDisabledGroup();
- }
- }
- }
- addGraphsArea.End();
- }
- graphsArea.End();
- DrawSettings();
- DrawSerializationSettings();
- DrawOptimizationSettings();
- DrawAboutArea();
- bool showNavGraphs = EditorGUILayout.Toggle("Show Graphs", script.showNavGraphs);
- if (script.showNavGraphs != showNavGraphs) {
- script.showNavGraphs = showNavGraphs;
- RepaintSceneView();
- }
- }
-
- void DrawOptimizationSettings () {
- optimizationSettingsArea.Begin();
- optimizationSettingsArea.Header("Optimization");
- if (optimizationSettingsArea.BeginFade()) {
- defines = defines ?? OptimizationHandler.FindDefines();
- EditorGUILayout.HelpBox("Using C# pre-processor directives, performance and memory usage can be improved by disabling features that you don't use in the project.\n" +
- "Every change to these settings requires recompiling the scripts", MessageType.Info);
- foreach (var define in defines) {
- EditorGUILayout.Separator();
- var label = new GUIContent(ObjectNames.NicifyVariableName(define.name), define.description);
- define.enabled = EditorGUILayout.Toggle(label, define.enabled);
- EditorGUILayout.HelpBox(define.description, MessageType.None);
- if (!define.consistent) {
- GUIUtilityx.PushTint(Color.red);
- EditorGUILayout.HelpBox("This define is not consistent for all build targets, some have it enabled enabled some have it disabled. Press Apply to change them to the same value", MessageType.Error);
- GUIUtilityx.PopTint();
- }
- }
- EditorGUILayout.Separator();
- GUILayout.BeginHorizontal();
- GUILayout.FlexibleSpace();
- if (GUILayout.Button("Apply", GUILayout.Width(150))) {
- if (EditorUtility.DisplayDialog("Apply Optimizations", "Applying optimizations requires (in case anything changed) a recompilation of the scripts. The inspector also has to be reloaded. Do you want to continue?", "Ok", "Cancel")) {
- OptimizationHandler.ApplyDefines(defines);
- AssetDatabase.Refresh();
- defines = null;
- }
- }
- GUILayout.FlexibleSpace();
- GUILayout.EndHorizontal();
- }
- optimizationSettingsArea.End();
- }
-
-
-
-
-
- public static System.Version FullyDefinedVersion (System.Version v) {
- return new System.Version(Mathf.Max(v.Major, 0), Mathf.Max(v.Minor, 0), Mathf.Max(v.Build, 0), Mathf.Max(v.Revision, 0));
- }
- void DrawAboutArea () {
- aboutArea.Begin();
- GUILayout.BeginHorizontal();
- if (GUILayout.Button("About", level0LabelStyle)) {
- aboutArea.open = !aboutArea.open;
- GUI.changed = true;
- }
- #if !ASTAR_ATAVISM
- System.Version newVersion = AstarUpdateChecker.latestVersion;
- bool beta = false;
-
- if (FullyDefinedVersion(AstarUpdateChecker.latestVersion) > FullyDefinedVersion(AstarPath.Version) || FullyDefinedVersion(AstarUpdateChecker.latestBetaVersion) > FullyDefinedVersion(AstarPath.Version)) {
- if (FullyDefinedVersion(AstarUpdateChecker.latestVersion) <= FullyDefinedVersion(AstarPath.Version)) {
- newVersion = AstarUpdateChecker.latestBetaVersion;
- beta = true;
- }
- }
-
- if (FullyDefinedVersion(newVersion) > FullyDefinedVersion(AstarPath.Version)) {
- GUIUtilityx.PushTint(Color.green);
- if (GUILayout.Button((beta ? "Beta" : "New") + " Version Available! "+newVersion, thinHelpBox, GUILayout.Height(15))) {
- Application.OpenURL(AstarUpdateChecker.GetURL("download"));
- }
- GUIUtilityx.PopTint();
- GUILayout.Space(20);
- }
- #endif
- GUILayout.EndHorizontal();
- if (aboutArea.BeginFade()) {
- GUILayout.Label("The A* Pathfinding Project was made by Aron Granberg\nYour current version is "+AstarPath.Version);
- #if !ASTAR_ATAVISM
- if (FullyDefinedVersion(newVersion) > FullyDefinedVersion(AstarPath.Version)) {
- EditorGUILayout.HelpBox("A new "+(beta ? "beta " : "")+"version of the A* Pathfinding Project is available, the new version is "+
- newVersion, MessageType.Info);
- if (GUILayout.Button("What's new?")) {
- Application.OpenURL(AstarUpdateChecker.GetURL(beta ? "beta_changelog" : "changelog"));
- }
- if (GUILayout.Button("Click here to find out more")) {
- Application.OpenURL(AstarUpdateChecker.GetURL("findoutmore"));
- }
- GUIUtilityx.PushTint(new Color(0.3F, 0.9F, 0.3F));
- if (GUILayout.Button("Download new version")) {
- Application.OpenURL(AstarUpdateChecker.GetURL("download"));
- }
- GUIUtilityx.PopTint();
- }
- #endif
- if (GUILayout.Button(new GUIContent("Documentation", "Open the documentation for the A* Pathfinding Project"))) {
- Application.OpenURL(AstarUpdateChecker.GetURL("documentation"));
- }
- if (GUILayout.Button(new GUIContent("Project Homepage", "Open the homepage for the A* Pathfinding Project"))) {
- Application.OpenURL(AstarUpdateChecker.GetURL("homepage"));
- }
- }
- aboutArea.End();
- }
-
- GraphEditor graphNameFocused;
- void DrawGraphHeader (GraphEditor graphEditor) {
- var graph = graphEditor.target;
-
- string graphGUIDString = graph.guid.ToString();
- GUILayout.BeginHorizontal();
- if (graphNameFocused == graphEditor) {
- GUI.SetNextControlName(graphGUIDString);
- graph.name = GUILayout.TextField(graph.name ?? "", level1LabelStyle, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(false));
-
- if ((Event.current.type == EventType.Repaint && GUI.GetNameOfFocusedControl() != graphGUIDString) || (Event.current.type == EventType.KeyUp && (Event.current.keyCode == KeyCode.Return || Event.current.keyCode == KeyCode.Escape))) {
- if (Event.current.type == EventType.KeyUp) Event.current.Use();
- graphNameFocused = null;
- }
- } else {
-
- if (graph.name == null || graph.name == "") graph.name = graphEditorTypes[graph.GetType().Name].displayName;
- if (GUILayout.Button(graph.name, level1LabelStyle)) {
- graphEditor.fadeArea.open = graph.open = !graph.open;
- if (!graph.open) {
- graph.infoScreenOpen = false;
- }
- RepaintSceneView();
- }
- }
- #pragma warning disable 0618
- if (script.prioritizeGraphs) {
- #pragma warning restore 0618
- var moveUp = GUILayout.Button(new GUIContent("Up", "Increase the graph priority"), GUILayout.Width(40));
- var moveDown = GUILayout.Button(new GUIContent("Down", "Decrease the graph priority"), GUILayout.Width(40));
- if (moveUp || moveDown) {
- int index = script.data.GetGraphIndex(graph);
- int next;
- if (moveUp) {
-
- next = index-1;
- for (; next >= 0; next--) if (script.graphs[next] != null) break;
- } else {
-
- next = index+1;
- for (; next < script.graphs.Length; next++) if (script.graphs[next] != null) break;
- }
- if (next >= 0 && next < script.graphs.Length) {
- NavGraph tmp = script.graphs[next];
- script.graphs[next] = graph;
- script.graphs[index] = tmp;
- GraphEditor tmpEditor = graphEditors[next];
- graphEditors[next] = graphEditors[index];
- graphEditors[index] = tmpEditor;
- }
- CheckGraphEditors();
- Repaint();
- }
- }
-
- graph.drawGizmos = GUILayout.Toggle(graph.drawGizmos, new GUIContent("Draw Gizmos", "Draw Gizmos"), graphGizmoButtonStyle);
- if (GUILayout.Button(new GUIContent("", "Edit Name"), graphEditNameButtonStyle)) {
- graphNameFocused = graphEditor;
- GUI.FocusControl(graphGUIDString);
- }
- if (GUILayout.Toggle(graph.infoScreenOpen, new GUIContent("Info", "Info"), graphInfoButtonStyle)) {
- if (!graph.infoScreenOpen) {
- graphEditor.infoFadeArea.open = graph.infoScreenOpen = true;
- graphEditor.fadeArea.open = graph.open = true;
- }
- } else {
- graphEditor.infoFadeArea.open = graph.infoScreenOpen = false;
- }
- if (GUILayout.Button(new GUIContent("Delete", "Delete"), graphDeleteButtonStyle)) {
- RemoveGraph(graph);
- }
- GUILayout.EndHorizontal();
- }
- void DrawGraphInfoArea (GraphEditor graphEditor) {
- graphEditor.infoFadeArea.Begin();
- if (graphEditor.infoFadeArea.BeginFade()) {
- bool anyNodesNull = false;
- int total = 0;
- int numWalkable = 0;
-
- KeyValuePair<float, KeyValuePair<int, int> > pair;
- graphNodeCounts = graphNodeCounts ?? new Dictionary<NavGraph, KeyValuePair<float, KeyValuePair<int, int> > >();
- if (!graphNodeCounts.TryGetValue(graphEditor.target, out pair) || (Time.realtimeSinceStartup-pair.Key) > 2) {
- graphEditor.target.GetNodes(node => {
- if (node == null) {
- anyNodesNull = true;
- } else {
- total++;
- if (node.Walkable) numWalkable++;
- }
- });
- pair = new KeyValuePair<float, KeyValuePair<int, int> >(Time.realtimeSinceStartup, new KeyValuePair<int, int>(total, numWalkable));
- graphNodeCounts[graphEditor.target] = pair;
- }
- total = pair.Value.Key;
- numWalkable = pair.Value.Value;
- EditorGUI.indentLevel++;
- if (anyNodesNull) {
- Debug.LogError("Some nodes in the graph are null. Please report this error.");
- }
- EditorGUILayout.LabelField("Nodes", total.ToString());
- EditorGUILayout.LabelField("Walkable", numWalkable.ToString());
- EditorGUILayout.LabelField("Unwalkable", (total-numWalkable).ToString());
- if (total == 0) EditorGUILayout.HelpBox("The number of nodes in the graph is zero. The graph might not be scanned", MessageType.Info);
- EditorGUI.indentLevel--;
- }
- graphEditor.infoFadeArea.End();
- }
-
- void DrawGraph (GraphEditor graphEditor) {
- graphEditor.fadeArea.Begin();
- DrawGraphHeader(graphEditor);
- if (graphEditor.fadeArea.BeginFade()) {
- DrawGraphInfoArea(graphEditor);
- graphEditor.OnInspectorGUI(graphEditor.target);
- graphEditor.OnBaseInspectorGUI(graphEditor.target);
- }
- graphEditor.fadeArea.End();
- }
- public void OnSceneGUI () {
- script = target as AstarPath;
- DrawSceneGUISettings();
-
-
-
-
-
- if (script.isScanning) {
- return;
- }
- script.ConfigureReferencesInternal();
- EditorGUI.BeginChangeCheck();
- if (!LoadStyles()) return;
-
- EventType et = Event.current.type;
- CheckGraphEditors();
- for (int i = 0; i < script.graphs.Length; i++) {
- NavGraph graph = script.graphs[i];
- if (graph != null) {
- graphEditors[i].OnSceneGUI(graph);
- }
- }
- SaveGraphsAndUndo(et);
- if (EditorGUI.EndChangeCheck()) {
- EditorUtility.SetDirty(target);
- }
- }
- void DrawSceneGUISettings () {
- var darkSkin = EditorGUIUtility.GetBuiltinSkin(EditorSkin.Scene);
- Handles.BeginGUI();
- float width = 180;
- float height = 76;
- float margin = 10;
- var origWidth = EditorGUIUtility.labelWidth;
- EditorGUIUtility.labelWidth = 144;
- GUILayout.BeginArea(new Rect(Camera.current.pixelWidth - width, Camera.current.pixelHeight - height, width - margin, height - margin), "Graph Display", astarSkin.FindStyle("SceneBoxDark"));
- EditorGUILayout.BeginHorizontal();
- EditorGUILayout.PrefixLabel("Show Graphs", darkSkin.toggle, astarSkin.FindStyle("ScenePrefixLabel"));
- script.showNavGraphs = EditorGUILayout.Toggle(script.showNavGraphs, darkSkin.toggle);
- EditorGUILayout.EndHorizontal();
- if (GUILayout.Button("Scan", darkSkin.button)) {
- MenuScan();
- }
-
- GUI.Button(new Rect(0, 0, width - margin, height - margin), "", GUIStyle.none);
- GUILayout.EndArea();
- EditorGUIUtility.labelWidth = origWidth;
- Handles.EndGUI();
- }
- TextAsset SaveGraphData (byte[] bytes, TextAsset target = null) {
- string projectPath = System.IO.Path.GetDirectoryName(Application.dataPath) + "/";
- string path;
- if (target != null) {
- path = AssetDatabase.GetAssetPath(target);
- } else {
-
- int i = 0;
- do {
- path = "Assets/GraphCaches/GraphCache" + (i == 0 ? "" : i.ToString()) + ".bytes";
- i++;
- } while (System.IO.File.Exists(projectPath+path));
- }
- string fullPath = projectPath + path;
- System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(fullPath));
- var fileInfo = new System.IO.FileInfo(fullPath);
-
- if (fileInfo.Exists && fileInfo.IsReadOnly)
- fileInfo.IsReadOnly = false;
- System.IO.File.WriteAllBytes(fullPath, bytes);
- AssetDatabase.Refresh();
- return AssetDatabase.LoadAssetAtPath<TextAsset>(path);
- }
- void DrawSerializationSettings () {
- serializationSettingsArea.Begin();
- GUILayout.BeginHorizontal();
- if (GUILayout.Button("Save & Load", level0LabelStyle)) {
- serializationSettingsArea.open = !serializationSettingsArea.open;
- }
- if (script.data.cacheStartup && script.data.file_cachedStartup != null) {
- GUIUtilityx.PushTint(Color.yellow);
- GUILayout.Label("Startup cached", thinHelpBox, GUILayout.Height(15));
- GUILayout.Space(20);
- GUIUtilityx.PopTint();
- }
- GUILayout.EndHorizontal();
-
- if (serializationSettingsArea.BeginFade()) {
- 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);
- script.data.file_cachedStartup = EditorGUILayout.ObjectField(script.data.file_cachedStartup, typeof(TextAsset), false) as TextAsset;
- if (script.data.cacheStartup && script.data.file_cachedStartup == null) {
- EditorGUILayout.HelpBox("No cache has been generated", MessageType.Error);
- }
- if (script.data.cacheStartup && script.data.file_cachedStartup != null) {
- EditorGUILayout.HelpBox("All graph settings will be replaced with the ones from the cache when the game starts", MessageType.Info);
- }
- GUILayout.BeginHorizontal();
- if (GUILayout.Button("Generate cache")) {
- var serializationSettings = new Pathfinding.Serialization.SerializeSettings();
- serializationSettings.nodes = true;
- if (EditorUtility.DisplayDialog("Scan before generating cache?", "Do you want to scan the graphs before saving the cache.\n" +
- "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")) {
- MenuScan();
- }
-
- var bytes = script.data.SerializeGraphs(serializationSettings);
-
- script.data.file_cachedStartup = SaveGraphData(bytes, script.data.file_cachedStartup);
- script.data.cacheStartup = true;
- }
- if (GUILayout.Button("Load from cache")) {
- 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")) {
- script.data.LoadFromCache();
- }
- }
- GUILayout.EndHorizontal();
- if (script.data.data_cachedStartup != null && script.data.data_cachedStartup.Length > 0) {
- EditorGUILayout.HelpBox("Storing the cached starup data on the AstarPath object has been deprecated. It is now stored " +
- "in a separate file.", MessageType.Error);
- if (GUILayout.Button("Transfer cache data to separate file")) {
- script.data.file_cachedStartup = SaveGraphData(script.data.data_cachedStartup);
- script.data.data_cachedStartup = null;
- }
- }
- GUILayout.Space(5);
- GUILayout.BeginHorizontal();
- if (GUILayout.Button("Save to file")) {
- string path = EditorUtility.SaveFilePanel("Save Graphs", "", "graph.bytes", "bytes");
- if (path != "") {
- var serializationSettings = Pathfinding.Serialization.SerializeSettings.Settings;
- if (EditorUtility.DisplayDialog("Include node data?", "Do you want to include node data in the save file. " +
- "If node data is included the graph can be restored completely without having to scan it first.", "Include node data", "Only settings")) {
- serializationSettings.nodes = true;
- }
- if (serializationSettings.nodes && EditorUtility.DisplayDialog("Scan before saving?", "Do you want to scan the graphs before saving? " +
- "\nNot scanning can cause node data to be omitted from the file if the graph is not yet scanned.", "Scan", "Don't scan")) {
- MenuScan();
- }
- uint checksum;
- var bytes = SerializeGraphs(serializationSettings, out checksum);
- Pathfinding.Serialization.AstarSerializer.SaveToFile(path, bytes);
- EditorUtility.DisplayDialog("Done Saving", "Done saving graph data.", "Ok");
- }
- }
- if (GUILayout.Button("Load from file")) {
- string path = EditorUtility.OpenFilePanel("Load Graphs", "", "");
- if (path != "") {
- try {
- byte[] bytes = Pathfinding.Serialization.AstarSerializer.LoadFromFile(path);
- DeserializeGraphs(bytes);
- } catch (System.Exception e) {
- Debug.LogError("Could not load from file at '"+path+"'\n"+e);
- }
- }
- }
- GUILayout.EndHorizontal();
- }
- serializationSettingsArea.End();
- }
- void DrawSettings () {
- settingsArea.Begin();
- settingsArea.Header("Settings", ref showSettings);
- if (settingsArea.BeginFade()) {
- DrawPathfindingSettings();
- DrawDebugSettings();
- DrawColorSettings();
- DrawTagSettings();
- DrawEditorSettings();
- }
- settingsArea.End();
- }
- void DrawPathfindingSettings () {
- alwaysVisibleArea.Begin();
- alwaysVisibleArea.HeaderLabel("Pathfinding");
- alwaysVisibleArea.BeginFade();
- #if !ASTAR_ATAVISM
- EditorGUI.BeginDisabledGroup(Application.isPlaying);
- script.threadCount = (ThreadCount)EditorGUILayout.EnumPopup(new GUIContent("Thread Count", "Number of threads to run the pathfinding in (if any). More threads " +
- "can boost performance on multi core systems. \n" +
- "Use None for debugging or if you dont use pathfinding that much.\n " +
- "See docs for more info"), script.threadCount);
- EditorGUI.EndDisabledGroup();
- int threads = AstarPath.CalculateThreadCount(script.threadCount);
- if (threads > 0) EditorGUILayout.HelpBox("Using " + threads +" thread(s)" + (script.threadCount < 0 ? " on your machine" : ""), MessageType.None);
- else EditorGUILayout.HelpBox("Using a single coroutine (no threads)" + (script.threadCount < 0 ? " on your machine" : ""), MessageType.None);
- if (threads > SystemInfo.processorCount) EditorGUILayout.HelpBox("Using more threads than there are CPU cores may not have a positive effect on performance", MessageType.Warning);
- if (script.threadCount == ThreadCount.None) {
- script.maxFrameTime = EditorGUILayout.FloatField(new GUIContent("Max Frame Time", "Max number of milliseconds to use for path calculation per frame"), script.maxFrameTime);
- } else {
- script.maxFrameTime = 10;
- }
- script.maxNearestNodeDistance = EditorGUILayout.FloatField(new GUIContent("Max Nearest Node Distance",
- "Normally, if the nearest node to e.g the start point of a path was not walkable" +
- " a search will be done for the nearest node which is walkble. This is the maximum distance (world units) which it will search"),
- script.maxNearestNodeDistance);
- script.heuristic = (Heuristic)EditorGUILayout.EnumPopup("Heuristic", script.heuristic);
- if (script.heuristic == Heuristic.Manhattan || script.heuristic == Heuristic.Euclidean || script.heuristic == Heuristic.DiagonalManhattan) {
- EditorGUI.indentLevel++;
- script.heuristicScale = EditorGUILayout.FloatField("Heuristic Scale", script.heuristicScale);
- EditorGUI.indentLevel--;
- }
- GUILayout.Label(new GUIContent("Advanced"), EditorStyles.boldLabel);
- DrawHeuristicOptimizationSettings();
- 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);
- if (script.batchGraphUpdates) {
- EditorGUI.indentLevel++;
- script.graphUpdateBatchingInterval = EditorGUILayout.FloatField(new GUIContent("Update Interval (s)", "Minimum number of seconds between each batch of graph updates"), script.graphUpdateBatchingInterval);
- EditorGUI.indentLevel--;
- }
-
-
- if (script.data.FindGraphWhichInheritsFrom(typeof(NavmeshBase)) != null) {
- 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);
- }
- #pragma warning disable 0618
- 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" +
- "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"),
- script.prioritizeGraphs);
- if (script.prioritizeGraphs) {
- EditorGUI.indentLevel++;
- script.prioritizeGraphsLimit = EditorGUILayout.FloatField("Priority Limit", script.prioritizeGraphsLimit);
- EditorGUI.indentLevel--;
- }
- #pragma warning restore 0618
- script.fullGetNearestSearch = EditorGUILayout.Toggle(new GUIContent("Full Get Nearest Node Search", "Forces more accurate searches on all graphs. " +
- "Normally only the closest graph in the initial fast check will perform additional searches, " +
- "if this is toggled, all graphs will do additional searches. Slower, but more accurate"), script.fullGetNearestSearch);
- #endif
- 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);
- alwaysVisibleArea.End();
- }
- void DrawHeuristicOptimizationSettings () {
- script.euclideanEmbedding.mode = (HeuristicOptimizationMode)EditorGUILayout.EnumPopup(new GUIContent("Heuristic Optimization"), script.euclideanEmbedding.mode);
- EditorGUI.indentLevel++;
- if (script.euclideanEmbedding.mode == HeuristicOptimizationMode.Random) {
- script.euclideanEmbedding.spreadOutCount = EditorGUILayout.IntField(new GUIContent("Count", "Number of optimization points, higher numbers give better heuristics and could make it faster, " +
- "but too many could make the overhead too great and slow it down. Try to find the optimal value for your map. Recommended value < 100"), script.euclideanEmbedding.spreadOutCount);
- } else if (script.euclideanEmbedding.mode == HeuristicOptimizationMode.Custom) {
- script.euclideanEmbedding.pivotPointRoot = EditorGUILayout.ObjectField(new GUIContent("Pivot point root",
- "All children of this transform are going to be used as pivot points. " +
- "Recommended count < 100"), script.euclideanEmbedding.pivotPointRoot, typeof(Transform), true) as Transform;
- if (script.euclideanEmbedding.pivotPointRoot == null) {
- EditorGUILayout.HelpBox("Please assign an object", MessageType.Error);
- }
- } else if (script.euclideanEmbedding.mode == HeuristicOptimizationMode.RandomSpreadOut) {
- script.euclideanEmbedding.pivotPointRoot = EditorGUILayout.ObjectField(new GUIContent("Pivot point root",
- "All children of this transform are going to be used as pivot points. " +
- "They will seed the calculation of more pivot points. " +
- "Recommended count < 100"), script.euclideanEmbedding.pivotPointRoot, typeof(Transform), true) as Transform;
- if (script.euclideanEmbedding.pivotPointRoot == null) {
- EditorGUILayout.HelpBox("No root is assigned. A random node will be choosen as the seed.", MessageType.Info);
- }
- script.euclideanEmbedding.spreadOutCount = EditorGUILayout.IntField(new GUIContent("Count", "Number of optimization points, higher numbers give better heuristics and could make it faster, " +
- "but too many could make the overhead too great and slow it down. Try to find the optimal value for your map. Recommended value < 100"), script.euclideanEmbedding.spreadOutCount);
- }
- if (script.euclideanEmbedding.mode != HeuristicOptimizationMode.None) {
- EditorGUILayout.HelpBox("Heuristic optimization assumes the graph remains static. No graph updates, dynamic obstacles or similar should be applied to the graph " +
- "when using heuristic optimization.", MessageType.Info);
- }
- EditorGUI.indentLevel--;
- }
-
- public static void EditTags () {
- AstarPath astar = GameObject.FindObjectOfType<AstarPath>();
- if (astar != null) {
- editTags = true;
- showSettings = true;
- Selection.activeGameObject = astar.gameObject;
- } else {
- Debug.LogWarning("No AstarPath component in the scene");
- }
- }
- void DrawTagSettings () {
- tagsArea.Begin();
- tagsArea.Header("Tag Names", ref editTags);
- if (tagsArea.BeginFade()) {
- string[] tagNames = script.GetTagNames();
- for (int i = 0; i < tagNames.Length; i++) {
- tagNames[i] = EditorGUILayout.TextField(new GUIContent("Tag "+i, "Name for tag "+i), tagNames[i]);
- if (tagNames[i] == "") tagNames[i] = ""+i;
- }
- }
- tagsArea.End();
- }
- void DrawEditorSettings () {
- editorSettingsArea.Begin();
- editorSettingsArea.Header("Editor");
- if (editorSettingsArea.BeginFade()) {
- FadeArea.fancyEffects = EditorGUILayout.Toggle("Smooth Transitions", FadeArea.fancyEffects);
- }
- editorSettingsArea.End();
- }
- static void DrawColorSlider (ref float left, ref float right, bool editable) {
- GUILayout.BeginHorizontal();
- GUILayout.Space(20);
- GUILayout.BeginVertical();
- GUILayout.Box("", astarSkin.GetStyle("ColorInterpolationBox"));
- GUILayout.BeginHorizontal();
- if (editable) {
- left = EditorGUILayout.IntField((int)left);
- } else {
- GUILayout.Label(left.ToString("0"));
- }
- GUILayout.FlexibleSpace();
- if (editable) {
- right = EditorGUILayout.IntField((int)right);
- } else {
- GUILayout.Label(right.ToString("0"));
- }
- GUILayout.EndHorizontal();
- GUILayout.EndVertical();
- GUILayout.Space(4);
- GUILayout.EndHorizontal();
- }
- void DrawDebugSettings () {
- alwaysVisibleArea.Begin();
- alwaysVisibleArea.HeaderLabel("Debug");
- alwaysVisibleArea.BeginFade();
- script.logPathResults = (PathLog)EditorGUILayout.EnumPopup("Path Logging", script.logPathResults);
- script.debugMode = (GraphDebugMode)EditorGUILayout.EnumPopup("Graph Coloring", script.debugMode);
- if (script.debugMode == GraphDebugMode.SolidColor) {
- EditorGUI.BeginChangeCheck();
- script.colorSettings._SolidColor = EditorGUILayout.ColorField(new GUIContent("Color", "Color used for the graph when 'Graph Coloring'='Solid Color'"), script.colorSettings._SolidColor);
- if (EditorGUI.EndChangeCheck()) {
- script.colorSettings.PushToStatic(script);
- }
- }
- if (script.debugMode == GraphDebugMode.G || script.debugMode == GraphDebugMode.H || script.debugMode == GraphDebugMode.F || script.debugMode == GraphDebugMode.Penalty) {
- script.manualDebugFloorRoof = !EditorGUILayout.Toggle("Automatic Limits", !script.manualDebugFloorRoof);
- DrawColorSlider(ref script.debugFloor, ref script.debugRoof, script.manualDebugFloorRoof);
- }
- script.showSearchTree = EditorGUILayout.Toggle("Show Search Tree", script.showSearchTree);
- if (script.showSearchTree) {
- EditorGUILayout.HelpBox("Show Search Tree is enabled, you may see rendering glitches in the graph rendering" +
- " 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" +
- " are being rendered. You can pause the game to see an accurate rendering.", MessageType.Info);
- }
- script.showUnwalkableNodes = EditorGUILayout.Toggle("Show Unwalkable Nodes", script.showUnwalkableNodes);
- if (script.showUnwalkableNodes) {
- EditorGUI.indentLevel++;
- script.unwalkableNodeDebugSize = EditorGUILayout.FloatField("Size", script.unwalkableNodeDebugSize);
- EditorGUI.indentLevel--;
- }
- alwaysVisibleArea.End();
- }
- void DrawColorSettings () {
- colorSettingsArea.Begin();
- colorSettingsArea.Header("Colors");
- if (colorSettingsArea.BeginFade()) {
-
- AstarColor colors = script.colorSettings = script.colorSettings ?? new AstarColor();
- colors._SolidColor = EditorGUILayout.ColorField(new GUIContent("Solid Color", "Color used for the graph when 'Graph Coloring'='Solid Color'"), colors._SolidColor);
- colors._UnwalkableNode = EditorGUILayout.ColorField("Unwalkable Node", colors._UnwalkableNode);
- colors._BoundsHandles = EditorGUILayout.ColorField("Bounds Handles", colors._BoundsHandles);
- colors._ConnectionLowLerp = EditorGUILayout.ColorField("Connection Gradient (low)", colors._ConnectionLowLerp);
- colors._ConnectionHighLerp = EditorGUILayout.ColorField("Connection Gradient (high)", colors._ConnectionHighLerp);
- colors._MeshEdgeColor = EditorGUILayout.ColorField("Mesh Edge", colors._MeshEdgeColor);
- if (EditorResourceHelper.GizmoSurfaceMaterial != null && EditorResourceHelper.GizmoLineMaterial != null) {
- EditorGUI.BeginChangeCheck();
- var col1 = EditorResourceHelper.GizmoSurfaceMaterial.color;
- col1.a = EditorGUILayout.Slider("Navmesh Surface Opacity", col1.a, 0, 1);
- var col2 = EditorResourceHelper.GizmoLineMaterial.color;
- col2.a = EditorGUILayout.Slider("Navmesh Outline Opacity", col2.a, 0, 1);
- var fade = EditorResourceHelper.GizmoSurfaceMaterial.GetColor("_FadeColor");
- fade.a = EditorGUILayout.Slider("Opacity Behind Objects", fade.a, 0, 1);
- if (EditorGUI.EndChangeCheck()) {
- Undo.RecordObjects(new [] { EditorResourceHelper.GizmoSurfaceMaterial, EditorResourceHelper.GizmoLineMaterial }, "Change navmesh transparency");
- EditorResourceHelper.GizmoSurfaceMaterial.color = col1;
- EditorResourceHelper.GizmoLineMaterial.color = col2;
- EditorResourceHelper.GizmoSurfaceMaterial.SetColor("_FadeColor", fade);
- EditorResourceHelper.GizmoLineMaterial.SetColor("_FadeColor", fade * new Color(1, 1, 1, 0.7f));
- }
- }
- colors._AreaColors = colors._AreaColors ?? new Color[0];
-
- customAreaColorsOpen = EditorGUILayout.Foldout(customAreaColorsOpen, "Custom Area Colors");
- if (customAreaColorsOpen) {
- EditorGUI.indentLevel += 2;
- for (int i = 0; i < colors._AreaColors.Length; i++) {
- GUILayout.BeginHorizontal();
- colors._AreaColors[i] = EditorGUILayout.ColorField("Area "+i+(i == 0 ? " (not used usually)" : ""), colors._AreaColors[i]);
- if (GUILayout.Button(new GUIContent("", "Reset to the default color"), astarSkin.FindStyle("SmallReset"), GUILayout.Width(20))) {
- colors._AreaColors[i] = AstarMath.IntToColor(i, 1F);
- }
- GUILayout.EndHorizontal();
- }
- GUILayout.BeginHorizontal();
- EditorGUI.BeginDisabledGroup(colors._AreaColors.Length > 255);
- if (GUILayout.Button("Add New")) {
- var newcols = new Color[colors._AreaColors.Length+1];
- colors._AreaColors.CopyTo(newcols, 0);
- newcols[newcols.Length-1] = AstarMath.IntToColor(newcols.Length-1, 1F);
- colors._AreaColors = newcols;
- }
- EditorGUI.EndDisabledGroup();
- EditorGUI.BeginDisabledGroup(colors._AreaColors.Length == 0);
- if (GUILayout.Button("Remove last") && colors._AreaColors.Length > 0) {
- var newcols = new Color[colors._AreaColors.Length-1];
- for (int i = 0; i < colors._AreaColors.Length-1; i++) {
- newcols[i] = colors._AreaColors[i];
- }
- colors._AreaColors = newcols;
- }
- EditorGUI.EndDisabledGroup();
- GUILayout.EndHorizontal();
- EditorGUI.indentLevel -= 2;
- }
- if (GUI.changed) {
- colors.PushToStatic(script);
- }
- }
- colorSettingsArea.End();
- }
-
- void CheckGraphEditors (bool forceRebuild = false) {
- if (forceRebuild || graphEditors == null || script.graphs == null || script.graphs.Length != graphEditors.Length) {
- if (script.data.graphs == null) {
- script.data.graphs = new NavGraph[0];
- }
- graphEditors = new GraphEditor[script.graphs.Length];
- for (int i = 0; i < script.graphs.Length; i++) {
- NavGraph graph = script.graphs[i];
- if (graph == null) continue;
- if (graph.guid == new Pathfinding.Util.Guid()) {
- graph.guid = Pathfinding.Util.Guid.NewGuid();
- }
- graphEditors[i] = CreateGraphEditor(graph);
- }
- } else {
- for (int i = 0; i < script.graphs.Length; i++) {
- if (script.graphs[i] == null) continue;
- if (graphEditors[i] == null || graphEditorTypes[script.graphs[i].GetType().Name].editorType != graphEditors[i].GetType()) {
- CheckGraphEditors(true);
- return;
- }
- if (script.graphs[i].guid == new Pathfinding.Util.Guid()) {
- script.graphs[i].guid = Pathfinding.Util.Guid.NewGuid();
- }
- graphEditors[i].target = script.graphs[i];
- }
- }
- }
- void RemoveGraph (NavGraph graph) {
- script.data.RemoveGraph(graph);
- CheckGraphEditors(true);
- GUI.changed = true;
- Repaint();
- }
- void AddGraph (System.Type type) {
- script.data.AddGraph(type);
- CheckGraphEditors();
- GUI.changed = true;
- }
-
- GraphEditor CreateGraphEditor (NavGraph graph) {
- var graphType = graph.GetType().Name;
- GraphEditor result;
- if (graphEditorTypes.ContainsKey(graphType)) {
- result = System.Activator.CreateInstance(graphEditorTypes[graphType].editorType) as GraphEditor;
- } else {
- Debug.LogError("Couldn't find an editor for the graph type '" + graphType + "' There are " + graphEditorTypes.Count + " available graph editors");
- result = new GraphEditor();
- }
- result.editor = this;
- result.fadeArea = new FadeArea(graph.open, this, level1AreaStyle, level1LabelStyle);
- result.infoFadeArea = new FadeArea(graph.infoScreenOpen, this, null, null);
- result.target = graph;
- result.OnEnable();
- return result;
- }
- bool HandleUndo () {
-
- if (script.data.GetData() == null) {
- script.data.SetData(new byte[0]);
- } else {
- LoadGraphs();
- return true;
- }
- return false;
- }
-
- static int ByteArrayHash (byte[] arr) {
- if (arr == null) return -1;
- int hash = -1;
- for (int i = 0; i < arr.Length; i++) {
- hash ^= (arr[i]^i)*3221;
- }
- return hash;
- }
- void SerializeIfDataChanged () {
- uint checksum;
- byte[] bytes = SerializeGraphs(out checksum);
- int byteHash = ByteArrayHash(bytes);
- int dataHash = ByteArrayHash(script.data.GetData());
-
- bool isDifferent = checksum != ignoredChecksum && dataHash != byteHash;
-
- if (isDifferent) {
-
- script.data.SetData(bytes);
- EditorUtility.SetDirty(script);
- Undo.IncrementCurrentGroup();
- Undo.RegisterCompleteObjectUndo(script, "A* Graph Settings");
- }
- }
-
- void OnUndoRedoPerformed () {
- if (!this) return;
- uint checksum;
- byte[] bytes = SerializeGraphs(out checksum);
-
- bool isDifferent = ByteArrayHash(script.data.GetData()) != ByteArrayHash(bytes);
- if (isDifferent) {
- HandleUndo();
- }
- CheckGraphEditors();
-
-
-
- SerializeGraphs(out checksum);
- ignoredChecksum = checksum;
- }
- public void SaveGraphsAndUndo (EventType et = EventType.Used, string eventCommand = "") {
-
-
-
-
- if (Application.isPlaying || script.isScanning || script.IsAnyWorkItemInProgress) {
- return;
- }
- if ((Undo.GetCurrentGroup() != lastUndoGroup || et == EventType.MouseUp) && eventCommand != "UndoRedoPerformed") {
- SerializeIfDataChanged();
- lastUndoGroup = Undo.GetCurrentGroup();
- }
- if (Event.current == null || script.data.GetData() == null) {
- SerializeIfDataChanged();
- return;
- }
- }
-
- public void LoadGraphs () {
- DeserializeGraphs();
- }
- public byte[] SerializeGraphs (out uint checksum) {
- var settings = Pathfinding.Serialization.SerializeSettings.Settings;
- settings.editorSettings = true;
- return SerializeGraphs(settings, out checksum);
- }
- public byte[] SerializeGraphs (Pathfinding.Serialization.SerializeSettings settings, out uint checksum) {
- byte[] bytes = null;
- uint tmpChecksum = 0;
-
- var output = new System.Text.StringBuilder();
- for (int i = 0; i < graphEditors.Length; i++) {
- if (graphEditors[i] == null) continue;
- output.Length = 0;
- Pathfinding.Serialization.TinyJsonSerializer.Serialize(graphEditors[i], output);
- (graphEditors[i].target as IGraphInternals).SerializedEditorSettings = output.ToString();
- }
-
- bytes = script.data.SerializeGraphs(settings, out tmpChecksum);
-
- AstarPath.active.FlushWorkItems();
- checksum = tmpChecksum;
- return bytes;
- }
- void DeserializeGraphs () {
- if (script.data.GetData() == null || script.data.GetData().Length == 0) {
- script.data.graphs = new NavGraph[0];
- } else {
- DeserializeGraphs(script.data.GetData());
- }
- }
- void DeserializeGraphs (byte[] bytes) {
- try {
- script.data.DeserializeGraphs(bytes);
-
- CheckGraphEditors();
-
- for (int i = 0; i < graphEditors.Length; i++) {
- var data = (graphEditors[i].target as IGraphInternals).SerializedEditorSettings;
- if (data != null) Pathfinding.Serialization.TinyJsonDeserializer.Deserialize(data, graphEditors[i].GetType(), graphEditors[i], script.gameObject);
- }
- } catch (System.Exception e) {
- Debug.LogError("Failed to deserialize graphs");
- Debug.LogException(e);
- script.data.SetData(null);
- }
- }
- [MenuItem("Edit/Pathfinding/Scan All Graphs %&s")]
- public static void MenuScan () {
- if (AstarPath.active == null) {
- AstarPath.active = FindObjectOfType<AstarPath>();
- if (AstarPath.active == null) {
- return;
- }
- }
- if (!Application.isPlaying && (AstarPath.active.data.graphs == null || AstarPath.active.data.graphTypes == null)) {
- EditorUtility.DisplayProgressBar("Scanning", "Deserializing", 0);
- AstarPath.active.data.DeserializeGraphs();
- }
- try {
- var lastMessageTime = Time.realtimeSinceStartup;
- foreach (var p in AstarPath.active.ScanAsync()) {
-
- if (Time.realtimeSinceStartup - lastMessageTime > 0.2f) {
-
- UnityEditor.EditorUtility.DisplayProgressBar("Scanning", p.description, p.progress);
- lastMessageTime = Time.realtimeSinceStartup;
- }
- }
-
-
- UnityEditorInternal.InternalEditorUtility.RepaintAllViews();
- } catch (System.Exception e) {
- 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");
- EditorUtility.DisplayDialog("Error Generating Graphs", "There was an error when generating graphs, check the console for more info", "Ok");
- throw e;
- } finally {
- EditorUtility.ClearProgressBar();
- }
- }
-
- void FindGraphTypes () {
- graphEditorTypes = new Dictionary<string, CustomGraphEditorAttribute>();
- var graphList = new List<System.Type>();
- foreach (var assembly in System.AppDomain.CurrentDomain.GetAssemblies()) {
- System.Type[] types = null;
- try {
- types = assembly.GetTypes();
- } catch {
-
-
- continue;
- }
-
- foreach (var type in types) {
- System.Type baseType = type.BaseType;
- while (!System.Type.Equals(baseType, null)) {
- if (System.Type.Equals(baseType, typeof(GraphEditor))) {
- System.Object[] att = type.GetCustomAttributes(false);
-
- foreach (System.Object attribute in att) {
- var cge = attribute as CustomGraphEditorAttribute;
- if (cge != null && !System.Type.Equals(cge.graphType, null)) {
- cge.editorType = type;
- graphList.Add(cge.graphType);
- graphEditorTypes.Add(cge.graphType.Name, cge);
- }
- }
- break;
- }
- baseType = baseType.BaseType;
- }
- }
- }
-
- script.data.FindGraphTypes();
- }
- }
- }
|