作用在Visual Effect Graph的节点中拖入ShaderGraph的时候,节点显示ShaderGraph变量,可以进行设置部分显示部分不显示。
【开关】Tools/VFX/Enable ShaderGraph Foldout
代码块
#if UNITY_EDITOR
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
namespace CYJ.VFX
{
// ========================================================================
// 数据存储:使用 EditorPrefs 保存每个节点的属性隐藏状态
// ========================================================================
internal static class VFXShaderGraphFoldoutStore
{
private const string PREFS_KEY = "VFXSG_FoldoutData";
private static Dictionary<string, HashSet<string>> data;
private static bool dirty;
private static void EnsureLoaded()
{
if (data != null) return;
data = new Dictionary<string, HashSet<string>>();
var json = EditorPrefs.GetString(PREFS_KEY, "");
if (string.IsNullOrEmpty(json)) return;
try
{
var arr = MiniJson.Deserialize(json) as List<object>;
if (arr == null) return;
foreach (Dictionary<string, object> entry in arr)
{
var guid = entry["k"] as string;
var names = entry["v"] as List<object>;
if (guid == null || names == null) continue;
var set = new HashSet<string>();
foreach (string n in names) set.Add(n);
data[guid] = set;
}
}
catch { }
}
private static void Save()
{
if (!dirty) return;
dirty = false;
var arr = new List<Dictionary<string, object>>();
foreach (var kv in data)
{
arr.Add(new Dictionary<string, object>
{
{ "k", kv.Key },
{ "v", new List<string>(kv.Value) }
});
}
EditorPrefs.SetString(PREFS_KEY, MiniJson.Serialize(arr));
}
public static bool IsHidden(string nodeGUID, string propertyName)
{
EnsureLoaded();
return data.TryGetValue(nodeGUID, out var set) && set.Contains(propertyName);
}
public static void SetHidden(string nodeGUID, string propertyName, bool hidden)
{
EnsureLoaded();
if (!data.TryGetValue(nodeGUID, out var set))
{
set = new HashSet<string>();
data[nodeGUID] = set;
}
if (hidden)
{
if (set.Add(propertyName)) { dirty = true; Save(); }
}
else
{
if (set.Remove(propertyName)) { dirty = true; Save(); }
}
}
public static List<string> GetHiddenProperties(string nodeGUID)
{
EnsureLoaded();
if (data.TryGetValue(nodeGUID, out var set))
return new List<string>(set);
return new List<string>();
}
public static void SyncWithShaderGraph(string nodeGUID, List<string> currentPropertyNames)
{
EnsureLoaded();
if (!data.TryGetValue(nodeGUID, out var set)) return;
var removed = set.Where(p => !currentPropertyNames.Contains(p)).ToList();
if (removed.Count > 0)
{
foreach (var r in removed) set.Remove(r);
dirty = true;
Save();
}
}
}
// ========================================================================
// 极简 JSON 序列化
// ========================================================================
internal static class MiniJson
{
public static string Serialize(object obj)
{
if (obj == null) return "null";
if (obj is string s) return Escape(s);
if (obj is bool b) return b ? "true" : "false";
if (obj is int i) return i.ToString();
if (obj is long l) return l.ToString();
if (obj is float f) return f.ToString("R");
if (obj is double d) return d.ToString("R");
if (obj is IList list)
{
var items = new List<string>();
foreach (var item in list) items.Add(Serialize(item));
return "[" + string.Join(",", items) + "]";
}
if (obj is IDictionary dict)
{
var pairs = new List<string>();
foreach (DictionaryEntry kv in dict)
pairs.Add(Escape(kv.Key.ToString()) + ":" + Serialize(kv.Value));
return "{" + string.Join(",", pairs) + "}";
}
return "null";
}
public static object Deserialize(string json)
{
var parser = new Parser(json);
return parser.Parse();
}
private static string Escape(string s)
{
return "\"" + s.Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\n", "\\n").Replace("\r", "\\r") + "\"";
}
private class Parser
{
private readonly string json;
private int pos;
public Parser(string json) { this.json = json; pos = 0; }
public object Parse()
{
SkipWhitespace();
if (pos >= json.Length) return null;
char c = json[pos];
if (c == '{') return ParseObject();
if (c == '[') return ParseArray();
if (c == '"') return ParseString();
if (c == 't' || c == 'f') return ParseBool();
if (c == 'n') return ParseNull();
if (c == '-' || (c >= '0' && c <= '9')) return ParseNumber();
return null;
}
private Dictionary<string, object> ParseObject()
{
pos++;
var dict = new Dictionary<string, object>();
SkipWhitespace();
if (pos < json.Length && json[pos] == '}') { pos++; return dict; }
while (true)
{
SkipWhitespace();
string key = ParseString();
SkipWhitespace();
pos++;
var val = Parse();
dict[key] = val;
SkipWhitespace();
if (pos >= json.Length || json[pos] != ',') break;
pos++;
}
if (pos < json.Length && json[pos] == '}') pos++;
return dict;
}
private List<object> ParseArray()
{
pos++;
var list = new List<object>();
SkipWhitespace();
if (pos < json.Length && json[pos] == ']') { pos++; return list; }
while (true)
{
list.Add(Parse());
SkipWhitespace();
if (pos >= json.Length || json[pos] != ',') break;
pos++;
}
if (pos < json.Length && json[pos] == ']') pos++;
return list;
}
private string ParseString()
{
pos++;
int start = pos;
var sb = new System.Text.StringBuilder();
while (pos < json.Length)
{
if (json[pos] == '\\')
{
sb.Append(json, start, pos - start);
pos++;
if (pos < json.Length)
{
char esc = json[pos];
if (esc == 'n') sb.Append('\n');
else if (esc == 'r') sb.Append('\r');
else if (esc == 't') sb.Append('\t');
else if (esc == '"') sb.Append('"');
else if (esc == '\\') sb.Append('\\');
else sb.Append(esc);
}
pos++;
start = pos;
}
else if (json[pos] == '"')
{
sb.Append(json, start, pos - start);
pos++;
return sb.ToString();
}
else { pos++; }
}
sb.Append(json, start, pos - start);
return sb.ToString();
}
private bool ParseBool()
{
if (json[pos] == 't') { pos += 4; return true; }
pos += 5; return false;
}
private object ParseNull() { pos += 4; return null; }
private object ParseNumber()
{
int start = pos;
if (json[pos] == '-') pos++;
while (pos < json.Length && json[pos] >= '0' && json[pos] <= '9') pos++;
if (pos < json.Length && json[pos] == '.') { pos++; while (pos < json.Length && json[pos] >= '0' && json[pos] <= '9') pos++; }
if (pos < json.Length && (json[pos] == 'e' || json[pos] == 'E')) { pos++; if (pos < json.Length && (json[pos] == '+' || json[pos] == '-')) pos++; while (pos < json.Length && json[pos] >= '0' && json[pos] <= '9') pos++; }
long lv;
if (long.TryParse(json.Substring(start, pos - start), out lv)) return lv;
return 0;
}
private void SkipWhitespace()
{
while (pos < json.Length && char.IsWhiteSpace(json[pos])) pos++;
}
}
}
// ========================================================================
// Shader Graph 属性解析器
// ========================================================================
public static class VFXShaderGraphPropertyParser
{
public static List<ShaderGraphPropertyInfo> ParseProperties(UnityEngine.Object shaderGraphAsset)
{
var result = new List<ShaderGraphPropertyInfo>();
if (shaderGraphAsset == null) return result;
string path = AssetDatabase.GetAssetPath(shaderGraphAsset);
if (string.IsNullOrEmpty(path)) return result;
string text = System.IO.File.ReadAllText(path);
if (string.IsNullOrEmpty(text)) return result;
var segments = SplitJsonSegments(text);
foreach (var seg in segments)
{
if (!seg.Contains("m_DefaultReferenceName") && !seg.Contains("m_Name"))
continue;
var nameVal = ExtractJsonStringField(seg, "m_Name");
var refNameVal = ExtractJsonStringField(seg, "m_DefaultReferenceName");
var overrideRefNameVal = ExtractJsonStringField(seg, "m_OverrideReferenceName");
var typeStr = ExtractJsonStringField(seg, "m_Type");
if (typeStr == null || !typeStr.Contains("ShaderProperty")) continue;
if (string.IsNullOrEmpty(nameVal)) continue;
var effectiveRefName = !string.IsNullOrEmpty(overrideRefNameVal)
? overrideRefNameVal
: refNameVal;
if (string.IsNullOrEmpty(effectiveRefName)) continue;
result.Add(new ShaderGraphPropertyInfo
{
displayName = nameVal,
referenceName = effectiveRefName,
propertyType = InferPropertyType(typeStr),
isCollapsed = false
});
}
return result;
}
private static List<string> SplitJsonSegments(string text)
{
var segments = new List<string>();
int depth = 0;
int start = -1;
for (int i = 0; i < text.Length; i++)
{
if (text[i] == '{')
{
if (depth == 0) start = i;
depth++;
}
else if (text[i] == '}')
{
depth--;
if (depth == 0 && start >= 0)
{
segments.Add(text.Substring(start, i - start + 1));
start = -1;
}
}
}
return segments;
}
private static string ExtractJsonStringField(string json, string fieldName)
{
string pattern = "\"" + fieldName + "\": \"";
int idx = json.IndexOf(pattern, StringComparison.Ordinal);
if (idx < 0)
{
pattern = "\"" + fieldName + "\":\"";
idx = json.IndexOf(pattern, StringComparison.Ordinal);
}
if (idx < 0) return null;
int valueStart = idx + pattern.Length;
int valueEnd = json.IndexOf('"', valueStart);
if (valueEnd < 0) return null;
return json.Substring(valueStart, valueEnd - valueStart);
}
private static ShaderGraphPropertyType InferPropertyType(string typeStr)
{
if (typeStr.Contains("ColorShaderProperty")) return ShaderGraphPropertyType.Color;
if (typeStr.Contains("Vector1ShaderProperty") || typeStr.Contains("FloatShaderProperty"))
return ShaderGraphPropertyType.Vector1;
if (typeStr.Contains("Vector2ShaderProperty")) return ShaderGraphPropertyType.Vector2;
if (typeStr.Contains("Vector3ShaderProperty")) return ShaderGraphPropertyType.Vector3;
if (typeStr.Contains("Vector4ShaderProperty")) return ShaderGraphPropertyType.Vector4;
if (typeStr.Contains("Texture2DShaderProperty")) return ShaderGraphPropertyType.Texture2D;
if (typeStr.Contains("Texture3DShaderProperty")) return ShaderGraphPropertyType.Texture3D;
if (typeStr.Contains("CubemapShaderProperty")) return ShaderGraphPropertyType.Cubemap;
if (typeStr.Contains("BooleanShaderProperty")) return ShaderGraphPropertyType.Boolean;
return ShaderGraphPropertyType.Unknown;
}
}
public enum ShaderGraphPropertyType
{
Unknown,
Color,
Vector1,
Vector2,
Vector3,
Vector4,
Texture2D,
Texture3D,
Cubemap,
Boolean
}
public class ShaderGraphPropertyInfo
{
public string displayName;
public string referenceName;
public ShaderGraphPropertyType propertyType;
public bool isCollapsed;
public string PropertyTypeLabel
{
get
{
switch (propertyType)
{
case ShaderGraphPropertyType.Color: return "Color";
case ShaderGraphPropertyType.Vector1: return "Float";
case ShaderGraphPropertyType.Vector2: return "Vec2";
case ShaderGraphPropertyType.Vector3: return "Vec3";
case ShaderGraphPropertyType.Vector4: return "Vec4";
case ShaderGraphPropertyType.Texture2D: return "Tex2D";
case ShaderGraphPropertyType.Texture3D: return "Tex3D";
case ShaderGraphPropertyType.Cubemap: return "Cube";
case ShaderGraphPropertyType.Boolean: return "Bool";
default: return "???";
}
}
}
}
// ========================================================================
// Inspector 面板 Hook
// ========================================================================
[InitializeOnLoad]
public static class VFXShaderGraphFoldoutInspectorHook
{
private static readonly List<ShaderGraphPropertyInfo> cachedProperties = new List<ShaderGraphPropertyInfo>();
private static UnityEngine.Object lastShaderGraphAsset;
private static string lastNodeGUID;
private static bool sectionExpanded = true;
static VFXShaderGraphFoldoutInspectorHook()
{
EditorApplication.delayCall += RegisterInspectorHook;
}
private static void RegisterInspectorHook()
{
Editor.finishedDefaultHeaderGUI += OnFinishedHeaderGUI;
}
private static void OnFinishedHeaderGUI(Editor inspector)
{
if (!VFXShaderGraphNodeFoldoutDecorator.Enabled) return;
var target = inspector.target;
if (target == null) return;
var sgAsset = TryGetShaderGraphFromTarget(target, out string sgGUID);
if (sgAsset == null) return;
string nodeGUID = GetNodeGUID(target);
if (string.IsNullOrEmpty(nodeGUID)) return;
if (sgAsset != lastShaderGraphAsset || nodeGUID != lastNodeGUID)
{
lastShaderGraphAsset = sgAsset;
lastNodeGUID = nodeGUID;
cachedProperties.Clear();
cachedProperties.AddRange(VFXShaderGraphPropertyParser.ParseProperties(sgAsset));
var hiddenNames = VFXShaderGraphFoldoutStore.GetHiddenProperties(nodeGUID);
foreach (var prop in cachedProperties)
{
prop.isCollapsed = hiddenNames.Contains(prop.referenceName);
}
}
DrawShaderGraphFoldoutSection(nodeGUID);
}
internal static string GetNodeGUID(UnityEngine.Object target)
{
var globalId = GlobalObjectId.GetGlobalObjectIdSlow(target);
if (globalId.identifierType != 0)
return globalId.ToString();
return "instance_" + target.GetInstanceID();
}
private static UnityEngine.Object TryGetShaderGraphFromTarget(UnityEngine.Object target, out string sgGUID)
{
sgGUID = null;
var sgField = target.GetType().GetField("shaderGraph",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (sgField != null)
{
var sgObj = sgField.GetValue(target) as UnityEngine.Object;
if (sgObj != null)
{
var path = AssetDatabase.GetAssetPath(sgObj);
if (!string.IsNullOrEmpty(path) && path.EndsWith(".shadergraph"))
{
sgGUID = AssetDatabase.AssetPathToGUID(path);
return sgObj;
}
}
}
var so = new SerializedObject(target);
var prop = so.FindProperty("shaderGraph");
if (prop != null && prop.propertyType == SerializedPropertyType.ObjectReference && prop.objectReferenceValue != null)
{
var sgObj = prop.objectReferenceValue;
var path = AssetDatabase.GetAssetPath(sgObj);
if (!string.IsNullOrEmpty(path) && path.EndsWith(".shadergraph"))
{
sgGUID = AssetDatabase.AssetPathToGUID(path);
return sgObj;
}
}
return null;
}
private static void DrawShaderGraphFoldoutSection(string nodeGUID)
{
if (cachedProperties.Count == 0) return;
EditorGUILayout.Space(6);
var rect = EditorGUILayout.GetControlRect(false, 1);
EditorGUI.DrawRect(rect, new Color(0.4f, 0.4f, 0.4f, 1f));
EditorGUILayout.Space(4);
sectionExpanded = EditorGUILayout.Foldout(sectionExpanded,
$"Shader Graph Properties ({cachedProperties.Count})", true, EditorStyles.boldLabel);
if (!sectionExpanded) return;
EditorGUILayout.Space(2);
foreach (var prop in cachedProperties)
{
DrawPropertyRow(nodeGUID, prop);
}
EditorGUILayout.Space(2);
if (GUILayout.Button("Refresh", EditorStyles.miniButton))
{
cachedProperties.Clear();
cachedProperties.AddRange(VFXShaderGraphPropertyParser.ParseProperties(lastShaderGraphAsset));
var hiddenNames = VFXShaderGraphFoldoutStore.GetHiddenProperties(nodeGUID);
foreach (var prop in cachedProperties)
{
prop.isCollapsed = hiddenNames.Contains(prop.referenceName);
}
}
}
private static void DrawPropertyRow(string nodeGUID, ShaderGraphPropertyInfo prop)
{
EditorGUILayout.BeginHorizontal(EditorStyles.helpBox);
var typeRect = EditorGUILayout.GetControlRect(GUILayout.Width(45));
EditorGUI.LabelField(typeRect, prop.PropertyTypeLabel, EditorStyles.miniLabel);
EditorGUILayout.LabelField(prop.displayName, GUILayout.MinWidth(80));
GUILayout.FlexibleSpace();
bool isVisible = !prop.isCollapsed;
bool newVisible = EditorGUILayout.ToggleLeft("Show", isVisible, GUILayout.Width(50));
if (newVisible != isVisible)
{
prop.isCollapsed = !newVisible;
VFXShaderGraphFoldoutStore.SetHidden(nodeGUID, prop.referenceName, prop.isCollapsed);
VFXShaderGraphNodeFoldoutDecorator.NotifyFoldoutChanged();
}
EditorGUILayout.EndHorizontal();
}
[MenuItem("Tools/VFX/ShaderGraph Foldout Manager")]
public static void OpenFoldoutManager()
{
var obj = Selection.activeObject;
if (obj == null) return;
var sgAsset = FindShaderGraphFromSelected(obj, out string guid);
if (sgAsset == null)
{
EditorUtility.DisplayDialog("VFX SG Foldout", "No Shader Graph found.", "OK");
return;
}
EditorUtility.FocusProjectWindow();
Debug.Log("[VFX SG Foldout] Shader Graph found: " + sgAsset.name + "\nClick on the VFX Output node in VFX Graph Editor to see properties in Inspector.");
}
internal static UnityEngine.Object FindShaderGraphFromSelected(UnityEngine.Object selected, out string guid)
{
guid = null;
var path = AssetDatabase.GetAssetPath(selected);
if (string.IsNullOrEmpty(path)) return null;
if (path.EndsWith(".shadergraph"))
{
guid = AssetDatabase.AssetPathToGUID(path);
return selected;
}
return null;
}
}
// ========================================================================
// 节点装饰器:控制 VFX 节点上的 slot 显示/隐藏
// ========================================================================
[InitializeOnLoad]
public static class VFXShaderGraphNodeFoldoutDecorator
{
private const string ENABLED_PREFS_KEY = "VFXSG_Foldout_Enabled";
private static readonly Dictionary<string, bool> nodeFoldoutStates = new Dictionary<string, bool>();
public static bool Enabled
{
get => EditorPrefs.GetBool(ENABLED_PREFS_KEY, true);
set => EditorPrefs.SetBool(ENABLED_PREFS_KEY, value);
}
private static readonly Dictionary<int, VisualElement> injectedFoldoutElements = new Dictionary<int, VisualElement>();
private static readonly Dictionary<int, string> lastCollapseSigs = new Dictionary<int, string>();
private static double lastRefreshTime;
private static bool forceDirty = true;
private class NodeCache
{
public string nodeGUID;
public UnityEngine.Object sgAsset;
public bool hasShaderGraph;
public List<ShaderGraphPropertyInfo> properties;
public HashSet<string> hiddenSet;
public string hiddenSig;
}
private static readonly Dictionary<int, NodeCache> nodeCaches = new Dictionary<int, NodeCache>();
private static readonly Dictionary<int, List<ShaderGraphPropertyInfo>> sgParseCache = new Dictionary<int, List<ShaderGraphPropertyInfo>>();
// 反射缓存
private static readonly Dictionary<Type, PropertyInfo> controllerPropCache = new Dictionary<Type, PropertyInfo>();
private static readonly Dictionary<Type, PropertyInfo> modelPropCache = new Dictionary<Type, PropertyInfo>();
private static readonly Dictionary<Type, PropertyInfo> inputContainerPropCache = new Dictionary<Type, PropertyInfo>();
private static readonly Dictionary<Type, FieldInfo> shaderGraphFieldCache = new Dictionary<Type, FieldInfo>();
private static readonly Dictionary<Type, PropertyInfo> anchorControllerPropCache = new Dictionary<Type, PropertyInfo>();
private static readonly Dictionary<Type, PropertyInfo> anchorModelPropCache = new Dictionary<Type, PropertyInfo>();
private static readonly Dictionary<Type, PropertyInfo> slotPropertyPropCache = new Dictionary<Type, PropertyInfo>();
private static readonly Dictionary<Type, MethodInfo> isMasterSlotMethodCache = new Dictionary<Type, MethodInfo>();
private static readonly Dictionary<Type, MethodInfo> getMasterSlotMethodCache = new Dictionary<Type, MethodInfo>();
private static readonly Dictionary<Type, PropertyInfo> connectedPropCache = new Dictionary<Type, PropertyInfo>();
private static FieldInfo s_VfxPropertyNameField;
private static FieldInfo GetVFXPropertyNameField(Type vfxPropertyType)
{
if (s_VfxPropertyNameField == null && vfxPropertyType != null)
s_VfxPropertyNameField = vfxPropertyType.GetField("name");
return s_VfxPropertyNameField;
}
static VFXShaderGraphNodeFoldoutDecorator()
{
EditorApplication.delayCall += Register;
}
static void Register()
{
EditorApplication.update += OnEditorUpdate;
}
private static void OnEditorUpdate()
{
if (!Enabled) return;
if (IsDragging()) return;
if (!forceDirty && EditorApplication.timeSinceStartup - lastRefreshTime < 0.5) return;
lastRefreshTime = EditorApplication.timeSinceStartup;
forceDirty = false;
try { RefreshAllVFXNodes(); }
catch (Exception ex) { Debug.LogError("[VFXSGFoldout] " + ex.Message + "\n" + ex.StackTrace); }
}
private static bool IsDragging()
{
return UnityEngine.Input.GetMouseButton(0) || UnityEngine.Input.GetMouseButton(1);
}
public static void NotifyFoldoutChanged()
{
forceDirty = true;
lastCollapseSigs.Clear();
foreach (var nc in nodeCaches.Values)
{
nc.hiddenSet = null;
nc.hiddenSig = null;
}
}
private static PropertyInfo GetCachedProp(Dictionary<Type, PropertyInfo> cache, Type type, string name)
{
if (!cache.TryGetValue(type, out var prop))
{
prop = FindPropertyInHierarchy(type, name);
cache[type] = prop;
}
return prop;
}
private static PropertyInfo FindPropertyInHierarchy(Type type, string propertyName)
{
var t = type;
while (t != null && t != typeof(object))
{
var prop = t.GetProperty(propertyName,
BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
if (prop != null) return prop;
t = t.BaseType;
}
return null;
}
private static MethodInfo GetCachedMethod(Dictionary<Type, MethodInfo> cache, Type type, string name)
{
if (!cache.TryGetValue(type, out var method))
{
method = type.GetMethod(name, BindingFlags.Instance | BindingFlags.Public);
cache[type] = method;
}
return method;
}
private static PropertyInfo GetCachedPropertyNonPublic(Dictionary<Type, PropertyInfo> cache, Type type, string name)
{
if (!cache.TryGetValue(type, out var prop))
{
prop = type.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
cache[type] = prop;
}
return prop;
}
private static void RefreshAllVFXNodes()
{
var vfxViewWindowType = Type.GetType("UnityEditor.VFX.UI.VFXViewWindow, Unity.VisualEffectGraph.Editor");
if (vfxViewWindowType == null) return;
var windows = Resources.FindObjectsOfTypeAll(vfxViewWindowType);
if (windows == null || windows.Length == 0) return;
foreach (var win in windows)
{
if (!(win is EditorWindow ew) || ew.rootVisualElement == null) continue;
var vfxView = ew.rootVisualElement.Q(className: "graphView");
if (vfxView == null) continue;
var contextNodes = vfxView.Query<VisualElement>(className: "VFXContext").ToList();
foreach (var nodeElement in contextNodes)
{
ProcessNode(nodeElement);
}
}
}
private static void ProcessNode(VisualElement nodeElement)
{
var controllerProp = GetCachedProp(controllerPropCache, nodeElement.GetType(), "controller");
if (controllerProp == null) return;
var controller = controllerProp.GetValue(nodeElement);
if (controller == null) return;
var modelProp = GetCachedProp(modelPropCache, controller.GetType(), "model");
if (modelProp == null) return;
var model = modelProp.GetValue(controller) as UnityEngine.Object;
if (model == null) return;
int instanceID = model.GetInstanceID();
if (!nodeCaches.TryGetValue(instanceID, out var cache))
{
cache = new NodeCache();
nodeCaches[instanceID] = cache;
}
if (cache.sgAsset == null && !cache.hasShaderGraph)
{
var sgField = GetCachedShaderGraphField(model.GetType());
if (sgField != null)
{
cache.sgAsset = sgField.GetValue(model) as UnityEngine.Object;
if (cache.sgAsset != null)
{
var path = AssetDatabase.GetAssetPath(cache.sgAsset);
if (string.IsNullOrEmpty(path) || !path.EndsWith(".shadergraph"))
cache.sgAsset = null;
}
}
if (cache.sgAsset == null)
{
var so = new SerializedObject(model);
var prop = so.FindProperty("shaderGraph");
if (prop != null && prop.propertyType == SerializedPropertyType.ObjectReference && prop.objectReferenceValue != null)
{
var path = AssetDatabase.GetAssetPath(prop.objectReferenceValue);
if (!string.IsNullOrEmpty(path) && path.EndsWith(".shadergraph"))
cache.sgAsset = prop.objectReferenceValue;
}
}
cache.hasShaderGraph = cache.sgAsset != null;
if (cache.hasShaderGraph)
cache.nodeGUID = VFXShaderGraphFoldoutInspectorHook.GetNodeGUID(model);
}
if (!cache.hasShaderGraph)
{
RemoveFoldoutElement(instanceID, nodeElement);
lastCollapseSigs.Remove(instanceID);
return;
}
int sgInstanceID = cache.sgAsset.GetInstanceID();
if (!sgParseCache.TryGetValue(sgInstanceID, out var allProperties))
{
try
{
allProperties = VFXShaderGraphPropertyParser.ParseProperties(cache.sgAsset);
sgParseCache[sgInstanceID] = allProperties;
}
catch (Exception ex)
{
Debug.LogError($"[VFXSGFoldout] ParseProperties FAILED: {ex.Message}");
return;
}
}
cache.properties = allProperties;
if (cache.hiddenSet == null)
{
var hiddenNames = VFXShaderGraphFoldoutStore.GetHiddenProperties(cache.nodeGUID);
cache.hiddenSet = new HashSet<string>(hiddenNames);
cache.hiddenSig = string.Join(",", hiddenNames);
}
ApplySlotVisibility(nodeElement, cache.hiddenSet);
bool sigChanged = !lastCollapseSigs.TryGetValue(instanceID, out var oldSig) || oldSig != cache.hiddenSig;
if (sigChanged)
{
var collapsedProps = allProperties.FindAll(p => cache.hiddenSet.Contains(p.referenceName));
InjectFoldoutElement(instanceID, nodeElement, cache.nodeGUID, collapsedProps, cache.hiddenSig);
lastCollapseSigs[instanceID] = cache.hiddenSig;
}
}
private static FieldInfo GetCachedShaderGraphField(Type type)
{
if (!shaderGraphFieldCache.TryGetValue(type, out var field))
{
field = type.GetField("shaderGraph", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
shaderGraphFieldCache[type] = field;
}
return field;
}
private static void ApplySlotVisibility(VisualElement nodeElement, HashSet<string> collapsedSet)
{
var inputContainerProp = GetCachedProp(inputContainerPropCache, nodeElement.GetType(), "inputContainer");
VisualElement container;
if (inputContainerProp != null)
container = inputContainerProp.GetValue(nodeElement) as VisualElement;
else
container = nodeElement.Q("input");
if (container == null) return;
foreach (var anchor in container.Children())
{
try
{
var anchorType = anchor.GetType();
var ctrlProp = GetCachedProp(anchorControllerPropCache, anchorType, "controller");
if (ctrlProp == null) continue;
var ctrl = ctrlProp.GetValue(anchor);
if (ctrl == null) continue;
var ctrlType = ctrl.GetType();
var modelProp = GetCachedProp(anchorModelPropCache, ctrlType, "model");
if (modelProp == null) continue;
var slotModel = modelProp.GetValue(ctrl) as UnityEngine.Object;
if (slotModel == null) continue;
var slotType = slotModel.GetType();
string slotName = null;
var propProp = GetCachedProp(slotPropertyPropCache, slotType, "property");
if (propProp != null)
{
var propVal = propProp.GetValue(slotModel);
if (propVal != null)
{
var nameField = GetVFXPropertyNameField(propVal.GetType());
if (nameField != null)
slotName = nameField.GetValue(propVal) as string;
}
}
if (string.IsNullOrEmpty(slotName)) continue;
bool isMasterSlot = true;
var isMasterMethod = GetCachedMethod(isMasterSlotMethodCache, slotType, "IsMasterSlot");
if (isMasterMethod != null)
isMasterSlot = (bool)isMasterMethod.Invoke(slotModel, null);
string masterSlotName = null;
if (!isMasterSlot)
{
var getMasterMethod = GetCachedMethod(getMasterSlotMethodCache, slotType, "GetMasterSlot");
if (getMasterMethod != null)
{
var masterSlot = getMasterMethod.Invoke(slotModel, null) as UnityEngine.Object;
if (masterSlot != null)
{
var masterPropProp = GetCachedProp(slotPropertyPropCache, masterSlot.GetType(), "property");
if (masterPropProp != null)
{
var masterPropVal = masterPropProp.GetValue(masterSlot);
if (masterPropVal != null)
{
var nameField = GetVFXPropertyNameField(masterPropVal.GetType());
if (nameField != null)
masterSlotName = nameField.GetValue(masterPropVal) as string;
}
}
}
}
}
bool shouldHide = isMasterSlot
? collapsedSet.Contains(slotName)
: !string.IsNullOrEmpty(masterSlotName) && collapsedSet.Contains(masterSlotName);
if (shouldHide)
{
var connectedProp = GetCachedPropertyNonPublic(connectedPropCache, ctrlType, "connected");
if (connectedProp != null && (bool)connectedProp.GetValue(ctrl))
shouldHide = false;
}
if (shouldHide)
{
if (!anchor.ClassListContains("sg-folded"))
{
anchor.AddToClassList("sg-folded");
anchor.style.display = DisplayStyle.None;
}
}
else
{
if (anchor.ClassListContains("sg-folded"))
{
anchor.RemoveFromClassList("sg-folded");
anchor.style.display = DisplayStyle.Flex;
}
}
}
catch { }
}
}
private static void InjectFoldoutElement(int modelInstanceID, VisualElement nodeElement,
string nodeGUID, List<ShaderGraphPropertyInfo> collapsedProps, string collapseSig)
{
RemoveFoldoutElement(modelInstanceID, nodeElement);
if (collapsedProps.Count == 0) return;
var foldoutContainer = new VisualElement();
foldoutContainer.name = "sg-foldout-section";
foldoutContainer.AddToClassList("sg-foldout-section");
foldoutContainer.userData = collapseSig;
foldoutContainer.style.backgroundColor = new Color(0.18f, 0.18f, 0.18f, 0.95f);
foldoutContainer.style.borderTopWidth = 1;
foldoutContainer.style.borderTopColor = new Color(0.35f, 0.35f, 0.35f, 1f);
foldoutContainer.style.paddingLeft = 6;
foldoutContainer.style.paddingRight = 6;
foldoutContainer.style.paddingTop = 4;
foldoutContainer.style.paddingBottom = 4;
var foldoutBtn = new Button(() =>
{
if (!nodeFoldoutStates.ContainsKey(nodeGUID))
nodeFoldoutStates[nodeGUID] = false;
nodeFoldoutStates[nodeGUID] = !nodeFoldoutStates[nodeGUID];
UpdateFoldoutContent(nodeGUID, foldoutContainer, collapsedProps);
})
{
text = $"▼ Collapsed ({collapsedProps.Count})",
style =
{
backgroundColor = Color.clear,
color = new Color(0.7f, 0.7f, 0.7f, 1f),
fontSize = 10,
unityTextAlign = TextAnchor.MiddleLeft,
marginTop = 0, marginBottom = 0,
marginLeft = -4, marginRight = 0,
paddingTop = 0, paddingBottom = 0,
paddingLeft = 0, paddingRight = 0,
}
};
foldoutContainer.Add(foldoutBtn);
var contentArea = new VisualElement { name = "sg-foldout-content" };
contentArea.style.display = DisplayStyle.None;
foldoutContainer.Add(contentArea);
var outputContainer = nodeElement.Q("output");
if (outputContainer != null)
{
var idx = outputContainer.parent.IndexOf(outputContainer);
outputContainer.parent.Insert(idx + 1, foldoutContainer);
}
else
{
nodeElement.Add(foldoutContainer);
}
injectedFoldoutElements[modelInstanceID] = foldoutContainer;
UpdateFoldoutContent(nodeGUID, foldoutContainer, collapsedProps);
}
private static void UpdateFoldoutContent(string nodeGUID, VisualElement foldoutContainer, List<ShaderGraphPropertyInfo> collapsedProps)
{
var contentArea = foldoutContainer.Q("sg-foldout-content");
var foldoutBtn = foldoutContainer.Q<Button>();
if (contentArea == null || foldoutBtn == null) return;
bool expanded = nodeFoldoutStates.ContainsKey(nodeGUID) && nodeFoldoutStates[nodeGUID];
foldoutBtn.text = expanded ? $"▼ Collapsed ({collapsedProps.Count})" : $"► Collapsed ({collapsedProps.Count})";
contentArea.style.display = expanded ? DisplayStyle.Flex : DisplayStyle.None;
contentArea.Clear();
if (!expanded) return;
foreach (var prop in collapsedProps)
{
var row = new VisualElement
{
style = { flexDirection = FlexDirection.Row, marginTop = 2, marginBottom = 1 }
};
var typeLabel = new Label(prop.PropertyTypeLabel)
{
style = { color = new Color(0.5f, 0.8f, 1f, 1f), fontSize = 9, width = 40, unityTextAlign = TextAnchor.MiddleLeft }
};
var nameLabel = new Label(prop.displayName)
{
style = { color = new Color(0.65f, 0.65f, 0.65f, 1f), fontSize = 9, unityTextAlign = TextAnchor.MiddleLeft }
};
row.Add(typeLabel);
row.Add(nameLabel);
contentArea.Add(row);
}
}
private static void RemoveFoldoutElement(int modelInstanceID, VisualElement nodeElement)
{
if (injectedFoldoutElements.TryGetValue(modelInstanceID, out var existing))
{
existing.RemoveFromHierarchy();
injectedFoldoutElements.Remove(modelInstanceID);
}
var old = nodeElement.Q("sg-foldout-section");
if (old != null) old.RemoveFromHierarchy();
}
public static bool ShouldHideSlot(string nodeGUID, string referenceName)
{
return VFXShaderGraphFoldoutStore.IsHidden(nodeGUID, referenceName);
}
[MenuItem("Tools/VFX/Enable ShaderGraph Foldout", false, 100)]
private static void ToggleEnabled()
{
Enabled = !Enabled;
if (Enabled)
{
forceDirty = true;
NotifyFoldoutChanged();
}
}
[MenuItem("Tools/VFX/Enable ShaderGraph Foldout", true)]
private static bool ToggleEnabledValidate()
{
Menu.SetChecked("Tools/VFX/Enable ShaderGraph Foldout", Enabled);
return true;
}
}
}
#endif
免责声明:本文系网络转载或改编,未找到原创作者,版权归原作者所有。如涉及版权,请联系删