-
Notifications
You must be signed in to change notification settings - Fork 870
Expand file tree
/
Copy pathGraphUtil.cs
More file actions
437 lines (387 loc) · 16.8 KB
/
GraphUtil.cs
File metadata and controls
437 lines (387 loc) · 16.8 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
using System;
using System.Text;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Text.RegularExpressions;
using UnityEditor.Graphing;
using UnityEditor.Graphing.Util;
using UnityEditorInternal;
using Debug = UnityEngine.Debug;
using System.Reflection;
using System.Runtime.Remoting.Metadata.W3cXsd2001;
using UnityEditor.ProjectWindowCallback;
using UnityEditor.ShaderGraph.Internal;
using UnityEngine;
using UnityEngine.Rendering;
using Object = System.Object;
namespace UnityEditor.ShaderGraph
{
// a structure used to track active variable dependencies in the shader code
// (i.e. the use of uv0 in the pixel shader means we need a uv0 interpolator, etc.)
struct Dependency
{
public string name; // the name of the thing
public string dependsOn; // the thing above depends on this -- it reads it / calls it / requires it to be defined
public Dependency(string name, string dependsOn)
{
this.name = name;
this.dependsOn = dependsOn;
}
};
[System.AttributeUsage(System.AttributeTargets.Struct)]
class InterpolatorPack : System.Attribute
{
public InterpolatorPack()
{
}
}
// attribute used to flag a field as needing an HLSL semantic applied
// i.e. float3 position : POSITION;
// ^ semantic
[System.AttributeUsage(System.AttributeTargets.Field)]
class Semantic : System.Attribute
{
public string semantic;
public Semantic(string semantic)
{
this.semantic = semantic;
}
}
// attribute used to flag a field as being optional
// i.e. if it is not active, then we can omit it from the struct
[System.AttributeUsage(System.AttributeTargets.Field)]
class Optional : System.Attribute
{
public Optional()
{
}
}
// attribute used to override the HLSL type of a field with a custom type string
[System.AttributeUsage(System.AttributeTargets.Field)]
class OverrideType : System.Attribute
{
public string typeName;
public OverrideType(string typeName)
{
this.typeName = typeName;
}
}
// attribute used to force system generated fields to bottom of structs
[System.AttributeUsage(System.AttributeTargets.Field)]
class SystemGenerated : System.Attribute
{
public SystemGenerated()
{
}
}
// attribute used to disable a field using a preprocessor #if
[System.AttributeUsage(System.AttributeTargets.Field)]
class PreprocessorIf : System.Attribute
{
public string conditional;
public PreprocessorIf(string conditional)
{
this.conditional = conditional;
}
}
class NewGraphAction : EndNameEditAction
{
Target[] m_Targets;
public Target[] targets
{
get => m_Targets;
set => m_Targets = value;
}
BlockFieldDescriptor[] m_Blocks;
public BlockFieldDescriptor[] blocks
{
get => m_Blocks;
set => m_Blocks = value;
}
public override void Action(int instanceId, string pathName, string resourceFile)
{
var graph = new GraphData();
graph.AddContexts();
graph.InitializeOutputs(m_Targets, m_Blocks);
graph.path = "Shader Graphs";
FileUtilities.WriteShaderGraphToDisk(pathName, graph);
AssetDatabase.Refresh();
UnityEngine.Object obj = AssetDatabase.LoadAssetAtPath<Shader>(pathName);
Selection.activeObject = obj;
}
}
static class GraphUtil
{
internal static bool CheckForRecursiveDependencyOnPendingSave(string saveFilePath, IEnumerable<SubGraphNode> subGraphNodes, string context = null)
{
var overwriteGUID = AssetDatabase.AssetPathToGUID(saveFilePath);
if (!string.IsNullOrEmpty(overwriteGUID))
{
foreach (var sgNode in subGraphNodes)
{
var asset = sgNode?.asset;
if (asset == null)
{
// cannot read the asset; might be recursive but we can't tell... should we return "maybe"?
// I think to be minimally intrusive to the user we can assume "No" in this case,
// even though this may miss recursions in extraordinary cases.
// it's more important to allow the user to save their files than to catch 100% of recursions
continue;
}
else if ((asset.assetGuid == overwriteGUID) || asset.descendents.Contains(overwriteGUID))
{
if (context != null)
{
Debug.LogWarning(context + " CANCELLED to avoid a generating a reference loop: the SubGraph '" + sgNode.asset.name + "' references the target file '" + saveFilePath + "'");
EditorUtility.DisplayDialog(
context + " CANCELLED",
"Saving the file would generate a reference loop, because the SubGraph '" + sgNode.asset.name + "' references the target file '" + saveFilePath + "'", "Cancel");
}
return true;
}
}
}
return false;
}
internal static string ConvertCamelCase(string text, bool preserveAcronyms)
{
if (string.IsNullOrEmpty(text))
return string.Empty;
StringBuilder newText = new StringBuilder(text.Length * 2);
newText.Append(text[0]);
for (int i = 1; i < text.Length; i++)
{
if (char.IsUpper(text[i]))
if ((text[i - 1] != ' ' && !char.IsUpper(text[i - 1])) ||
(preserveAcronyms && char.IsUpper(text[i - 1]) &&
i < text.Length - 1 && !char.IsUpper(text[i + 1])))
newText.Append(' ');
newText.Append(text[i]);
}
return newText.ToString();
}
public static void CreateNewGraph()
{
var graphItem = ScriptableObject.CreateInstance<NewGraphAction>();
graphItem.targets = null;
ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, graphItem,
string.Format("New Shader Graph.{0}", ShaderGraphImporter.Extension), null, null);
}
public static void CreateNewGraphWithOutputs(Target[] targets, BlockFieldDescriptor[] blockDescriptors)
{
var graphItem = ScriptableObject.CreateInstance<NewGraphAction>();
graphItem.targets = targets;
graphItem.blocks = blockDescriptors;
ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, graphItem,
string.Format("New Shader Graph.{0}", ShaderGraphImporter.Extension), null, null);
}
public static bool TryGetMetadataOfType<T>(this Shader shader, out T obj) where T : ScriptableObject
{
obj = null;
if (!shader.IsShaderGraphAsset())
return false;
var path = AssetDatabase.GetAssetPath(shader);
foreach (var asset in AssetDatabase.LoadAllAssetsAtPath(path))
{
if (asset is T metadataAsset)
{
obj = metadataAsset;
return true;
}
}
return false;
}
// this will work on ALL shadergraph-built shaders, in memory or asset based
public static bool IsShaderGraph(this Material material)
{
var shaderGraphTag = material.GetTag("ShaderGraphShader", false, null);
return !string.IsNullOrEmpty(shaderGraphTag);
}
// NOTE: this ONLY works for ASSET based Shaders, if you created a temporary shader in memory, it won't work
public static bool IsShaderGraphAsset(this Shader shader)
{
var path = AssetDatabase.GetAssetPath(shader);
var importer = AssetImporter.GetAtPath(path);
return importer is ShaderGraphImporter;
}
[Obsolete("Use IsShaderGraphAsset instead", false)]
public static bool IsShaderGraph(this Shader shader) => shader.IsShaderGraphAsset();
static void Visit(List<AbstractMaterialNode> outputList, Dictionary<string, AbstractMaterialNode> unmarkedNodes, AbstractMaterialNode node)
{
if (!unmarkedNodes.ContainsKey(node.objectId))
return;
foreach (var slot in node.GetInputSlots<MaterialSlot>())
{
foreach (var edge in node.owner.GetEdges(slot.slotReference))
{
var inputNode = edge.outputSlot.node;
Visit(outputList, unmarkedNodes, inputNode);
}
}
unmarkedNodes.Remove(node.objectId);
outputList.Add(node);
}
static Dictionary<SerializationHelper.TypeSerializationInfo, SerializationHelper.TypeSerializationInfo> s_LegacyTypeRemapping;
public static Dictionary<SerializationHelper.TypeSerializationInfo, SerializationHelper.TypeSerializationInfo> GetLegacyTypeRemapping()
{
if (s_LegacyTypeRemapping == null)
{
s_LegacyTypeRemapping = new Dictionary<SerializationHelper.TypeSerializationInfo, SerializationHelper.TypeSerializationInfo>();
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
foreach (var type in assembly.GetTypesOrNothing())
{
if (type.IsAbstract)
continue;
foreach (var attribute in type.GetCustomAttributes(typeof(FormerNameAttribute), false))
{
var legacyAttribute = (FormerNameAttribute)attribute;
var serializationInfo = new SerializationHelper.TypeSerializationInfo { fullName = legacyAttribute.fullName };
s_LegacyTypeRemapping[serializationInfo] = SerializationHelper.GetTypeSerializableAsString(type);
}
}
}
}
return s_LegacyTypeRemapping;
}
/// <summary>
/// Sanitizes a supplied string such that it does not collide
/// with any other name in a collection.
/// </summary>
/// <param name="existingNames">
/// A collection of names that the new name should not collide with.
/// </param>
/// <param name="duplicateFormat">
/// The format applied to the name if a duplicate exists.
/// This must be a format string that contains `{0}` and `{1}`
/// once each. An example could be `{0} ({1})`, which will append ` (n)`
/// to the name for the n`th duplicate.
/// </param>
/// <param name="name">
/// The name to be sanitized.
/// </param>
/// <returns>
/// A name that is distinct form any name in `existingNames`.
/// </returns>
internal static string SanitizeName(IEnumerable<string> existingNames, string duplicateFormat, string name, string disallowedPatternRegex = "\"")
{
name = Regex.Replace(name, disallowedPatternRegex, "_");
return DeduplicateName(existingNames, duplicateFormat, name);
}
internal static string SanitizeCategoryName(string categoryName, string disallowedPatternRegex = "\"")
{
return Regex.Replace(categoryName, disallowedPatternRegex, "_");
}
internal static string DeduplicateName(IEnumerable<string> existingNames, string duplicateFormat, string name)
{
if (!existingNames.Contains(name))
return name;
string escapedDuplicateFormat = Regex.Escape(duplicateFormat);
// Escaped format will escape string interpolation, so the escape characters must be removed for these.
escapedDuplicateFormat = escapedDuplicateFormat.Replace(@"\{0}", @"{0}");
escapedDuplicateFormat = escapedDuplicateFormat.Replace(@"\{1}", @"{1}");
var baseRegex = new Regex(string.Format(escapedDuplicateFormat, @"^(.*)", @"(\d+)"));
var baseMatch = baseRegex.Match(name);
if (baseMatch.Success)
name = baseMatch.Groups[1].Value;
string baseNameExpression = string.Format(@"^{0}", Regex.Escape(name));
var regex = new Regex(string.Format(escapedDuplicateFormat, baseNameExpression, @"(\d+)") + "$");
var existingDuplicateNumbers = existingNames.Select(existingName => regex.Match(existingName)).Where(m => m.Success).Select(m => int.Parse(m.Groups[1].Value)).Where(n => n > 0).Distinct().ToList();
var duplicateNumber = 1;
existingDuplicateNumbers.Sort();
if (existingDuplicateNumbers.Count > 0 && existingDuplicateNumbers.First() == 1)
{
duplicateNumber = existingDuplicateNumbers.Last() + 1;
for (var i = 1; i < existingDuplicateNumbers.Count; i++)
{
if (existingDuplicateNumbers[i - 1] != existingDuplicateNumbers[i] - 1)
{
duplicateNumber = existingDuplicateNumbers[i - 1] + 1;
break;
}
}
}
return string.Format(duplicateFormat, name, duplicateNumber);
}
public static bool WriteToFile(string path, string content)
{
try
{
File.WriteAllText(path, content);
return true;
}
catch (Exception e)
{
Debug.LogError(e);
return false;
}
}
public static void OpenFile(string path)
{
string filePath = Path.GetFullPath(path);
if (!File.Exists(filePath))
{
Debug.LogError(string.Format("Path {0} doesn't exists", path));
return;
}
string externalScriptEditor = ScriptEditorUtility.GetExternalScriptEditor();
if (externalScriptEditor != "internal")
{
InternalEditorUtility.OpenFileAtLineExternal(filePath, 0);
}
else
{
Process p = new Process();
p.StartInfo.FileName = filePath;
p.EnableRaisingEvents = true;
p.Exited += (Object obj, EventArgs args) =>
{
if (p.ExitCode != 0)
Debug.LogWarningFormat("Unable to open {0}: Check external editor in preferences", filePath);
};
p.Start();
}
}
//
// Find all nodes of the given type downstream from the given node
// Returns a unique list. So even if a node can be reached through different paths it will be present only once.
//
public static List<NodeType> FindDownStreamNodesOfType<NodeType>(AbstractMaterialNode node) where NodeType : AbstractMaterialNode
{
// Should never be called without a node
Debug.Assert(node != null);
HashSet<AbstractMaterialNode> visitedNodes = new HashSet<AbstractMaterialNode>();
List<NodeType> vtNodes = new List<NodeType>();
Queue<AbstractMaterialNode> nodeStack = new Queue<AbstractMaterialNode>();
nodeStack.Enqueue(node);
visitedNodes.Add(node);
while (nodeStack.Count > 0)
{
AbstractMaterialNode visit = nodeStack.Dequeue();
// Flood fill through all the nodes
foreach (var slot in visit.GetInputSlots<MaterialSlot>())
{
foreach (var edge in visit.owner.GetEdges(slot.slotReference))
{
var inputNode = edge.outputSlot.node;
if (!visitedNodes.Contains(inputNode))
{
nodeStack.Enqueue(inputNode);
visitedNodes.Add(inputNode);
}
}
}
// Extract vt node
if (visit is NodeType)
{
NodeType vtNode = visit as NodeType;
vtNodes.Add(vtNode);
}
}
return vtNodes;
}
}
}