1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
|
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.Reflection;
using Pathfinding.Graphs.Util;
using Pathfinding.Util;
namespace Pathfinding {
[CustomEditor(typeof(AstarPath))]
public class AstarPathEditor : Editor {
/// <summary>List of all graph editors available (e.g GridGraphEditor)</summary>
static Dictionary<string, CustomGraphEditorAttribute> graphEditorTypes = new Dictionary<string, CustomGraphEditorAttribute>();
/// <summary>
/// Holds node counts for each graph to avoid calculating it every frame.
/// Only used for visualization purposes
/// </summary>
static Dictionary<NavGraph, KeyValuePair<float, KeyValuePair<int, int> > > graphNodeCounts;
/// <summary>List of all graph editors for the graphs</summary>
GraphEditor[] graphEditors;
System.Type[] graphTypes {
get {
return script.data.graphTypes;
}
}
static int lastUndoGroup = -1000;
/// <summary>Used to make sure correct behaviour when handling undos</summary>
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
/// <summary>AstarPath instance that is being inspected</summary>
public AstarPath script { get; private set; }
public bool isPrefab { 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
/// <summary>Holds defines found in script files, used for optimizations.</summary>
List<OptimizationHandler.DefineDefinition> defines;
/// <summary>Enables editor stuff. Loads graphs, reads settings and sets everything up</summary>
public void OnEnable () {
script = target as AstarPath;
isPrefab = PrefabUtility.IsPartOfPrefabAsset(script);
// Make sure all references are set up to avoid NullReferenceExceptions
script.ConfigureReferencesInternal();
if (!isPrefab) HideToolsWhileActive();
Undo.undoRedoPerformed += OnUndoRedoPerformed;
// Search the assembly for graph types and graph editors
if (graphEditorTypes == null || graphEditorTypes.Count == 0)
FindGraphTypes();
try {
GetAstarEditorSettings();
} catch (System.Exception e) {
Debug.LogException(e);
}
LoadStyles();
// Load graphs only when not playing, or in extreme cases, when data.graphs is null
if ((!Application.isPlaying && (script.data == null || script.data.graphs == null || script.data.graphs.Length == 0)) || script.data.graphs == null) {
LoadGraphs();
}
CreateFadeAreas();
}
/// <summary>
/// Hide position/rotation/scale tools for the AstarPath object. Instead, OnSceneGUI will draw position tools for each graph.
///
/// We cannot rely on the inspector's OnEnable/OnDisable events, because they are tied to the lifetime of the inspector,
/// which does not necessarily follow which object is selected. In particular if there are multiple inspector windows, or
/// an inspector window is locked.
/// </summary>
void HideToolsWhileActive () {
EditorApplication.CallbackFunction toolsCheck = null;
var activelyHidden = true;
Tools.hidden = true;
AssemblyReloadEvents.AssemblyReloadCallback onAssemblyReload = () => {
if (activelyHidden) {
Tools.hidden = false;
activelyHidden = false;
}
};
// Ensure that the tools become visible when Unity reloads scripts.
// To avoid it getting stuck in the hidden state.
AssemblyReloadEvents.beforeAssemblyReload += onAssemblyReload;
toolsCheck = () => {
// This will trigger if the inspector is disabled
if (script == null) {
EditorApplication.update -= toolsCheck;
AssemblyReloadEvents.beforeAssemblyReload -= onAssemblyReload;
if (activelyHidden) {
Tools.hidden = false;
activelyHidden = false;
}
return;
}
if (Selection.activeGameObject == script.gameObject) {
Tools.hidden = true;
activelyHidden = true;
} else if (activelyHidden) {
Tools.hidden = false;
activelyHidden = false;
}
};
EditorApplication.update += toolsCheck;
}
void CreateFadeAreas () {
if (settingsArea == null) {
aboutArea = new FadeArea(false, this, level0AreaStyle, level0LabelStyle);
optimizationSettingsArea = new FadeArea(false, this, level0AreaStyle, level0LabelStyle);
graphsArea = new FadeArea(script.showGraphs, 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);
}
}
/// <summary>Cleans up editor stuff</summary>
public void OnDisable () {
Undo.undoRedoPerformed -= OnUndoRedoPerformed;
SetAstarEditorSettings();
script = null;
}
/// <summary>Reads settings frome EditorPrefs</summary>
void GetAstarEditorSettings () {
FadeArea.fancyEffects = EditorPrefs.GetBool("EditorGUILayoutx.fancyEffects", true);
}
void SetAstarEditorSettings () {
EditorPrefs.SetBool("EditorGUILayoutx.fancyEffects", FadeArea.fancyEffects);
}
/// <summary>
/// Repaints Scene View.
/// Warning: Uses Undocumented Unity Calls (should be safe for Unity 3.x though)
/// </summary>
void RepaintSceneView () {
if (!Application.isPlaying || EditorApplication.isPaused) SceneView.RepaintAll();
}
/// <summary>Tell Unity that we want to use the whole inspector width</summary>
public override bool UseDefaultMargins () {
return false;
}
public override void OnInspectorGUI () {
// Do some loading and checking
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 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();
// End loading and checking
EditorGUI.indentLevel = 1;
// Apparently these can sometimes get eaten by unity components
// so I catch them here for later use
EventType storedEventType = Event.current.type;
string storedEventCommand = Event.current.commandName;
DrawMainArea();
GUILayout.Space(5);
if (isPrefab) {
EditorGUI.BeginDisabledGroup(true);
GUILayout.Button(new GUIContent("Scan", "Cannot recalculate graphs on prefabs"));
EditorGUI.EndDisabledGroup();
} else {
if (GUILayout.Button(new GUIContent("Scan", "Recalculate all graphs. Shortcut cmd+alt+s ( ctrl+alt+s on windows )"))) {
RunTask(MenuScan);
}
}
// Handle undo
SaveGraphsAndUndo(storedEventType, storedEventCommand);
if (EditorGUI.EndChangeCheck()) {
RepaintSceneView();
EditorUtility.SetDirty(script);
}
}
/// <summary>
/// Loads GUISkin and sets up styles.
/// See: EditorResourceHelper.LocateEditorAssets
/// Returns: True if all styles were found, false if there was an error somewhere
/// </summary>
public static bool LoadStyles () {
if (stylesLoaded) return true;
// Dummy styles in case the loading fails
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 the first style is null, then the rest are likely corrupted as well
// Probably due to the user not copying meta files
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;
}
/// <summary>Draws the main area in the inspector</summary>
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 && script.graphs[i].showInInspector) {
anyNonNull = true;
DrawGraph(graphEditors[i]);
}
}
// Draw the Add Graph button
addGraphsArea.Begin();
addGraphsArea.open |= !anyNonNull;
addGraphsArea.Header("Add New Graph");
if (addGraphsArea.BeginFade()) {
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") && graphTypes[i] != typeof(LinkGraph)) {
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();
}
}
/// <summary>Draws optimizations settings.</summary>
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))) {
RunTask(() => {
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();
}
/// <summary>
/// Returns a version with all fields fully defined.
/// This is used because by default new Version(3,0,0) > new Version(3,0).
/// This is not the desired behaviour so we make sure that all fields are defined here
/// </summary>
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;
// Check if either the latest release version or the latest beta version is newer than this version
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;
}
}
// Check if the latest version is newer than this version
if (FullyDefinedVersion(newVersion) > FullyDefinedVersion(AstarPath.Version)
) {
GUIUtilityx.PushTint(Color.green);
if (GUILayout.Button((beta ? "Beta" : "New") + " Version Available! "+newVersion, thinHelpBox, GUILayout.Height(16))) {
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();
}
/// <summary>Graph editor which has its 'name' field focused</summary>
GraphEditor graphNameFocused;
void DrawGraphHeader (GraphEditor graphEditor) {
var graph = graphEditor.target;
// Graph guid, just used to get a unique value
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));
// Mark the name field as deselected when it has been deselected or when the user presses Return or Escape
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 the graph name text field is not focused and the graph name is empty, then fill it in
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();
}
}
// The OnInspectorGUI method ensures that the scene view is repainted when gizmos are toggled on or off by checking for EndChangeCheck
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;
// Calculate number of nodes in the graph
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();
}
/// <summary>Draws the inspector for the given graph with the given graph editor</summary>
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();
// OnSceneGUI may be called from EditorUtility.DisplayProgressBar
// which is called repeatedly while the graphs are scanned in the
// editor. However running the OnSceneGUI method while the graphs
// are being scanned is a bad idea since it can interfere with
// scanning, especially by serializing changes
if (script.isScanning) {
return;
}
script.ConfigureReferencesInternal();
EditorGUI.BeginChangeCheck();
if (!LoadStyles()) return;
// Some GUI controls might change this to Used, so we need to grab it here
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] != 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)) {
RunTask(MenuScan);
}
// Invisible button to capture clicks. This prevents a click inside the box from causing some other GameObject to be selected.
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 {
// Find a valid file name
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);
// Make sure we can write to the file
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(16));
GUILayout.Space(20);
GUIUtilityx.PopTint();
}
GUILayout.EndHorizontal();
// This displays the serialization settings
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")) {
RunTask(() => {
var serializationSettings = new Pathfinding.Serialization.SerializeSettings();
if (isPrefab) {
if (!EditorUtility.DisplayDialog("Can only save settings", "Only graph settings can be saved when the AstarPath object is a prefab. Instantiate the prefab in a scene to be able to save node data as well.", "Save settings", "Cancel")) {
return;
}
} else {
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();
}
}
// Save graphs
var bytes = script.data.SerializeGraphs(serializationSettings);
// Store it in a file
script.data.file_cachedStartup = SaveGraphData(bytes, script.data.file_cachedStartup);
script.data.cacheStartup = true;
});
}
if (GUILayout.Button("Load from cache")) {
RunTask(() => {
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();
GUILayout.Space(5);
GUILayout.BeginHorizontal();
if (GUILayout.Button("Save to file")) {
RunTask(() => {
string path = EditorUtility.SaveFilePanel("Save Graphs", "", "graph.bytes", "bytes");
if (path != "") {
var serializationSettings = Pathfinding.Serialization.SerializeSettings.Settings;
if (isPrefab) {
if (!EditorUtility.DisplayDialog("Can only save settings", "Only graph settings can be saved when the AstarPath object is a prefab. Instantiate the prefab in a scene to be able to save node data as well.", "Save settings", "Cancel")) {
return;
}
} else {
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")) {
RunTask(() => {
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();
}
public void RunTask (System.Action action) {
EditorApplication.CallbackFunction wrapper = null;
wrapper = () => {
try {
// Run the callback only if the editor has not been disabled since the task was scheduled
if (script != null) action();
} finally {
EditorApplication.update -= wrapper;
}
};
EditorApplication.update += wrapper;
}
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);
script.heuristicScale = Mathf.Clamp01(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--;
}
// Only show if there is actually a navmesh/recast graph in the scene
// to help reduce clutter for other users.
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);
}
#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();
}
readonly string[] heuristicOptimizationOptions = new [] {
"None",
"Random (low quality)",
"RandomSpreadOut (high quality)",
"Custom"
};
void DrawHeuristicOptimizationSettings () {
script.euclideanEmbedding.mode = (HeuristicOptimizationMode)EditorGUILayout.Popup(new GUIContent("Heuristic Optimization"), (int)script.euclideanEmbedding.mode, heuristicOptimizationOptions);
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--;
}
/// <summary>Opens the A* Inspector and shows the section for editing tags</summary>
public static void EditTags () {
AstarPath astar = UnityCompatibility.FindAnyObjectByType<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()) {
// Make sure the object is not null
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];
// Custom Area Colors
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();
}
/// <summary>Make sure every graph has a graph editor</summary>
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();
}
if (graph.showInInspector) graphEditors[i] = CreateGraphEditor(graph);
}
} else {
for (int i = 0; i < script.graphs.Length; i++) {
var graph = script.graphs[i];
if (graph == null || !graph.showInInspector) continue;
// TODO
if (graphEditors[i] == null || !graphEditorTypes.TryGetValue(graph.GetType().Name, out var ed) || ed.editorType != graphEditors[i].GetType()) {
CheckGraphEditors(true);
return;
}
if (graph.guid == new Pathfinding.Util.Guid()) {
graph.guid = Pathfinding.Util.Guid.NewGuid();
}
graphEditors[i].target = graph;
}
}
}
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;
}
/// <summary>Creates a GraphEditor for a graph</summary>
GraphEditor CreateGraphEditor (NavGraph graph) {
var graphType = graph.GetType().Name;
GraphEditor result;
if (graphEditorTypes.TryGetValue(graphType, out var graphEditorTypeAttr)) {
var graphEditorType = graphEditorTypeAttr.editorType;
result = System.Activator.CreateInstance(graphEditorType) as GraphEditor;
// Deserialize editor settings
var editorData = (graph as IGraphInternals).SerializedEditorSettings;
if (editorData != null) Pathfinding.Serialization.TinyJsonDeserializer.Deserialize(editorData, graphEditorType, result, script.gameObject);
} else {
Debug.LogError("Couldn't find an editor for the graph type '" + graphType + "' There are " + graphEditorTypes.Count + " available graph editors");
result = new GraphEditor();
graphEditorTypes[graphType] = new CustomGraphEditorAttribute(graph.GetType(), graphType) {
editorType = typeof(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;
}
void HandleUndo () {
// The user has tried to undo something, apply that
if (script.data.GetData() == null) {
script.data.SetData(new byte[0]);
} else {
LoadGraphs();
}
}
/// <summary>Hashes the contents of a byte array</summary>
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 () {
byte[] bytes = SerializeGraphs(out var checksum);
int byteHash = ByteArrayHash(bytes);
int dataHash = ByteArrayHash(script.data.GetData());
//Check if the data is different than the previous data, use checksums
bool isDifferent = checksum != ignoredChecksum && dataHash != byteHash;
//Only save undo if the data was different from the last saved undo
if (isDifferent) {
Undo.RegisterCompleteObjectUndo(script, "A* Graph Settings");
Undo.IncrementCurrentGroup();
//Assign the new data
script.data.SetData(bytes);
EditorUtility.SetDirty(script);
}
}
/// <summary>Called when an undo or redo operation has been performed</summary>
void OnUndoRedoPerformed () {
if (!this) return;
byte[] bytes = SerializeGraphs(out var checksum);
//Check if the data is different than the previous data, use checksums
bool isDifferent = ByteArrayHash(script.data.GetData()) != ByteArrayHash(bytes);
if (isDifferent) {
HandleUndo();
}
CheckGraphEditors();
// Deserializing a graph does not necessarily yield the same hash as the data loaded from
// this is (probably) because editor settings are not saved all the time
// so we explicitly ignore the new hash
SerializeGraphs(out checksum);
ignoredChecksum = checksum;
}
public void SaveGraphsAndUndo (EventType et = EventType.Used, string eventCommand = "") {
// Serialize the settings of the graphs
// Dont process undo events in editor, we don't want to reset graphs
// Also don't do this if the graph is being updated as serializing the graph
// might interfere with that (in particular it might unblock the path queue).
// Also don't do this if the AstarPath object is not the active one, since serialization uses the singleton in some ways.
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;
}
}
/// <summary>Load graphs from serialized data</summary>
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) {
CheckGraphEditors();
// Serialize all graph editors
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();
}
// Serialize all graphs (including serialized editor data)
return script.data.SerializeGraphs(settings, out checksum);
}
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);
// Make sure every graph has a graph editor
CheckGraphEditors();
} 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.FindAstarPath();
if (AstarPath.active == null) {
return;
}
}
try {
var lastMessageTime = Time.realtimeSinceStartup;
foreach (var p in AstarPath.active.ScanAsync()) {
// Displaying the progress bar is pretty slow, so don't do it too often
if (Time.realtimeSinceStartup - lastMessageTime > 0.2f) {
// Display a progress bar of the scan
UnityEditor.EditorUtility.DisplayProgressBar("Scanning", p.ToString(), p.progress);
lastMessageTime = Time.realtimeSinceStartup;
}
}
// Repaint the game view in addition to just the scene view.
// In case the user only has the game view open it's nice to refresh it so they can see the graph.
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();
}
}
/// <summary>Searches in the current assembly for GraphEditor and NavGraph types</summary>
void FindGraphTypes () {
graphEditorTypes = new Dictionary<string, CustomGraphEditorAttribute>();
foreach (var assembly in System.AppDomain.CurrentDomain.GetAssemblies()) {
System.Type[] types = null;
try {
types = assembly.GetTypes();
} catch {
// Ignore type load exceptions and things like that.
// We might not be able to read all assemblies for some reason, but hopefully the relevant types exist in the assemblies that we can read
continue;
}
// Iterate through the assembly for classes which inherit from GraphEditor
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);
// Loop through the attributes for the CustomGraphEditorAttribute attribute
foreach (var attribute in att) {
if (attribute is CustomGraphEditorAttribute cge && !System.Type.Equals(cge.graphType, null)) {
cge.editorType = type;
graphEditorTypes.Add(cge.graphType.Name, cge);
}
}
break;
}
baseType = baseType.BaseType;
}
}
}
// Make sure graph types (not graph editor types) are also up to date
script.data.FindGraphTypes();
}
}
}
|