This commit is contained in:
2026-11-24 15:51:02 +01:00
parent cca4d73e41
commit f4aa17114a
22092 changed files with 5042406 additions and 0 deletions
@@ -0,0 +1,359 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor.Experimental.GraphView;
using UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers;
using UnityEditor.ShaderGraph.Drawing.Views;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.ShaderGraph.Drawing.Inspector
{
class InspectorView : GraphSubWindow
{
const float k_InspectorUpdateInterval = 0.25f;
const int k_InspectorElementLimit = 20;
bool m_GraphSettingsTabFocused = false;
int m_CurrentlyInspectedElementsCount = 0;
readonly List<Type> m_PropertyDrawerList = new List<Type>();
HashSet<IInspectable> cachedInspectables = new();
// There's persistent data that is stored in the graph settings property drawer that we need to hold onto between interactions
IPropertyDrawer m_graphSettingsPropertyDrawer = new GraphDataPropertyDrawer();
public override string windowTitle => "Graph Inspector";
public override string elementName => "InspectorView";
public override string styleName => "InspectorView";
public override string UxmlName => "GraphInspector";
public override string layoutKey => "UnityEditor.ShaderGraph.InspectorWindow";
TabView m_GraphInspectorView;
Tab m_GraphSettingsTab;
Tab m_NodeSettingsTab;
protected VisualElement m_GraphSettingsContainer;
protected VisualElement m_NodeSettingsContainer;
List<IPropertyDrawer> m_AllActivePropertyDrawers = new List<IPropertyDrawer>();
Label m_MaxItemsMessageLabel;
void RegisterPropertyDrawer(Type newPropertyDrawerType)
{
if (typeof(IPropertyDrawer).IsAssignableFrom(newPropertyDrawerType) == false)
{
Debug.Log("Attempted to register a property drawer that doesn't inherit from IPropertyDrawer!");
return;
}
var newPropertyDrawerAttribute = newPropertyDrawerType.GetCustomAttribute<SGPropertyDrawerAttribute>();
if (newPropertyDrawerAttribute != null)
{
foreach (var existingPropertyDrawerType in m_PropertyDrawerList)
{
var existingPropertyDrawerAttribute = existingPropertyDrawerType.GetCustomAttribute<SGPropertyDrawerAttribute>();
if (newPropertyDrawerAttribute.propertyType.IsSubclassOf(existingPropertyDrawerAttribute.propertyType))
{
// Derived types need to be at start of list
m_PropertyDrawerList.Insert(0, newPropertyDrawerType);
return;
}
if (existingPropertyDrawerAttribute.propertyType.IsSubclassOf(newPropertyDrawerAttribute.propertyType))
{
// Add new base class type to end of list
m_PropertyDrawerList.Add(newPropertyDrawerType);
// Shift already added existing type to the beginning of the list
m_PropertyDrawerList.Remove(existingPropertyDrawerType);
m_PropertyDrawerList.Insert(0, existingPropertyDrawerType);
return;
}
}
m_PropertyDrawerList.Add(newPropertyDrawerType);
}
else
Debug.Log("Attempted to register property drawer: " + newPropertyDrawerType + " that isn't marked up with the SGPropertyDrawer attribute!");
}
public InspectorView(InspectorViewModel viewModel) : base(viewModel)
{
m_GraphInspectorView = m_MainContainer.Q<TabView>("GraphInspectorView");
m_GraphSettingsTab = m_GraphInspectorView.Q<Tab>("GraphSettingsTab");
m_NodeSettingsTab = m_GraphInspectorView.Q<Tab>("NodeSettingsTab");
m_GraphSettingsContainer = m_GraphInspectorView.Q<VisualElement>("GraphSettingsContainer");
m_NodeSettingsContainer = m_GraphInspectorView.Q<VisualElement>("NodeSettingsContainer");
m_MaxItemsMessageLabel = m_GraphInspectorView.Q<Label>("maxItemsMessageLabel");
m_ContentContainer.Add(m_GraphInspectorView);
m_ScrollView = this.Q<ScrollView>();
m_GraphSettingsTab.selected += GraphSettingsTabClicked;
m_NodeSettingsTab.selected += NodeSettingsTabClicked;
isWindowScrollable = true;
isWindowResizable = true;
var unregisteredPropertyDrawerTypes = TypeCache.GetTypesDerivedFrom<IPropertyDrawer>().ToList();
foreach (var type in unregisteredPropertyDrawerTypes)
{
RegisterPropertyDrawer(type);
}
// By default at startup, show graph settings
m_GraphInspectorView.activeTab = m_GraphSettingsTab;
}
void GraphSettingsTabClicked(Tab _)
{
m_GraphSettingsTabFocused = true;
}
void NodeSettingsTabClicked(Tab _)
{
m_GraphSettingsTabFocused = false;
}
public void InitializeGraphSettings()
{
ShowGraphSettings_Internal(m_GraphSettingsContainer);
}
public bool doesInspectorNeedUpdate { get; set; }
public void TriggerInspectorUpdate(IEnumerable<ISelectable> selectionList)
{
// An optimization that prevents inspector updates from getting triggered every time a selection event is issued in the event of large selections
if (selectionList?.Count() > k_InspectorElementLimit)
return;
doesInspectorNeedUpdate = true;
}
public void Update()
{
// Tear down all existing active property drawers, everything is getting rebuilt
foreach (IPropertyDrawer propDrawer in m_AllActivePropertyDrawers)
propDrawer.DisposePropertyDrawer();
m_AllActivePropertyDrawers.Clear();
ShowGraphSettings_Internal(m_GraphSettingsContainer);
m_NodeSettingsContainer.Clear();
try
{
bool anySelectables = false;
int currentInspectablesCount = 0;
var currentInspectables = new HashSet<IInspectable>();
foreach (var selectable in selection)
{
if (selectable is IInspectable inspectable && inspectable.GetObjectToInspect() != null)
{
DrawInspectable(m_NodeSettingsContainer, inspectable);
currentInspectablesCount++;
anySelectables = true;
currentInspectables.Add(inspectable);
}
if (currentInspectablesCount == k_InspectorElementLimit)
{
m_NodeSettingsContainer.Add(m_MaxItemsMessageLabel);
m_MaxItemsMessageLabel.style.visibility = Visibility.Visible;
break;
}
}
// If we have changed our inspector selection while the graph settings tab was focused, we want to switch back to the node settings tab, so invalidate the flag
foreach (var currentInspectable in currentInspectables)
{
if (cachedInspectables.Contains(currentInspectable) == false)
m_GraphSettingsTabFocused = false;
}
cachedInspectables = currentInspectables;
m_CurrentlyInspectedElementsCount = currentInspectablesCount;
if (anySelectables && !m_GraphSettingsTabFocused)
{
// Anything selectable in the graph (GraphSettings not included) is only ever interacted with through the
// Node Settings tab so we can make the assumption they want to see that tab
m_GraphInspectorView.activeTab = m_NodeSettingsTab;
}
}
catch (Exception e)
{
Debug.LogError(e);
}
if (doesInspectorNeedUpdate)
doesInspectorNeedUpdate = false;
m_NodeSettingsContainer.MarkDirtyRepaint();
}
public void RefreshInspectables()
{
// And redraw the inspector
doesInspectorNeedUpdate = true;
Update();
}
private static void FindChildrenRecursive<T>(VisualElement element, List<T> results)
{
foreach (var child in element.Children())
{
if (child is T tChild)
results.Add(tChild);
FindChildrenRecursive(child, results);
}
}
void DrawInspectable(
VisualElement outputVisualElement,
IInspectable inspectable,
IPropertyDrawer propertyDrawerToUse = null)
{
InspectorUtils.GatherInspectorContent(m_PropertyDrawerList, outputVisualElement, inspectable, TriggerInspectorUpdate, m_AllActivePropertyDrawers, propertyDrawerToUse);
}
internal void HandleGraphChanges()
{
float timePassed = (float)(EditorApplication.timeSinceStartup % k_InspectorUpdateInterval);
int currentInspectablesCount = 0;
foreach (var selectable in selection)
{
if (selectable is IInspectable)
currentInspectablesCount++;
}
// Don't update for selections beyond a certain amount as they are no longer visible in the inspector past a certain point and only cost performance as the user performs operations
if (timePassed < 0.01f && selection.Count < k_InspectorElementLimit && currentInspectablesCount != m_CurrentlyInspectedElementsCount)
{
m_GraphSettingsTabFocused = false;
Update();
}
}
void TriggerInspectorUpdate()
{
Update();
}
public override void Dispose()
{
m_AllActivePropertyDrawers.Clear();
m_PropertyDrawerList.Clear();
m_graphSettingsPropertyDrawer = null;
m_GraphInspectorView.Q<Tab>("GraphSettingsTab").selected -= GraphSettingsTabClicked;
m_GraphInspectorView.Q<Tab>("NodeSettingsTab").selected -= NodeSettingsTabClicked;
m_GraphInspectorView = null;
m_GraphSettingsContainer = null;
m_NodeSettingsContainer = null;
m_MaxItemsMessageLabel = null;
}
// This should be implemented by any inspector class that wants to define its own GraphSettings
// which for SG, is a representation of the settings in GraphData
protected virtual void ShowGraphSettings_Internal(VisualElement contentContainer)
{
contentContainer.Clear();
var graphEditorView = ParentView.GetFirstAncestorOfType<GraphEditorView>();
if (graphEditorView == null)
return;
DrawInspectable(contentContainer, (IInspectable)ParentView, m_graphSettingsPropertyDrawer);
contentContainer.MarkDirtyRepaint();
}
}
public static class InspectorUtils
{
internal static void GatherInspectorContent(
List<Type> propertyDrawerList,
VisualElement outputVisualElement,
IInspectable inspectable,
Action propertyChangeCallback,
List<IPropertyDrawer> allPropertyDrawerInstances,
IPropertyDrawer propertyDrawerToUse = null)
{
var dataObject = inspectable.GetObjectToInspect();
if (dataObject == null)
throw new NullReferenceException("DataObject returned by Inspectable is null!");
var properties = inspectable.GetType().GetProperties(BindingFlags.Default | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (properties == null)
throw new NullReferenceException("PropertyInfos returned by Inspectable is null!");
foreach (var propertyInfo in properties)
{
var attribute = propertyInfo.GetCustomAttribute<InspectableAttribute>();
if (attribute == null)
continue;
var propertyType = propertyInfo.GetGetMethod(true).Invoke(inspectable, new object[] { }).GetType();
var propertyDrawerInstance = propertyDrawerToUse;
if (propertyDrawerInstance == null)
{
if (IsPropertyTypeHandled(propertyDrawerList, propertyType, out var propertyDrawerTypeToUse))
propertyDrawerInstance = (IPropertyDrawer)Activator.CreateInstance(propertyDrawerTypeToUse);
}
if (propertyDrawerInstance != null)
{
// Assign the inspector update delegate so any property drawer can trigger an inspector update if it needs it
propertyDrawerInstance.inspectorUpdateDelegate = propertyChangeCallback;
// Supply any required data to this particular kind of property drawer
inspectable.SupplyDataToPropertyDrawer(propertyDrawerInstance, propertyChangeCallback);
var propertyGUI = propertyDrawerInstance.DrawProperty(propertyInfo, dataObject, attribute);
outputVisualElement.Add(propertyGUI);
if (allPropertyDrawerInstances != null)
allPropertyDrawerInstances.Add(propertyDrawerInstance);
}
}
}
static bool IsPropertyTypeHandled(
List<Type> propertyDrawerList,
Type typeOfProperty,
out Type propertyDrawerToUse)
{
propertyDrawerToUse = null;
// Check to see if a property drawer has been registered that handles this type
foreach (var propertyDrawerType in propertyDrawerList)
{
var typeHandledByPropertyDrawer = propertyDrawerType.GetCustomAttribute<SGPropertyDrawerAttribute>();
// Numeric types and boolean wrapper types like ToggleData handled here
if (typeHandledByPropertyDrawer.propertyType == typeOfProperty)
{
propertyDrawerToUse = propertyDrawerType;
return true;
}
// Generics and Enumerable types are handled here
else if (typeHandledByPropertyDrawer.propertyType.IsAssignableFrom(typeOfProperty))
{
// Before returning it, check for a more appropriate type further
propertyDrawerToUse = propertyDrawerType;
return true;
}
// Enums are weird and need to be handled explicitly as done below as their runtime type isn't the same as System.Enum
else if (typeHandledByPropertyDrawer.propertyType == typeOfProperty.BaseType)
{
propertyDrawerToUse = propertyDrawerType;
return true;
}
}
return false;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 6759820ca0a974f36b1a63ec6f6e1a57
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,247 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEngine;
using UnityEditor.Graphing;
using UnityEditor.Graphing.Util;
using UnityEditor.ShaderGraph.Drawing.Interfaces;
using Object = UnityEngine.Object;
#if UNITY_6000_5_OR_NEWER
using UnityEngine.Assemblies;
#endif
using UnityEditor.UIElements;
using UnityEngine.UIElements;
namespace UnityEditor.ShaderGraph.Drawing.Inspector
{
class MasterPreviewView : VisualElement, ISGResizable
{
PreviewManager m_PreviewManager;
GraphData m_Graph;
PreviewRenderData m_PreviewRenderHandle;
Image m_PreviewTextureView;
public Image previewTextureView
{
get { return m_PreviewTextureView; }
}
Vector2 m_PreviewScrollPosition;
ObjectField m_PreviewMeshPicker;
Mesh m_PreviousMesh;
ResizableElement m_ResizableElement;
VisualElement m_Preview;
Label m_Title;
public VisualElement preview
{
get { return m_Preview; }
}
List<string> m_DoNotShowPrimitives = new List<string>(new string[] { PrimitiveType.Plane.ToString() });
public string assetName
{
get { return m_Title.text; }
set { m_Title.text = value; }
}
public Action onResized;
public MasterPreviewView(PreviewManager previewManager, GraphData graph)
{
style.overflow = Overflow.Hidden;
m_PreviewManager = previewManager;
m_Graph = graph;
styleSheets.Add(Resources.Load<StyleSheet>("Styles/MasterPreviewView"));
m_PreviewRenderHandle = previewManager.masterRenderData;
if (m_PreviewRenderHandle != null)
{
m_PreviewRenderHandle.onPreviewChanged += OnPreviewChanged;
}
var mainContainer = new VisualElement();
mainContainer.AddToClassList("mainContainer");
var topContainer = new VisualElement() { name = "top" };
{
m_Title = new Label() { name = "title" };
m_Title.text = "Main Preview";
topContainer.Add(m_Title);
}
mainContainer.Add(topContainer);
m_Preview = new VisualElement { name = "middle" };
{
m_PreviewTextureView = CreatePreview(Texture2D.blackTexture);
m_PreviewScrollPosition = new Vector2(0f, 0f);
preview.Add(m_PreviewTextureView);
preview.AddManipulator(new Scrollable(OnScroll));
}
mainContainer.Add(preview);
Add(mainContainer);
m_ResizableElement = new ResizableElement();
Add(m_ResizableElement);
RegisterCallback<GeometryChangedEvent>(OnGeometryChanged);
}
Image CreatePreview(Texture texture)
{
if (m_PreviewRenderHandle?.texture != null)
{
texture = m_PreviewRenderHandle.texture;
}
var image = new Image { name = "preview", image = texture, scaleMode = ScaleMode.ScaleAndCrop };
image.AddManipulator(new Draggable(OnMouseDragPreviewMesh, true));
image.AddManipulator(new MasterPreviewManipulator((Action<ContextualMenuPopulateEvent>)BuildContextualMenu));
return image;
}
void BuildContextualMenu(ContextualMenuPopulateEvent evt)
{
Target currentMainTarget = null;
if (m_Graph != null)
{
foreach (var target in m_Graph.activeTargets)
{
currentMainTarget = target;
break;
}
}
bool prefersUITK = currentMainTarget?.prefersUITKPreview ?? false;
DropdownMenuAction.Status EnabledIfNotPreferUITK(DropdownMenuAction a)
=> prefersUITK ? DropdownMenuAction.Status.Disabled : DropdownMenuAction.Status.Normal;
foreach (var primitiveTypeName in Enum.GetNames(typeof(PrimitiveType)))
{
if (m_DoNotShowPrimitives.Contains(primitiveTypeName))
continue;
evt.menu.AppendAction(primitiveTypeName, e => ChangePrimitiveMesh(primitiveTypeName), EnabledIfNotPreferUITK);
}
evt.menu.AppendAction("Sprite", e => ChangeMeshSprite(), EnabledIfNotPreferUITK);
evt.menu.AppendAction("Custom Mesh", e => ChangeMeshCustom(), EnabledIfNotPreferUITK);
}
void OnPreviewChanged()
{
m_PreviewTextureView.image = m_PreviewRenderHandle?.texture ?? Texture2D.blackTexture;
if (m_PreviewRenderHandle != null && m_PreviewRenderHandle.shaderData.isOutOfDate)
m_PreviewTextureView.tintColor = new Color(1.0f, 1.0f, 1.0f, 0.3f);
else
m_PreviewTextureView.tintColor = Color.white;
m_PreviewTextureView.MarkDirtyRepaint();
}
void ChangePrimitiveMesh(string primitiveName)
{
Mesh changedPrimitiveMesh = Resources.GetBuiltinResource(typeof(Mesh), string.Format("{0}.fbx", primitiveName)) as Mesh;
ChangeMesh(changedPrimitiveMesh);
}
void ChangeMesh(Mesh mesh)
{
Mesh changedMesh = mesh;
m_PreviewManager.UpdateMasterPreview(ModificationScope.Node);
if (m_Graph.previewData.serializedMesh.mesh != changedMesh)
{
m_Graph.previewData.rotation = Quaternion.identity;
m_PreviewScrollPosition = Vector2.zero;
}
m_Graph.previewData.preventRotation = false;
m_Graph.previewData.serializedMesh.mesh = changedMesh;
}
void OnMeshChanged(Object obj)
{
var mesh = obj as Mesh;
if (mesh == null)
mesh = m_PreviousMesh;
ChangeMesh(mesh);
}
void ChangeMeshSprite()
{
ChangePrimitiveMesh(PrimitiveType.Quad.ToString());
m_Graph.previewData.rotation = Quaternion.identity;
m_Graph.previewData.preventRotation = true;
}
void ChangeMeshCustom()
{
InternalBridge.ObjectSelector.Show(null, typeof(Mesh), null, false, null, (Action<Object>)OnMeshChanged, (Action<Object>)OnMeshChanged, false);
}
void OnGeometryChanged(GeometryChangedEvent evt)
{
var currentWidth = m_PreviewRenderHandle?.texture != null ? m_PreviewRenderHandle.texture.width : -1;
var currentHeight = m_PreviewRenderHandle?.texture != null ? m_PreviewRenderHandle.texture.height : -1;
var targetWidth = Mathf.Max(1f, m_PreviewTextureView.contentRect.width);
var targetHeight = Mathf.Max(1f, m_PreviewTextureView.contentRect.height);
if (Mathf.Approximately(currentWidth, targetHeight) && Mathf.Approximately(currentHeight, targetWidth))
return;
m_PreviewTextureView.style.width = evt.newRect.width;
const float offsetFromHeader = 40.0f;
const float offsetFromMargin = 2 * 6.0f;
m_PreviewTextureView.style.height = evt.newRect.height - (offsetFromHeader + offsetFromMargin);
m_PreviewManager.ResizeMasterPreview(new Vector2(evt.newRect.width, evt.newRect.width));
}
void OnScroll(float scrollValue)
{
float rescaleAmount = -scrollValue * .03f;
m_Graph.previewData.scale = Mathf.Clamp(m_Graph.previewData.scale + rescaleAmount, 0.2f, 5f);
m_PreviewManager.UpdateMasterPreview(ModificationScope.Node);
}
void OnMouseDragPreviewMesh(Vector2 deltaMouse)
{
if (m_Graph.previewData.preventRotation) return;
Vector2 previewSize = m_PreviewTextureView.contentRect.size;
m_PreviewScrollPosition -= deltaMouse * (Event.current.shift ? 3f : 1f) / Mathf.Min(previewSize.x, previewSize.y) * 140f;
m_PreviewScrollPosition.y = Mathf.Clamp(m_PreviewScrollPosition.y, -90f, 90f);
Quaternion previewRotation = Quaternion.Euler(m_PreviewScrollPosition.y, 0, 0) * Quaternion.Euler(0, m_PreviewScrollPosition.x, 0);
m_Graph.previewData.rotation = previewRotation;
m_PreviewManager.UpdateMasterPreview(ModificationScope.Node);
}
public void OnStartResize()
{
}
public void OnResized()
{
onResized?.Invoke();
}
public bool CanResizePastParentBounds() => false;
public bool KeepSquareAspect() => true;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 546947d46a85b284a971a3f056495735
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,281 @@
using System;
using UnityEngine.UIElements;
using UnityEngine;
using UnityEditor.UIElements;
using UnityEditor.Graphing.Util;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph.Internal;
using System.Collections.Generic;
namespace UnityEditor.ShaderGraph.Drawing.Inspector
{
public static class PropertyDrawerUtils
{
public static Label CreateLabel(string text, int indentLevel = 0, FontStyle fontStyle = FontStyle.Normal)
{
string label = new string(' ', indentLevel * 4);
var labelVisualElement = new Label(label + text);
labelVisualElement.style.unityFontStyleAndWeight = fontStyle;
labelVisualElement.name = "header";
return labelVisualElement;
}
public static Label CreateLabel(string text, int indentLevel = 0)
{
string label = new string(' ', indentLevel * 4);
var labelVisualElement = new Label(label + text);
return labelVisualElement;
}
internal enum UIPrecisionForShaderGraphs
{
Inherit = Precision.Inherit,
Single = Precision.Single,
Half = Precision.Half,
UseGraphPrecision = Precision.Graph,
}
internal static void AddDefaultNodeProperties(VisualElement parentElement, AbstractMaterialNode node, Action setNodesAsDirtyCallback, Action updateNodeViewsCallback)
{
EnumField precisionField = null;
if (node.canSetPrecision)
{
precisionField = new EnumField((UIPrecisionForShaderGraphs)node.precision);
var propertyRow = new PropertyRow(new Label("Precision"));
propertyRow.Add(precisionField, (field) =>
{
field.RegisterValueChangedCallback(evt =>
{
if (evt.newValue.Equals(node.precision))
return;
setNodesAsDirtyCallback?.Invoke();
node.owner.owner.RegisterCompleteObjectUndo("Change precision");
node.precision = (Precision)evt.newValue;
node.owner.ValidateGraph();
updateNodeViewsCallback?.Invoke();
node.Dirty(ModificationScope.Graph);
});
});
if (node is Serialization.MultiJsonInternal.UnknownNodeType)
precisionField.SetEnabled(false);
parentElement.Add(propertyRow);
}
EnumField previewField = null;
if (node.hasPreview)
{
previewField = new EnumField(node.m_PreviewMode);
var propertyRow = new PropertyRow(new Label("Preview"));
propertyRow.Add(previewField, (field) =>
{
field.RegisterValueChangedCallback(evt =>
{
if (evt.newValue.Equals(node.m_PreviewMode))
return;
setNodesAsDirtyCallback?.Invoke();
node.owner.owner.RegisterCompleteObjectUndo("Change preview");
node.m_PreviewMode = (PreviewMode)evt.newValue;
updateNodeViewsCallback?.Invoke();
node.Dirty(ModificationScope.Graph);
});
});
if (node is Serialization.MultiJsonInternal.UnknownNodeType)
previewField.SetEnabled(false);
parentElement.Add(propertyRow);
}
if (node is BlockNode bnode)
{
AddCustomInterpolatorProperties(parentElement, bnode, setNodesAsDirtyCallback, updateNodeViewsCallback);
}
if (node is CustomInterpolatorNode cinode)
{
if (cinode.e_targetBlockNode != null)
{
AddCustomInterpolatorProperties(parentElement, cinode.e_targetBlockNode, setNodesAsDirtyCallback, updateNodeViewsCallback);
}
}
}
internal static void AddCustomInterpolatorProperties(VisualElement parentElement, BlockNode node, Action setNodesAsDirtyCallback, Action updateNodeViewsCallback)
{
if (!node.isCustomBlock)
return;
TextField textField = null;
{
textField = new TextField { value = node.customName, multiline = false };
var propertyRow = new PropertyRow(new Label("Name"));
propertyRow.Add(textField, (field) =>
{
field.RegisterCallback<FocusOutEvent>(evt =>
{
if (field.value.Equals(node.customName))
return;
HashSet<string> usedNames = new HashSet<string>();
foreach (var other in node.contextData.blocks)
if (other != node)
usedNames.Add(other.value.descriptor.displayName);
setNodesAsDirtyCallback?.Invoke();
node.owner.owner.RegisterCompleteObjectUndo("Change Block Name");
field.value = node.customName = GraphUtil.SanitizeName(usedNames, "{0}_{1}", NodeUtils.ConvertToValidHLSLIdentifier(field.value));
updateNodeViewsCallback?.Invoke();
node.Dirty(ModificationScope.Node);
node.owner?.ValidateGraph();
});
});
parentElement.Add(propertyRow);
}
EnumField typeField = null;
{
typeField = new EnumField(node.customWidth);
var propertyRow = new PropertyRow(new Label("Type"));
propertyRow.Add(typeField, (field) =>
{
field.RegisterValueChangedCallback(evt =>
{
if (evt.newValue.Equals(node.customWidth))
return;
setNodesAsDirtyCallback?.Invoke();
node.owner.owner.RegisterCompleteObjectUndo("Change Block Type");
node.customWidth = (BlockNode.CustomBlockType)evt.newValue;
updateNodeViewsCallback?.Invoke();
node.Dirty(ModificationScope.Topological);
node.owner?.ValidateGraph();
});
});
parentElement.Add(propertyRow);
}
EnumField interpolationField = null;
{
interpolationField = new EnumField(node.customInterpolation);
var propertyRow = new PropertyRow(new Label("Interpolation"));
propertyRow.Add(interpolationField, (field) =>
{
field.RegisterValueChangedCallback(evt =>
{
if (evt.newValue.Equals(node.customInterpolation))
return;
setNodesAsDirtyCallback?.Invoke();
node.owner.owner.RegisterCompleteObjectUndo("Change Block Interpolation");
node.customInterpolation = (BlockNode.CustomInterpolationType)evt.newValue;
updateNodeViewsCallback?.Invoke();
node.Dirty(ModificationScope.Topological);
node.owner?.ValidateGraph();
});
});
parentElement.Add(propertyRow);
}
}
internal static void AddCustomCheckboxProperty(
VisualElement parentElement, AbstractMaterialNode node,
Action setNodesAsDirtyCallback, Action updateNodeViewsCallback,
String label,
String undoLabel,
Func<bool> GetterFn,
Action<bool> SetterFn)
{
var fieldObj = new Toggle();
fieldObj.value = GetterFn();
var propertyRow = new PropertyRow(new Label(label));
propertyRow.Add(fieldObj, (field) =>
{
field.RegisterValueChangedCallback(evt =>
{
if (evt.newValue.Equals(GetterFn()))
return;
setNodesAsDirtyCallback?.Invoke();
node.owner.owner.RegisterCompleteObjectUndo(undoLabel);
SetterFn((bool)evt.newValue);
node.owner.ValidateGraph();
updateNodeViewsCallback?.Invoke();
node.Dirty(ModificationScope.Graph);
});
});
if (node is Serialization.MultiJsonInternal.UnknownNodeType)
fieldObj.SetEnabled(false);
parentElement.Add(propertyRow);
}
internal static void AddCustomEnumProperty<T>(
VisualElement parentElement, AbstractMaterialNode node,
Action setNodesAsDirtyCallback, Action updateNodeViewsCallback,
String label,
String undoLabel,
Func<T> GetterFn,
Action<T> SetterFn) where T : System.Enum, IConvertible
{
var fieldObj = new EnumField(GetterFn());
//fieldObj.value = ;
var propertyRow = new PropertyRow(new Label(label));
propertyRow.Add(fieldObj, (field) =>
{
field.RegisterValueChangedCallback(evt =>
{
if (evt.newValue.Equals(GetterFn()))
return;
setNodesAsDirtyCallback?.Invoke();
node.owner.owner.RegisterCompleteObjectUndo(undoLabel);
SetterFn((T)evt.newValue);
node.owner.ValidateGraph();
updateNodeViewsCallback?.Invoke();
node.Dirty(ModificationScope.Graph);
});
});
if (node is Serialization.MultiJsonInternal.UnknownNodeType)
fieldObj.SetEnabled(false);
parentElement.Add(propertyRow);
}
internal static void AddCustomIntegerProperty(
VisualElement parentElement, AbstractMaterialNode node,
Action setNodesAsDirtyCallback, Action updateNodeViewsCallback,
String label,
String undoLabel,
int min,
int max,
Func<int> GetterFn,
Action<int> SetterFn)
{
var fieldObj = new IntegerField { isDelayed = true };
fieldObj.value = GetterFn();
var propertyRow = new PropertyRow(new Label(label));
propertyRow.Add(fieldObj, (field) =>
{
field.RegisterValueChangedCallback(evt =>
{
int clamped = Mathf.Clamp(evt.newValue, min, max);
if (clamped != evt.newValue)
fieldObj.SetValueWithoutNotify(clamped);
if (clamped.Equals(GetterFn()))
return;
setNodesAsDirtyCallback?.Invoke();
node.owner.owner.RegisterCompleteObjectUndo(undoLabel);
SetterFn(clamped);
node.owner.ValidateGraph();
updateNodeViewsCallback?.Invoke();
// Topological (not Graph): an integer can drive the node's slot set (e.g. a sample count),
// and only a topological modification makes the node view add/remove and re-order ports.
node.Dirty(ModificationScope.Topological);
});
});
if (node is Serialization.MultiJsonInternal.UnknownNodeType)
fieldObj.SetEnabled(false);
parentElement.Add(propertyRow);
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: bee8af59ecde4f88b12e15e45df7704c
timeCreated: 1587016996
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 8488c4add4764941a2d903bf014329b9
timeCreated: 1588090481
@@ -0,0 +1,110 @@
using System;
using System.Reflection;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph;
using UnityEditor.ShaderGraph.Drawing;
using UnityEditor.ShaderGraph.Drawing.Inspector;
using UnityEditor.ShaderGraph.Internal;
using UnityEngine.UIElements;
using UnityEditor.UIElements;
using UnityEditor.Graphing.Util;
using UnityEngine;
namespace UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers
{
internal interface IGetNodePropertyDrawerPropertyData
{
void GetPropertyData(Action setNodesAsDirtyCallback, Action updateNodeViewsCallback);
}
[SGPropertyDrawer(typeof(AbstractMaterialNode))]
public class AbstractMaterialNodePropertyDrawer : IPropertyDrawer, IGetNodePropertyDrawerPropertyData
{
public Action inspectorUpdateDelegate { get; set; }
Action m_setNodesAsDirtyCallback;
Action m_updateNodeViewsCallback;
public void GetPropertyData(Action setNodesAsDirtyCallback, Action updateNodeViewsCallback)
{
m_setNodesAsDirtyCallback = setNodesAsDirtyCallback;
m_updateNodeViewsCallback = updateNodeViewsCallback;
}
internal virtual void AddCustomNodeProperties(VisualElement parentElement, AbstractMaterialNode node, Action setNodesAsDirtyCallback, Action updateNodeViewsCallback)
{
}
VisualElement CreateGUI(AbstractMaterialNode node, InspectableAttribute attribute, out VisualElement propertyVisualElement)
{
VisualElement nodeSettings = new VisualElement();
var nameLabel = PropertyDrawerUtils.CreateLabel($"{node.displayName} Node", 0, FontStyle.Bold);
nodeSettings.Add(nameLabel);
if (node.sgVersion < node.latestVersion)
{
string deprecationText = null;
string buttonText = null;
string labelText = null;
MessageType messageType = MessageType.Warning;
if (node is IHasCustomDeprecationMessage nodeWithCustomDeprecationSettings)
{
nodeWithCustomDeprecationSettings.GetCustomDeprecationMessage(out deprecationText, out buttonText, out labelText, out messageType);
}
Action dismissAction = null;
if (node.dismissedUpdateVersion < node.latestVersion)
{
dismissAction = () =>
{ // dismiss
m_setNodesAsDirtyCallback?.Invoke();
node.owner.owner.RegisterCompleteObjectUndo($"Dismiss {node.name} Node Upgrade Flag");
node.dismissedUpdateVersion = node.latestVersion;
node.owner.messageManager.ClearNodesFromProvider(node.owner, new AbstractMaterialNode[] { node });
node.Dirty(ModificationScope.Graph);
inspectorUpdateDelegate?.Invoke();
m_updateNodeViewsCallback?.Invoke();
};
}
var help = HelpBoxRow.CreateUpgradePrompt($"{node.name} Node",
() =>
{ // upgrade
m_setNodesAsDirtyCallback?.Invoke();
node.owner.owner.RegisterCompleteObjectUndo($"Update {node.name} Node");
node.ChangeVersion(node.latestVersion);
node.owner.messageManager.ClearNodesFromProvider(node.owner, new AbstractMaterialNode[] { node });
node.Dirty(ModificationScope.Graph);
inspectorUpdateDelegate?.Invoke();
m_updateNodeViewsCallback?.Invoke();
},
dismissAction, deprecationText, buttonText, labelText, messageType);
if (help != null)
{
nodeSettings.Insert(0, help);
}
}
PropertyDrawerUtils.AddDefaultNodeProperties(nodeSettings, node, m_setNodesAsDirtyCallback, m_updateNodeViewsCallback);
AddCustomNodeProperties(nodeSettings, node, m_setNodesAsDirtyCallback, m_updateNodeViewsCallback);
propertyVisualElement = null;
return nodeSettings;
}
public VisualElement DrawProperty(PropertyInfo propertyInfo, object actualObject, InspectableAttribute attribute)
{
return this.CreateGUI(
(AbstractMaterialNode)actualObject,
attribute,
out var propertyVisualElement);
}
internal virtual void DisposePropertyDrawer()
{
}
void IPropertyDrawer.DisposePropertyDrawer() { DisposePropertyDrawer(); }
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 6436de6b57634b32a3c95d37c1b9b2c0
timeCreated: 1588712275
@@ -0,0 +1,57 @@
using System;
using System.Reflection;
using UnityEditor.Graphing.Util;
using UnityEditor.ShaderGraph.Drawing;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers
{
[SGPropertyDrawer(typeof(bool))]
class BoolPropertyDrawer : IPropertyDrawer
{
internal delegate void ValueChangedCallback(bool newValue);
internal VisualElement CreateGUI(
ValueChangedCallback valueChangedCallback,
bool fieldToDraw,
string labelName,
out VisualElement propertyToggle,
int indentLevel = 0)
{
var row = new PropertyRow(PropertyDrawerUtils.CreateLabel(labelName, indentLevel));
// Create and assign toggle as out variable here so that callers can also do additional work with enabling/disabling if needed
propertyToggle = new Toggle();
row.Add((Toggle)propertyToggle, (toggle) =>
{
toggle.value = fieldToDraw;
});
if (valueChangedCallback != null)
{
var toggle = (Toggle)propertyToggle;
toggle.OnToggleChanged(evt => valueChangedCallback(evt.newValue));
}
row.styleSheets.Add(Resources.Load<StyleSheet>("Styles/PropertyRow"));
return row;
}
public Action inspectorUpdateDelegate { get; set; }
public VisualElement DrawProperty(
PropertyInfo propertyInfo,
object actualObject,
InspectableAttribute attribute)
{
return this.CreateGUI(
// Use the setter from the provided property as the callback
newBoolValue => propertyInfo.GetSetMethod(true).Invoke(actualObject, new object[] { newBoolValue }),
(bool)propertyInfo.GetValue(actualObject),
attribute.labelName,
out var propertyVisualElement);
}
void IPropertyDrawer.DisposePropertyDrawer() { }
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: c6b03af40f8944e4a3c303c7875029d0
timeCreated: 1588094617
@@ -0,0 +1,50 @@
using System;
using System.Reflection;
using UnityEditor.ShaderGraph.Drawing;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers
{
[SGPropertyDrawer(typeof(Color))]
class ColorPropertyDrawer : IPropertyDrawer
{
internal delegate void ValueChangedCallback(Color newValue);
internal VisualElement CreateGUI(
ValueChangedCallback valueChangedCallback,
Color fieldToDraw,
string labelName,
out VisualElement propertyColorField,
int indentLevel = 0)
{
var colorField = new ColorField { value = fieldToDraw, showEyeDropper = false, hdr = false };
if (valueChangedCallback != null)
{
colorField.RegisterValueChangedCallback(evt => { valueChangedCallback((Color)evt.newValue); });
}
propertyColorField = colorField;
var defaultRow = new PropertyRow(PropertyDrawerUtils.CreateLabel(labelName, indentLevel));
defaultRow.Add(propertyColorField);
return defaultRow;
}
public Action inspectorUpdateDelegate { get; set; }
public VisualElement DrawProperty(PropertyInfo propertyInfo, object actualObject, InspectableAttribute attribute)
{
return this.CreateGUI(
// Use the setter from the provided property as the callback
newValue => propertyInfo.GetSetMethod(true).Invoke(actualObject, new object[] { newValue }),
(Color)propertyInfo.GetValue(actualObject),
attribute.labelName,
out var propertyVisualElement);
}
void IPropertyDrawer.DisposePropertyDrawer() { }
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 4773ec31c0c943a8b8fe7eca5bbe8c16
timeCreated: 1588106342
@@ -0,0 +1,51 @@
using System;
using System.Reflection;
using UnityEditor.ShaderGraph.Drawing;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers
{
[SGPropertyDrawer(typeof(Cubemap))]
class CubemapPropertyDrawer : IPropertyDrawer
{
internal delegate void ValueChangedCallback(Cubemap newValue);
internal VisualElement CreateGUI(
ValueChangedCallback valueChangedCallback,
Cubemap fieldToDraw,
string labelName,
out VisualElement propertyCubemapField,
int indentLevel = 0)
{
var objectField = new ObjectField { value = fieldToDraw, objectType = typeof(Cubemap) };
if (valueChangedCallback != null)
{
objectField.RegisterValueChangedCallback(evt => { valueChangedCallback((Cubemap)evt.newValue); });
}
propertyCubemapField = objectField;
var defaultRow = new PropertyRow(PropertyDrawerUtils.CreateLabel(labelName, indentLevel));
defaultRow.Add(propertyCubemapField);
defaultRow.styleSheets.Add(Resources.Load<StyleSheet>("Styles/PropertyRow"));
return defaultRow;
}
public Action inspectorUpdateDelegate { get; set; }
public VisualElement DrawProperty(PropertyInfo propertyInfo, object actualObject, InspectableAttribute attribute)
{
return this.CreateGUI(
// Use the setter from the provided property as the callback
newValue => propertyInfo.GetSetMethod(true).Invoke(actualObject, new object[] { newValue }),
(Cubemap)propertyInfo.GetValue(actualObject),
attribute.labelName,
out var propertyVisualElement);
}
void IPropertyDrawer.DisposePropertyDrawer() { }
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: e000b1294b904558acc68a1527795048
timeCreated: 1588106499
@@ -0,0 +1,61 @@
using System;
using System.Reflection;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph;
using UnityEditor.ShaderGraph.Drawing;
using UnityEditor.ShaderGraph.Drawing.Inspector;
using UnityEngine.UIElements;
using UnityEngine;
namespace UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers
{
[SGPropertyDrawer(typeof(CustomFunctionNode))]
public class CustomFunctionNodePropertyDrawer : IPropertyDrawer, IGetNodePropertyDrawerPropertyData
{
Action m_setNodesAsDirtyCallback;
Action m_updateNodeViewsCallback;
void IGetNodePropertyDrawerPropertyData.GetPropertyData(Action setNodesAsDirtyCallback, Action updateNodeViewsCallback)
{
m_setNodesAsDirtyCallback = setNodesAsDirtyCallback;
m_updateNodeViewsCallback = updateNodeViewsCallback;
}
VisualElement CreateGUI(CustomFunctionNode node, InspectableAttribute attribute,
out VisualElement propertyVisualElement)
{
var propertySheet = new PropertySheet(PropertyDrawerUtils.CreateLabel($"{node.name} Node", 0, FontStyle.Bold));
PropertyDrawerUtils.AddDefaultNodeProperties(propertySheet, node, m_setNodesAsDirtyCallback, m_updateNodeViewsCallback);
var inputListView = new ReorderableSlotListView(node, SlotType.Input, true);
inputListView.OnAddCallback += list => inspectorUpdateDelegate();
inputListView.OnRemoveCallback += list => inspectorUpdateDelegate();
inputListView.OnListRecreatedCallback += () => inspectorUpdateDelegate();
propertySheet.Add(inputListView);
var outputListView = new ReorderableSlotListView(node, SlotType.Output, true);
outputListView.OnAddCallback += list => inspectorUpdateDelegate();
outputListView.OnRemoveCallback += list => inspectorUpdateDelegate();
outputListView.OnListRecreatedCallback += () => inspectorUpdateDelegate();
propertySheet.Add(outputListView);
propertySheet.Add(new HlslFunctionView(node));
propertyVisualElement = null;
return propertySheet;
}
public Action inspectorUpdateDelegate { get; set; }
public VisualElement DrawProperty(PropertyInfo propertyInfo, object actualObject,
InspectableAttribute attribute)
{
return this.CreateGUI(
(CustomFunctionNode)actualObject,
attribute,
out var propertyVisualElement);
}
void IPropertyDrawer.DisposePropertyDrawer() { }
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 5b314925e5a04562b330a7147571e838
timeCreated: 1588810391
@@ -0,0 +1,51 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor.ShaderGraph.Drawing;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers
{
[SGPropertyDrawer(typeof(IEnumerable<string>))]
class DropdownPropertyDrawer : IPropertyDrawer
{
internal delegate void ValueChangedCallback(int newValue);
internal VisualElement CreateGUI(
ValueChangedCallback valueChangedCallback,
IEnumerable<string> fieldToDraw,
string labelName,
out VisualElement textArrayField,
int indentLevel = 0)
{
var propertyRow = new PropertyRow(PropertyDrawerUtils.CreateLabel(labelName, indentLevel));
textArrayField = new PopupField<string>(fieldToDraw.ToList(), 0);
propertyRow.Add(textArrayField);
var popupField = (PopupField<string>)textArrayField;
popupField.RegisterValueChangedCallback(evt =>
{
valueChangedCallback(popupField.index);
});
propertyRow.styleSheets.Add(Resources.Load<StyleSheet>("Styles/PropertyRow"));
return propertyRow;
}
public Action inspectorUpdateDelegate { get; set; }
public VisualElement DrawProperty(PropertyInfo propertyInfo, object actualObject, InspectableAttribute attribute)
{
return this.CreateGUI(
// Use the setter from the provided property as the callback
newSelectedIndex => propertyInfo.GetSetMethod(true).Invoke(actualObject, new object[] { newSelectedIndex }),
(IEnumerable<string>)propertyInfo.GetValue(actualObject),
attribute.labelName,
out var textArrayField);
}
void IPropertyDrawer.DisposePropertyDrawer() { }
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: f9a394b3df374578ae75b90960ee4790
timeCreated: 1588106059
@@ -0,0 +1,58 @@
using System;
using System.Reflection;
using UnityEditor.Graphing.Util;
using UnityEditor.ShaderGraph.Drawing;
using UnityEditor.UIElements;
using UnityEngine.UIElements;
namespace UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers
{
[SGPropertyDrawer(typeof(Enum))]
class EnumPropertyDrawer : IPropertyDrawer
{
internal delegate void ValueChangedCallback(Enum newValue);
internal VisualElement CreateGUI(
ValueChangedCallback valueChangedCallback,
Enum fieldToDraw,
string labelName,
Enum defaultValue,
out VisualElement propertyVisualElement,
int indentLevel = 0,
string tooltip = null)
{
var row = new PropertyRow(PropertyDrawerUtils.CreateLabel(labelName, indentLevel));
row.tooltip = tooltip;
propertyVisualElement = new EnumField(defaultValue);
row.Add((EnumField)propertyVisualElement, (field) =>
{
field.value = fieldToDraw;
});
if (valueChangedCallback != null)
{
var enumField = (EnumField)propertyVisualElement;
enumField.RegisterValueChangedCallback(evt => valueChangedCallback(evt.newValue));
}
return row;
}
public Action inspectorUpdateDelegate { get; set; }
public VisualElement DrawProperty(
PropertyInfo propertyInfo,
object actualObject,
InspectableAttribute attribute)
{
return this.CreateGUI(newEnumValue =>
propertyInfo.GetSetMethod(true).Invoke(actualObject, new object[] { newEnumValue }),
(Enum)propertyInfo.GetValue(actualObject),
attribute.labelName,
(Enum)attribute.defaultValue,
out var propertyVisualElement);
}
void IPropertyDrawer.DisposePropertyDrawer() { }
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: f08c6b905c574da0b669976fa5353fa8
timeCreated: 1588094508
@@ -0,0 +1,51 @@
using System;
using System.Reflection;
using UnityEditor.ShaderGraph.Drawing;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers
{
[SGPropertyDrawer(typeof(float))]
class FloatPropertyDrawer : IPropertyDrawer
{
internal delegate void ValueChangedCallback(float newValue);
internal VisualElement CreateGUI(
ValueChangedCallback valueChangedCallback,
float fieldToDraw,
string labelName,
out VisualElement propertyFloatField,
int indentLevel = 0)
{
var floatField = new FloatField { label = "X", value = fieldToDraw };
floatField.labelElement.style.minWidth = 15;
if (valueChangedCallback != null)
{
floatField.RegisterValueChangedCallback(evt => { valueChangedCallback((float)evt.newValue); });
}
propertyFloatField = floatField;
var defaultRow = new PropertyRow(PropertyDrawerUtils.CreateLabel(labelName, indentLevel));
defaultRow.Add(propertyFloatField);
defaultRow.styleSheets.Add(Resources.Load<StyleSheet>("Styles/PropertyRow"));
return defaultRow;
}
public Action inspectorUpdateDelegate { get; set; }
public VisualElement DrawProperty(PropertyInfo propertyInfo, object actualObject, InspectableAttribute attribute)
{
return this.CreateGUI(
// Use the setter from the provided property as the callback
newValue => propertyInfo.GetSetMethod(true).Invoke(actualObject, new object[] { newValue }),
(float)propertyInfo.GetValue(actualObject),
attribute.labelName,
out var propertyVisualElement);
}
void IPropertyDrawer.DisposePropertyDrawer() { }
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: d316720413684b89abb49286f25a4e94
timeCreated: 1588106146
@@ -0,0 +1,124 @@
using System;
using System.Reflection;
using UnityEditor.ShaderGraph.Drawing;
using UnityEditor.ShaderGraph.Drawing.Controls;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers
{
[SGPropertyDrawer(typeof(Gradient))]
class GradientPropertyDrawer : IPropertyDrawer
{
internal delegate void ValueChangedCallback(Gradient newValue);
ValueChangedCallback m_ValueChangedCallback;
Action m_PreValueChangedCallback;
GradientObject m_GradientObject;
SerializedObject m_SerializedObject;
GradientField m_Field;
GradientUndoSession m_UndoSession;
internal VisualElement CreateGUI(
ValueChangedCallback valueChangedCallback,
Gradient fieldToDraw,
string labelName,
out VisualElement propertyGradientField,
int indentLevel = 0,
Action preValueChangedCallback = null)
{
m_ValueChangedCallback = valueChangedCallback;
m_PreValueChangedCallback = preValueChangedCallback;
m_GradientObject = ScriptableObject.CreateInstance<GradientObject>();
m_GradientObject.gradient = new Gradient();
m_GradientObject.gradient.SetKeys(fieldToDraw.colorKeys, fieldToDraw.alphaKeys);
m_GradientObject.gradient.mode = fieldToDraw.mode;
m_SerializedObject = new SerializedObject(m_GradientObject);
m_Field = new GradientField { value = m_GradientObject.gradient, colorSpace = ColorSpace.Linear, hdr = true };
m_Field.RegisterValueChangedCallback(OnFieldValueChanged);
if (preValueChangedCallback != null)
{
m_Field.pickerClosed += OnPickerClosed;
m_UndoSession = new GradientUndoSession(
() => m_GradientObject.gradient,
value => m_ValueChangedCallback?.Invoke(value),
() => m_PreValueChangedCallback(),
() => true);
}
propertyGradientField = m_Field;
// Any core widgets used by the inspector over and over should come from some kind of factory
var defaultRow = new PropertyRow(PropertyDrawerUtils.CreateLabel(labelName, indentLevel));
defaultRow.Add(propertyGradientField);
defaultRow.styleSheets.Add(Resources.Load<StyleSheet>("Styles/PropertyRow"));
defaultRow.RegisterCallback<AttachToPanelEvent>(OnAttachToPanel);
defaultRow.RegisterCallback<DetachFromPanelEvent>(OnDetachFromPanel);
return defaultRow;
}
void OnAttachToPanel(AttachToPanelEvent evt)
{
Undo.undoRedoPerformed += OnUndoRedoPerformed;
}
void OnFieldValueChanged(ChangeEvent<Gradient> evt)
{
m_SerializedObject.Update();
if (evt.newValue.Equals(m_GradientObject.gradient))
return;
m_UndoSession?.BeginChange();
Undo.RegisterCompleteObjectUndo(m_GradientObject, "Modify Gradient Stop");
m_GradientObject.gradient.SetKeys(evt.newValue.colorKeys, evt.newValue.alphaKeys);
m_GradientObject.gradient.mode = evt.newValue.mode;
m_SerializedObject.ApplyModifiedProperties();
m_ValueChangedCallback?.Invoke(m_GradientObject.gradient);
}
void OnUndoRedoPerformed()
{
if (m_GradientObject == null || m_Field == null)
return;
m_SerializedObject.Update();
m_ValueChangedCallback?.Invoke(m_GradientObject.gradient);
m_Field.SetValueWithoutNotify(m_GradientObject.gradient);
}
void OnPickerClosed()
{
m_UndoSession.RecordNetChange();
}
void OnDetachFromPanel(DetachFromPanelEvent evt)
{
m_UndoSession?.RecordNetChange();
Undo.undoRedoPerformed -= OnUndoRedoPerformed;
m_Field.pickerClosed -= OnPickerClosed;
}
public Action inspectorUpdateDelegate { get; set; }
public VisualElement DrawProperty(PropertyInfo propertyInfo, object actualObject, InspectableAttribute attribute)
{
return this.CreateGUI(
// Use the setter from the provided property as the callback
newValue => propertyInfo.GetSetMethod(true).Invoke(actualObject, new object[] { newValue }),
(Gradient)propertyInfo.GetValue(actualObject),
attribute.labelName,
out var propertyVisualElement);
}
void IPropertyDrawer.DisposePropertyDrawer() { }
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 6095116b11f143f0a9d9a47f7733261b
timeCreated: 1588106639
@@ -0,0 +1,518 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor.Graphing.Util;
using UnityEditor.ShaderGraph;
using UnityEditor.ShaderGraph.Drawing;
using UnityEditor.ShaderGraph.Internal;
using UnityEngine;
using UnityEngine.UIElements;
using UnityEditorInternal;
using UnityEditor.ShaderGraph.Serialization;
using System.Text.RegularExpressions;
namespace UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers
{
[SGPropertyDrawer(typeof(GraphData))]
public class GraphDataPropertyDrawer : IPropertyDrawer
{
public delegate void ChangeGraphDefaultPrecisionCallback(GraphPrecision newDefaultGraphPrecision);
public delegate void PostTargetSettingsChangedCallback();
internal delegate void GraphSettingsChangedCallback();
GraphSettingsChangedCallback m_changeGraphSettingsCallback;
PostTargetSettingsChangedCallback m_postChangeTargetSettingsCallback;
ChangeGraphDefaultPrecisionCallback m_changeGraphDefaultPrecisionCallback;
bool m_AdvancedSettingsFoldout;
const string customPragmaTooltip = @"The following pragmas will be added in the given order, after other pragmas.
Enter what comes after '#pragma' (e.g.: enable_debug_symbols or use_dxc)";
const string customDefineTooltip = @"The following defines will be added in the given order, after other graph defines.
Enter what comes after '#define' (e.g.: _DEBUG or MAX_STEPS 32 // your comments.)
Uncheck the checkbox to temporarily disable the define.";
const string customIncludeTooltip = @"The following hlsl files will be included in the given order, prior to other graph includes (e.g.: Custom Function Nodes).";
Dictionary<Target, bool> m_TargetFoldouts = new Dictionary<Target, bool>();
Dictionary<AbstractShaderGraphDataExtension, bool> m_SubDataFoldouts = new Dictionary<AbstractShaderGraphDataExtension, bool>();
internal void GetPropertyData(
PostTargetSettingsChangedCallback postChangeValueCallback,
GraphSettingsChangedCallback changeGraphSettingsCallback,
ChangeGraphDefaultPrecisionCallback changeGraphDefaultPrecisionCallback)
{
m_postChangeTargetSettingsCallback = postChangeValueCallback;
m_changeGraphSettingsCallback = changeGraphSettingsCallback;
m_changeGraphDefaultPrecisionCallback = changeGraphDefaultPrecisionCallback;
}
VisualElement GetAdvancedSettings(GraphData graphData, Action onChange)
{
var element = new VisualElement() { name = "advGraphSettings" };
void RegisterActionToUndo(string actionName)
{
graphData.owner.RegisterCompleteObjectUndo(actionName);
}
// Advanced Settings
var advancedSettingsFoldout = new Foldout() { text = "Preprocessor Directives", value = m_AdvancedSettingsFoldout, name = "advGraphSettings" };
advancedSettingsFoldout.style.unityFontStyleAndWeight = FontStyle.Bold;
element.Add(advancedSettingsFoldout);
advancedSettingsFoldout.AddToClassList("MainFoldout");
advancedSettingsFoldout.RegisterValueChangedCallback(evt =>
{
m_AdvancedSettingsFoldout = evt.newValue;
advancedSettingsFoldout.value = evt.newValue;
onChange();
});
if (advancedSettingsFoldout.value)
{
var advancedSettingsElement = new VisualElement();
element.Add(advancedSettingsElement);
// Custom Pragmas
var customPragmasList = new ReorderableListView<string>(
graphData.m_CustomPragmas,
new GUIContent("Pragmas", customPragmaTooltip));
customPragmasList.OnBeforeChangeCallback +=
(ReorderableListView<string>.ListActionType changeType) =>
{
RegisterActionToUndo($"{changeType} Pragma");
};
customPragmasList.OnChangeCallback +=
(ReorderableListView<string>.ListActionType changeType) =>
{
onChange();
};
customPragmasList.DrawItemCallback += (Rect rect, int idx) =>
{
EditorGUI.BeginChangeCheck();
var data = graphData.m_CustomPragmas[idx];
data = EditorGUI.DelayedTextField(rect, "", data);
if (EditorGUI.EndChangeCheck())
{
RegisterActionToUndo("Change Pragma");
data = ValidatePragma(data);
graphData.m_CustomPragmas[idx] = data;
onChange();
}
};
advancedSettingsElement.Add(customPragmasList);
// Custom Defines
var customDefineList = new ReorderableListView<GraphData.CustomDefineDescriptor>(
graphData.m_CustomDefines,
new GUIContent("Local Defines", customDefineTooltip));
customDefineList.OnNewItemCallback += () => new GraphData.CustomDefineDescriptor("_DEFINE");
customDefineList.OnBeforeChangeCallback +=
(ReorderableListView<GraphData.CustomDefineDescriptor>.ListActionType changeType) =>
{
RegisterActionToUndo($"{changeType} Local Define");
};
customDefineList.OnChangeCallback +=
(ReorderableListView<GraphData.CustomDefineDescriptor>.ListActionType changeType) =>
{
onChange();
};
customDefineList.DrawItemCallback += (Rect rect, int idx) =>
{
Rect objectFieldRect = new Rect(rect.x, rect.y, rect.width - 24, rect.height);
Rect toggleRect = new Rect(objectFieldRect.max.x+8, rect.y, 24, rect.height);
var data = graphData.m_CustomDefines[idx];
EditorGUI.BeginChangeCheck();
data.Define = EditorGUI.DelayedTextField(objectFieldRect, new GUIContent("", ""), data.Define);
data.Enabled = EditorGUI.ToggleLeft(toggleRect, "", data.Enabled);
if (EditorGUI.EndChangeCheck())
{
RegisterActionToUndo("Change Local Define");
data.Define = ValidateDefine(data.Define);
graphData.m_CustomDefines[idx] = data;
onChange();
}
};
advancedSettingsElement.Add(customDefineList);
// Custom Includes
var customIncludeList = new ReorderableListView<GraphData.CustomIncludeDescriptor>(
graphData.m_CustomIncludes,
new GUIContent("Graph Includes", customIncludeTooltip));
customIncludeList.OnNewItemCallback += () => new GraphData.CustomIncludeDescriptor();
customIncludeList.OnBeforeChangeCallback +=
(ReorderableListView<GraphData.CustomIncludeDescriptor>.ListActionType changeType) =>
{
RegisterActionToUndo($"{changeType} Graph Include");
};
customIncludeList.OnChangeCallback +=
(ReorderableListView<GraphData.CustomIncludeDescriptor>.ListActionType changeType) =>
{
onChange();
};
customIncludeList.DrawItemCallback += (Rect rect, int idx) =>
{
const float labelWidth = 85f;
Rect objectFieldRect = new Rect(rect.x, rect.y, rect.width - (labelWidth + 24), rect.height);
Rect toggleRect = new Rect(objectFieldRect.max.x + 8, rect.y, labelWidth + 24, rect.height);
EditorGUI.BeginChangeCheck();
var data = graphData.m_CustomIncludes[idx];
var previousLabelWidth = EditorGUIUtility.labelWidth;
EditorGUIUtility.labelWidth = labelWidth;
data.Include = (ShaderInclude)EditorGUI.ObjectField(objectFieldRect, "", data.Include, typeof(ShaderInclude), false);
data.IncludeWithPragmas = EditorGUI.Toggle(toggleRect, new GUIContent("with pragmas", "Should the pragma directives in the include also be included."), data.IncludeWithPragmas);
EditorGUIUtility.labelWidth = previousLabelWidth;
if (EditorGUI.EndChangeCheck())
{
RegisterActionToUndo("Change Graph Include");
graphData.m_CustomIncludes[idx] = data;
onChange();
}
};
advancedSettingsElement.Add(customIncludeList);
}
return element;
}
static string ValidatePragma(string input)
{
if (string.IsNullOrWhiteSpace(input))
return "";
if (input.StartsWith("#pragma "))
return input.Replace("#pragma ", "");
return input;
}
static string ValidateDefine(string input)
{
if (string.IsNullOrWhiteSpace(input))
return "";
if (input.StartsWith("#define "))
input = input.Replace("#define ", "");
// Split comment
string comment = "";
var commentMatch = Regex.Match(input, @"//.*$");
if (commentMatch.Success)
{
comment = commentMatch.Value;
input = input.Substring(0, commentMatch.Index);
}
// Normalize whitespace
input = Regex.Replace(input, @"\s+", " ").Trim();
var parts = input.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 0)
return "";
// Clean NAME
string name = Regex.Replace(parts[0], @"[^A-Za-z0-9_]", "");
if (Regex.IsMatch(name, @"^[0-9]"))
name = "_" + name;
// Clean VALUE
string value = "";
if (parts.Length > 1)
value = Regex.Replace(parts[1], @"[^A-Za-z0-9_]", "");
// Rebuild
string result = name;
if (!string.IsNullOrEmpty(value))
result += " " + value;
if (!string.IsNullOrEmpty(comment))
result += " " + comment;
return result;
}
VisualElement GetSettings(GraphData graphData, Action onChange)
{
var element = new VisualElement() { name = "graphSettings" };
if (graphData.isSubGraph)
return element;
void RegisterActionToUndo(string actionName)
{
graphData.owner.RegisterCompleteObjectUndo(actionName);
}
// Targets
var targetSettingsLabel = new Label("Target Settings");
targetSettingsLabel.style.unityFontStyleAndWeight = FontStyle.Bold;
element.Add(new PropertyRow(targetSettingsLabel));
var targetList = new ReorderableTextListView<JsonData<Target>>(
graphData.m_ActiveTargets,
"Active Targets",
false, // disallow reordering (active list is sorted)
target => target.value.displayName);
var validTargets = graphData.GetValidTargets();
targetList.GetAddMenuOptions = () => validTargets.Select(o => o.displayName).ToList();
targetList.OnAddMenuItemCallback +=
(list, addMenuOptionIndex, addMenuOption) =>
{
RegisterActionToUndo("Add Target");
var target = validTargets.ElementAt(addMenuOptionIndex);
graphData.SetTargetActive(target);
m_postChangeTargetSettingsCallback();
};
targetList.RemoveItemCallback +=
(list, itemIndex) =>
{
RegisterActionToUndo("Remove Target");
graphData.SetTargetInactive(list[itemIndex].value);
m_postChangeTargetSettingsCallback();
};
element.Add(targetList);
// Iterate active TargetImplementations
foreach (var target in graphData.activeTargets)
{
// Ensure enabled state is being tracked and get value
bool foldoutActive;
if (!m_TargetFoldouts.TryGetValue(target, out foldoutActive))
{
foldoutActive = true;
m_TargetFoldouts.Add(target, foldoutActive);
}
// Create foldout
var foldout = new Foldout() { text = target.displayName, value = foldoutActive, name = "foldout" };
element.Add(foldout);
foldout.AddToClassList("MainFoldout");
foldout.RegisterValueChangedCallback(evt =>
{
// Update foldout value and rebuild
m_TargetFoldouts[target] = evt.newValue;
foldout.value = evt.newValue;
onChange();
});
if (foldout.value)
{
// Get settings for Target
var context = new TargetPropertyGUIContext(graphData.ValidateGraph);
// Indent the content of the foldout
context.globalIndentLevel++;
target.GetPropertiesGUI(ref context, onChange, RegisterActionToUndo);
context.globalIndentLevel--;
element.Add(context);
}
}
// Data Extensions
var validExtensions = AbstractShaderGraphDataExtension.ValidExtensions();
if (validExtensions.Count() > 0 || graphData.SubDatas.Count() > 0)
{
var dataExtensionSettings = new Label("\nData Extension Settings");
dataExtensionSettings.style.unityFontStyleAndWeight = FontStyle.Bold;
element.Add(new PropertyRow(dataExtensionSettings));
var extensionList = new ReorderableTextListView<JsonData<AbstractShaderGraphDataExtension>>(
graphData.m_SubDatas,
"Active Data Extensions",
false,
data => data.value.displayName);
extensionList.GetAddMenuOptions = () => validExtensions.Select(o => o.displayName).ToList();
extensionList.OnAddMenuItemCallback +=
(list, addMenuOptionIndex, addMenuOption) =>
{
RegisterActionToUndo("Add Data Extension");
graphData.m_SubDatas.Add(validExtensions[addMenuOptionIndex]);
onChange();
};
extensionList.RemoveItemCallback +=
(list, itemIndex) =>
{
RegisterActionToUndo("Remove Data Extension");
graphData.m_SubDatas.RemoveAt(itemIndex);
onChange();
};
element.Add(extensionList);
foreach (var subData in graphData.SubDatas)
{
if (subData != null) // I think we need to do this in case it didn't serialize correctly.
{
bool foldoutActive;
if (!m_SubDataFoldouts.TryGetValue(subData, out foldoutActive))
{
foldoutActive = true;
m_SubDataFoldouts.Add(subData, foldoutActive);
}
var foldout = new Foldout() { text = subData.displayName, value = foldoutActive, name = "foldout" };
element.Add(foldout);
foldout.AddToClassList("MainFoldout");
foldout.RegisterValueChangedCallback(evt =>
{
// Update foldout value and rebuild
m_SubDataFoldouts[subData] = evt.newValue;
foldout.value = evt.newValue;
onChange();
});
if (foldout.value)
{
var subDataElement = new VisualElement();
subData.OnPropertiesGUI(subDataElement, onChange, RegisterActionToUndo, graphData);
element.Add(subDataElement);
}
}
}
}
#if VFX_GRAPH_10_0_0_OR_NEWER
// Inform the user that VFXTarget is deprecated, if they are using one.
if (graphData.m_ActiveTargets.Any(t => t.value is VFXTarget)) //Use Old VFXTarget
{
var vfxWarning = new HelpBoxRow("The Visual Effect target is deprecated.\n" +
"Use the SRP target(s) instead, and enable 'Support VFX Graph' in the Graph Inspector.\n" +
"Then, you can remove the Visual Effect Target.", MessageType.Info);
element.Add(vfxWarning);
}
#endif
return element;
}
// used to display UI to select GraphPrecision in the GraphData inspector
enum UI_GraphPrecision
{
Single = GraphPrecision.Single,
Half = GraphPrecision.Half,
};
enum UI_SubGraphPrecision
{
Single = GraphPrecision.Single,
Half = GraphPrecision.Half,
Switchable = GraphPrecision.Graph,
};
internal VisualElement CreateGUI(GraphData graphData)
{
var propertySheet = new VisualElement() { name = "graphSettings" };
if (graphData == null)
{
Debug.Log("Attempting to draw something that isn't of type GraphData with a GraphDataPropertyDrawer");
return propertySheet;
}
if (!graphData.isSubGraph)
{
// precision selector for shader graphs
var enumPropertyDrawer = new EnumPropertyDrawer();
propertySheet.Add(enumPropertyDrawer.CreateGUI(
newValue => { m_changeGraphDefaultPrecisionCallback((GraphPrecision)newValue); },
(UI_GraphPrecision)graphData.graphDefaultPrecision,
"Precision",
UI_GraphPrecision.Single,
out var propertyVisualElement));
}
if (graphData.isSubGraph)
{
{
var enum2PropertyDrawer = new EnumPropertyDrawer();
propertySheet.Add(enum2PropertyDrawer.CreateGUI(
newValue => { m_changeGraphDefaultPrecisionCallback((GraphPrecision)newValue); },
(UI_SubGraphPrecision)graphData.graphDefaultPrecision,
"Precision",
UI_SubGraphPrecision.Switchable,
out var propertyVisualElement2));
}
var enumPropertyDrawer = new EnumPropertyDrawer();
propertySheet.Add(enumPropertyDrawer.CreateGUI(
newValue =>
{
graphData.owner.RegisterCompleteObjectUndo("Change Preview Mode");
graphData.previewMode = (PreviewMode)newValue;
},
graphData.previewMode,
"Preview",
PreviewMode.Inherit,
out var propertyVisualElement));
var deprecationToggle = new BoolPropertyDrawer();
propertySheet.Add(deprecationToggle.CreateGUI(
newValue =>
{
graphData.owner.RegisterCompleteObjectUndo("Change Deprecation State");
graphData.m_DeprecateSubgraph = newValue;
this.m_postChangeTargetSettingsCallback();
},
graphData.m_DeprecateSubgraph,
"Deprecate",
out _
));
if (graphData.m_DeprecateSubgraph)
{
var deprecationMsg = new TextPropertyDrawer();
propertySheet.Add(deprecationMsg.CreateGUI(
newValue =>
{
graphData.owner.RegisterCompleteObjectUndo("Change Deprecation Message");
graphData.m_DeprecateSubgraphMessage = newValue;
},
graphData.m_DeprecateSubgraphMessage,
"Deprecation Message"
));
}
}
propertySheet.Add(GetSettings(graphData, () => this.m_postChangeTargetSettingsCallback()));
if (!graphData.isSubGraph)
propertySheet.Add(GetAdvancedSettings(graphData, () => this.m_changeGraphSettingsCallback()));
return propertySheet;
}
public Action inspectorUpdateDelegate { get; set; }
public VisualElement DrawProperty(PropertyInfo propertyInfo, object actualObject, InspectableAttribute attribute)
{
return this.CreateGUI((GraphData)actualObject);
}
void IPropertyDrawer.DisposePropertyDrawer() { }
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 4d28f79bb9e147e0837f0411a2269513
timeCreated: 1586821312
@@ -0,0 +1,9 @@
using static UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers.ShaderInputPropertyDrawer;
namespace UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers
{
interface IShaderPropertyDrawer
{
internal void HandlePropertyField(PropertySheet propertySheet, PreChangeValueCallback preChangeValueCallback, PostChangeValueCallback postChangeValueCallback);
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0f2710f417f893e4db3c7f3649adfa0e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,54 @@
using System;
using System.Reflection;
using UnityEditor.ShaderGraph.Drawing;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers
{
[SGPropertyDrawer(typeof(int))]
class IntegerPropertyDrawer : IPropertyDrawer
{
internal delegate void ValueChangedCallback(int newValue);
internal VisualElement CreateGUI(
ValueChangedCallback valueChangedCallback,
int fieldToDraw,
string labelName,
out VisualElement propertyFloatField,
int indentLevel = 0,
string tooltip = null)
{
var integerField = new IntegerField { value = fieldToDraw };
if (valueChangedCallback != null)
{
integerField.RegisterValueChangedCallback(evt => { valueChangedCallback(evt.newValue); });
}
propertyFloatField = integerField;
var defaultRow = new PropertyRow(PropertyDrawerUtils.CreateLabel(labelName, indentLevel));
defaultRow.tooltip = tooltip;
defaultRow.Add(propertyFloatField);
defaultRow.styleSheets.Add(Resources.Load<StyleSheet>("Styles/PropertyRow"));
return defaultRow;
}
public Action inspectorUpdateDelegate { get; set; }
public VisualElement DrawProperty(PropertyInfo propertyInfo, object actualObject, InspectableAttribute attribute)
{
return this.CreateGUI(
// Use the setter from the provided property as the callback
newValue => propertyInfo.GetSetMethod(true).Invoke(actualObject, new object[] { newValue }),
(int)propertyInfo.GetValue(actualObject),
attribute.labelName,
out var propertyVisualElement);
}
void IPropertyDrawer.DisposePropertyDrawer() { }
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: f2163038c8be4befb58f6aff22e6bd00
timeCreated: 1588106107
@@ -0,0 +1,374 @@
using System;
using System.Reflection;
using UnityEditor.ShaderGraph.Drawing;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers
{
[SGPropertyDrawer(typeof(Matrix4x4))]
class MatrixPropertyDrawer : IPropertyDrawer
{
public enum MatrixDimensions
{
Two,
Three,
Four
}
public MatrixDimensions dimension { get; set; }
public delegate Vector4 GetMatrixRowDelegate(int rowNumber);
internal Action PreValueChangeCallback;
internal delegate void ValueChangedCallback(Matrix4x4 newValue);
internal Action PostValueChangeCallback;
// Matrix4x4, Matrix3x3, Matrix2x2 are all value types,
// hence the local value doesn't stay up to date after modified
// Need a callback to fetch the row data directly from the source
internal GetMatrixRowDelegate MatrixRowFetchCallback;
void HandleMatrix2Property(
ValueChangedCallback valueChangedCallback,
PropertySheet propertySheet,
Matrix4x4 matrix2Property,
string labelName = "Default")
{
var vector2PropertyDrawer = new Vector2PropertyDrawer();
vector2PropertyDrawer.preValueChangeCallback = PreValueChangeCallback;
vector2PropertyDrawer.postValueChangeCallback = PostValueChangeCallback;
propertySheet.Add(vector2PropertyDrawer.CreateGUI(
newValue =>
{
Vector2 row1 = MatrixRowFetchCallback(1);
valueChangedCallback(new Matrix4x4()
{
m00 = newValue.x,
m01 = newValue.y,
m02 = 0,
m03 = 0,
m10 = row1.x,
m11 = row1.y,
m12 = 0,
m13 = 0,
m20 = 0,
m21 = 0,
m22 = 0,
m23 = 0,
m30 = 0,
m31 = 0,
m32 = 0,
m33 = 0,
});
},
matrix2Property.GetRow(0),
labelName,
out var row0Field
));
propertySheet.Add(vector2PropertyDrawer.CreateGUI(
newValue =>
{
Vector2 row0 = MatrixRowFetchCallback(0);
valueChangedCallback(new Matrix4x4()
{
m00 = row0.x,
m01 = row0.y,
m02 = 0,
m03 = 0,
m10 = newValue.x,
m11 = newValue.y,
m12 = 0,
m13 = 0,
m20 = 0,
m21 = 0,
m22 = 0,
m23 = 0,
m30 = 0,
m31 = 0,
m32 = 0,
m33 = 0,
});
},
matrix2Property.GetRow(1),
"",
out var row1Field
));
}
void HandleMatrix3Property(
ValueChangedCallback valueChangedCallback,
PropertySheet propertySheet,
Matrix4x4 matrix3Property,
string labelName = "Default")
{
var vector3PropertyDrawer = new Vector3PropertyDrawer();
vector3PropertyDrawer.preValueChangeCallback = PreValueChangeCallback;
vector3PropertyDrawer.postValueChangeCallback = PostValueChangeCallback;
propertySheet.Add(vector3PropertyDrawer.CreateGUI(
newValue =>
{
Vector3 row1 = MatrixRowFetchCallback(1);
Vector3 row2 = MatrixRowFetchCallback(2);
valueChangedCallback(new Matrix4x4()
{
m00 = newValue.x,
m01 = newValue.y,
m02 = newValue.z,
m03 = 0,
m10 = row1.x,
m11 = row1.y,
m12 = row1.z,
m13 = 0,
m20 = row2.x,
m21 = row2.y,
m22 = row2.z,
m23 = 0,
m30 = 0,
m31 = 0,
m32 = 0,
m33 = 0,
});
},
matrix3Property.GetRow(0),
labelName,
out var row0Field
));
propertySheet.Add(vector3PropertyDrawer.CreateGUI(
newValue =>
{
Vector3 row0 = MatrixRowFetchCallback(0);
Vector3 row2 = MatrixRowFetchCallback(2);
valueChangedCallback(new Matrix4x4()
{
m00 = row0.x,
m01 = row0.y,
m02 = row0.z,
m03 = 0,
m10 = newValue.x,
m11 = newValue.y,
m12 = newValue.z,
m13 = 0,
m20 = row2.x,
m21 = row2.y,
m22 = row2.z,
m23 = 0,
m30 = 0,
m31 = 0,
m32 = 0,
m33 = 0,
});
},
matrix3Property.GetRow(1),
"",
out var row1Field
));
propertySheet.Add(vector3PropertyDrawer.CreateGUI(
newValue =>
{
Vector3 row0 = MatrixRowFetchCallback(0);
Vector3 row1 = MatrixRowFetchCallback(1);
valueChangedCallback(new Matrix4x4()
{
m00 = row0.x,
m01 = row0.y,
m02 = row0.z,
m03 = 0,
m10 = row1.x,
m11 = row1.y,
m12 = row1.z,
m13 = 0,
m20 = newValue.x,
m21 = newValue.y,
m22 = newValue.z,
m23 = 0,
m30 = 0,
m31 = 0,
m32 = 0,
m33 = 0,
});
},
matrix3Property.GetRow(2),
"",
out var row2Field
));
}
void HandleMatrix4Property(
ValueChangedCallback valueChangedCallback,
PropertySheet propertySheet,
Matrix4x4 matrix4Property,
string labelName = "Default")
{
var vector4PropertyDrawer = new Vector4PropertyDrawer();
vector4PropertyDrawer.preValueChangeCallback = PreValueChangeCallback;
vector4PropertyDrawer.postValueChangeCallback = PostValueChangeCallback;
propertySheet.Add(vector4PropertyDrawer.CreateGUI(
newValue =>
{
Vector4 row1 = MatrixRowFetchCallback(1);
Vector4 row2 = MatrixRowFetchCallback(2);
Vector4 row3 = MatrixRowFetchCallback(3);
valueChangedCallback(new Matrix4x4()
{
m00 = newValue.x,
m01 = newValue.y,
m02 = newValue.z,
m03 = newValue.w,
m10 = row1.x,
m11 = row1.y,
m12 = row1.z,
m13 = row1.w,
m20 = row2.x,
m21 = row2.y,
m22 = row2.z,
m23 = row2.w,
m30 = row3.x,
m31 = row3.y,
m32 = row3.z,
m33 = row3.w,
});
},
matrix4Property.GetRow(0),
labelName,
out var row0Field
));
propertySheet.Add(vector4PropertyDrawer.CreateGUI(
newValue =>
{
Vector4 row0 = MatrixRowFetchCallback(0);
Vector4 row2 = MatrixRowFetchCallback(2);
Vector4 row3 = MatrixRowFetchCallback(3);
valueChangedCallback(new Matrix4x4()
{
m00 = row0.x,
m01 = row0.y,
m02 = row0.z,
m03 = row0.w,
m10 = newValue.x,
m11 = newValue.y,
m12 = newValue.z,
m13 = newValue.w,
m20 = row2.x,
m21 = row2.y,
m22 = row2.z,
m23 = row2.w,
m30 = row3.x,
m31 = row3.y,
m32 = row3.z,
m33 = row3.w,
});
},
matrix4Property.GetRow(1),
"",
out var row1Field
));
propertySheet.Add(vector4PropertyDrawer.CreateGUI(
newValue =>
{
Vector4 row0 = MatrixRowFetchCallback(0);
Vector4 row1 = MatrixRowFetchCallback(1);
Vector4 row3 = MatrixRowFetchCallback(3);
valueChangedCallback(new Matrix4x4()
{
m00 = row0.x,
m01 = row0.y,
m02 = row0.z,
m03 = row0.w,
m10 = row1.x,
m11 = row1.y,
m12 = row1.z,
m13 = row1.w,
m20 = newValue.x,
m21 = newValue.y,
m22 = newValue.z,
m23 = newValue.w,
m30 = row3.x,
m31 = row3.y,
m32 = row3.z,
m33 = row3.w,
});
},
matrix4Property.GetRow(2),
"",
out var row2Field));
propertySheet.Add(vector4PropertyDrawer.CreateGUI(
newValue =>
{
Vector4 row0 = MatrixRowFetchCallback(0);
Vector4 row1 = MatrixRowFetchCallback(1);
Vector4 row2 = MatrixRowFetchCallback(2);
valueChangedCallback(new Matrix4x4()
{
m00 = row0.x,
m01 = row0.y,
m02 = row0.z,
m03 = row0.w,
m10 = row1.x,
m11 = row1.y,
m12 = row1.z,
m13 = row1.w,
m20 = row2.x,
m21 = row2.y,
m22 = row2.z,
m23 = row2.w,
m30 = newValue.x,
m31 = newValue.y,
m32 = newValue.z,
m33 = newValue.w,
});
},
matrix4Property.GetRow(3),
"",
out var row3Field
));
}
internal VisualElement CreateGUI(
ValueChangedCallback valueChangedCallback,
Matrix4x4 fieldToDraw,
string labelName,
out VisualElement propertyMatrixField,
int indentLevel = 0)
{
var propertySheet = new PropertySheet();
switch (dimension)
{
case MatrixDimensions.Two:
HandleMatrix2Property(valueChangedCallback, propertySheet, fieldToDraw, labelName);
break;
case MatrixDimensions.Three:
HandleMatrix3Property(valueChangedCallback, propertySheet, fieldToDraw, labelName);
break;
case MatrixDimensions.Four:
HandleMatrix4Property(valueChangedCallback, propertySheet, fieldToDraw, labelName);
break;
}
propertyMatrixField = propertySheet;
return propertyMatrixField;
}
public Action inspectorUpdateDelegate { get; set; }
public VisualElement DrawProperty(PropertyInfo propertyInfo, object actualObject, InspectableAttribute attribute)
{
return this.CreateGUI(
// Use the setter from the provided property as the callback
newValue => propertyInfo.GetSetMethod(true).Invoke(actualObject, new object[] { newValue }),
(Matrix4x4)propertyInfo.GetValue(actualObject),
attribute.labelName,
out var propertyVisualElement);
}
void IPropertyDrawer.DisposePropertyDrawer() { }
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: e28fc1d401304229b06d7d0cb83dafce
timeCreated: 1588106778
@@ -0,0 +1,34 @@
using System;
using UnityEditor.UIElements;
using UnityEditor.Graphing;
using UnityEditor.Graphing.Util;
using UnityEngine.UIElements;
namespace UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers
{
[SGPropertyDrawer(typeof(PositionNode))]
class PositionNodePropertyDrawer : AbstractMaterialNodePropertyDrawer
{
internal override void AddCustomNodeProperties(VisualElement parentElement, AbstractMaterialNode nodeBase, Action setNodesAsDirtyCallback, Action updateNodeViewsCallback)
{
var node = nodeBase as PositionNode;
var previewField = new EnumField(node.m_PositionSource);
var propertyRow = new PropertyRow(new Label("Source"));
propertyRow.Add(previewField, (field) =>
{
field.RegisterValueChangedCallback(evt =>
{
if (evt.newValue.Equals(node.m_PositionSource))
return;
setNodesAsDirtyCallback?.Invoke();
node.owner.owner.RegisterCompleteObjectUndo("Change position source");
node.m_PositionSource = (UnityEditor.ShaderGraph.Internal.PositionSource)evt.newValue;
updateNodeViewsCallback?.Invoke();
node.Dirty(ModificationScope.Graph);
});
});
parentElement.Add(propertyRow);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 5a49cf3652c693645931ba8ef38e8e1e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,64 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using UnityEditor.UIElements;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph.Drawing;
using UnityEditor.Graphing.Util;
using UnityEditor.ShaderGraph.Internal;
using UnityEngine.UIElements;
namespace UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers
{
#if PROCEDURAL_VT_IN_GRAPH
[SGPropertyDrawer(typeof(ProceduralVirtualTextureNode))]
class ProceduralVirtualTextureNodePropertyDrawer : AbstractMaterialNodePropertyDrawer
{
// Use the same HLSLDeclarationStrings as used by the ShaderInputPropertyDrawer, for consistency
static string[] allHLSLDeclarationStrings = new string[]
{
"Do Not Declare", // HLSLDeclaration.DoNotDeclare
"Global", // HLSLDeclaration.Global
"Per Material", // HLSLDeclaration.UnityPerMaterial
"Hybrid Per Instance", // HLSLDeclaration.HybridPerInstance
};
internal override void AddCustomNodeProperties(VisualElement parentElement, AbstractMaterialNode nodeBase, Action setNodesAsDirtyCallback, Action updateNodeViewsCallback)
{
var node = nodeBase as ProceduralVirtualTextureNode;
var hlslDecls = Enum.GetValues(typeof(HLSLDeclaration));
var allowedDecls = new List<HLSLDeclaration>();
for (int i = 0; i < hlslDecls.Length; i++)
{
HLSLDeclaration decl = (HLSLDeclaration)hlslDecls.GetValue(i);
var allowed = node.AllowHLSLDeclaration(decl);
if (allowed)
allowedDecls.Add(decl);
}
var propertyRow = new PropertyRow(new Label("Shader Declaration"));
var popupField = new PopupField<HLSLDeclaration>(
allowedDecls,
node.shaderDeclaration,
(h => allHLSLDeclarationStrings[(int)h]),
(h => allHLSLDeclarationStrings[(int)h]));
popupField.RegisterValueChangedCallback(
evt =>
{
if (node.shaderDeclaration == evt.newValue)
return;
setNodesAsDirtyCallback?.Invoke();
node.owner.owner.RegisterCompleteObjectUndo("Change PVT shader declaration");
node.shaderDeclaration = (UnityEditor.ShaderGraph.Internal.HLSLDeclaration)evt.newValue;
updateNodeViewsCallback?.Invoke();
node.Dirty(ModificationScope.Graph);
});
propertyRow.Add(popupField);
parentElement.Add(propertyRow);
}
}
#endif // PROCEDURAL_VT_IN_GRAPH
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 910f6b8c5cf5eb9449864d4b7f2e40ce
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,24 @@
using System;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph.Drawing;
using UnityEngine.UIElements;
namespace UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers
{
[SGPropertyDrawer(typeof(SampleElementTextureNode))]
class SampleElementTextureNodePropertyDrawer : AbstractMaterialNodePropertyDrawer
{
internal override void AddCustomNodeProperties(VisualElement parentElement, AbstractMaterialNode nodeBase, Action setNodesAsDirtyCallback, Action updateNodeViewsCallback)
{
var node = nodeBase as SampleElementTextureNode;
PropertyDrawerUtils.AddCustomIntegerProperty(
parentElement, nodeBase, setNodesAsDirtyCallback, updateNodeViewsCallback,
"Sample Count", "Change Sample Count", 1, 32,
() => node.sampleCount, (val) => node.sampleCount = val);
PropertyDrawerUtils.AddCustomEnumProperty<ElementTextureMipSamplingMode>(
parentElement, nodeBase, setNodesAsDirtyCallback, updateNodeViewsCallback,
"Mip Sampling Mode", "Change Mip Sampling Mode",
() => node.mipSamplingMode, (val) => node.mipSamplingMode = val);
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 39e16e6626e1ca742be7960773098a00
@@ -0,0 +1,29 @@
using System;
using System.Reflection;
using UnityEngine;
using UnityEditor.UIElements;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph.Drawing;
using UnityEditor.Graphing.Util;
using UnityEditor.ShaderGraph.Internal;
using UnityEngine.UIElements;
namespace UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers
{
[SGPropertyDrawer(typeof(SampleTexture2DArrayNode))]
class SampleTexture2DArrayNodePropertyDrawer : AbstractMaterialNodePropertyDrawer
{
internal override void AddCustomNodeProperties(VisualElement parentElement, AbstractMaterialNode nodeBase, Action setNodesAsDirtyCallback, Action updateNodeViewsCallback)
{
var node = nodeBase as SampleTexture2DArrayNode;
PropertyDrawerUtils.AddCustomCheckboxProperty(
parentElement, nodeBase, setNodesAsDirtyCallback, updateNodeViewsCallback,
"Use Global Mip Bias", "Change Enable Global Mip Bias",
() => node.enableGlobalMipBias, (val) => node.enableGlobalMipBias = val);
PropertyDrawerUtils.AddCustomEnumProperty<Texture2DMipSamplingMode>(
parentElement, nodeBase, setNodesAsDirtyCallback, updateNodeViewsCallback,
"Mip Sampling Mode", "Change Mip Sampling Mode",
() => node.mipSamplingMode, (val) => node.mipSamplingMode = val);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c9a458e42c243844a8725ccc1e32f53b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,29 @@
using System;
using System.Reflection;
using UnityEngine;
using UnityEditor.UIElements;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph.Drawing;
using UnityEditor.Graphing.Util;
using UnityEditor.ShaderGraph.Internal;
using UnityEngine.UIElements;
namespace UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers
{
[SGPropertyDrawer(typeof(SampleTexture2DNode))]
class SampleTexture2DNodePropertyDrawer : AbstractMaterialNodePropertyDrawer
{
internal override void AddCustomNodeProperties(VisualElement parentElement, AbstractMaterialNode nodeBase, Action setNodesAsDirtyCallback, Action updateNodeViewsCallback)
{
var node = nodeBase as SampleTexture2DNode;
PropertyDrawerUtils.AddCustomCheckboxProperty(
parentElement, nodeBase, setNodesAsDirtyCallback, updateNodeViewsCallback,
"Use Global Mip Bias", "Change Enable Global Mip Bias",
() => node.enableGlobalMipBias, (val) => node.enableGlobalMipBias = val);
PropertyDrawerUtils.AddCustomEnumProperty<Texture2DMipSamplingMode>(
parentElement, nodeBase, setNodesAsDirtyCallback, updateNodeViewsCallback,
"Mip Sampling Mode", "Change Mip Sampling Mode",
() => node.mipSamplingMode, (val) => node.mipSamplingMode = val);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 18b701456606a9f4ea2b0a8c601ab24b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,25 @@
using System;
using System.Reflection;
using UnityEngine;
using UnityEditor.UIElements;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph.Drawing;
using UnityEditor.Graphing.Util;
using UnityEditor.ShaderGraph.Internal;
using UnityEngine.UIElements;
namespace UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers
{
[SGPropertyDrawer(typeof(SampleTexture3DNode))]
class SampleTexture3DNodePropertyDrawer : AbstractMaterialNodePropertyDrawer
{
internal override void AddCustomNodeProperties(VisualElement parentElement, AbstractMaterialNode nodeBase, Action setNodesAsDirtyCallback, Action updateNodeViewsCallback)
{
var node = nodeBase as SampleTexture3DNode;
PropertyDrawerUtils.AddCustomEnumProperty<Texture3DMipSamplingMode>(
parentElement, nodeBase, setNodesAsDirtyCallback, updateNodeViewsCallback,
"Mip Sampling Mode", "Change Mip Sampling Mode",
() => node.mipSamplingMode, (val) => node.mipSamplingMode = val);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 229381d565da42440bcbc93f7ab89799
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,142 @@
using System;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEditor.Graphing;
using UnityEditor.Graphing.Util;
using UnityEditor.ShaderGraph;
using UnityEditor.ShaderGraph.Drawing;
using UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.UIElements;
namespace UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers
{
[SGPropertyDrawer(typeof(SampleVirtualTextureNode))]
public class SampleVirtualTextureNodePropertyDrawer : IPropertyDrawer
{
VisualElement CreateGUI(SampleVirtualTextureNode node, InspectableAttribute attribute,
out VisualElement propertyVisualElement)
{
PropertySheet propertySheet = new PropertySheet();
var enumPropertyDrawer = new EnumPropertyDrawer();
propertySheet.Add(enumPropertyDrawer.CreateGUI((newValue) =>
{
if (node.addressMode == (SampleVirtualTextureNode.AddressMode)newValue)
return;
node.owner.owner.RegisterCompleteObjectUndo("Address Mode Change");
node.addressMode = (SampleVirtualTextureNode.AddressMode)newValue;
},
node.addressMode,
"Address Mode",
SampleVirtualTextureNode.AddressMode.VtAddressMode_Wrap,
out var addressModeVisualElement));
propertySheet.Add(enumPropertyDrawer.CreateGUI((newValue) =>
{
if (node.lodCalculation == (SampleVirtualTextureNode.LodCalculation)newValue)
return;
node.owner.owner.RegisterCompleteObjectUndo("Lod Mode Change");
node.lodCalculation = (SampleVirtualTextureNode.LodCalculation)newValue;
},
node.lodCalculation,
"Lod Mode",
SampleVirtualTextureNode.LodCalculation.VtLevel_Automatic,
out var lodCalculationVisualElement));
propertySheet.Add(enumPropertyDrawer.CreateGUI((newValue) =>
{
if (node.sampleQuality == (SampleVirtualTextureNode.QualityMode)newValue)
return;
node.owner.owner.RegisterCompleteObjectUndo("Quality Change");
node.sampleQuality = (SampleVirtualTextureNode.QualityMode)newValue;
},
node.sampleQuality,
"Quality",
SampleVirtualTextureNode.QualityMode.VtSampleQuality_High,
out var qualityVisualElement));
var boolPropertyDrawer = new BoolPropertyDrawer();
propertySheet.Add(boolPropertyDrawer.CreateGUI((newValue) =>
{
if (node.noFeedback == !newValue)
return;
node.owner.owner.RegisterCompleteObjectUndo("Feedback Settings Change");
node.noFeedback = !newValue;
},
!node.noFeedback,
"Automatic Streaming",
out var propertyToggle));
propertySheet.Add(boolPropertyDrawer.CreateGUI((newValue) =>
{
if (node.enableGlobalMipBias == newValue)
return;
node.owner.owner.RegisterCompleteObjectUndo("Enable Global Mip Bias VT Change");
node.enableGlobalMipBias = newValue;
},
node.enableGlobalMipBias,
"Use Global Mip Bias",
out var enableGlobalMipBias));
// display warning if the current master node doesn't support virtual texturing
// TODO: Add warning when no active subTarget supports VT
// if (!node.owner.isSubGraph)
// {
// bool supportedByMasterNode =
// node.owner.GetNodes<IMasterNode>().FirstOrDefault()?.supportsVirtualTexturing ?? false;
// if (!supportedByMasterNode)
// propertySheet.Add(new HelpBoxRow(MessageType.Warning),
// (row) => row.Add(new Label(
// "The current master node does not support Virtual Texturing, this node will do regular 2D sampling.")));
// }
// display warning if the current render pipeline doesn't support virtual texturing
string labelText;
IVirtualTexturingEnabledRenderPipeline vtRp =
GraphicsSettings.currentRenderPipeline as IVirtualTexturingEnabledRenderPipeline;
if (vtRp == null)
labelText = "The current render pipeline does not support Virtual Texturing, this node will do regular 2D sampling.";
else if (vtRp.virtualTexturingEnabled == false)
labelText = "The current render pipeline has disabled Virtual Texturing, this node will do regular 2D sampling.";
else
{
#if !ENABLE_VIRTUALTEXTURES
labelText = "Virtual Texturing is disabled globally (possibly by the render pipeline settings), this node will do regular 2D sampling.";
#else
labelText = "";
#endif
}
if (!string.IsNullOrEmpty(labelText))
{
propertySheet.Add(new HelpBoxRow(labelText, MessageType.Warning));
}
propertyVisualElement = propertySheet;
return propertySheet;
}
public Action inspectorUpdateDelegate { get; set; }
public VisualElement DrawProperty(PropertyInfo propertyInfo, object actualObject,
InspectableAttribute attribute)
{
return this.CreateGUI(
(SampleVirtualTextureNode)actualObject,
attribute,
out var propertyVisualElement);
}
void IPropertyDrawer.DisposePropertyDrawer() { }
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4ba5078c03394fbc8daa0a30927da29d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,34 @@
using System;
using UnityEditor.UIElements;
using UnityEditor.Graphing;
using UnityEditor.Graphing.Util;
using UnityEngine.UIElements;
namespace UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers
{
[SGPropertyDrawer(typeof(SamplerStateNode))]
class SamplerStateNodePropertyDrawer : AbstractMaterialNodePropertyDrawer
{
internal override void AddCustomNodeProperties(VisualElement parentElement, AbstractMaterialNode nodeBase, Action setNodesAsDirtyCallback, Action updateNodeViewsCallback)
{
var node = nodeBase as SamplerStateNode;
var previewField = new EnumField(node.anisotropic);
var propertyRow = new PropertyRow(new Label("Anisotropic Filtering"));
propertyRow.Add(previewField, (field) =>
{
field.RegisterValueChangedCallback(evt =>
{
if (evt.newValue.Equals(node.anisotropic))
return;
setNodesAsDirtyCallback?.Invoke();
node.owner.owner.RegisterCompleteObjectUndo("Change anisotropic filtering");
node.anisotropic = (TextureSamplerState.Anisotropic)evt.newValue;
updateNodeViewsCallback?.Invoke();
node.Dirty(ModificationScope.Graph);
});
});
parentElement.Add(propertyRow);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: d58a109f5d7f9154a862ddc85c4d1cc1
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: bf8c61714a08403bb754cbc99f1963a8
timeCreated: 1586807917
@@ -0,0 +1,54 @@
using System;
using System.Reflection;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph;
using UnityEditor.ShaderGraph.Drawing;
using UnityEditor.ShaderGraph.Drawing.Inspector;
using UnityEngine.UIElements;
using UnityEngine;
namespace UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers
{
[SGPropertyDrawer(typeof(SubGraphOutputNode))]
public class SubGraphOutputNodePropertyDrawer : IPropertyDrawer, IGetNodePropertyDrawerPropertyData
{
Action m_setNodesAsDirtyCallback;
Action m_updateNodeViewsCallback;
public void GetPropertyData(Action setNodesAsDirtyCallback, Action updateNodeViewsCallback)
{
m_setNodesAsDirtyCallback = setNodesAsDirtyCallback;
m_updateNodeViewsCallback = updateNodeViewsCallback;
}
VisualElement CreateGUI(SubGraphOutputNode node, InspectableAttribute attribute,
out VisualElement propertyVisualElement)
{
var propertySheet = new PropertySheet(PropertyDrawerUtils.CreateLabel($"{node.name} Node", 0, FontStyle.Bold));
PropertyDrawerUtils.AddDefaultNodeProperties(propertySheet, node, m_setNodesAsDirtyCallback, m_updateNodeViewsCallback);
var inputListView = new ReorderableSlotListView(node, SlotType.Input, false);
inputListView.OnAddCallback += list => inspectorUpdateDelegate();
inputListView.OnRemoveCallback += list => inspectorUpdateDelegate();
inputListView.OnListRecreatedCallback += () => inspectorUpdateDelegate();
inputListView.AllowedTypeCallback = SlotValueHelper.AllowedAsSubgraphOutput;
propertySheet.Add(inputListView);
propertyVisualElement = propertySheet;
return propertySheet;
}
public Action inspectorUpdateDelegate { get; set; }
public VisualElement DrawProperty(PropertyInfo propertyInfo, object actualObject,
InspectableAttribute attribute)
{
return this.CreateGUI(
(SubGraphOutputNode)actualObject,
attribute,
out var propertyVisualElement);
}
void IPropertyDrawer.DisposePropertyDrawer() { }
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: e628cecc47c94d4da6cd8ac547e1a4ef
timeCreated: 1588810477
@@ -0,0 +1,103 @@
using System;
using UnityEditor.Graphing;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers
{
[SGPropertyDrawer(typeof(SwitchNode))]
class SwitchNodeNodePropertyDrawer : AbstractMaterialNodePropertyDrawer
{
private SwitchNode node;
internal override void AddCustomNodeProperties(VisualElement parentElement, AbstractMaterialNode nodeBase, Action setNodesAsDirtyCallback, Action updateNodeViewsCallback)
{
node = nodeBase as SwitchNode;
if (node.UpstreamFloatEnumProperty != null)
parentElement.Add(new HelpBoxRow($"Enum cases found in property '{node.UpstreamFloatEnumProperty.displayName}'.", MessageType.Info));
var intModeToggle = new Toggle("Floor Predicate") { value = node.m_floorPredicate };
intModeToggle.OnToggleChanged((evt) =>
{
node.owner.owner.RegisterCompleteObjectUndo("Toggle Change");
node.m_floorPredicate = evt.newValue;
node.Dirty(ModificationScope.Node);
});
parentElement.Add(intModeToggle);
// We are reading enum cases from a property, so we won't display the list view.
if (node.UpstreamFloatEnumProperty != null)
return;
var listView = new ReorderableListView<SwitchNode.EntryCase>(node.m_cases, "Conditions");
listView.OnCanAddCallback = () => node.m_cases.Count < SwitchNode.kMaxCases;
listView.OnNewItemCallback +=
() => new SwitchNode.EntryCase { comparisonType = ComparisonType.Equal, threshold = node.m_cases.Count };
listView.OnBeforeChangeCallback +=
(ReorderableListView<SwitchNode.EntryCase>.ListActionType changeType) =>
{
node.owner.owner.RegisterCompleteObjectUndo($"{changeType} Switch Condition");
};
listView.OnChangeCallback +=
(ReorderableListView<SwitchNode.EntryCase>.ListActionType changeType) =>
{
node.Dirty(ModificationScope.Topological);
node.UpdateNodeAfterDeserialization();
inspectorUpdateDelegate();
};
listView.DrawItemCallback += (Rect rect, int idx) =>
{
EditorGUI.BeginChangeCheck();
var data = node.m_cases[idx];
var trirect = TriRectSplit(rect, 0);
EditorGUI.LabelField(trirect.a, $"Case {(char)(idx + 'A')} ");
data.comparisonType = (ComparisonType)EditorGUI.EnumPopup(trirect.b, (ComparisonType)data.comparisonType);
data.threshold = EditorGUI.DelayedFloatField(trirect.c, data.threshold);
if (EditorGUI.EndChangeCheck())
{
node.owner.owner.RegisterCompleteObjectUndo("switch Entry Value Change");
node.m_cases[idx] = data;
node.Dirty(ModificationScope.Node);
node.UpdateNodeAfterDeserialization();
}
};
parentElement.Add(listView);
}
private static (Rect pad, Rect a, Rect b, Rect c) TriRectSplit(Rect rect, float padding)
{
var width = rect.width - padding;
var P = rect.xMin;
var A = P + padding;
var B = rect.xMin + width / 3;
var C = B + width / 3;
var D = rect.xMax;
Rect p = rect;
Rect a = rect;
Rect b = rect;
Rect c = rect;
p.xMin = P;
p.xMax = A;
a.xMin = A;
a.xMax = B;
b.xMin = B;
b.xMax = C;
c.xMin = C;
c.xMax = D;
return (p, a, b, c);
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 08d70afa217adb948a9c45a911ba0d3e
@@ -0,0 +1,57 @@
using System;
using System.Reflection;
using UnityEditor.Graphing.Util;
using UnityEditor.ShaderGraph.Drawing;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers
{
[SGPropertyDrawer(typeof(string))]
class TextPropertyDrawer : IPropertyDrawer
{
public TextField textField;
public Label label;
internal delegate void ValueChangedCallback(string newValue);
internal VisualElement CreateGUI(
ValueChangedCallback valueChangedCallback,
string fieldToDraw,
string labelName,
int indentLevel = 0,
string tooltip = null)
{
label = PropertyDrawerUtils.CreateLabel(labelName, indentLevel);
var propertyRow = new PropertyRow(label);
propertyRow.tooltip = tooltip;
textField = new TextField(512, false, false, ' ') { isDelayed = true };
propertyRow.Add(textField,
textField =>
{
textField.value = fieldToDraw;
});
if (valueChangedCallback != null)
{
textField.RegisterValueChangedCallback(evt => valueChangedCallback(evt.newValue));
}
propertyRow.styleSheets.Add(Resources.Load<StyleSheet>("Styles/PropertyRow"));
return propertyRow;
}
public Action inspectorUpdateDelegate { get; set; }
public VisualElement DrawProperty(PropertyInfo propertyInfo, object actualObject, InspectableAttribute attribute)
{
return this.CreateGUI(
// Use the setter from the provided property as the callback
newStringValue => propertyInfo.GetSetMethod(true).Invoke(actualObject, new object[] { newStringValue }),
(string)propertyInfo.GetValue(actualObject),
attribute.labelName);
}
void IPropertyDrawer.DisposePropertyDrawer() { }
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: e68777ed02ae4f5db2f87972b309ae0e
timeCreated: 1588105779
@@ -0,0 +1,51 @@
using System;
using System.Reflection;
using UnityEditor.ShaderGraph.Drawing;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers
{
[SGPropertyDrawer(typeof(Texture2DArray))]
class Texture2DArrayPropertyDrawer : IPropertyDrawer
{
internal delegate void ValueChangedCallback(Texture2DArray newValue);
internal VisualElement CreateGUI(
ValueChangedCallback valueChangedCallback,
Texture2DArray fieldToDraw,
string labelName,
out VisualElement propertyColorField,
int indentLevel = 0)
{
var objectField = new ObjectField { value = fieldToDraw, objectType = typeof(Texture2DArray) };
if (valueChangedCallback != null)
{
objectField.RegisterValueChangedCallback(evt => { valueChangedCallback((Texture2DArray)evt.newValue); });
}
propertyColorField = objectField;
var defaultRow = new PropertyRow(PropertyDrawerUtils.CreateLabel(labelName, indentLevel));
defaultRow.Add(propertyColorField);
defaultRow.styleSheets.Add(Resources.Load<StyleSheet>("Styles/PropertyRow"));
return defaultRow;
}
public Action inspectorUpdateDelegate { get; set; }
public VisualElement DrawProperty(PropertyInfo propertyInfo, object actualObject, InspectableAttribute attribute)
{
return this.CreateGUI(
// Use the setter from the provided property as the callback
newValue => propertyInfo.GetSetMethod(true).Invoke(actualObject, new object[] { newValue }),
(Texture2DArray)propertyInfo.GetValue(actualObject),
attribute.labelName,
out var propertyVisualElement);
}
void IPropertyDrawer.DisposePropertyDrawer() { }
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 2d40dca50e4f4bd2ad13b8d9b7cf0242
timeCreated: 1588106412
@@ -0,0 +1,51 @@
using System;
using System.Reflection;
using UnityEditor.ShaderGraph.Drawing;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers
{
[SGPropertyDrawer(typeof(Texture))]
class Texture2DPropertyDrawer : IPropertyDrawer
{
internal delegate void ValueChangedCallback(Texture newValue);
internal VisualElement CreateGUI(
ValueChangedCallback valueChangedCallback,
Texture fieldToDraw,
string labelName,
out VisualElement propertyColorField,
int indentLevel = 0)
{
var objectField = new ObjectField { value = fieldToDraw, objectType = typeof(Texture) };
if (valueChangedCallback != null)
{
objectField.RegisterValueChangedCallback(evt => { valueChangedCallback((Texture)evt.newValue); });
}
propertyColorField = objectField;
var defaultRow = new PropertyRow(PropertyDrawerUtils.CreateLabel(labelName, indentLevel));
defaultRow.Add(propertyColorField);
defaultRow.styleSheets.Add(Resources.Load<StyleSheet>("Styles/PropertyRow"));
return defaultRow;
}
public Action inspectorUpdateDelegate { get; set; }
public VisualElement DrawProperty(PropertyInfo propertyInfo, object actualObject, InspectableAttribute attribute)
{
return this.CreateGUI(
// Use the setter from the provided property as the callback
newValue => propertyInfo.GetSetMethod(true).Invoke(actualObject, new object[] { newValue }),
(Texture)propertyInfo.GetValue(actualObject),
attribute.labelName,
out var propertyVisualElement);
}
void IPropertyDrawer.DisposePropertyDrawer() { }
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: b37bc2e95bab46b781fef0da2e9a2ece
timeCreated: 1588106384
@@ -0,0 +1,51 @@
using System;
using System.Reflection;
using UnityEditor.ShaderGraph.Drawing;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers
{
[SGPropertyDrawer(typeof(Texture3D))]
class Texture3DPropertyDrawer : IPropertyDrawer
{
internal delegate void ValueChangedCallback(Texture3D newValue);
internal VisualElement CreateGUI(
ValueChangedCallback valueChangedCallback,
Texture fieldToDraw,
string labelName,
out VisualElement propertyColorField,
int indentLevel = 0)
{
var objectField = new ObjectField { value = fieldToDraw, objectType = typeof(Texture3D) };
if (valueChangedCallback != null)
{
objectField.RegisterValueChangedCallback(evt => { valueChangedCallback((Texture3D)evt.newValue); });
}
propertyColorField = objectField;
var defaultRow = new PropertyRow(PropertyDrawerUtils.CreateLabel(labelName, indentLevel));
defaultRow.Add(propertyColorField);
defaultRow.styleSheets.Add(Resources.Load<StyleSheet>("Styles/PropertyRow"));
return defaultRow;
}
public Action inspectorUpdateDelegate { get; set; }
public VisualElement DrawProperty(PropertyInfo propertyInfo, object actualObject, InspectableAttribute attribute)
{
return this.CreateGUI(
// Use the setter from the provided property as the callback
newValue => propertyInfo.GetSetMethod(true).Invoke(actualObject, new object[] { newValue }),
(Texture3D)propertyInfo.GetValue(actualObject),
attribute.labelName,
out var propertyVisualElement);
}
void IPropertyDrawer.DisposePropertyDrawer() { }
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 63458f45f3af4d04b99a4ccd21430c8a
timeCreated: 1588106453
@@ -0,0 +1,60 @@
using System;
using System.Reflection;
using UnityEditor.Graphing.Util;
using UnityEditor.ShaderGraph.Drawing;
using UnityEditor.ShaderGraph.Drawing.Controls;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers
{
[SGPropertyDrawer(typeof(ToggleData))]
class ToggleDataPropertyDrawer : IPropertyDrawer
{
internal delegate void ValueChangedCallback(ToggleData newValue);
internal VisualElement CreateGUI(
ValueChangedCallback valueChangedCallback,
ToggleData fieldToDraw,
string labelName,
out VisualElement propertyToggle,
int indentLevel = 0,
string tooltip = null)
{
var row = new PropertyRow(PropertyDrawerUtils.CreateLabel(labelName, indentLevel));
row.tooltip = tooltip;
// Create and assign toggle as out variable here so that callers can also do additional work with enabling/disabling if needed
propertyToggle = new Toggle();
row.Add((Toggle)propertyToggle, (toggle) =>
{
toggle.value = fieldToDraw.isOn;
});
if (valueChangedCallback != null)
{
var toggle = (Toggle)propertyToggle;
toggle.OnToggleChanged(evt => valueChangedCallback(new ToggleData(evt.newValue)));
}
row.styleSheets.Add(Resources.Load<StyleSheet>("Styles/PropertyRow"));
return row;
}
public Action inspectorUpdateDelegate { get; set; }
public VisualElement DrawProperty(
PropertyInfo propertyInfo,
object actualObject,
InspectableAttribute attribute)
{
return this.CreateGUI(
// Use the setter from the provided property as the callback
newBoolValue => propertyInfo.GetSetMethod(true).Invoke(actualObject, new object[] { newBoolValue }),
(ToggleData)propertyInfo.GetValue(actualObject),
attribute.labelName,
out var propertyVisualElement);
}
void IPropertyDrawer.DisposePropertyDrawer() { }
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 57c3182c4f4d4ee8a6eccd63407c695d
timeCreated: 1588094576
@@ -0,0 +1,61 @@
using System;
using UnityEditor.UIElements;
using UnityEditor.Graphing;
using UnityEditor.Graphing.Util;
using UnityEngine.UIElements;
using UnityEditor.ShaderGraph.Internal;
namespace UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers
{
[SGPropertyDrawer(typeof(TransformNode))]
class TransformNodePropertyDrawer : AbstractMaterialNodePropertyDrawer
{
TransformNode node;
PropertyRow normalizePropRow;
void UpdateVisibility()
{
normalizePropRow.visible = (node.sgVersion >= 2) && (node.conversionType != ConversionType.Position);
}
internal override void AddCustomNodeProperties(VisualElement parentElement, AbstractMaterialNode nodeBase, Action setNodesAsDirtyCallback, Action updateNodeViewsCallback)
{
node = nodeBase as TransformNode;
var normalizeControl = new Toggle();
normalizeControl.value = node.normalize;
normalizePropRow = new PropertyRow(new Label("Normalize Output"));
normalizePropRow.Add(normalizeControl, (field) =>
{
field.RegisterValueChangedCallback(evt =>
{
if (evt.newValue.Equals(node.normalize))
return;
setNodesAsDirtyCallback?.Invoke();
node.owner.owner.RegisterCompleteObjectUndo("Change normalize");
node.normalize = evt.newValue;
updateNodeViewsCallback?.Invoke();
node.Dirty(ModificationScope.Graph);
});
});
parentElement.Add(normalizePropRow);
UpdateVisibility();
node.RegisterCallback(OnNodeModified);
}
// when node is modified we want to update the visibility
void OnNodeModified(AbstractMaterialNode node, ModificationScope scope)
{
UpdateVisibility();
}
internal override void DisposePropertyDrawer()
{
node.UnregisterCallback(OnNodeModified);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 83fc180327d27574e82b361da1ea2d11
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,78 @@
using System;
using UnityEditor.UIElements;
using UnityEditor.Graphing;
using UnityEditor.Graphing.Util;
using UnityEngine.UIElements;
using UnityEditor.ShaderGraph.Internal;
namespace UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers
{
[SGPropertyDrawer(typeof(TriplanarNode))]
class TriplanarNodePropertyDrawer : AbstractMaterialNodePropertyDrawer
{
TriplanarNode node;
PropertyRow inputPropRow;
PropertyRow normalOutputPropRow;
void UpdateVisibility()
{
normalOutputPropRow.visible = (node.textureType == TextureType.Normal);
}
// when node is modified we want to update the visibility
void OnNodeModified(AbstractMaterialNode node, ModificationScope scope)
{
UpdateVisibility();
}
internal override void AddCustomNodeProperties(VisualElement parentElement, AbstractMaterialNode nodeBase, Action setNodesAsDirtyCallback, Action updateNodeViewsCallback)
{
node = nodeBase as TriplanarNode;
var previewField = new EnumField(node.inputSpace);
inputPropRow = new PropertyRow(new Label("Input Space"));
inputPropRow.Add(previewField, (field) =>
{
field.RegisterValueChangedCallback(evt =>
{
if (evt.newValue.Equals(node.inputSpace))
return;
setNodesAsDirtyCallback?.Invoke();
node.owner.owner.RegisterCompleteObjectUndo("Change normal input space");
node.inputSpace = (CoordinateSpace)evt.newValue;
updateNodeViewsCallback?.Invoke();
node.Dirty(ModificationScope.Graph);
});
});
parentElement.Add(inputPropRow);
previewField = new EnumField(node.normalOutputSpace);
normalOutputPropRow = new PropertyRow(new Label("Normal Output Space"));
normalOutputPropRow.Add(previewField, (field) =>
{
field.RegisterValueChangedCallback(evt =>
{
if (evt.newValue.Equals(node.normalOutputSpace))
return;
setNodesAsDirtyCallback?.Invoke();
node.owner.owner.RegisterCompleteObjectUndo("Change normal output space");
node.normalOutputSpace = (CoordinateSpace)evt.newValue;
updateNodeViewsCallback?.Invoke();
node.Dirty(ModificationScope.Graph);
});
});
parentElement.Add(normalOutputPropRow);
UpdateVisibility();
node.RegisterCallback(OnNodeModified);
}
internal override void DisposePropertyDrawer()
{
node.UnregisterCallback(OnNodeModified);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 676609a53124d5b4692470f7f7a5f9a8
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,106 @@
using System;
using System.Reflection;
using UnityEditor;
using UnityEditor.ShaderGraph.Drawing;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers
{
[SGPropertyDrawer(typeof(Vector2))]
class Vector2PropertyDrawer : IPropertyDrawer
{
internal delegate void ValueChangedCallback(Vector2 newValue);
public Action preValueChangeCallback { get; set; }
public Action postValueChangeCallback { get; set; }
EventCallback<KeyDownEvent> m_KeyDownCallback;
EventCallback<FocusOutEvent> m_FocusOutCallback;
public int mUndoGroup { get; set; } = -1;
public Vector2PropertyDrawer()
{
CreateCallbacks();
}
void CreateCallbacks()
{
m_KeyDownCallback = new EventCallback<KeyDownEvent>(evt =>
{
// Record Undo for input field edit
if (mUndoGroup == -1)
{
mUndoGroup = Undo.GetCurrentGroup();
preValueChangeCallback?.Invoke();
}
// Handle escaping input field edit
if (evt.keyCode == KeyCode.Escape && mUndoGroup > -1)
{
Undo.RevertAllDownToGroup(mUndoGroup);
mUndoGroup = -1;
evt.StopPropagation();
}
// Dont record Undo again until input field is unfocused
mUndoGroup++;
postValueChangeCallback?.Invoke();
});
m_FocusOutCallback = new EventCallback<FocusOutEvent>(evt =>
{
// Reset UndoGroup when done editing input field
mUndoGroup = -1;
});
}
internal VisualElement CreateGUI(
ValueChangedCallback valueChangedCallback,
Vector2 fieldToDraw,
string labelName,
out VisualElement propertyVec2Field,
int indentLevel = 0)
{
var vector2Field = new Vector2Field { value = fieldToDraw };
var inputFields = vector2Field.Query("unity-text-input").ToList();
foreach (var inputField in inputFields)
{
inputField.RegisterCallback<KeyDownEvent>(m_KeyDownCallback, TrickleDown.TrickleDown);
inputField.RegisterCallback<FocusOutEvent>(m_FocusOutCallback, TrickleDown.TrickleDown);
}
// Bind value changed event to callback to handle dragger behavior before actually settings the value
vector2Field.RegisterValueChangedCallback(evt =>
{
// Only true when setting value via FieldMouseDragger
// Undo recorded once per dragger release
if (mUndoGroup == -1)
preValueChangeCallback?.Invoke();
valueChangedCallback(evt.newValue);
postValueChangeCallback?.Invoke();
});
propertyVec2Field = vector2Field;
var defaultRow = new PropertyRow(PropertyDrawerUtils.CreateLabel(labelName, indentLevel));
defaultRow.Add(propertyVec2Field);
defaultRow.styleSheets.Add(Resources.Load<StyleSheet>("Styles/PropertyRow"));
return defaultRow;
}
public Action inspectorUpdateDelegate { get; set; }
public VisualElement DrawProperty(PropertyInfo propertyInfo, object actualObject, InspectableAttribute attribute)
{
return this.CreateGUI(
// Use the setter from the provided property as the callback
newValue => propertyInfo.GetSetMethod(true).Invoke(actualObject, new object[] { newValue }),
(Vector2)propertyInfo.GetValue(actualObject),
attribute.labelName,
out var propertyVisualElement);
}
void IPropertyDrawer.DisposePropertyDrawer() { }
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: aa85af60c0d1444181e900d4406b8fab
timeCreated: 1588106188
@@ -0,0 +1,107 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEditor;
using UnityEditor.ShaderGraph.Drawing;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers
{
[SGPropertyDrawer(typeof(Vector3))]
class Vector3PropertyDrawer : IPropertyDrawer
{
internal delegate void ValueChangedCallback(Vector3 newValue);
public Action preValueChangeCallback { get; set; }
public Action postValueChangeCallback { get; set; }
EventCallback<KeyDownEvent> m_KeyDownCallback;
EventCallback<FocusOutEvent> m_FocusOutCallback;
public int mUndoGroup { get; set; } = -1;
void CreateCallbacks()
{
m_KeyDownCallback = new EventCallback<KeyDownEvent>(evt =>
{
// Record Undo for input field edit
if (mUndoGroup == -1)
{
mUndoGroup = Undo.GetCurrentGroup();
preValueChangeCallback?.Invoke();
}
// Handle escaping input field edit
if (evt.keyCode == KeyCode.Escape && mUndoGroup > -1)
{
Undo.RevertAllDownToGroup(mUndoGroup);
mUndoGroup = -1;
evt.StopPropagation();
}
// Dont record Undo again until input field is unfocused
mUndoGroup++;
postValueChangeCallback?.Invoke();
});
m_FocusOutCallback = new EventCallback<FocusOutEvent>(evt =>
{
// Reset UndoGroup when done editing input field
mUndoGroup = -1;
});
}
public Vector3PropertyDrawer()
{
CreateCallbacks();
}
internal VisualElement CreateGUI(
ValueChangedCallback valueChangedCallback,
Vector3 fieldToDraw,
string labelName,
out VisualElement propertyVec3Field,
int indentLevel = 0)
{
var vector3Field = new Vector3Field { value = fieldToDraw };
var inputFields = vector3Field.Query("unity-text-input").ToList();
foreach (var inputField in inputFields)
{
inputField.RegisterCallback<KeyDownEvent>(m_KeyDownCallback, TrickleDown.TrickleDown);
inputField.RegisterCallback<FocusOutEvent>(m_FocusOutCallback, TrickleDown.TrickleDown);
}
vector3Field.RegisterValueChangedCallback(evt =>
{
// Only true when setting value via FieldMouseDragger
// Undo recorded once per dragger release
if (mUndoGroup == -1)
preValueChangeCallback?.Invoke();
valueChangedCallback(evt.newValue);
postValueChangeCallback?.Invoke();
});
propertyVec3Field = vector3Field;
var defaultRow = new PropertyRow(PropertyDrawerUtils.CreateLabel(labelName, indentLevel));
defaultRow.Add(propertyVec3Field);
defaultRow.styleSheets.Add(Resources.Load<StyleSheet>("Styles/PropertyRow"));
return defaultRow;
}
public Action inspectorUpdateDelegate { get; set; }
public VisualElement DrawProperty(PropertyInfo propertyInfo, object actualObject, InspectableAttribute attribute)
{
return this.CreateGUI(
// Use the setter from the provided property as the callback
newValue => propertyInfo.GetSetMethod(true).Invoke(actualObject, new object[] { newValue }),
(Vector3)propertyInfo.GetValue(actualObject),
attribute.labelName,
out var propertyVisualElement);
}
void IPropertyDrawer.DisposePropertyDrawer() { }
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 11cd8a6794214c528e811067773e9e6e
timeCreated: 1588106256
@@ -0,0 +1,106 @@
using System;
using System.Reflection;
using UnityEditor;
using UnityEditor.ShaderGraph.Drawing;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers
{
[SGPropertyDrawer(typeof(Vector4))]
class Vector4PropertyDrawer : IPropertyDrawer
{
internal delegate void ValueChangedCallback(Vector4 newValue);
public Action preValueChangeCallback { get; set; }
public Action postValueChangeCallback { get; set; }
EventCallback<KeyDownEvent> m_KeyDownCallback;
EventCallback<FocusOutEvent> m_FocusOutCallback;
public int mUndoGroup { get; set; } = -1;
void CreateCallbacks()
{
m_KeyDownCallback = new EventCallback<KeyDownEvent>(evt =>
{
// Record Undo for input field edit
if (mUndoGroup == -1)
{
mUndoGroup = Undo.GetCurrentGroup();
preValueChangeCallback?.Invoke();
}
// Handle escaping input field edit
if (evt.keyCode == KeyCode.Escape && mUndoGroup > -1)
{
Undo.RevertAllDownToGroup(mUndoGroup);
mUndoGroup = -1;
evt.StopPropagation();
}
// Dont record Undo again until input field is unfocused
mUndoGroup++;
postValueChangeCallback?.Invoke();
});
m_FocusOutCallback = new EventCallback<FocusOutEvent>(evt =>
{
// Reset UndoGroup when done editing input field
mUndoGroup = -1;
});
}
public Vector4PropertyDrawer()
{
CreateCallbacks();
}
internal VisualElement CreateGUI(
ValueChangedCallback valueChangedCallback,
Vector4 fieldToDraw,
string labelName,
out VisualElement propertyVec4Field,
int indentLevel = 0)
{
var vector4Field = new Vector4Field { value = fieldToDraw };
var inputFields = vector4Field.Query("unity-text-input").ToList();
foreach (var inputField in inputFields)
{
inputField.RegisterCallback<KeyDownEvent>(m_KeyDownCallback, TrickleDown.TrickleDown);
inputField.RegisterCallback<FocusOutEvent>(m_FocusOutCallback, TrickleDown.TrickleDown);
}
vector4Field.RegisterValueChangedCallback(evt =>
{
// Only true when setting value via FieldMouseDragger
// Undo recorded once per dragger release
if (mUndoGroup == -1)
preValueChangeCallback?.Invoke();
valueChangedCallback(evt.newValue);
postValueChangeCallback?.Invoke();
});
propertyVec4Field = vector4Field;
var defaultRow = new PropertyRow(PropertyDrawerUtils.CreateLabel(labelName, indentLevel));
defaultRow.Add(propertyVec4Field);
defaultRow.styleSheets.Add(Resources.Load<StyleSheet>("Styles/PropertyRow"));
return defaultRow;
}
public Action inspectorUpdateDelegate { get; set; }
public VisualElement DrawProperty(PropertyInfo propertyInfo, object actualObject, InspectableAttribute attribute)
{
return this.CreateGUI(
// Use the setter from the provided property as the callback
newValue => propertyInfo.GetSetMethod(true).Invoke(actualObject, new object[] { newValue }),
(Vector4)propertyInfo.GetValue(actualObject),
attribute.labelName,
out var propertyVisualElement);
}
void IPropertyDrawer.DisposePropertyDrawer() { }
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 55f775cc6637496c92d1b8df4030ada4
timeCreated: 1588106301
@@ -0,0 +1,369 @@
using System;
using System.Collections.Generic;
using UnityEditor.ShaderGraph.Drawing;
using UnityEditor.ShaderGraph.Drawing.Colors;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.UIElements;
namespace UnityEditor.ShaderGraph
{
[CustomEditor(typeof(ShaderGraphHeatmapValues))]
[CoreRPHelpURL("index", "com.unity.shadergraph")]
class ShaderGraphHeatmapValuesEditor : Editor
{
const string k_TemplatePath = "Packages/com.unity.shadergraph/Editor/Resources/UXML/HeatmapValuesEditor.uxml";
const string k_StylePath = "Packages/com.unity.shadergraph/Editor/Resources/Styles/HeatmapValuesEditor.uss";
const string k_ColorsListName = "colors-list";
const string k_NodeListName = "nodes-list";
const string k_SubgraphListName = "subgraph-list";
const string k_NodeTitleColumnName = "node";
const string k_SubgraphColumnName = "subgraph";
const string k_HeatValueColumnName = "value";
const string k_HeatFieldUssClassName = "sg-heatmap__heat-field";
const string k_SubgraphPickerUssClassName = "sg-heatmap__subgraph-picker";
const string k_NodeLabelUssClassName = "sg-heatmap__node-label";
const string k_RefreshNodesHintName = "refresh-nodes-hint";
const string k_RefreshNodesButtonName = "refresh-nodes-button";
const string k_HelpBoxHiddenUssModifier = "sg-heatmap__help-box--hidden";
const int k_MaxColorsEntries = 500;
const int k_MaxSubgraphEntries = 500;
ShaderGraphHeatmapValues HeatmapValuesTarget => target as ShaderGraphHeatmapValues;
MultiColumnListView m_NodesListView;
MultiColumnListView m_SubgraphListView;
VisualElement m_RefreshNodesHint;
internal static void UpdateShaderGraphWindows()
{
foreach (var window in Resources.FindObjectsOfTypeAll<MaterialGraphEditWindow>())
{
var graphEditorView = window.graphEditorView;
if (graphEditorView == null)
{
continue;
}
var colorManager = graphEditorView.colorManager;
if (colorManager.activeProviderName != HeatmapColors.Title)
{
continue;
}
var nodeList = graphEditorView.Query<MaterialNodeView>().ToList();
colorManager.UpdateNodeViews(nodeList);
}
}
static Dictionary<string, string> s_NodeTypeNamesToTitles;
static Dictionary<string, string> NodeTypeNamesToTitles
{
get
{
if (s_NodeTypeNamesToTitles is null)
{
s_NodeTypeNamesToTitles = new Dictionary<string, string>();
foreach (var knownNodeType in NodeClassCache.knownNodeTypes)
{
var node = (AbstractMaterialNode) Activator.CreateInstance(knownNodeType);
s_NodeTypeNamesToTitles[knownNodeType.Name] = node.name;
}
}
return s_NodeTypeNamesToTitles;
}
}
static string GetTitleForNode(string nodeTypeName)
{
return string.IsNullOrEmpty(nodeTypeName)
? string.Empty
: NodeTypeNamesToTitles.GetValueOrDefault(nodeTypeName, nodeTypeName);
}
static void ConfigureNodeLabelColumn(Column column, Func<HeatmapEntries> getEntries)
{
column.makeCell = () =>
{
var ve = new Label();
ve.AddToClassList(k_NodeLabelUssClassName);
return ve;
};
column.bindCell = (v, i) =>
{
// Resolve via getter on every bind: the underlying List<HeatmapEntry> reference can be
// replaced during undo deserialization, so a captured reference would go stale and throw on RefreshItems.
var entries = getEntries().Entries;
if ((uint)i >= (uint)entries.Count)
return;
var label = (Label) v;
label.text = GetTitleForNode(entries[i].m_NodeName);
};
}
void ConfigureSubgraphPickerColumn(Column column)
{
var serializedEntries = serializedObject.FindProperty("m_Subgraphs");
column.makeCell = () =>
{
var ve = new ObjectField
{
tooltip = "Subgraph asset.",
objectType = typeof(SubGraphAsset),
allowSceneObjects = false,
};
ve.AddToClassList(k_SubgraphPickerUssClassName);
return ve;
};
column.bindCell = (v, i) =>
{
var objectField = (ObjectField) v;
objectField.RegisterCallback<ChangeEvent<UnityEngine.Object>, int>(OnSubgraphChanged, i);
// Resolve dynamically — see ConfigureNodeLabelColumn for why we can't capture the list.
var entries = HeatmapValuesTarget.Subgraphs.Entries;
if ((uint)i >= (uint)entries.Count)
return;
if (string.IsNullOrEmpty(entries[i].m_NodeName))
{
return;
}
var assetPath = AssetDatabase.GUIDToAssetPath(entries[i].m_NodeName);
var asset = AssetDatabase.LoadAssetAtPath<SubGraphAsset>(assetPath);
objectField.SetValueWithoutNotify(asset);
};
column.unbindCell = (v, i) =>
{
var objectField = (ObjectField) v;
objectField.UnregisterCallback<ChangeEvent<UnityEngine.Object>, int>(OnSubgraphChanged);
};
return;
void OnSubgraphChanged(ChangeEvent<UnityEngine.Object> changeEvent, int index)
{
if (changeEvent.newValue is not SubGraphAsset subgraph)
{
return;
}
serializedEntries
.FindPropertyRelative("m_Entries")
.GetArrayElementAtIndex(index)
.FindPropertyRelative("m_NodeName")
.stringValue = subgraph.assetGuid;
ApplyChanges();
}
}
void ConfigureCategoryColumn(Column c, SerializedProperty serializedEntries, Func<HeatmapEntries> getEntries)
{
c.makeCell = () =>
{
var ve = new IntegerField
{
tooltip = "Category assigned to this node, which determines its color.",
isDelayed = true,
};
ve.AddToClassList(k_HeatFieldUssClassName);
return ve;
};
c.bindCell = (v, i) =>
{
var entries = getEntries().Entries;
if ((uint)i >= (uint)entries.Count)
return;
var intField = (IntegerField) v;
intField.SetValueWithoutNotify(entries[i].m_Category);
intField.RegisterCallback<ChangeEvent<int>, int>(OnHeatChanged, i);
};
c.unbindCell = (v, i) =>
{
var intField = (IntegerField) v;
intField.UnregisterCallback<ChangeEvent<int>, int>(OnHeatChanged);
};
return;
void OnHeatChanged(ChangeEvent<int> changeEvent, int index)
{
serializedEntries
.FindPropertyRelative("m_Entries")
.GetArrayElementAtIndex(index)
.FindPropertyRelative("m_Category")
.intValue = changeEvent.newValue;
ApplyChanges();
}
}
void OnEnable()
{
Undo.undoRedoPerformed += OnUndoRedo;
}
void OnDisable()
{
Undo.undoRedoPerformed -= OnUndoRedo;
}
void OnUndoRedo()
{
// Target might not be what we expect if our inspector isn't focused.
if (HeatmapValuesTarget != null)
{
m_RefreshNodesHint.EnableInClassList(k_HelpBoxHiddenUssModifier, HeatmapValuesTarget.ContainsAllApplicableNodes());
// Re-bind itemsSource (the underlying List<T> reference may have been replaced during deserialization) and force a redraw.
serializedObject.Update();
if (m_SubgraphListView != null)
{
m_SubgraphListView.itemsSource = HeatmapValuesTarget.Subgraphs.Entries;
m_SubgraphListView.RefreshItems();
}
if (m_NodesListView != null)
{
m_NodesListView.itemsSource = HeatmapValuesTarget.Nodes.Entries;
m_NodesListView.RefreshItems();
}
}
UpdateShaderGraphWindows();
}
void RefreshNodeListFromProject()
{
Undo.RecordObject(target, $"Refresh Node List in {target.name}");
HeatmapValuesTarget.PopulateNodesFromProject();
serializedObject.Update();
m_NodesListView.RefreshItems();
m_RefreshNodesHint.EnableInClassList(k_HelpBoxHiddenUssModifier, true);
UpdateShaderGraphWindows();
}
void ApplyChanges()
{
serializedObject.ApplyModifiedProperties();
UpdateShaderGraphWindows();
}
public override VisualElement CreateInspectorGUI()
{
var root = new VisualElement();
AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(k_TemplatePath).CloneTree(root);
var styleSheet = AssetDatabase.LoadAssetAtPath<StyleSheet>(k_StylePath);
root.styleSheets.Add(styleSheet);
var colorsListView = root.Q<ListView>(k_ColorsListName);
void LimitTextFieldValue(TextField target, ChangeEvent<string> ev, int limit)
{
if (int.TryParse(ev.newValue, out int newValue))
{
target.value = Math.Min(newValue, limit).ToString();
// Consume the event to ensure no additional callbacks fire based on the invalid input
if (newValue > limit)
ev.StopPropagation();
}
}
// Limit the max number of color entries
TextField colorsArraySizeField = colorsListView.Q<TextField>(className: BaseListView.arraySizeFieldUssClassName);
colorsArraySizeField?.RegisterCallback((ChangeEvent<string> ev) =>
{
LimitTextFieldValue(colorsArraySizeField, ev, k_MaxColorsEntries);
}, TrickleDown.TrickleDown);
colorsListView.bindingPath = serializedObject.FindProperty(nameof(ShaderGraphHeatmapValues.m_Colors)).propertyPath;
colorsListView.makeItem = () => new ColorField {showAlpha = false, hdr = false};
colorsListView.bindItem = (v, i) =>
{
var colorField = (ColorField) v;
colorField.label = $"Category {i}";
colorField.tooltip = $"Color for category {i}.";
colorField.RegisterValueChangedCallback(_ => ApplyChanges());
// Assigning bindingPath makes itemsSource into a list of SerializedProperties, so we can bind directly.
colorField.BindProperty((SerializedProperty) colorsListView.itemsSource[i]);
};
colorsListView.Bind(serializedObject);
var nodeEntries = HeatmapValuesTarget.Nodes;
m_NodesListView = root.Q<MultiColumnListView>(k_NodeListName);
m_RefreshNodesHint = root.Q<HelpBox>(k_RefreshNodesHintName);
m_RefreshNodesHint.EnableInClassList(k_HelpBoxHiddenUssModifier, HeatmapValuesTarget.ContainsAllApplicableNodes());
m_RefreshNodesHint.Q<Button>(k_RefreshNodesButtonName).clicked += RefreshNodeListFromProject;
var nodesSerializedProperty = serializedObject.FindProperty("m_Nodes");
ConfigureNodeLabelColumn(m_NodesListView.columns[k_NodeTitleColumnName], () => HeatmapValuesTarget.Nodes);
ConfigureCategoryColumn(m_NodesListView.columns[k_HeatValueColumnName], nodesSerializedProperty, () => HeatmapValuesTarget.Nodes);
m_NodesListView.AddManipulator(new ContextualMenuManipulator(evt =>
{
evt.menu.AppendSeparator();
evt.menu.AppendAction("Refresh Node List", _ => RefreshNodeListFromProject());
}));
// MultiColumnListView doesn't support binding as of writing, but we can still track property changes
// to reflect undo, redo, reset, etc.
m_NodesListView.TrackPropertyValue(nodesSerializedProperty, _ => { m_NodesListView.RefreshItems(); });
m_NodesListView.itemsSource = nodeEntries.Entries;
var subgraphEntries = HeatmapValuesTarget.Subgraphs;
m_SubgraphListView = root.Q<MultiColumnListView>(k_SubgraphListName);
// Limit the max number of subgraph entries
TextField subgraphArraySizeField = m_SubgraphListView.Q<TextField>(className: BaseListView.arraySizeFieldUssClassName);
subgraphArraySizeField?.RegisterCallback((ChangeEvent<string> ev) =>
{
LimitTextFieldValue(subgraphArraySizeField, ev, k_MaxSubgraphEntries);
}, TrickleDown.TrickleDown);
var subgraphsSerializedProperty = serializedObject.FindProperty("m_Subgraphs");
ConfigureSubgraphPickerColumn(m_SubgraphListView.columns[k_SubgraphColumnName]);
ConfigureCategoryColumn(m_SubgraphListView.columns[k_HeatValueColumnName], subgraphsSerializedProperty, () => HeatmapValuesTarget.Subgraphs);
m_SubgraphListView.TrackPropertyValue(subgraphsSerializedProperty, _ => { m_SubgraphListView.RefreshItems(); });
m_SubgraphListView.itemsSource = subgraphEntries.Entries;
// Route +/- through SerializedProperty so ApplyModifiedProperties records undo.
var subgraphEntriesProperty = subgraphsSerializedProperty.FindPropertyRelative("m_Entries");
m_SubgraphListView.onAdd = _ =>
{
subgraphEntriesProperty.arraySize++;
ApplyChanges();
};
m_SubgraphListView.onRemove = list =>
{
if (subgraphEntriesProperty.arraySize == 0)
return;
int index = list.selectedIndex >= 0 ? list.selectedIndex : subgraphEntriesProperty.arraySize - 1;
subgraphEntriesProperty.DeleteArrayElementAtIndex(index);
ApplyChanges();
};
return root;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: e5886001cd1b4a10a07093babfd6f7a6
timeCreated: 1695071048
@@ -0,0 +1,149 @@
using System;
using UnityEngine;
using UnityEngine.UIElements;
using UnityEngine.UIElements.StyleSheets;
namespace UnityEditor.ShaderGraph.Drawing
{
[Serializable]
internal class WindowDockingLayout
{
[SerializeField]
bool m_DockingLeft;
public bool dockingLeft
{
get => m_DockingLeft;
set => m_DockingLeft = value;
}
[SerializeField]
bool m_DockingTop;
public bool dockingTop
{
get => m_DockingTop;
set => m_DockingTop = value;
}
[SerializeField]
float m_VerticalOffset;
public float verticalOffset
{
get => m_VerticalOffset;
set => m_VerticalOffset = value;
}
[SerializeField]
float m_HorizontalOffset;
public float horizontalOffset
{
get => m_HorizontalOffset;
set => m_HorizontalOffset = value;
}
[SerializeField]
Vector2 m_Size;
public Vector2 size
{
get => m_Size;
set => m_Size = value;
}
public void CalculateDockingCornerAndOffset(Rect layout, Rect parentLayout)
{
Vector2 layoutCenter = new Vector2(layout.x + layout.width * .5f, layout.y + layout.height * .5f);
layoutCenter /= parentLayout.size;
m_DockingLeft = layoutCenter.x < .5f;
m_DockingTop = layoutCenter.y < .5f;
if (m_DockingLeft)
{
m_HorizontalOffset = layout.x;
}
else
{
m_HorizontalOffset = parentLayout.width - layout.x - layout.width;
}
if (m_DockingTop)
{
m_VerticalOffset = layout.y;
}
else
{
m_VerticalOffset = parentLayout.height - layout.y - layout.height;
}
m_Size = layout.size;
}
public void ClampToParentWindow(Rect parentLayout)
{
m_HorizontalOffset = Mathf.Clamp(m_HorizontalOffset, 0, parentLayout.width - m_Size.x);
m_VerticalOffset = Mathf.Clamp(m_VerticalOffset, 0, parentLayout.height - m_Size.y);
}
public void ApplyPosition(VisualElement target)
{
if (dockingLeft)
{
target.style.right = float.NaN;
target.style.left = horizontalOffset;
}
else
{
target.style.right = horizontalOffset;
target.style.left = float.NaN;
}
if (dockingTop)
{
target.style.bottom = float.NaN;
target.style.top = verticalOffset;
}
else
{
target.style.top = float.NaN;
target.style.bottom = verticalOffset;
}
}
public void ApplySize(VisualElement target)
{
target.style.width = size.x;
target.style.height = size.y;
}
public Rect GetLayout(Rect parentLayout)
{
Rect layout = new Rect();
layout.size = size;
if (dockingLeft)
{
layout.x = horizontalOffset;
}
else
{
layout.x = parentLayout.width - size.x - horizontalOffset;
}
if (dockingTop)
{
layout.y = verticalOffset;
}
else
{
layout.y = parentLayout.height - size.y - verticalOffset;
}
return layout;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 5f70875ecccbc924b8f9f0d58bbb37e8
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: