-
Notifications
You must be signed in to change notification settings - Fork 866
Expand file tree
/
Copy pathMaterialGraphEditWindow.cs
More file actions
1325 lines (1146 loc) · 53.5 KB
/
MaterialGraphEditWindow.cs
File metadata and controls
1325 lines (1146 loc) · 53.5 KB
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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEditor.Graphing;
using UnityEditor.Graphing.Util;
using Debug = UnityEngine.Debug;
using Object = UnityEngine.Object;
using UnityEngine.Rendering;
using UnityEditor.UIElements;
using Edge = UnityEditor.Experimental.GraphView.Edge;
using UnityEditor.Experimental.GraphView;
using UnityEditor.ShaderGraph.Internal;
using UnityEditor.ShaderGraph.Serialization;
using UnityEngine.UIElements;
using UnityEditor.VersionControl;
using Unity.Profiling;
using UnityEngine.Assertions;
namespace UnityEditor.ShaderGraph.Drawing
{
class MaterialGraphEditWindow : EditorWindow
{
// For conversion to Sub Graph: keys for remembering the user's desired path
const string k_PrevSubGraphPathKey = "SHADER_GRAPH_CONVERT_TO_SUB_GRAPH_PATH";
const string k_PrevSubGraphPathDefaultValue = "?"; // Special character that NTFS does not allow, so that no directory could match it.
[SerializeField]
string m_Selected;
[SerializeField]
GraphObject m_GraphObject;
// this stores the contents of the file on disk, as of the last time we saved or loaded it from disk
[SerializeField]
string m_LastSerializedFileContents;
[NonSerialized]
HashSet<string> m_ChangedFileDependencyGUIDs = new HashSet<string>();
ColorSpace m_ColorSpace;
RenderPipelineAsset m_RenderPipelineAsset;
[NonSerialized]
bool m_FrameAllAfterLayout;
[NonSerialized]
bool m_HasError;
[NonSerialized]
bool m_ProTheme;
[NonSerialized]
int m_customInterpWarn;
[NonSerialized]
int m_customInterpErr;
[SerializeField]
bool m_AssetMaybeChangedOnDisk;
[SerializeField]
bool m_AssetMaybeDeleted;
MessageManager m_MessageManager;
MessageManager messageManager
{
get { return m_MessageManager ?? (m_MessageManager = new MessageManager()); }
}
GraphEditorView m_GraphEditorView;
internal GraphEditorView graphEditorView
{
get { return m_GraphEditorView; }
private set
{
if (m_GraphEditorView != null)
{
m_GraphEditorView.RemoveFromHierarchy();
m_GraphEditorView.Dispose();
}
m_GraphEditorView = value;
if (m_GraphEditorView != null)
{
m_GraphEditorView.saveRequested += () => SaveAsset();
m_GraphEditorView.saveAsRequested += SaveAs;
m_GraphEditorView.convertToSubgraphRequested += ToSubGraph;
m_GraphEditorView.showInProjectRequested += PingAsset;
m_GraphEditorView.isCheckedOut += IsGraphAssetCheckedOut;
m_GraphEditorView.checkOut += CheckoutAsset;
m_GraphEditorView.RegisterCallback<GeometryChangedEvent>(OnGeometryChanged);
m_FrameAllAfterLayout = true;
this.rootVisualElement.Add(graphEditorView);
}
}
}
internal GraphObject graphObject
{
get { return m_GraphObject; }
set
{
if (m_GraphObject != null)
DestroyImmediate(m_GraphObject);
m_GraphObject = value;
}
}
public string selectedGuid
{
get { return m_Selected; }
private set
{
m_Selected = value;
}
}
public string assetName
{
get { return titleContent.text; }
}
bool AssetFileExists()
{
var assetPath = AssetDatabase.GUIDToAssetPath(selectedGuid);
return File.Exists(assetPath);
}
// returns true when the graph has been successfully saved, or the user has indicated they are ok with discarding the local graph
// returns false when saving has failed
bool DisplayDeletedFromDiskDialog(bool reopen = true)
{
// first double check if we've actually been deleted
bool saved = false;
bool okToClose = false;
string originalAssetPath = AssetDatabase.GUIDToAssetPath(selectedGuid);
while (true)
{
int option = EditorUtility.DisplayDialogComplex(
"Graph removed from project",
"The file has been deleted or removed from the project folder.\n\n" +
originalAssetPath +
"\n\nWould you like to save your Graph Asset?",
"Save As...", "Cancel", "Discard Graph and Close Window");
if (option == 0)
{
string savedPath = SaveAsImplementation(false);
if (savedPath != null)
{
saved = true;
// either close or reopen the local window editor
graphObject = null;
selectedGuid = (reopen ? AssetDatabase.AssetPathToGUID(savedPath) : null);
break;
}
}
else if (option == 2)
{
okToClose = true;
graphObject = null;
selectedGuid = null;
break;
}
else if (option == 1)
{
// continue in deleted state...
break;
}
}
return (saved || okToClose);
}
void Update()
{
if (m_HasError)
return;
bool updateTitle = false;
if (m_AssetMaybeDeleted)
{
m_AssetMaybeDeleted = false;
if (AssetFileExists())
{
// it exists... just to be sure, let's check if it changed
m_AssetMaybeChangedOnDisk = true;
}
else
{
// it was really deleted, ask the user what to do
bool handled = DisplayDeletedFromDiskDialog(true);
}
updateTitle = true;
}
if (PlayerSettings.colorSpace != m_ColorSpace)
{
graphEditorView = null;
m_ColorSpace = PlayerSettings.colorSpace;
}
if (GraphicsSettings.renderPipelineAsset != m_RenderPipelineAsset)
{
graphEditorView = null;
m_RenderPipelineAsset = GraphicsSettings.renderPipelineAsset;
}
if (EditorGUIUtility.isProSkin != m_ProTheme)
{
if (graphObject != null && graphObject.graph != null)
{
updateTitle = true; // trigger icon swap
m_ProTheme = EditorGUIUtility.isProSkin;
}
}
bool revalidate = false;
if (m_customInterpWarn != ShaderGraphProjectSettings.instance.customInterpolatorWarningThreshold)
{
m_customInterpWarn = ShaderGraphProjectSettings.instance.customInterpolatorWarningThreshold;
revalidate = true;
}
if (m_customInterpErr != ShaderGraphProjectSettings.instance.customInterpolatorErrorThreshold)
{
m_customInterpErr = ShaderGraphProjectSettings.instance.customInterpolatorErrorThreshold;
revalidate = true;
}
if (revalidate)
{
graphEditorView?.graphView?.graph?.ValidateGraph();
}
if (m_AssetMaybeChangedOnDisk)
{
m_AssetMaybeChangedOnDisk = false;
// if we don't have any graph, then it doesn't really matter if the file on disk changed or not
// as we're going to reload it below anyways
if (graphObject?.graph != null)
{
// check if it actually did change on disk
if (FileOnDiskHasChanged())
{
// don't worry people about "losing changes" unless there are changes to lose
bool graphChanged = GraphHasChangedSinceLastSerialization();
if (EditorUtility.DisplayDialog(
"Graph has changed on disk",
AssetDatabase.GUIDToAssetPath(selectedGuid) + "\n\n" +
(graphChanged ? "Do you want to reload it and lose the changes made in the graph?" : "Do you want to reload it?"),
graphChanged ? "Discard Changes And Reload" : "Reload",
"Don't Reload"))
{
// clear graph, trigger reload
graphObject = null;
}
}
}
updateTitle = true;
}
try
{
if (graphObject == null && selectedGuid != null)
{
var guid = selectedGuid;
selectedGuid = null;
Initialize(guid);
}
if (graphObject == null)
{
Close();
return;
}
var materialGraph = graphObject.graph as GraphData;
if (materialGraph == null)
return;
if (graphEditorView == null)
{
messageManager.ClearAll();
materialGraph.messageManager = messageManager;
string assetPath = AssetDatabase.GUIDToAssetPath(selectedGuid);
string graphName = Path.GetFileNameWithoutExtension(assetPath);
graphEditorView = new GraphEditorView(this, materialGraph, messageManager, graphName)
{
viewDataKey = selectedGuid,
};
m_ColorSpace = PlayerSettings.colorSpace;
m_RenderPipelineAsset = GraphicsSettings.renderPipelineAsset;
graphObject.Validate();
// update blackboard title for the new graphEditorView
updateTitle = true;
}
if (m_ChangedFileDependencyGUIDs.Count > 0 && graphObject != null && graphObject.graph != null)
{
bool reloadedSomething = false;
foreach (var guid in m_ChangedFileDependencyGUIDs)
{
if (AssetDatabase.GUIDToAssetPath(guid) != null)
{
// update preview for changed textures
graphEditorView?.previewManager?.ReloadChangedFiles(guid);
}
}
var subGraphNodes = graphObject.graph.GetNodes<SubGraphNode>();
foreach (var subGraphNode in subGraphNodes)
{
var reloaded = subGraphNode.Reload(m_ChangedFileDependencyGUIDs);
reloadedSomething |= reloaded;
}
if (subGraphNodes.Count() > 0)
{
// Keywords always need to be updated to test against variant limit
// No Keywords may indicate removal and this may have now made the Graph valid again
// Need to validate Graph to clear errors in this case
materialGraph.OnKeywordChanged();
UpdateDropdownEntries();
materialGraph.OnDropdownChanged();
}
foreach (var customFunctionNode in graphObject.graph.GetNodes<CustomFunctionNode>())
{
var reloaded = customFunctionNode.Reload(m_ChangedFileDependencyGUIDs);
reloadedSomething |= reloaded;
}
// reloading files may change serialization
if (reloadedSomething)
{
updateTitle = true;
// may also need to re-run validation/concretization
graphObject.Validate();
}
m_ChangedFileDependencyGUIDs.Clear();
}
var wasUndoRedoPerformed = graphObject.wasUndoRedoPerformed;
if (wasUndoRedoPerformed)
{
graphEditorView.HandleGraphChanges(true);
graphObject.graph.ClearChanges();
graphObject.HandleUndoRedo();
}
if (graphObject.isDirty || wasUndoRedoPerformed)
{
updateTitle = true;
graphObject.isDirty = false;
hasUnsavedChanges = false;
}
// Called again to handle changes from deserialization in case an undo/redo was performed
graphEditorView.HandleGraphChanges(wasUndoRedoPerformed);
graphObject.graph.ClearChanges();
if (updateTitle)
UpdateTitle();
}
catch (Exception e)
{
m_HasError = true;
m_GraphEditorView = null;
graphObject = null;
Debug.LogException(e);
throw;
}
}
public void ReloadSubGraphsOnNextUpdate(List<string> changedFileGUIDs)
{
foreach (var changedFileGUID in changedFileGUIDs)
{
m_ChangedFileDependencyGUIDs.Add(changedFileGUID);
}
}
void UpdateDropdownEntries()
{
var subGraphNodes = graphObject.graph.GetNodes<SubGraphNode>();
foreach (var subGraphNode in subGraphNodes)
{
var nodeView = graphEditorView.graphView.nodes.ToList().OfType<IShaderNodeView>()
.FirstOrDefault(p => p.node != null && p.node == subGraphNode);
if (nodeView != null)
{
nodeView.UpdateDropdownEntries();
}
}
}
void OnEnable()
{
this.SetAntiAliasing(4);
}
void OnDisable()
{
graphEditorView = null;
messageManager.ClearAll();
}
// returns true only when the file on disk doesn't match the graph we last loaded or saved to disk (i.e. someone else changed it)
internal bool FileOnDiskHasChanged()
{
var currentFileJson = ReadAssetFile();
return !string.Equals(currentFileJson, m_LastSerializedFileContents, StringComparison.Ordinal);
}
// returns true only when the graph in this window would serialize different from the last time we loaded or saved it
internal bool GraphHasChangedSinceLastSerialization()
{
Assert.IsTrue(graphObject?.graph != null); // this should be checked by calling code
var currentGraphJson = MultiJson.Serialize(graphObject.graph);
return !string.Equals(currentGraphJson, m_LastSerializedFileContents, StringComparison.Ordinal);
}
// returns true only when saving the graph in this window would serialize different from the file on disk
internal bool GraphIsDifferentFromFileOnDisk()
{
Assert.IsTrue(graphObject?.graph != null); // this should be checked by calling code
var currentGraphJson = MultiJson.Serialize(graphObject.graph);
var currentFileJson = ReadAssetFile();
return !string.Equals(currentGraphJson, currentFileJson, StringComparison.Ordinal);
}
// NOTE: we're using the AssetPostprocessor Asset Import and Deleted callbacks as a proxy for detecting file changes
// We could probably replace both m_AssetMaybeDeleted and m_AssetMaybeChangedOnDisk with a combined "need to check the real status of the file" flag
public void CheckForChanges()
{
if (!m_AssetMaybeDeleted && graphObject?.graph != null)
{
m_AssetMaybeChangedOnDisk = true;
UpdateTitle();
}
}
public void AssetWasDeleted()
{
m_AssetMaybeDeleted = true;
UpdateTitle();
}
public void UpdateTitle()
{
string assetPath = AssetDatabase.GUIDToAssetPath(selectedGuid);
string shaderName = Path.GetFileNameWithoutExtension(assetPath);
// update blackboard title (before we add suffixes)
if (graphEditorView != null)
graphEditorView.assetName = shaderName;
// build the window title (with suffixes)
string title = shaderName;
if (graphObject?.graph == null)
title = title + " (nothing loaded)";
else
{
if (GraphHasChangedSinceLastSerialization())
{
hasUnsavedChanges = true;
// This is the message EditorWindow will show when prompting to close while dirty
saveChangesMessage = GetSaveChangesMessage();
}
else
{
hasUnsavedChanges = false;
saveChangesMessage = "";
}
if (!AssetFileExists())
title = title + " (deleted)";
}
// get window icon
bool isSubGraph = graphObject?.graph?.isSubGraph ?? false;
Texture2D icon;
{
string theme = EditorGUIUtility.isProSkin ? "_dark" : "_light";
if (isSubGraph)
icon = Resources.Load<Texture2D>("Icons/sg_subgraph_icon_gray" + theme);
else
icon = Resources.Load<Texture2D>("Icons/sg_graph_icon_gray" + theme);
}
titleContent = new GUIContent(title, icon);
}
void OnDestroy()
{
// Prompting the user if they want to close is mostly handled via the EditorWindow's system (hasUnsavedChanges).
// There's unfortunately a code path (Reload Window) that doesn't go through this path. The old logic is left
// here as a fallback to catch this. This has one edge case with "Reload Window" -> "Cancel" which will produce
// two shader graph windows: one unmodified (that the editor opens) and one modified (that we open below).
// we are closing the shadergraph window
MaterialGraphEditWindow newWindow = null;
if (!PromptSaveIfDirtyOnQuit())
{
// user does not want to close the window.
// we can't stop the close from this code path though..
// all we can do is open a new window and transfer our data to the new one to avoid losing it
// newWin = Instantiate<MaterialGraphEditWindow>(this);
newWindow = EditorWindow.CreateWindow<MaterialGraphEditWindow>(typeof(MaterialGraphEditWindow), typeof(SceneView));
newWindow.Initialize(this);
}
else
{
// the window is closing for good.. cleanup undo history for the graph object
Undo.ClearUndo(graphObject);
}
// Discard any unsaved modification on the generated material
if (graphObject && graphObject.materialArtifact && EditorUtility.IsDirty(graphObject.materialArtifact))
{
var material = new Material(AssetDatabase.LoadAssetAtPath<Shader>(AssetDatabase.GUIDToAssetPath(graphObject.AssetGuid)));
graphObject.materialArtifact.CopyPropertiesFromMaterial(material);
CoreUtils.Destroy(material);
}
graphObject = null;
graphEditorView = null;
// show new window if we have one
if (newWindow != null)
{
newWindow.Show();
newWindow.Focus();
}
}
public void PingAsset()
{
if (selectedGuid != null)
{
var path = AssetDatabase.GUIDToAssetPath(selectedGuid);
var asset = AssetDatabase.LoadAssetAtPath<Object>(path);
EditorGUIUtility.PingObject(asset);
}
}
public bool IsGraphAssetCheckedOut()
{
if (selectedGuid != null)
{
var path = AssetDatabase.GUIDToAssetPath(selectedGuid);
var asset = AssetDatabase.LoadAssetAtPath<Object>(path);
return AssetDatabase.IsOpenForEdit(asset, StatusQueryOptions.UseCachedIfPossible);
}
return false;
}
public void CheckoutAsset()
{
if (selectedGuid != null)
{
var path = AssetDatabase.GUIDToAssetPath(selectedGuid);
var asset = AssetDatabase.LoadAssetAtPath<Object>(path);
Task task = Provider.Checkout(asset, CheckoutMode.Both);
task.Wait();
}
}
// returns true if the asset was succesfully saved
public bool SaveAsset()
{
bool saved = false;
if (selectedGuid != null && graphObject != null)
{
var path = AssetDatabase.GUIDToAssetPath(selectedGuid);
if (string.IsNullOrEmpty(path) || graphObject == null)
return false;
if (GraphUtil.CheckForRecursiveDependencyOnPendingSave(path, graphObject.graph.GetNodes<SubGraphNode>(), "Save"))
return false;
ShaderGraphAnalytics.SendShaderGraphEvent(selectedGuid, graphObject.graph);
var oldShader = AssetDatabase.LoadAssetAtPath<Shader>(path);
if (oldShader != null)
ShaderUtil.ClearShaderMessages(oldShader);
var newFileContents = FileUtilities.WriteShaderGraphToDisk(path, graphObject.graph);
if (newFileContents != null)
{
saved = true;
m_LastSerializedFileContents = newFileContents;
AssetDatabase.ImportAsset(path);
}
OnSaveGraph(path);
hasUnsavedChanges = false;
}
UpdateTitle();
return saved;
}
void OnSaveGraph(string path)
{
if (GraphData.onSaveGraph == null)
return;
if (graphObject.graph.isSubGraph)
return;
var shader = AssetDatabase.LoadAssetAtPath<Shader>(path);
if (shader == null)
return;
foreach (var target in graphObject.graph.activeTargets)
{
GraphData.onSaveGraph(shader, target.saveContext);
}
}
public void SaveAs()
{
SaveAsImplementation(true);
}
// returns the asset path the file was saved to, or NULL if nothing was saved
string SaveAsImplementation(bool openWhenSaved)
{
string savedFilePath = null;
if (selectedGuid != null && graphObject?.graph != null)
{
var oldFilePath = AssetDatabase.GUIDToAssetPath(selectedGuid);
if (string.IsNullOrEmpty(oldFilePath) || graphObject == null)
return null;
// The asset's name needs to be removed from the path, otherwise SaveFilePanel assumes it's a folder
string oldDirectory = Path.GetDirectoryName(oldFilePath);
var extension = graphObject.graph.isSubGraph ? ShaderSubGraphImporter.Extension : ShaderGraphImporter.Extension;
var newFilePath = EditorUtility.SaveFilePanelInProject("Save Graph As...", Path.GetFileNameWithoutExtension(oldFilePath), extension, "", oldDirectory);
newFilePath = newFilePath.Replace(Application.dataPath, "Assets");
if (newFilePath != oldFilePath)
{
if (!string.IsNullOrEmpty(newFilePath))
{
// If the newPath already exists, we are overwriting an existing file, and could be creating recursions. Let's check.
if (GraphUtil.CheckForRecursiveDependencyOnPendingSave(newFilePath, graphObject.graph.GetNodes<SubGraphNode>(), "Save As"))
return null;
bool success = (FileUtilities.WriteShaderGraphToDisk(newFilePath, graphObject.graph) != null);
AssetDatabase.ImportAsset(newFilePath);
if (success)
{
if (openWhenSaved)
ShaderGraphImporterEditor.ShowGraphEditWindow(newFilePath);
OnSaveGraph(newFilePath);
savedFilePath = newFilePath;
}
}
}
else
{
// saving to the current path
if (SaveAsset())
{
graphObject.isDirty = false;
savedFilePath = oldFilePath;
}
}
}
return savedFilePath;
}
public void ToSubGraph()
{
var graphView = graphEditorView.graphView;
string path;
string sessionStateResult = SessionState.GetString(k_PrevSubGraphPathKey, k_PrevSubGraphPathDefaultValue);
string pathToOriginSG = Path.GetDirectoryName(AssetDatabase.GUIDToAssetPath(selectedGuid));
if (!sessionStateResult.Equals(k_PrevSubGraphPathDefaultValue))
{
path = sessionStateResult;
}
else
{
path = pathToOriginSG;
}
path = EditorUtility.SaveFilePanelInProject("Save Sub Graph", "New Shader Sub Graph", ShaderSubGraphImporter.Extension, "", path);
path = path.Replace(Application.dataPath, "Assets");
// Friendly warning that the user is generating a subgraph that would overwrite the one they are currently working on.
if (AssetDatabase.AssetPathToGUID(path) == selectedGuid)
{
if (!EditorUtility.DisplayDialog("Overwrite Current Subgraph", "Do you want to overwrite this Sub Graph that you are currently working on? You cannot undo this operation.", "Yes", "Cancel"))
{
path = "";
}
}
if (path.Length == 0)
return;
var nodes = graphView.selection.OfType<IShaderNodeView>().Where(x => !(x.node is PropertyNode || x.node is SubGraphOutputNode)).Select(x => x.node).Where(x => x.allowedInSubGraph).ToArray();
// Convert To Subgraph could create recursive reference loops if the target path already exists
// Let's check for that here
if (!string.IsNullOrEmpty(path))
{
if (GraphUtil.CheckForRecursiveDependencyOnPendingSave(path, nodes.OfType<SubGraphNode>(), "Convert To SubGraph"))
return;
}
graphObject.RegisterCompleteObjectUndo("Convert To Subgraph");
var bounds = Rect.MinMaxRect(float.PositiveInfinity, float.PositiveInfinity, float.NegativeInfinity, float.NegativeInfinity);
foreach (var node in nodes)
{
var center = node.drawState.position.center;
bounds = Rect.MinMaxRect(
Mathf.Min(bounds.xMin, center.x),
Mathf.Min(bounds.yMin, center.y),
Mathf.Max(bounds.xMax, center.x),
Mathf.Max(bounds.yMax, center.y));
}
var middle = bounds.center;
bounds.center = Vector2.zero;
// Collect graph inputs
var graphInputs = graphView.selection.OfType<SGBlackboardField>().Select(x => x.userData as ShaderInput);
var categories = graphView.selection.OfType<SGBlackboardCategory>().Select(x => x.userData as CategoryData);
// Collect the property nodes and get the corresponding properties
var propertyNodes = graphView.selection.OfType<IShaderNodeView>().Where(x => (x.node is PropertyNode)).Select(x => ((PropertyNode)x.node).property);
var metaProperties = graphView.graph.properties.Where(x => propertyNodes.Contains(x));
// Collect the keyword nodes and get the corresponding keywords
var keywordNodes = graphView.selection.OfType<IShaderNodeView>().Where(x => (x.node is KeywordNode)).Select(x => ((KeywordNode)x.node).keyword);
var dropdownNodes = graphView.selection.OfType<IShaderNodeView>().Where(x => (x.node is DropdownNode)).Select(x => ((DropdownNode)x.node).dropdown);
var metaKeywords = graphView.graph.keywords.Where(x => keywordNodes.Contains(x));
var metaDropdowns = graphView.graph.dropdowns.Where(x => dropdownNodes.Contains(x));
var copyPasteGraph = new CopyPasteGraph(graphView.selection.OfType<ShaderGroup>().Select(x => x.userData),
nodes,
graphView.selection.OfType<Edge>().Select(x => x.userData as Graphing.Edge),
graphInputs,
categories,
metaProperties,
metaKeywords,
metaDropdowns,
graphView.selection.OfType<StickyNote>().Select(x => x.userData),
true,
false);
// why do we serialize and deserialize only to make copies of everything in the steps below?
// is this just to clear out all non-serialized data?
var deserialized = CopyPasteGraph.FromJson(MultiJson.Serialize(copyPasteGraph), graphView.graph);
if (deserialized == null)
return;
var subGraph = new GraphData { isSubGraph = true, path = "Sub Graphs" };
var subGraphOutputNode = new SubGraphOutputNode();
{
var drawState = subGraphOutputNode.drawState;
drawState.position = new Rect(new Vector2(bounds.xMax + 200f, 0f), drawState.position.size);
subGraphOutputNode.drawState = drawState;
}
subGraph.AddNode(subGraphOutputNode);
subGraph.outputNode = subGraphOutputNode;
// Always copy deserialized keyword inputs
foreach (ShaderKeyword keyword in deserialized.metaKeywords)
{
var copiedInput = (ShaderKeyword)subGraph.AddCopyOfShaderInput(keyword);
// Update the keyword nodes that depends on the copied keyword
var dependentKeywordNodes = deserialized.GetNodes<KeywordNode>().Where(x => x.keyword == keyword);
foreach (var node in dependentKeywordNodes)
{
node.owner = graphView.graph;
node.keyword = copiedInput;
}
}
// Always copy deserialized dropdown inputs
foreach (ShaderDropdown dropdown in deserialized.metaDropdowns)
{
var copiedInput = (ShaderDropdown)subGraph.AddCopyOfShaderInput(dropdown);
// Update the dropdown nodes that depends on the copied dropdown
var dependentDropdownNodes = deserialized.GetNodes<DropdownNode>().Where(x => x.dropdown == dropdown);
foreach (var node in dependentDropdownNodes)
{
node.owner = graphView.graph;
node.dropdown = copiedInput;
}
}
foreach (GroupData groupData in deserialized.groups)
{
subGraph.CreateGroup(groupData);
}
foreach (var node in deserialized.GetNodes<AbstractMaterialNode>())
{
var drawState = node.drawState;
drawState.position = new Rect(drawState.position.position - middle, drawState.position.size);
node.drawState = drawState;
// Checking if the group guid is also being copied.
// If not then nullify that guid
if (node.group != null && !subGraph.groups.Contains(node.group))
{
node.group = null;
}
subGraph.AddNode(node);
}
foreach (var note in deserialized.stickyNotes)
{
if (note.group != null && !subGraph.groups.Contains(note.group))
{
note.group = null;
}
subGraph.AddStickyNote(note);
}
// figure out what needs remapping
var externalOutputSlots = new List<Graphing.Edge>();
var externalInputSlots = new List<Graphing.Edge>();
var passthroughSlots = new List<Graphing.Edge>();
foreach (var edge in deserialized.edges)
{
var outputSlot = edge.outputSlot;
var inputSlot = edge.inputSlot;
var outputSlotExistsInSubgraph = subGraph.ContainsNode(outputSlot.node);
var inputSlotExistsInSubgraph = subGraph.ContainsNode(inputSlot.node);
// pasting nice internal links!
if (outputSlotExistsInSubgraph && inputSlotExistsInSubgraph)
{
subGraph.Connect(outputSlot, inputSlot);
}
// one edge needs to go to outside world
else if (outputSlotExistsInSubgraph)
{
externalInputSlots.Add(edge);
}
else if (inputSlotExistsInSubgraph)
{
externalOutputSlots.Add(edge);
}
else
{
externalInputSlots.Add(edge);
externalOutputSlots.Add(edge);
passthroughSlots.Add(edge);
}
}
// Find the unique edges coming INTO the graph
var uniqueIncomingEdges = externalOutputSlots.GroupBy(
edge => edge.outputSlot,
edge => edge,
(key, edges) => new { slotRef = key, edges = edges.ToList() });
var externalInputNeedingConnection = new List<KeyValuePair<IEdge, AbstractShaderProperty>>();
var amountOfProps = uniqueIncomingEdges.Count();
const int height = 40;
const int subtractHeight = 20;
var propPos = new Vector2(0, -((amountOfProps / 2) + height) - subtractHeight);
var passthroughSlotRefLookup = new Dictionary<SlotReference, SlotReference>();
var passedInProperties = new Dictionary<AbstractShaderProperty, AbstractShaderProperty>();
foreach (var group in uniqueIncomingEdges)
{
var sr = group.slotRef;
var fromNode = sr.node;
var fromSlot = sr.slot;
var materialGraph = graphObject.graph;
var fromProperty = fromNode is PropertyNode fromPropertyNode
? materialGraph.properties.FirstOrDefault(p => p == fromPropertyNode.property)
: null;
AbstractShaderProperty prop;
if (fromProperty != null && passedInProperties.TryGetValue(fromProperty, out prop))
{
}
else
{
switch (fromSlot.concreteValueType)
{
case ConcreteSlotValueType.Texture2D:
prop = new Texture2DShaderProperty();
break;
case ConcreteSlotValueType.Texture2DArray:
prop = new Texture2DArrayShaderProperty();
break;
case ConcreteSlotValueType.Texture3D:
prop = new Texture3DShaderProperty();
break;
case ConcreteSlotValueType.Cubemap:
prop = new CubemapShaderProperty();
break;
case ConcreteSlotValueType.Vector4:
prop = new Vector4ShaderProperty();
break;
case ConcreteSlotValueType.Vector3:
prop = new Vector3ShaderProperty();
break;
case ConcreteSlotValueType.Vector2:
prop = new Vector2ShaderProperty();
break;
case ConcreteSlotValueType.Vector1:
prop = new Vector1ShaderProperty();
break;
case ConcreteSlotValueType.Boolean:
prop = new BooleanShaderProperty();
break;
case ConcreteSlotValueType.Matrix2:
prop = new Matrix2ShaderProperty();
break;
case ConcreteSlotValueType.Matrix3:
prop = new Matrix3ShaderProperty();
break;
case ConcreteSlotValueType.Matrix4:
prop = new Matrix4ShaderProperty();
break;
case ConcreteSlotValueType.SamplerState:
prop = new SamplerStateShaderProperty();
break;
case ConcreteSlotValueType.Gradient:
prop = new GradientShaderProperty();
break;
case ConcreteSlotValueType.VirtualTexture:
prop = new VirtualTextureShaderProperty()
{
// also copy the VT settings over from the original property (if there is one)
value = (fromProperty as VirtualTextureShaderProperty)?.value ?? new SerializableVirtualTexture()
};
break;
default:
throw new ArgumentOutOfRangeException();
}
var propName = fromProperty != null
? fromProperty.displayName
: fromSlot.concreteValueType.ToString();
prop.SetDisplayNameAndSanitizeForGraph(subGraph, propName);
subGraph.AddGraphInput(prop);
if (fromProperty != null)
{
passedInProperties.Add(fromProperty, prop);
}
}
var propNode = new PropertyNode();
{
var drawState = propNode.drawState;
drawState.position = new Rect(new Vector2(bounds.xMin - 300f, 0f) + propPos,
drawState.position.size);
propPos += new Vector2(0, height);
propNode.drawState = drawState;
}
subGraph.AddNode(propNode);
propNode.property = prop;
Vector2 avg = Vector2.zero;
foreach (var edge in group.edges)
{
if (passthroughSlots.Contains(edge) && !passthroughSlotRefLookup.ContainsKey(sr))
{
passthroughSlotRefLookup.Add(sr, new SlotReference(propNode, PropertyNode.OutputSlotId));