mirror of
https://github.com/Siccity/xNode.git
synced 2026-02-04 14:24:54 +08:00
Fixed broken namespaces.
This commit is contained in:
parent
f790b77575
commit
bfcef1ed34
@ -1,30 +1,39 @@
|
|||||||
using UnityEditor;
|
using UnityEditor;
|
||||||
using UnityEngine;
|
using UnityEngine;
|
||||||
|
using XNode;
|
||||||
#if ODIN_INSPECTOR
|
#if ODIN_INSPECTOR
|
||||||
using Sirenix.OdinInspector.Editor;
|
using Sirenix.OdinInspector.Editor;
|
||||||
using Sirenix.Utilities;
|
using Sirenix.Utilities;
|
||||||
using Sirenix.Utilities.Editor;
|
using Sirenix.Utilities.Editor;
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
namespace XNodeEditor {
|
namespace XNodeEditor
|
||||||
|
{
|
||||||
/// <summary> Override graph inspector to show an 'Open Graph' button at the top </summary>
|
/// <summary> Override graph inspector to show an 'Open Graph' button at the top </summary>
|
||||||
[CustomEditor(typeof(NodeGraph), true)]
|
[CustomEditor(typeof(NodeGraph), true)]
|
||||||
#if ODIN_INSPECTOR
|
#if ODIN_INSPECTOR
|
||||||
public class GlobalGraphEditor : OdinEditor {
|
public class GlobalGraphEditor : OdinEditor
|
||||||
public override void OnInspectorGUI() {
|
{
|
||||||
if (GUILayout.Button("Edit graph", GUILayout.Height(40))) {
|
public override void OnInspectorGUI()
|
||||||
|
{
|
||||||
|
if (GUILayout.Button("Edit graph", GUILayout.Height(40)))
|
||||||
|
{
|
||||||
NodeEditorWindow.Open(serializedObject.targetObject as XNode.NodeGraph);
|
NodeEditorWindow.Open(serializedObject.targetObject as XNode.NodeGraph);
|
||||||
}
|
}
|
||||||
|
|
||||||
base.OnInspectorGUI();
|
base.OnInspectorGUI();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#else
|
#else
|
||||||
[CanEditMultipleObjects]
|
[CanEditMultipleObjects]
|
||||||
public class GlobalGraphEditor : Editor {
|
public class GlobalGraphEditor : Editor
|
||||||
public override void OnInspectorGUI() {
|
{
|
||||||
|
public override void OnInspectorGUI()
|
||||||
|
{
|
||||||
serializedObject.Update();
|
serializedObject.Update();
|
||||||
|
|
||||||
if (GUILayout.Button("Edit graph", GUILayout.Height(40))) {
|
if (GUILayout.Button("Edit graph", GUILayout.Height(40)))
|
||||||
|
{
|
||||||
NodeEditorWindow.Open(serializedObject.targetObject as NodeGraph);
|
NodeEditorWindow.Open(serializedObject.targetObject as NodeGraph);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -40,23 +49,30 @@ namespace XNodeEditor {
|
|||||||
|
|
||||||
[CustomEditor(typeof(Node), true)]
|
[CustomEditor(typeof(Node), true)]
|
||||||
#if ODIN_INSPECTOR
|
#if ODIN_INSPECTOR
|
||||||
public class GlobalNodeEditor : OdinEditor {
|
public class GlobalNodeEditor : OdinEditor
|
||||||
public override void OnInspectorGUI() {
|
{
|
||||||
if (GUILayout.Button("Edit graph", GUILayout.Height(40))) {
|
public override void OnInspectorGUI()
|
||||||
|
{
|
||||||
|
if (GUILayout.Button("Edit graph", GUILayout.Height(40)))
|
||||||
|
{
|
||||||
SerializedProperty graphProp = serializedObject.FindProperty("graph");
|
SerializedProperty graphProp = serializedObject.FindProperty("graph");
|
||||||
NodeEditorWindow w = NodeEditorWindow.Open(graphProp.objectReferenceValue as XNode.NodeGraph);
|
NodeEditorWindow w = NodeEditorWindow.Open(graphProp.objectReferenceValue as XNode.NodeGraph);
|
||||||
w.Home(); // Focus selected node
|
w.Home(); // Focus selected node
|
||||||
}
|
}
|
||||||
|
|
||||||
base.OnInspectorGUI();
|
base.OnInspectorGUI();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#else
|
#else
|
||||||
[CanEditMultipleObjects]
|
[CanEditMultipleObjects]
|
||||||
public class GlobalNodeEditor : Editor {
|
public class GlobalNodeEditor : Editor
|
||||||
public override void OnInspectorGUI() {
|
{
|
||||||
|
public override void OnInspectorGUI()
|
||||||
|
{
|
||||||
serializedObject.Update();
|
serializedObject.Update();
|
||||||
|
|
||||||
if (GUILayout.Button("Edit graph", GUILayout.Height(40))) {
|
if (GUILayout.Button("Edit graph", GUILayout.Height(40)))
|
||||||
|
{
|
||||||
SerializedProperty graphProp = serializedObject.FindProperty("graph");
|
SerializedProperty graphProp = serializedObject.FindProperty("graph");
|
||||||
NodeEditorWindow w = NodeEditorWindow.Open(graphProp.objectReferenceValue as NodeGraph);
|
NodeEditorWindow w = NodeEditorWindow.Open(graphProp.objectReferenceValue as NodeGraph);
|
||||||
w.Home(); // Focus selected node
|
w.Home(); // Focus selected node
|
||||||
|
|||||||
@ -1,27 +1,33 @@
|
|||||||
using UnityEditor;
|
using UnityEditor;
|
||||||
|
using XNode;
|
||||||
|
|
||||||
namespace XNodeEditor {
|
namespace XNodeEditor
|
||||||
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// This asset processor resolves an issue with the new v2 AssetDatabase system present on 2019.3 and later. When
|
/// This asset processor resolves an issue with the new v2 AssetDatabase system present on 2019.3 and later. When
|
||||||
/// renaming a <see cref="NodeGraph"/> asset, it appears that sometimes the v2 AssetDatabase will swap which asset
|
/// renaming a <see cref="NodeGraph" /> asset, it appears that sometimes the v2 AssetDatabase will swap which asset
|
||||||
/// is the main asset (present at top level) between the <see cref="NodeGraph"/> and one of its <see cref="Node"/>
|
/// is the main asset (present at top level) between the <see cref="NodeGraph" /> and one of its <see cref="Node" />
|
||||||
/// sub-assets. As a workaround until Unity fixes this, this asset processor checks all renamed assets and if it
|
/// sub-assets. As a workaround until Unity fixes this, this asset processor checks all renamed assets and if it
|
||||||
/// finds a case where a <see cref="Node"/> has been made the main asset it will swap it back to being a sub-asset
|
/// finds a case where a <see cref="Node" /> has been made the main asset it will swap it back to being a sub-asset
|
||||||
/// and rename the node to the default name for that node type.
|
/// and rename the node to the default name for that node type.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
internal sealed class GraphRenameFixAssetProcessor : AssetPostprocessor {
|
internal sealed class GraphRenameFixAssetProcessor : AssetPostprocessor
|
||||||
|
{
|
||||||
private static void OnPostprocessAllAssets(
|
private static void OnPostprocessAllAssets(
|
||||||
string[] importedAssets,
|
string[] importedAssets,
|
||||||
string[] deletedAssets,
|
string[] deletedAssets,
|
||||||
string[] movedAssets,
|
string[] movedAssets,
|
||||||
string[] movedFromAssetPaths) {
|
string[] movedFromAssetPaths)
|
||||||
for (int i = 0; i < movedAssets.Length; i++) {
|
{
|
||||||
|
for (int i = 0; i < movedAssets.Length; i++)
|
||||||
|
{
|
||||||
Node nodeAsset = AssetDatabase.LoadMainAssetAtPath(movedAssets[i]) as Node;
|
Node nodeAsset = AssetDatabase.LoadMainAssetAtPath(movedAssets[i]) as Node;
|
||||||
|
|
||||||
// If the renamed asset is a node graph, but the v2 AssetDatabase has swapped a sub-asset node to be its
|
// If the renamed asset is a node graph, but the v2 AssetDatabase has swapped a sub-asset node to be its
|
||||||
// main asset, reset the node graph to be the main asset and rename the node asset back to its default
|
// main asset, reset the node graph to be the main asset and rename the node asset back to its default
|
||||||
// name.
|
// name.
|
||||||
if (nodeAsset != null && AssetDatabase.IsMainAsset(nodeAsset)) {
|
if (nodeAsset != null && AssetDatabase.IsMainAsset(nodeAsset))
|
||||||
|
{
|
||||||
AssetDatabase.SetMainObject(nodeAsset.graph, movedAssets[i]);
|
AssetDatabase.SetMainObject(nodeAsset.graph, movedAssets[i]);
|
||||||
AssetDatabase.ImportAsset(movedAssets[i]);
|
AssetDatabase.ImportAsset(movedAssets[i]);
|
||||||
|
|
||||||
|
|||||||
@ -1,20 +1,39 @@
|
|||||||
using UnityEngine;
|
using UnityEngine;
|
||||||
|
using XNode;
|
||||||
|
|
||||||
namespace XNodeEditor.Internal {
|
namespace XNodeEditor.Internal
|
||||||
public struct RerouteReference {
|
{
|
||||||
public NodePort port;
|
public struct RerouteReference
|
||||||
public int connectionIndex;
|
{
|
||||||
public int pointIndex;
|
public NodePort port;
|
||||||
|
public int connectionIndex;
|
||||||
|
public int pointIndex;
|
||||||
|
|
||||||
public RerouteReference(NodePort port, int connectionIndex, int pointIndex) {
|
public RerouteReference(NodePort port, int connectionIndex, int pointIndex)
|
||||||
this.port = port;
|
{
|
||||||
this.connectionIndex = connectionIndex;
|
this.port = port;
|
||||||
this.pointIndex = pointIndex;
|
this.connectionIndex = connectionIndex;
|
||||||
}
|
this.pointIndex = pointIndex;
|
||||||
|
}
|
||||||
|
|
||||||
public void InsertPoint(Vector2 pos) { port.GetReroutePoints(connectionIndex).Insert(pointIndex, pos); }
|
public void InsertPoint(Vector2 pos)
|
||||||
public void SetPoint(Vector2 pos) { port.GetReroutePoints(connectionIndex) [pointIndex] = pos; }
|
{
|
||||||
public void RemovePoint() { port.GetReroutePoints(connectionIndex).RemoveAt(pointIndex); }
|
port.GetReroutePoints(connectionIndex).Insert(pointIndex, pos);
|
||||||
public Vector2 GetPoint() { return port.GetReroutePoints(connectionIndex) [pointIndex]; }
|
}
|
||||||
}
|
|
||||||
|
public void SetPoint(Vector2 pos)
|
||||||
|
{
|
||||||
|
port.GetReroutePoints(connectionIndex)[pointIndex] = pos;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void RemovePoint()
|
||||||
|
{
|
||||||
|
port.GetReroutePoints(connectionIndex).RemoveAt(pointIndex);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Vector2 GetPoint()
|
||||||
|
{
|
||||||
|
return port.GetReroutePoints(connectionIndex)[pointIndex];
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@ -3,34 +3,53 @@ using System.Collections.Generic;
|
|||||||
using System.Linq;
|
using System.Linq;
|
||||||
using UnityEditor;
|
using UnityEditor;
|
||||||
using UnityEngine;
|
using UnityEngine;
|
||||||
|
using XNode;
|
||||||
|
using XNodeEditor.Internal;
|
||||||
#if ODIN_INSPECTOR
|
#if ODIN_INSPECTOR
|
||||||
using Sirenix.OdinInspector.Editor;
|
using Sirenix.OdinInspector.Editor;
|
||||||
using Sirenix.Utilities;
|
using Sirenix.Utilities;
|
||||||
using Sirenix.Utilities.Editor;
|
using Sirenix.Utilities.Editor;
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#if UNITY_2019_1_OR_NEWER && USE_ADVANCED_GENERIC_MENU
|
#if UNITY_2019_1_OR_NEWER && USE_ADVANCED_GENERIC_MENU
|
||||||
using GenericMenu = XNodeEditor.AdvancedGenericMenu;
|
using GenericMenu = XNodeEditor.AdvancedGenericMenu;
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
namespace XNodeEditor {
|
namespace XNodeEditor
|
||||||
|
{
|
||||||
/// <summary> Base class to derive custom Node editors from. Use this to create your own custom inspectors and editors for your nodes. </summary>
|
/// <summary> Base class to derive custom Node editors from. Use this to create your own custom inspectors and editors for your nodes. </summary>
|
||||||
[CustomNodeEditor(typeof(Node))]
|
[CustomNodeEditor(typeof(Node))]
|
||||||
public class NodeEditor : XNodeEditor.Internal.NodeEditorBase<NodeEditor, NodeEditor.CustomNodeEditorAttribute, Node> {
|
public class NodeEditor : NodeEditorBase<NodeEditor, NodeEditor.CustomNodeEditorAttribute, Node>
|
||||||
|
{
|
||||||
/// <summary> Fires every whenever a node was modified through the editor </summary>
|
/// <summary> Fires every whenever a node was modified through the editor </summary>
|
||||||
public static Action<Node> onUpdateNode;
|
public static Action<Node> onUpdateNode;
|
||||||
public readonly static Dictionary<NodePort, Vector2> portPositions = new Dictionary<NodePort, Vector2>();
|
public static readonly Dictionary<NodePort, Vector2> portPositions = new Dictionary<NodePort, Vector2>();
|
||||||
|
private Vector2 _lastClickPos;
|
||||||
|
|
||||||
#if ODIN_INSPECTOR
|
#if ODIN_INSPECTOR
|
||||||
protected internal static bool inNodeEditor = false;
|
protected internal static bool inNodeEditor = false;
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
public virtual void OnHeaderGUI() {
|
public virtual void OnHeaderGUI()
|
||||||
|
{
|
||||||
|
Event e = Event.current;
|
||||||
|
if (e.type == EventType.MouseDown)
|
||||||
|
{
|
||||||
|
if ((_lastClickPos - e.mousePosition).sqrMagnitude <= 5 * 5 && e.clickCount > 1)
|
||||||
|
{
|
||||||
|
Debug.Log("Renaming time!");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_lastClickPos = e.mousePosition;
|
||||||
|
}
|
||||||
|
|
||||||
GUILayout.Label(target.name, NodeEditorResources.styles.nodeHeader, GUILayout.Height(30));
|
GUILayout.Label(target.name, NodeEditorResources.styles.nodeHeader, GUILayout.Height(30));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Draws standard field editors for all public fields </summary>
|
/// <summary> Draws standard field editors for all public fields </summary>
|
||||||
public virtual void OnBodyGUI() {
|
public virtual void OnBodyGUI()
|
||||||
|
{
|
||||||
#if ODIN_INSPECTOR
|
#if ODIN_INSPECTOR
|
||||||
inNodeEditor = true;
|
inNodeEditor = true;
|
||||||
#endif
|
#endif
|
||||||
@ -45,12 +64,12 @@ namespace XNodeEditor {
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
#if ODIN_INSPECTOR_3
|
#if ODIN_INSPECTOR_3
|
||||||
objectTree.BeginDraw( true );
|
objectTree.BeginDraw(true);
|
||||||
#else
|
#else
|
||||||
InspectorUtilities.BeginDrawPropertyTree(objectTree, true);
|
InspectorUtilities.BeginDrawPropertyTree(objectTree, true);
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
catch ( ArgumentNullException )
|
catch (ArgumentNullException)
|
||||||
{
|
{
|
||||||
#if ODIN_INSPECTOR_3
|
#if ODIN_INSPECTOR_3
|
||||||
objectTree.EndDraw();
|
objectTree.EndDraw();
|
||||||
@ -61,8 +80,8 @@ namespace XNodeEditor {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
GUIHelper.PushLabelWidth( 84 );
|
GUIHelper.PushLabelWidth(84);
|
||||||
objectTree.Draw( true );
|
objectTree.Draw(true);
|
||||||
#if ODIN_INSPECTOR_3
|
#if ODIN_INSPECTOR_3
|
||||||
objectTree.EndDraw();
|
objectTree.EndDraw();
|
||||||
#else
|
#else
|
||||||
@ -74,16 +93,26 @@ namespace XNodeEditor {
|
|||||||
// Iterate through serialized properties and draw them like the Inspector (But with ports)
|
// Iterate through serialized properties and draw them like the Inspector (But with ports)
|
||||||
SerializedProperty iterator = serializedObject.GetIterator();
|
SerializedProperty iterator = serializedObject.GetIterator();
|
||||||
bool enterChildren = true;
|
bool enterChildren = true;
|
||||||
while (iterator.NextVisible(enterChildren)) {
|
while (iterator.NextVisible(enterChildren))
|
||||||
|
{
|
||||||
enterChildren = false;
|
enterChildren = false;
|
||||||
if (excludes.Contains(iterator.name)) continue;
|
if (excludes.Contains(iterator.name))
|
||||||
NodeEditorGUILayout.PropertyField(iterator, true);
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
NodeEditorGUILayout.PropertyField(iterator);
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
// Iterate through dynamic ports and draw them in the order in which they are serialized
|
// Iterate through dynamic ports and draw them in the order in which they are serialized
|
||||||
foreach (NodePort dynamicPort in target.DynamicPorts) {
|
foreach (NodePort dynamicPort in target.DynamicPorts)
|
||||||
if (NodeEditorGUILayout.IsDynamicPortListPort(dynamicPort)) continue;
|
{
|
||||||
|
if (NodeEditorGUILayout.IsDynamicPortListPort(dynamicPort))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
NodeEditorGUILayout.PortField(dynamicPort);
|
NodeEditorGUILayout.PortField(dynamicPort);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -91,7 +120,8 @@ namespace XNodeEditor {
|
|||||||
|
|
||||||
#if ODIN_INSPECTOR
|
#if ODIN_INSPECTOR
|
||||||
// Call repaint so that the graph window elements respond properly to layout changes coming from Odin
|
// Call repaint so that the graph window elements respond properly to layout changes coming from Odin
|
||||||
if (GUIHelper.RepaintRequested) {
|
if (GUIHelper.RepaintRequested)
|
||||||
|
{
|
||||||
GUIHelper.ClearRepaintRequest();
|
GUIHelper.ClearRepaintRequest();
|
||||||
window.Repaint();
|
window.Repaint();
|
||||||
}
|
}
|
||||||
@ -102,41 +132,56 @@ namespace XNodeEditor {
|
|||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
public virtual int GetWidth() {
|
public virtual int GetWidth()
|
||||||
|
{
|
||||||
Type type = target.GetType();
|
Type type = target.GetType();
|
||||||
int width;
|
int width;
|
||||||
if (type.TryGetAttributeWidth(out width)) return width;
|
if (type.TryGetAttributeWidth(out width))
|
||||||
else return 208;
|
{
|
||||||
|
return width;
|
||||||
|
}
|
||||||
|
|
||||||
|
return 208;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Returns color for target node </summary>
|
/// <summary> Returns color for target node </summary>
|
||||||
public virtual Color GetTint() {
|
public virtual Color GetTint()
|
||||||
|
{
|
||||||
// Try get color from [NodeTint] attribute
|
// Try get color from [NodeTint] attribute
|
||||||
Type type = target.GetType();
|
Type type = target.GetType();
|
||||||
Color color;
|
Color color;
|
||||||
if (type.TryGetAttributeTint(out color)) return color;
|
if (type.TryGetAttributeTint(out color))
|
||||||
|
{
|
||||||
|
return color;
|
||||||
|
}
|
||||||
// Return default color (grey)
|
// Return default color (grey)
|
||||||
else return NodeEditorPreferences.GetSettings().tintColor;
|
|
||||||
|
return NodeEditorPreferences.GetSettings().tintColor;
|
||||||
}
|
}
|
||||||
|
|
||||||
public virtual GUIStyle GetBodyStyle() {
|
public virtual GUIStyle GetBodyStyle()
|
||||||
|
{
|
||||||
return NodeEditorResources.styles.nodeBody;
|
return NodeEditorResources.styles.nodeBody;
|
||||||
}
|
}
|
||||||
|
|
||||||
public virtual GUIStyle GetBodyHighlightStyle() {
|
public virtual GUIStyle GetBodyHighlightStyle()
|
||||||
|
{
|
||||||
return NodeEditorResources.styles.nodeHighlight;
|
return NodeEditorResources.styles.nodeHighlight;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Override to display custom node header tooltips </summary>
|
/// <summary> Override to display custom node header tooltips </summary>
|
||||||
public virtual string GetHeaderTooltip() {
|
public virtual string GetHeaderTooltip()
|
||||||
|
{
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Add items for the context menu when right-clicking this node. Override to add custom menu items. </summary>
|
/// <summary> Add items for the context menu when right-clicking this node. Override to add custom menu items. </summary>
|
||||||
public virtual void AddContextMenuItems(GenericMenu menu) {
|
public virtual void AddContextMenuItems(GenericMenu menu)
|
||||||
|
{
|
||||||
bool canRemove = true;
|
bool canRemove = true;
|
||||||
// Actions if only one node is selected
|
// Actions if only one node is selected
|
||||||
if (Selection.objects.Length == 1 && Selection.activeObject is Node) {
|
if (Selection.objects.Length == 1 && Selection.activeObject is Node)
|
||||||
|
{
|
||||||
Node node = Selection.activeObject as Node;
|
Node node = Selection.activeObject as Node;
|
||||||
menu.AddItem(new GUIContent("Move To Top"), false, () => NodeEditorWindow.current.MoveNodeToTop(node));
|
menu.AddItem(new GUIContent("Move To Top"), false, () => NodeEditorWindow.current.MoveNodeToTop(node));
|
||||||
menu.AddItem(new GUIContent("Rename"), false, NodeEditorWindow.current.RenameSelectedNode);
|
menu.AddItem(new GUIContent("Rename"), false, NodeEditorWindow.current.RenameSelectedNode);
|
||||||
@ -148,38 +193,54 @@ namespace XNodeEditor {
|
|||||||
menu.AddItem(new GUIContent("Copy"), false, NodeEditorWindow.current.CopySelectedNodes);
|
menu.AddItem(new GUIContent("Copy"), false, NodeEditorWindow.current.CopySelectedNodes);
|
||||||
menu.AddItem(new GUIContent("Duplicate"), false, NodeEditorWindow.current.DuplicateSelectedNodes);
|
menu.AddItem(new GUIContent("Duplicate"), false, NodeEditorWindow.current.DuplicateSelectedNodes);
|
||||||
|
|
||||||
if (canRemove) menu.AddItem(new GUIContent("Remove"), false, NodeEditorWindow.current.RemoveSelectedNodes);
|
if (canRemove)
|
||||||
else menu.AddItem(new GUIContent("Remove"), false, null);
|
{
|
||||||
|
menu.AddItem(new GUIContent("Remove"), false, NodeEditorWindow.current.RemoveSelectedNodes);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
menu.AddItem(new GUIContent("Remove"), false, null);
|
||||||
|
}
|
||||||
|
|
||||||
// Custom sctions if only one node is selected
|
// Custom sctions if only one node is selected
|
||||||
if (Selection.objects.Length == 1 && Selection.activeObject is Node) {
|
if (Selection.objects.Length == 1 && Selection.activeObject is Node)
|
||||||
|
{
|
||||||
Node node = Selection.activeObject as Node;
|
Node node = Selection.activeObject as Node;
|
||||||
menu.AddCustomContextMenuItems(node);
|
menu.AddCustomContextMenuItems(node);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Rename the node asset. This will trigger a reimport of the node. </summary>
|
/// <summary> Rename the node asset. This will trigger a reimport of the node. </summary>
|
||||||
public void Rename(string newName) {
|
public void Rename(string newName)
|
||||||
if (newName == null || newName.Trim() == "") newName = NodeEditorUtilities.NodeDefaultName(target.GetType());
|
{
|
||||||
|
if (newName == null || newName.Trim() == "")
|
||||||
|
{
|
||||||
|
newName = NodeEditorUtilities.NodeDefaultName(target.GetType());
|
||||||
|
}
|
||||||
|
|
||||||
target.name = newName;
|
target.name = newName;
|
||||||
OnRename();
|
OnRename();
|
||||||
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(target));
|
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(target));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Called after this node's name has changed. </summary>
|
/// <summary> Called after this node's name has changed. </summary>
|
||||||
public virtual void OnRename() { }
|
public virtual void OnRename() {}
|
||||||
|
|
||||||
[AttributeUsage(AttributeTargets.Class)]
|
[AttributeUsage(AttributeTargets.Class)]
|
||||||
public class CustomNodeEditorAttribute : Attribute,
|
public class CustomNodeEditorAttribute : Attribute,
|
||||||
XNodeEditor.Internal.NodeEditorBase<NodeEditor, NodeEditor.CustomNodeEditorAttribute, Node>.INodeEditorAttrib {
|
INodeEditorAttrib
|
||||||
private Type inspectedType;
|
{
|
||||||
|
private readonly Type inspectedType;
|
||||||
|
|
||||||
/// <summary> Tells a NodeEditor which Node type it is an editor for </summary>
|
/// <summary> Tells a NodeEditor which Node type it is an editor for </summary>
|
||||||
/// <param name="inspectedType">Type that this editor can edit</param>
|
/// <param name="inspectedType">Type that this editor can edit</param>
|
||||||
public CustomNodeEditorAttribute(Type inspectedType) {
|
public CustomNodeEditorAttribute(Type inspectedType)
|
||||||
|
{
|
||||||
this.inspectedType = inspectedType;
|
this.inspectedType = inspectedType;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Type GetInspectedType() {
|
public Type GetInspectedType()
|
||||||
|
{
|
||||||
return inspectedType;
|
return inspectedType;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@ -1,64 +1,98 @@
|
|||||||
using UnityEditor;
|
using System;
|
||||||
using UnityEngine;
|
|
||||||
using System.IO;
|
using System.IO;
|
||||||
|
using UnityEditor;
|
||||||
|
using UnityEngine;
|
||||||
|
using XNode;
|
||||||
|
using Object = UnityEngine.Object;
|
||||||
|
|
||||||
namespace XNodeEditor {
|
namespace XNodeEditor
|
||||||
|
{
|
||||||
/// <summary> Deals with modified assets </summary>
|
/// <summary> Deals with modified assets </summary>
|
||||||
class NodeEditorAssetModProcessor : UnityEditor.AssetModificationProcessor {
|
internal class NodeEditorAssetModProcessor : AssetModificationProcessor
|
||||||
|
{
|
||||||
/// <summary> Automatically delete Node sub-assets before deleting their script.
|
/// <summary>
|
||||||
/// This is important to do, because you can't delete null sub assets.
|
/// Automatically delete Node sub-assets before deleting their script.
|
||||||
/// <para/> For another workaround, see: https://gitlab.com/RotaryHeart-UnityShare/subassetmissingscriptdelete </summary>
|
/// This is important to do, because you can't delete null sub assets.
|
||||||
private static AssetDeleteResult OnWillDeleteAsset (string path, RemoveAssetOptions options) {
|
/// <para />
|
||||||
|
/// For another workaround, see: https://gitlab.com/RotaryHeart-UnityShare/subassetmissingscriptdelete
|
||||||
|
/// </summary>
|
||||||
|
private static AssetDeleteResult OnWillDeleteAsset(string path, RemoveAssetOptions options)
|
||||||
|
{
|
||||||
// Skip processing anything without the .cs extension
|
// Skip processing anything without the .cs extension
|
||||||
if (Path.GetExtension(path) != ".cs") return AssetDeleteResult.DidNotDelete;
|
if (Path.GetExtension(path) != ".cs")
|
||||||
|
{
|
||||||
|
return AssetDeleteResult.DidNotDelete;
|
||||||
|
}
|
||||||
|
|
||||||
// Get the object that is requested for deletion
|
// Get the object that is requested for deletion
|
||||||
UnityEngine.Object obj = AssetDatabase.LoadAssetAtPath<UnityEngine.Object> (path);
|
Object obj = AssetDatabase.LoadAssetAtPath<Object>(path);
|
||||||
|
|
||||||
// If we aren't deleting a script, return
|
// If we aren't deleting a script, return
|
||||||
if (!(obj is UnityEditor.MonoScript)) return AssetDeleteResult.DidNotDelete;
|
if (!(obj is MonoScript))
|
||||||
|
{
|
||||||
|
return AssetDeleteResult.DidNotDelete;
|
||||||
|
}
|
||||||
|
|
||||||
// Check script type. Return if deleting a non-node script
|
// Check script type. Return if deleting a non-node script
|
||||||
UnityEditor.MonoScript script = obj as UnityEditor.MonoScript;
|
MonoScript script = obj as MonoScript;
|
||||||
System.Type scriptType = script.GetClass ();
|
Type scriptType = script.GetClass();
|
||||||
if (scriptType == null || (scriptType != typeof (Node) && !scriptType.IsSubclassOf (typeof (Node)))) return AssetDeleteResult.DidNotDelete;
|
if (scriptType == null || scriptType != typeof(Node) && !scriptType.IsSubclassOf(typeof(Node)))
|
||||||
|
{
|
||||||
|
return AssetDeleteResult.DidNotDelete;
|
||||||
|
}
|
||||||
|
|
||||||
// Find all ScriptableObjects using this script
|
// Find all ScriptableObjects using this script
|
||||||
string[] guids = AssetDatabase.FindAssets ("t:" + scriptType);
|
string[] guids = AssetDatabase.FindAssets("t:" + scriptType);
|
||||||
for (int i = 0; i < guids.Length; i++) {
|
for (int i = 0; i < guids.Length; i++)
|
||||||
string assetpath = AssetDatabase.GUIDToAssetPath (guids[i]);
|
{
|
||||||
Object[] objs = AssetDatabase.LoadAllAssetRepresentationsAtPath (assetpath);
|
string assetpath = AssetDatabase.GUIDToAssetPath(guids[i]);
|
||||||
for (int k = 0; k < objs.Length; k++) {
|
var objs = AssetDatabase.LoadAllAssetRepresentationsAtPath(assetpath);
|
||||||
|
for (int k = 0; k < objs.Length; k++)
|
||||||
|
{
|
||||||
Node node = objs[k] as Node;
|
Node node = objs[k] as Node;
|
||||||
if (node.GetType () == scriptType) {
|
if (node.GetType() == scriptType)
|
||||||
if (node != null && node.graph != null) {
|
{
|
||||||
|
if (node != null && node.graph != null)
|
||||||
|
{
|
||||||
// Delete the node and notify the user
|
// Delete the node and notify the user
|
||||||
Debug.LogWarning (node.name + " of " + node.graph + " depended on deleted script and has been removed automatically.", node.graph);
|
Debug.LogWarning(
|
||||||
node.graph.RemoveNode (node);
|
node.name + " of " + node.graph +
|
||||||
|
" depended on deleted script and has been removed automatically.", node.graph);
|
||||||
|
node.graph.RemoveNode(node);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// We didn't actually delete the script. Tell the internal system to carry on with normal deletion procedure
|
// We didn't actually delete the script. Tell the internal system to carry on with normal deletion procedure
|
||||||
return AssetDeleteResult.DidNotDelete;
|
return AssetDeleteResult.DidNotDelete;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Automatically re-add loose node assets to the Graph node list </summary>
|
/// <summary> Automatically re-add loose node assets to the Graph node list </summary>
|
||||||
[InitializeOnLoadMethod]
|
[InitializeOnLoadMethod]
|
||||||
private static void OnReloadEditor () {
|
private static void OnReloadEditor()
|
||||||
|
{
|
||||||
// Find all NodeGraph assets
|
// Find all NodeGraph assets
|
||||||
string[] guids = AssetDatabase.FindAssets ("t:" + typeof (NodeGraph));
|
string[] guids = AssetDatabase.FindAssets("t:" + typeof(NodeGraph));
|
||||||
for (int i = 0; i < guids.Length; i++) {
|
for (int i = 0; i < guids.Length; i++)
|
||||||
string assetpath = AssetDatabase.GUIDToAssetPath (guids[i]);
|
{
|
||||||
NodeGraph graph = AssetDatabase.LoadAssetAtPath (assetpath, typeof (NodeGraph)) as NodeGraph;
|
string assetpath = AssetDatabase.GUIDToAssetPath(guids[i]);
|
||||||
|
NodeGraph graph = AssetDatabase.LoadAssetAtPath(assetpath, typeof(NodeGraph)) as NodeGraph;
|
||||||
graph.nodes.RemoveAll(x => x == null); //Remove null items
|
graph.nodes.RemoveAll(x => x == null); //Remove null items
|
||||||
Object[] objs = AssetDatabase.LoadAllAssetRepresentationsAtPath (assetpath);
|
var objs = AssetDatabase.LoadAllAssetRepresentationsAtPath(assetpath);
|
||||||
// Ensure that all sub node assets are present in the graph node list
|
// Ensure that all sub node assets are present in the graph node list
|
||||||
for (int u = 0; u < objs.Length; u++) {
|
for (int u = 0; u < objs.Length; u++)
|
||||||
|
{
|
||||||
// Ignore null sub assets
|
// Ignore null sub assets
|
||||||
if (objs[u] == null) continue;
|
if (objs[u] == null)
|
||||||
if (!graph.nodes.Contains (objs[u] as Node)) graph.nodes.Add(objs[u] as Node);
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!graph.nodes.Contains(objs[u] as Node))
|
||||||
|
{
|
||||||
|
graph.nodes.Add(objs[u] as Node);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -4,6 +4,7 @@ using System.Collections.Generic;
|
|||||||
using System.Reflection;
|
using System.Reflection;
|
||||||
using UnityEditor;
|
using UnityEditor;
|
||||||
using UnityEngine;
|
using UnityEngine;
|
||||||
|
using XNode;
|
||||||
#if ODIN_INSPECTOR
|
#if ODIN_INSPECTOR
|
||||||
using Sirenix.OdinInspector.Editor;
|
using Sirenix.OdinInspector.Editor;
|
||||||
#endif
|
#endif
|
||||||
|
|||||||
@ -1,29 +1,38 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Reflection;
|
||||||
using UnityEditor;
|
using UnityEditor;
|
||||||
using UnityEngine;
|
using UnityEngine;
|
||||||
|
using XNode;
|
||||||
using XNodeEditor.Internal;
|
using XNodeEditor.Internal;
|
||||||
|
using Object = UnityEngine.Object;
|
||||||
#if UNITY_2019_1_OR_NEWER && USE_ADVANCED_GENERIC_MENU
|
#if UNITY_2019_1_OR_NEWER && USE_ADVANCED_GENERIC_MENU
|
||||||
using GenericMenu = XNodeEditor.AdvancedGenericMenu;
|
using GenericMenu = XNodeEditor.AdvancedGenericMenu;
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
namespace XNodeEditor {
|
namespace XNodeEditor
|
||||||
|
{
|
||||||
/// <summary> Contains GUI methods </summary>
|
/// <summary> Contains GUI methods </summary>
|
||||||
public partial class NodeEditorWindow {
|
public partial class NodeEditorWindow
|
||||||
|
{
|
||||||
public NodeGraphEditor graphEditor;
|
public NodeGraphEditor graphEditor;
|
||||||
private List<UnityEngine.Object> selectionCache;
|
private List<Object> selectionCache;
|
||||||
private List<Node> culledNodes;
|
private List<Node> culledNodes;
|
||||||
/// <summary> 19 if docked, 22 if not </summary>
|
/// <summary> 19 if docked, 22 if not </summary>
|
||||||
private int topPadding { get { return isDocked() ? 19 : 22; } }
|
private int topPadding => isDocked() ? 19 : 22;
|
||||||
/// <summary> Executed after all other window GUI. Useful if Zoom is ruining your day. Automatically resets after being run.</summary>
|
/// <summary> Executed after all other window GUI. Useful if Zoom is ruining your day. Automatically resets after being run.</summary>
|
||||||
public event Action onLateGUI;
|
public event Action onLateGUI;
|
||||||
private static readonly Vector3[] polyLineTempArray = new Vector3[2];
|
private static readonly Vector3[] polyLineTempArray = new Vector3[2];
|
||||||
|
|
||||||
protected virtual void OnGUI() {
|
protected virtual void OnGUI()
|
||||||
|
{
|
||||||
Event e = Event.current;
|
Event e = Event.current;
|
||||||
Matrix4x4 m = GUI.matrix;
|
Matrix4x4 m = GUI.matrix;
|
||||||
if (graph == null) return;
|
if (graph == null)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
ValidateGraphEditor();
|
ValidateGraphEditor();
|
||||||
Controls();
|
Controls();
|
||||||
|
|
||||||
@ -36,7 +45,8 @@ namespace XNodeEditor {
|
|||||||
graphEditor.OnGUI();
|
graphEditor.OnGUI();
|
||||||
|
|
||||||
// Run and reset onLateGUI
|
// Run and reset onLateGUI
|
||||||
if (onLateGUI != null) {
|
if (onLateGUI != null)
|
||||||
|
{
|
||||||
onLateGUI();
|
onLateGUI();
|
||||||
onLateGUI = null;
|
onLateGUI = null;
|
||||||
}
|
}
|
||||||
@ -44,28 +54,31 @@ namespace XNodeEditor {
|
|||||||
GUI.matrix = m;
|
GUI.matrix = m;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void BeginZoomed(Rect rect, float zoom, float topPadding) {
|
public static void BeginZoomed(Rect rect, float zoom, float topPadding)
|
||||||
|
{
|
||||||
GUI.EndClip();
|
GUI.EndClip();
|
||||||
|
|
||||||
GUIUtility.ScaleAroundPivot(Vector2.one / zoom, rect.size * 0.5f);
|
GUIUtility.ScaleAroundPivot(Vector2.one / zoom, rect.size * 0.5f);
|
||||||
Vector4 padding = new Vector4(0, topPadding, 0, 0);
|
Vector4 padding = new Vector4(0, topPadding, 0, 0);
|
||||||
padding *= zoom;
|
padding *= zoom;
|
||||||
GUI.BeginClip(new Rect(-((rect.width * zoom) - rect.width) * 0.5f, -(((rect.height * zoom) - rect.height) * 0.5f) + (topPadding * zoom),
|
GUI.BeginClip(new Rect(-(rect.width * zoom - rect.width) * 0.5f,
|
||||||
|
-((rect.height * zoom - rect.height) * 0.5f) + topPadding * zoom,
|
||||||
rect.width * zoom,
|
rect.width * zoom,
|
||||||
rect.height * zoom));
|
rect.height * zoom));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void EndZoomed(Rect rect, float zoom, float topPadding) {
|
public static void EndZoomed(Rect rect, float zoom, float topPadding)
|
||||||
|
{
|
||||||
GUIUtility.ScaleAroundPivot(Vector2.one * zoom, rect.size * 0.5f);
|
GUIUtility.ScaleAroundPivot(Vector2.one * zoom, rect.size * 0.5f);
|
||||||
Vector3 offset = new Vector3(
|
Vector3 offset = new Vector3(
|
||||||
(((rect.width * zoom) - rect.width) * 0.5f),
|
(rect.width * zoom - rect.width) * 0.5f,
|
||||||
(((rect.height * zoom) - rect.height) * 0.5f) + (-topPadding * zoom) + topPadding,
|
(rect.height * zoom - rect.height) * 0.5f + -topPadding * zoom + topPadding,
|
||||||
0);
|
0);
|
||||||
GUI.matrix = Matrix4x4.TRS(offset, Quaternion.identity, Vector3.one);
|
GUI.matrix = Matrix4x4.TRS(offset, Quaternion.identity, Vector3.one);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void DrawGrid(Rect rect, float zoom, Vector2 panOffset) {
|
public void DrawGrid(Rect rect, float zoom, Vector2 panOffset)
|
||||||
|
{
|
||||||
rect.position = Vector2.zero;
|
rect.position = Vector2.zero;
|
||||||
|
|
||||||
Vector2 center = rect.size / 2f;
|
Vector2 center = rect.size / 2f;
|
||||||
@ -89,8 +102,10 @@ namespace XNodeEditor {
|
|||||||
GUI.DrawTextureWithTexCoords(rect, crossTex, new Rect(tileOffset + new Vector2(0.5f, 0.5f), tileAmount));
|
GUI.DrawTextureWithTexCoords(rect, crossTex, new Rect(tileOffset + new Vector2(0.5f, 0.5f), tileAmount));
|
||||||
}
|
}
|
||||||
|
|
||||||
public void DrawSelectionBox() {
|
public void DrawSelectionBox()
|
||||||
if (currentActivity == NodeActivity.DragGrid) {
|
{
|
||||||
|
if (currentActivity == NodeActivity.DragGrid)
|
||||||
|
{
|
||||||
Vector2 curPos = WindowToGridPosition(Event.current.mousePosition);
|
Vector2 curPos = WindowToGridPosition(Event.current.mousePosition);
|
||||||
Vector2 size = curPos - dragBoxStart;
|
Vector2 size = curPos - dragBoxStart;
|
||||||
Rect r = new Rect(dragBoxStart, size);
|
Rect r = new Rect(dragBoxStart, size);
|
||||||
@ -100,52 +115,72 @@ namespace XNodeEditor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static bool DropdownButton(string name, float width) {
|
public static bool DropdownButton(string name, float width)
|
||||||
|
{
|
||||||
return GUILayout.Button(name, EditorStyles.toolbarDropDown, GUILayout.Width(width));
|
return GUILayout.Button(name, EditorStyles.toolbarDropDown, GUILayout.Width(width));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Show right-click context menu for hovered reroute </summary>
|
/// <summary> Show right-click context menu for hovered reroute </summary>
|
||||||
void ShowRerouteContextMenu(RerouteReference reroute) {
|
private void ShowRerouteContextMenu(RerouteReference reroute)
|
||||||
|
{
|
||||||
GenericMenu contextMenu = new GenericMenu();
|
GenericMenu contextMenu = new GenericMenu();
|
||||||
contextMenu.AddItem(new GUIContent("Remove"), false, () => reroute.RemovePoint());
|
contextMenu.AddItem(new GUIContent("Remove"), false, () => reroute.RemovePoint());
|
||||||
contextMenu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero));
|
contextMenu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero));
|
||||||
if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets();
|
if (NodeEditorPreferences.GetSettings().autoSave)
|
||||||
|
{
|
||||||
|
AssetDatabase.SaveAssets();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Show right-click context menu for hovered port </summary>
|
/// <summary> Show right-click context menu for hovered port </summary>
|
||||||
void ShowPortContextMenu(NodePort hoveredPort) {
|
private void ShowPortContextMenu(NodePort hoveredPort)
|
||||||
|
{
|
||||||
GenericMenu contextMenu = new GenericMenu();
|
GenericMenu contextMenu = new GenericMenu();
|
||||||
foreach (var port in hoveredPort.GetConnections()) {
|
foreach (NodePort port in hoveredPort.GetConnections())
|
||||||
var name = port.node.name;
|
{
|
||||||
var index = hoveredPort.GetConnectionIndex(port);
|
string name = port.node.name;
|
||||||
contextMenu.AddItem(new GUIContent(string.Format("Disconnect({0})", name)), false, () => hoveredPort.Disconnect(index));
|
int index = hoveredPort.GetConnectionIndex(port);
|
||||||
|
contextMenu.AddItem(new GUIContent(string.Format("Disconnect({0})", name)), false,
|
||||||
|
() => hoveredPort.Disconnect(index));
|
||||||
}
|
}
|
||||||
|
|
||||||
contextMenu.AddItem(new GUIContent("Clear Connections"), false, () => hoveredPort.ClearConnections());
|
contextMenu.AddItem(new GUIContent("Clear Connections"), false, () => hoveredPort.ClearConnections());
|
||||||
//Get compatible nodes with this port
|
//Get compatible nodes with this port
|
||||||
if (NodeEditorPreferences.GetSettings().createFilter) {
|
if (NodeEditorPreferences.GetSettings().createFilter)
|
||||||
|
{
|
||||||
contextMenu.AddSeparator("");
|
contextMenu.AddSeparator("");
|
||||||
|
|
||||||
if (hoveredPort.direction == NodePort.IO.Input)
|
if (hoveredPort.direction == NodePort.IO.Input)
|
||||||
|
{
|
||||||
graphEditor.AddContextMenuItems(contextMenu, hoveredPort.ValueType, NodePort.IO.Output);
|
graphEditor.AddContextMenuItems(contextMenu, hoveredPort.ValueType, NodePort.IO.Output);
|
||||||
|
}
|
||||||
else
|
else
|
||||||
|
{
|
||||||
graphEditor.AddContextMenuItems(contextMenu, hoveredPort.ValueType, NodePort.IO.Input);
|
graphEditor.AddContextMenuItems(contextMenu, hoveredPort.ValueType, NodePort.IO.Input);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
contextMenu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero));
|
contextMenu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero));
|
||||||
if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets();
|
if (NodeEditorPreferences.GetSettings().autoSave)
|
||||||
|
{
|
||||||
|
AssetDatabase.SaveAssets();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static Vector2 CalculateBezierPoint(Vector2 p0, Vector2 p1, Vector2 p2, Vector2 p3, float t) {
|
private static Vector2 CalculateBezierPoint(Vector2 p0, Vector2 p1, Vector2 p2, Vector2 p3, float t)
|
||||||
|
{
|
||||||
float u = 1 - t;
|
float u = 1 - t;
|
||||||
float tt = t * t, uu = u * u;
|
float tt = t * t, uu = u * u;
|
||||||
float uuu = uu * u, ttt = tt * t;
|
float uuu = uu * u, ttt = tt * t;
|
||||||
return new Vector2(
|
return new Vector2(
|
||||||
(uuu * p0.x) + (3 * uu * t * p1.x) + (3 * u * tt * p2.x) + (ttt * p3.x),
|
uuu * p0.x + 3 * uu * t * p1.x + 3 * u * tt * p2.x + ttt * p3.x,
|
||||||
(uuu * p0.y) + (3 * uu * t * p1.y) + (3 * u * tt * p2.y) + (ttt * p3.y)
|
uuu * p0.y + 3 * uu * t * p1.y + 3 * u * tt * p2.y + ttt * p3.y
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Draws a line segment without allocating temporary arrays </summary>
|
/// <summary> Draws a line segment without allocating temporary arrays </summary>
|
||||||
static void DrawAAPolyLineNonAlloc(float thickness, Vector2 p0, Vector2 p1) {
|
private static void DrawAAPolyLineNonAlloc(float thickness, Vector2 p0, Vector2 p1)
|
||||||
|
{
|
||||||
polyLineTempArray[0].x = p0.x;
|
polyLineTempArray[0].x = p0.x;
|
||||||
polyLineTempArray[0].y = p0.y;
|
polyLineTempArray[0].y = p0.y;
|
||||||
polyLineTempArray[1].x = p1.x;
|
polyLineTempArray[1].x = p1.x;
|
||||||
@ -154,36 +189,49 @@ namespace XNodeEditor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Draw a bezier from output to input in grid coordinates </summary>
|
/// <summary> Draw a bezier from output to input in grid coordinates </summary>
|
||||||
public void DrawNoodle(Gradient gradient, NoodlePath path, NoodleStroke stroke, float thickness, List<Vector2> gridPoints) {
|
public void DrawNoodle(Gradient gradient, NoodlePath path, NoodleStroke stroke, float thickness,
|
||||||
|
List<Vector2> gridPoints)
|
||||||
|
{
|
||||||
// convert grid points to window points
|
// convert grid points to window points
|
||||||
for (int i = 0; i < gridPoints.Count; ++i)
|
for (int i = 0; i < gridPoints.Count; ++i)
|
||||||
|
{
|
||||||
gridPoints[i] = GridToWindowPosition(gridPoints[i]);
|
gridPoints[i] = GridToWindowPosition(gridPoints[i]);
|
||||||
|
}
|
||||||
|
|
||||||
Color originalHandlesColor = Handles.color;
|
Color originalHandlesColor = Handles.color;
|
||||||
Handles.color = gradient.Evaluate(0f);
|
Handles.color = gradient.Evaluate(0f);
|
||||||
int length = gridPoints.Count;
|
int length = gridPoints.Count;
|
||||||
switch (path) {
|
switch (path)
|
||||||
|
{
|
||||||
case NoodlePath.Curvy:
|
case NoodlePath.Curvy:
|
||||||
Vector2 outputTangent = Vector2.right;
|
Vector2 outputTangent = Vector2.right;
|
||||||
for (int i = 0; i < length - 1; i++) {
|
for (int i = 0; i < length - 1; i++)
|
||||||
|
{
|
||||||
Vector2 inputTangent;
|
Vector2 inputTangent;
|
||||||
// Cached most variables that repeat themselves here to avoid so many indexer calls :p
|
// Cached most variables that repeat themselves here to avoid so many indexer calls :p
|
||||||
Vector2 point_a = gridPoints[i];
|
Vector2 point_a = gridPoints[i];
|
||||||
Vector2 point_b = gridPoints[i + 1];
|
Vector2 point_b = gridPoints[i + 1];
|
||||||
float dist_ab = Vector2.Distance(point_a, point_b);
|
float dist_ab = Vector2.Distance(point_a, point_b);
|
||||||
if (i == 0) outputTangent = zoom * dist_ab * 0.01f * Vector2.right;
|
if (i == 0)
|
||||||
if (i < length - 2) {
|
{
|
||||||
|
outputTangent = zoom * dist_ab * 0.01f * Vector2.right;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (i < length - 2)
|
||||||
|
{
|
||||||
Vector2 point_c = gridPoints[i + 2];
|
Vector2 point_c = gridPoints[i + 2];
|
||||||
Vector2 ab = (point_b - point_a).normalized;
|
Vector2 ab = (point_b - point_a).normalized;
|
||||||
Vector2 cb = (point_b - point_c).normalized;
|
Vector2 cb = (point_b - point_c).normalized;
|
||||||
Vector2 ac = (point_c - point_a).normalized;
|
Vector2 ac = (point_c - point_a).normalized;
|
||||||
Vector2 p = (ab + cb) * 0.5f;
|
Vector2 p = (ab + cb) * 0.5f;
|
||||||
float tangentLength = (dist_ab + Vector2.Distance(point_b, point_c)) * 0.005f * zoom;
|
float tangentLength = (dist_ab + Vector2.Distance(point_b, point_c)) * 0.005f * zoom;
|
||||||
float side = ((ac.x * (point_b.y - point_a.y)) - (ac.y * (point_b.x - point_a.x)));
|
float side = ac.x * (point_b.y - point_a.y) - ac.y * (point_b.x - point_a.x);
|
||||||
|
|
||||||
p = tangentLength * Mathf.Sign(side) * new Vector2(-p.y, p.x);
|
p = tangentLength * Mathf.Sign(side) * new Vector2(-p.y, p.x);
|
||||||
inputTangent = p;
|
inputTangent = p;
|
||||||
} else {
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
inputTangent = zoom * dist_ab * 0.01f * Vector2.left;
|
inputTangent = zoom * dist_ab * 0.01f * Vector2.left;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -196,67 +244,111 @@ namespace XNodeEditor {
|
|||||||
// Coloring and bezier drawing.
|
// Coloring and bezier drawing.
|
||||||
int draw = 0;
|
int draw = 0;
|
||||||
Vector2 bezierPrevious = point_a;
|
Vector2 bezierPrevious = point_a;
|
||||||
for (int j = 1; j <= division; ++j) {
|
for (int j = 1; j <= division; ++j)
|
||||||
if (stroke == NoodleStroke.Dashed) {
|
{
|
||||||
|
if (stroke == NoodleStroke.Dashed)
|
||||||
|
{
|
||||||
draw++;
|
draw++;
|
||||||
if (draw >= 2) draw = -2;
|
if (draw >= 2)
|
||||||
if (draw < 0) continue;
|
{
|
||||||
if (draw == 0) bezierPrevious = CalculateBezierPoint(point_a, tangent_a, tangent_b, point_b, (j - 1f) / (float) division);
|
draw = -2;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (draw < 0)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (draw == 0)
|
||||||
|
{
|
||||||
|
bezierPrevious = CalculateBezierPoint(point_a, tangent_a, tangent_b, point_b,
|
||||||
|
(j - 1f) / division);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (i == length - 2)
|
if (i == length - 2)
|
||||||
|
{
|
||||||
Handles.color = gradient.Evaluate((j + 1f) / division);
|
Handles.color = gradient.Evaluate((j + 1f) / division);
|
||||||
Vector2 bezierNext = CalculateBezierPoint(point_a, tangent_a, tangent_b, point_b, j / (float) division);
|
}
|
||||||
|
|
||||||
|
Vector2 bezierNext = CalculateBezierPoint(point_a, tangent_a, tangent_b, point_b,
|
||||||
|
j / (float)division);
|
||||||
DrawAAPolyLineNonAlloc(thickness, bezierPrevious, bezierNext);
|
DrawAAPolyLineNonAlloc(thickness, bezierPrevious, bezierNext);
|
||||||
bezierPrevious = bezierNext;
|
bezierPrevious = bezierNext;
|
||||||
}
|
}
|
||||||
|
|
||||||
outputTangent = -inputTangent;
|
outputTangent = -inputTangent;
|
||||||
}
|
}
|
||||||
|
|
||||||
break;
|
break;
|
||||||
case NoodlePath.Straight:
|
case NoodlePath.Straight:
|
||||||
for (int i = 0; i < length - 1; i++) {
|
for (int i = 0; i < length - 1; i++)
|
||||||
|
{
|
||||||
Vector2 point_a = gridPoints[i];
|
Vector2 point_a = gridPoints[i];
|
||||||
Vector2 point_b = gridPoints[i + 1];
|
Vector2 point_b = gridPoints[i + 1];
|
||||||
// Draws the line with the coloring.
|
// Draws the line with the coloring.
|
||||||
Vector2 prev_point = point_a;
|
Vector2 prev_point = point_a;
|
||||||
// Approximately one segment per 5 pixels
|
// Approximately one segment per 5 pixels
|
||||||
int segments = (int) Vector2.Distance(point_a, point_b) / 5;
|
int segments = (int)Vector2.Distance(point_a, point_b) / 5;
|
||||||
segments = Math.Max(segments, 1);
|
segments = Math.Max(segments, 1);
|
||||||
|
|
||||||
int draw = 0;
|
int draw = 0;
|
||||||
for (int j = 0; j <= segments; j++) {
|
for (int j = 0; j <= segments; j++)
|
||||||
|
{
|
||||||
draw++;
|
draw++;
|
||||||
float t = j / (float) segments;
|
float t = j / (float)segments;
|
||||||
Vector2 lerp = Vector2.Lerp(point_a, point_b, t);
|
Vector2 lerp = Vector2.Lerp(point_a, point_b, t);
|
||||||
if (draw > 0) {
|
if (draw > 0)
|
||||||
if (i == length - 2) Handles.color = gradient.Evaluate(t);
|
{
|
||||||
|
if (i == length - 2)
|
||||||
|
{
|
||||||
|
Handles.color = gradient.Evaluate(t);
|
||||||
|
}
|
||||||
|
|
||||||
DrawAAPolyLineNonAlloc(thickness, prev_point, lerp);
|
DrawAAPolyLineNonAlloc(thickness, prev_point, lerp);
|
||||||
}
|
}
|
||||||
|
|
||||||
prev_point = lerp;
|
prev_point = lerp;
|
||||||
if (stroke == NoodleStroke.Dashed && draw >= 2) draw = -2;
|
if (stroke == NoodleStroke.Dashed && draw >= 2)
|
||||||
|
{
|
||||||
|
draw = -2;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
break;
|
break;
|
||||||
case NoodlePath.Angled:
|
case NoodlePath.Angled:
|
||||||
for (int i = 0; i < length - 1; i++) {
|
for (int i = 0; i < length - 1; i++)
|
||||||
if (i == length - 1) continue; // Skip last index
|
{
|
||||||
if (gridPoints[i].x <= gridPoints[i + 1].x - (50 / zoom)) {
|
if (i == length - 1)
|
||||||
|
{
|
||||||
|
continue; // Skip last index
|
||||||
|
}
|
||||||
|
|
||||||
|
if (gridPoints[i].x <= gridPoints[i + 1].x - 50 / zoom)
|
||||||
|
{
|
||||||
float midpoint = (gridPoints[i].x + gridPoints[i + 1].x) * 0.5f;
|
float midpoint = (gridPoints[i].x + gridPoints[i + 1].x) * 0.5f;
|
||||||
Vector2 start_1 = gridPoints[i];
|
Vector2 start_1 = gridPoints[i];
|
||||||
Vector2 end_1 = gridPoints[i + 1];
|
Vector2 end_1 = gridPoints[i + 1];
|
||||||
start_1.x = midpoint;
|
start_1.x = midpoint;
|
||||||
end_1.x = midpoint;
|
end_1.x = midpoint;
|
||||||
if (i == length - 2) {
|
if (i == length - 2)
|
||||||
|
{
|
||||||
DrawAAPolyLineNonAlloc(thickness, gridPoints[i], start_1);
|
DrawAAPolyLineNonAlloc(thickness, gridPoints[i], start_1);
|
||||||
Handles.color = gradient.Evaluate(0.5f);
|
Handles.color = gradient.Evaluate(0.5f);
|
||||||
DrawAAPolyLineNonAlloc(thickness, start_1, end_1);
|
DrawAAPolyLineNonAlloc(thickness, start_1, end_1);
|
||||||
Handles.color = gradient.Evaluate(1f);
|
Handles.color = gradient.Evaluate(1f);
|
||||||
DrawAAPolyLineNonAlloc(thickness, end_1, gridPoints[i + 1]);
|
DrawAAPolyLineNonAlloc(thickness, end_1, gridPoints[i + 1]);
|
||||||
} else {
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
DrawAAPolyLineNonAlloc(thickness, gridPoints[i], start_1);
|
DrawAAPolyLineNonAlloc(thickness, gridPoints[i], start_1);
|
||||||
DrawAAPolyLineNonAlloc(thickness, start_1, end_1);
|
DrawAAPolyLineNonAlloc(thickness, start_1, end_1);
|
||||||
DrawAAPolyLineNonAlloc(thickness, end_1, gridPoints[i + 1]);
|
DrawAAPolyLineNonAlloc(thickness, end_1, gridPoints[i + 1]);
|
||||||
}
|
}
|
||||||
} else {
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
float midpoint = (gridPoints[i].y + gridPoints[i + 1].y) * 0.5f;
|
float midpoint = (gridPoints[i].y + gridPoints[i + 1].y) * 0.5f;
|
||||||
Vector2 start_1 = gridPoints[i];
|
Vector2 start_1 = gridPoints[i];
|
||||||
Vector2 end_1 = gridPoints[i + 1];
|
Vector2 end_1 = gridPoints[i + 1];
|
||||||
@ -266,7 +358,8 @@ namespace XNodeEditor {
|
|||||||
Vector2 end_2 = end_1;
|
Vector2 end_2 = end_1;
|
||||||
start_2.y = midpoint;
|
start_2.y = midpoint;
|
||||||
end_2.y = midpoint;
|
end_2.y = midpoint;
|
||||||
if (i == length - 2) {
|
if (i == length - 2)
|
||||||
|
{
|
||||||
DrawAAPolyLineNonAlloc(thickness, gridPoints[i], start_1);
|
DrawAAPolyLineNonAlloc(thickness, gridPoints[i], start_1);
|
||||||
Handles.color = gradient.Evaluate(0.25f);
|
Handles.color = gradient.Evaluate(0.25f);
|
||||||
DrawAAPolyLineNonAlloc(thickness, start_1, start_2);
|
DrawAAPolyLineNonAlloc(thickness, start_1, start_2);
|
||||||
@ -276,7 +369,9 @@ namespace XNodeEditor {
|
|||||||
DrawAAPolyLineNonAlloc(thickness, end_2, end_1);
|
DrawAAPolyLineNonAlloc(thickness, end_2, end_1);
|
||||||
Handles.color = gradient.Evaluate(1f);
|
Handles.color = gradient.Evaluate(1f);
|
||||||
DrawAAPolyLineNonAlloc(thickness, end_1, gridPoints[i + 1]);
|
DrawAAPolyLineNonAlloc(thickness, end_1, gridPoints[i + 1]);
|
||||||
} else {
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
DrawAAPolyLineNonAlloc(thickness, gridPoints[i], start_1);
|
DrawAAPolyLineNonAlloc(thickness, gridPoints[i], start_1);
|
||||||
DrawAAPolyLineNonAlloc(thickness, start_1, start_2);
|
DrawAAPolyLineNonAlloc(thickness, start_1, start_2);
|
||||||
DrawAAPolyLineNonAlloc(thickness, start_2, end_2);
|
DrawAAPolyLineNonAlloc(thickness, start_2, end_2);
|
||||||
@ -285,6 +380,7 @@ namespace XNodeEditor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
break;
|
break;
|
||||||
case NoodlePath.ShaderLab:
|
case NoodlePath.ShaderLab:
|
||||||
Vector2 start = gridPoints[0];
|
Vector2 start = gridPoints[0];
|
||||||
@ -297,58 +393,83 @@ namespace XNodeEditor {
|
|||||||
DrawAAPolyLineNonAlloc(thickness, start, gridPoints[0]);
|
DrawAAPolyLineNonAlloc(thickness, start, gridPoints[0]);
|
||||||
Handles.color = gradient.Evaluate(1f);
|
Handles.color = gradient.Evaluate(1f);
|
||||||
DrawAAPolyLineNonAlloc(thickness, end, gridPoints[length - 1]);
|
DrawAAPolyLineNonAlloc(thickness, end, gridPoints[length - 1]);
|
||||||
for (int i = 0; i < length - 1; i++) {
|
for (int i = 0; i < length - 1; i++)
|
||||||
|
{
|
||||||
Vector2 point_a = gridPoints[i];
|
Vector2 point_a = gridPoints[i];
|
||||||
Vector2 point_b = gridPoints[i + 1];
|
Vector2 point_b = gridPoints[i + 1];
|
||||||
// Draws the line with the coloring.
|
// Draws the line with the coloring.
|
||||||
Vector2 prev_point = point_a;
|
Vector2 prev_point = point_a;
|
||||||
// Approximately one segment per 5 pixels
|
// Approximately one segment per 5 pixels
|
||||||
int segments = (int) Vector2.Distance(point_a, point_b) / 5;
|
int segments = (int)Vector2.Distance(point_a, point_b) / 5;
|
||||||
segments = Math.Max(segments, 1);
|
segments = Math.Max(segments, 1);
|
||||||
|
|
||||||
int draw = 0;
|
int draw = 0;
|
||||||
for (int j = 0; j <= segments; j++) {
|
for (int j = 0; j <= segments; j++)
|
||||||
|
{
|
||||||
draw++;
|
draw++;
|
||||||
float t = j / (float) segments;
|
float t = j / (float)segments;
|
||||||
Vector2 lerp = Vector2.Lerp(point_a, point_b, t);
|
Vector2 lerp = Vector2.Lerp(point_a, point_b, t);
|
||||||
if (draw > 0) {
|
if (draw > 0)
|
||||||
if (i == length - 2) Handles.color = gradient.Evaluate(t);
|
{
|
||||||
|
if (i == length - 2)
|
||||||
|
{
|
||||||
|
Handles.color = gradient.Evaluate(t);
|
||||||
|
}
|
||||||
|
|
||||||
DrawAAPolyLineNonAlloc(thickness, prev_point, lerp);
|
DrawAAPolyLineNonAlloc(thickness, prev_point, lerp);
|
||||||
}
|
}
|
||||||
|
|
||||||
prev_point = lerp;
|
prev_point = lerp;
|
||||||
if (stroke == NoodleStroke.Dashed && draw >= 2) draw = -2;
|
if (stroke == NoodleStroke.Dashed && draw >= 2)
|
||||||
|
{
|
||||||
|
draw = -2;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
gridPoints[0] = start;
|
gridPoints[0] = start;
|
||||||
gridPoints[length - 1] = end;
|
gridPoints[length - 1] = end;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
Handles.color = originalHandlesColor;
|
Handles.color = originalHandlesColor;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Draws all connections </summary>
|
/// <summary> Draws all connections </summary>
|
||||||
public void DrawConnections() {
|
public void DrawConnections()
|
||||||
|
{
|
||||||
Vector2 mousePos = Event.current.mousePosition;
|
Vector2 mousePos = Event.current.mousePosition;
|
||||||
List<RerouteReference> selection = preBoxSelectionReroute != null ? new List<RerouteReference>(preBoxSelectionReroute) : new List<RerouteReference>();
|
var selection = preBoxSelectionReroute != null
|
||||||
|
? new List<RerouteReference>(preBoxSelectionReroute)
|
||||||
|
: new List<RerouteReference>();
|
||||||
hoveredReroute = new RerouteReference();
|
hoveredReroute = new RerouteReference();
|
||||||
|
|
||||||
List<Vector2> gridPoints = new List<Vector2>(2);
|
var gridPoints = new List<Vector2>(2);
|
||||||
|
|
||||||
Color col = GUI.color;
|
Color col = GUI.color;
|
||||||
foreach (Node node in graph.nodes) {
|
foreach (Node node in graph.nodes)
|
||||||
|
{
|
||||||
//If a null node is found, return. This can happen if the nodes associated script is deleted. It is currently not possible in Unity to delete a null asset.
|
//If a null node is found, return. This can happen if the nodes associated script is deleted. It is currently not possible in Unity to delete a null asset.
|
||||||
if (node == null) continue;
|
if (node == null)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
// Draw full connections and output > reroute
|
// Draw full connections and output > reroute
|
||||||
foreach (NodePort output in node.Outputs) {
|
foreach (NodePort output in node.Outputs)
|
||||||
|
{
|
||||||
//Needs cleanup. Null checks are ugly
|
//Needs cleanup. Null checks are ugly
|
||||||
Rect fromRect;
|
Rect fromRect;
|
||||||
if (!_portConnectionPoints.TryGetValue(output, out fromRect)) continue;
|
if (!portConnectionPoints.TryGetValue(output, out fromRect))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
Color portColor = graphEditor.GetPortColor(output);
|
Color portColor = graphEditor.GetPortColor(output);
|
||||||
GUIStyle portStyle = graphEditor.GetPortStyle(output);
|
GUIStyle portStyle = graphEditor.GetPortStyle(output);
|
||||||
|
|
||||||
for (int k = 0; k < output.ConnectionCount; k++) {
|
for (int k = 0; k < output.ConnectionCount; k++)
|
||||||
|
{
|
||||||
NodePort input = output.GetConnection(k);
|
NodePort input = output.GetConnection(k);
|
||||||
|
|
||||||
Gradient noodleGradient = graphEditor.GetNoodleGradient(output, input);
|
Gradient noodleGradient = graphEditor.GetNoodleGradient(output, input);
|
||||||
@ -357,12 +478,23 @@ namespace XNodeEditor {
|
|||||||
NoodleStroke noodleStroke = graphEditor.GetNoodleStroke(output, input);
|
NoodleStroke noodleStroke = graphEditor.GetNoodleStroke(output, input);
|
||||||
|
|
||||||
// Error handling
|
// Error handling
|
||||||
if (input == null) continue; //If a script has been updated and the port doesn't exist, it is removed and null is returned. If this happens, return.
|
if (input == null)
|
||||||
if (!input.IsConnectedTo(output)) input.Connect(output);
|
{
|
||||||
Rect toRect;
|
continue; //If a script has been updated and the port doesn't exist, it is removed and null is returned. If this happens, return.
|
||||||
if (!_portConnectionPoints.TryGetValue(input, out toRect)) continue;
|
}
|
||||||
|
|
||||||
List<Vector2> reroutePoints = output.GetReroutePoints(k);
|
if (!input.IsConnectedTo(output))
|
||||||
|
{
|
||||||
|
input.Connect(output);
|
||||||
|
}
|
||||||
|
|
||||||
|
Rect toRect;
|
||||||
|
if (!portConnectionPoints.TryGetValue(input, out toRect))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var reroutePoints = output.GetReroutePoints(k);
|
||||||
|
|
||||||
gridPoints.Clear();
|
gridPoints.Clear();
|
||||||
gridPoints.Add(fromRect.center);
|
gridPoints.Add(fromRect.center);
|
||||||
@ -371,7 +503,8 @@ namespace XNodeEditor {
|
|||||||
DrawNoodle(noodleGradient, noodlePath, noodleStroke, noodleThickness, gridPoints);
|
DrawNoodle(noodleGradient, noodlePath, noodleStroke, noodleThickness, gridPoints);
|
||||||
|
|
||||||
// Loop through reroute points again and draw the points
|
// Loop through reroute points again and draw the points
|
||||||
for (int i = 0; i < reroutePoints.Count; i++) {
|
for (int i = 0; i < reroutePoints.Count; i++)
|
||||||
|
{
|
||||||
RerouteReference rerouteRef = new RerouteReference(output, k, i);
|
RerouteReference rerouteRef = new RerouteReference(output, k, i);
|
||||||
// Draw reroute point at position
|
// Draw reroute point at position
|
||||||
Rect rect = new Rect(reroutePoints[i], new Vector2(12, 12));
|
Rect rect = new Rect(reroutePoints[i], new Vector2(12, 12));
|
||||||
@ -379,80 +512,137 @@ namespace XNodeEditor {
|
|||||||
rect = GridToWindowRect(rect);
|
rect = GridToWindowRect(rect);
|
||||||
|
|
||||||
// Draw selected reroute points with an outline
|
// Draw selected reroute points with an outline
|
||||||
if (selectedReroutes.Contains(rerouteRef)) {
|
if (selectedReroutes.Contains(rerouteRef))
|
||||||
|
{
|
||||||
GUI.color = NodeEditorPreferences.GetSettings().highlightColor;
|
GUI.color = NodeEditorPreferences.GetSettings().highlightColor;
|
||||||
GUI.DrawTexture(rect, portStyle.normal.background);
|
GUI.DrawTexture(rect, portStyle.normal.background);
|
||||||
}
|
}
|
||||||
|
|
||||||
GUI.color = portColor;
|
GUI.color = portColor;
|
||||||
GUI.DrawTexture(rect, portStyle.active.background);
|
GUI.DrawTexture(rect, portStyle.active.background);
|
||||||
if (rect.Overlaps(selectionBox)) selection.Add(rerouteRef);
|
if (rect.Overlaps(selectionBox))
|
||||||
if (rect.Contains(mousePos)) hoveredReroute = rerouteRef;
|
{
|
||||||
|
selection.Add(rerouteRef);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (rect.Contains(mousePos))
|
||||||
|
{
|
||||||
|
hoveredReroute = rerouteRef;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
GUI.color = col;
|
GUI.color = col;
|
||||||
if (Event.current.type != EventType.Layout && currentActivity == NodeActivity.DragGrid) selectedReroutes = selection;
|
if (Event.current.type != EventType.Layout && currentActivity == NodeActivity.DragGrid)
|
||||||
|
{
|
||||||
|
selectedReroutes = selection;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void DrawNodes() {
|
private void DrawNodes()
|
||||||
|
{
|
||||||
Event e = Event.current;
|
Event e = Event.current;
|
||||||
if (e.type == EventType.Layout) {
|
if (e.type == EventType.Layout)
|
||||||
selectionCache = new List<UnityEngine.Object>(Selection.objects);
|
{
|
||||||
|
selectionCache = new List<Object>(Selection.objects);
|
||||||
}
|
}
|
||||||
|
|
||||||
System.Reflection.MethodInfo onValidate = null;
|
MethodInfo onValidate = null;
|
||||||
if (Selection.activeObject != null && Selection.activeObject is Node) {
|
if (Selection.activeObject != null && Selection.activeObject is Node)
|
||||||
|
{
|
||||||
onValidate = Selection.activeObject.GetType().GetMethod("OnValidate");
|
onValidate = Selection.activeObject.GetType().GetMethod("OnValidate");
|
||||||
if (onValidate != null) EditorGUI.BeginChangeCheck();
|
if (onValidate != null)
|
||||||
|
{
|
||||||
|
EditorGUI.BeginChangeCheck();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
BeginZoomed(position, zoom, topPadding);
|
BeginZoomed(position, zoom, topPadding);
|
||||||
|
|
||||||
Vector2 mousePos = Event.current.mousePosition;
|
Vector2 mousePos = Event.current.mousePosition;
|
||||||
|
|
||||||
if (e.type != EventType.Layout) {
|
if (e.type != EventType.Layout)
|
||||||
|
{
|
||||||
hoveredNode = null;
|
hoveredNode = null;
|
||||||
hoveredPort = null;
|
hoveredPort = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
List<UnityEngine.Object> preSelection = preBoxSelection != null ? new List<UnityEngine.Object>(preBoxSelection) : new List<UnityEngine.Object>();
|
var preSelection = preBoxSelection != null ? new List<Object>(preBoxSelection) : new List<Object>();
|
||||||
|
|
||||||
// Selection box stuff
|
// Selection box stuff
|
||||||
Vector2 boxStartPos = GridToWindowPositionNoClipped(dragBoxStart);
|
Vector2 boxStartPos = GridToWindowPositionNoClipped(dragBoxStart);
|
||||||
Vector2 boxSize = mousePos - boxStartPos;
|
Vector2 boxSize = mousePos - boxStartPos;
|
||||||
if (boxSize.x < 0) { boxStartPos.x += boxSize.x; boxSize.x = Mathf.Abs(boxSize.x); }
|
if (boxSize.x < 0)
|
||||||
if (boxSize.y < 0) { boxStartPos.y += boxSize.y; boxSize.y = Mathf.Abs(boxSize.y); }
|
{
|
||||||
|
boxStartPos.x += boxSize.x;
|
||||||
|
boxSize.x = Mathf.Abs(boxSize.x);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (boxSize.y < 0)
|
||||||
|
{
|
||||||
|
boxStartPos.y += boxSize.y;
|
||||||
|
boxSize.y = Mathf.Abs(boxSize.y);
|
||||||
|
}
|
||||||
|
|
||||||
Rect selectionBox = new Rect(boxStartPos, boxSize);
|
Rect selectionBox = new Rect(boxStartPos, boxSize);
|
||||||
|
|
||||||
//Save guiColor so we can revert it
|
//Save guiColor so we can revert it
|
||||||
Color guiColor = GUI.color;
|
Color guiColor = GUI.color;
|
||||||
|
|
||||||
List<NodePort> removeEntries = new List<NodePort>();
|
var removeEntries = new List<NodePort>();
|
||||||
|
|
||||||
if (e.type == EventType.Layout) culledNodes = new List<Node>();
|
if (e.type == EventType.Layout)
|
||||||
for (int n = 0; n < graph.nodes.Count; n++) {
|
{
|
||||||
|
culledNodes = new List<Node>();
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int n = 0; n < graph.nodes.Count; n++)
|
||||||
|
{
|
||||||
// Skip null nodes. The user could be in the process of renaming scripts, so removing them at this point is not advisable.
|
// Skip null nodes. The user could be in the process of renaming scripts, so removing them at this point is not advisable.
|
||||||
if (graph.nodes[n] == null) continue;
|
if (graph.nodes[n] == null)
|
||||||
if (n >= graph.nodes.Count) return;
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (n >= graph.nodes.Count)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
Node node = graph.nodes[n];
|
Node node = graph.nodes[n];
|
||||||
|
|
||||||
// Culling
|
// Culling
|
||||||
if (e.type == EventType.Layout) {
|
if (e.type == EventType.Layout)
|
||||||
|
{
|
||||||
// Cull unselected nodes outside view
|
// Cull unselected nodes outside view
|
||||||
if (!Selection.Contains(node) && ShouldBeCulled(node)) {
|
if (!Selection.Contains(node) && ShouldBeCulled(node))
|
||||||
|
{
|
||||||
culledNodes.Add(node);
|
culledNodes.Add(node);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
} else if (culledNodes.Contains(node)) continue;
|
}
|
||||||
|
else if (culledNodes.Contains(node))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
if (e.type == EventType.Repaint) {
|
if (e.type == EventType.Repaint)
|
||||||
|
{
|
||||||
removeEntries.Clear();
|
removeEntries.Clear();
|
||||||
foreach (var kvp in _portConnectionPoints)
|
foreach (var kvp in portConnectionPoints)
|
||||||
if (kvp.Key.node == node) removeEntries.Add(kvp.Key);
|
{
|
||||||
foreach (var k in removeEntries) _portConnectionPoints.Remove(k);
|
if (kvp.Key.node == node)
|
||||||
|
{
|
||||||
|
removeEntries.Add(kvp.Key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (NodePort k in removeEntries)
|
||||||
|
{
|
||||||
|
portConnectionPoints.Remove(k);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
NodeEditor nodeEditor = NodeEditor.GetEditor(node, this);
|
NodeEditor nodeEditor = NodeEditor.GetEditor(node, this);
|
||||||
@ -469,7 +659,8 @@ namespace XNodeEditor {
|
|||||||
|
|
||||||
bool selected = selectionCache.Contains(graph.nodes[n]);
|
bool selected = selectionCache.Contains(graph.nodes[n]);
|
||||||
|
|
||||||
if (selected) {
|
if (selected)
|
||||||
|
{
|
||||||
GUIStyle style = new GUIStyle(nodeEditor.GetBodyStyle());
|
GUIStyle style = new GUIStyle(nodeEditor.GetBodyStyle());
|
||||||
GUIStyle highlightStyle = new GUIStyle(nodeEditor.GetBodyHighlightStyle());
|
GUIStyle highlightStyle = new GUIStyle(nodeEditor.GetBodyHighlightStyle());
|
||||||
highlightStyle.padding = style.padding;
|
highlightStyle.padding = style.padding;
|
||||||
@ -478,7 +669,9 @@ namespace XNodeEditor {
|
|||||||
GUILayout.BeginVertical(style);
|
GUILayout.BeginVertical(style);
|
||||||
GUI.color = NodeEditorPreferences.GetSettings().highlightColor;
|
GUI.color = NodeEditorPreferences.GetSettings().highlightColor;
|
||||||
GUILayout.BeginVertical(new GUIStyle(highlightStyle));
|
GUILayout.BeginVertical(new GUIStyle(highlightStyle));
|
||||||
} else {
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
GUIStyle style = new GUIStyle(nodeEditor.GetBodyStyle());
|
GUIStyle style = new GUIStyle(nodeEditor.GetBodyStyle());
|
||||||
GUI.color = nodeEditor.GetTint();
|
GUI.color = nodeEditor.GetTint();
|
||||||
GUILayout.BeginVertical(style);
|
GUILayout.BeginVertical(style);
|
||||||
@ -492,8 +685,13 @@ namespace XNodeEditor {
|
|||||||
nodeEditor.OnBodyGUI();
|
nodeEditor.OnBodyGUI();
|
||||||
|
|
||||||
//If user changed a value, notify other scripts through onUpdateNode
|
//If user changed a value, notify other scripts through onUpdateNode
|
||||||
if (EditorGUI.EndChangeCheck()) {
|
if (EditorGUI.EndChangeCheck())
|
||||||
if (NodeEditor.onUpdateNode != null) NodeEditor.onUpdateNode(node);
|
{
|
||||||
|
if (NodeEditor.onUpdateNode != null)
|
||||||
|
{
|
||||||
|
NodeEditor.onUpdateNode(node);
|
||||||
|
}
|
||||||
|
|
||||||
EditorUtility.SetDirty(node);
|
EditorUtility.SetDirty(node);
|
||||||
nodeEditor.serializedObject.ApplyModifiedProperties();
|
nodeEditor.serializedObject.ApplyModifiedProperties();
|
||||||
}
|
}
|
||||||
@ -501,12 +699,20 @@ namespace XNodeEditor {
|
|||||||
GUILayout.EndVertical();
|
GUILayout.EndVertical();
|
||||||
|
|
||||||
//Cache data about the node for next frame
|
//Cache data about the node for next frame
|
||||||
if (e.type == EventType.Repaint) {
|
if (e.type == EventType.Repaint)
|
||||||
|
{
|
||||||
Vector2 size = GUILayoutUtility.GetLastRect().size;
|
Vector2 size = GUILayoutUtility.GetLastRect().size;
|
||||||
if (nodeSizes.ContainsKey(node)) nodeSizes[node] = size;
|
if (nodeSizes.ContainsKey(node))
|
||||||
else nodeSizes.Add(node, size);
|
{
|
||||||
|
nodeSizes[node] = size;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
nodeSizes.Add(node, size);
|
||||||
|
}
|
||||||
|
|
||||||
foreach (var kvp in NodeEditor.portPositions) {
|
foreach (var kvp in NodeEditor.portPositions)
|
||||||
|
{
|
||||||
Vector2 portHandlePos = kvp.Value;
|
Vector2 portHandlePos = kvp.Value;
|
||||||
portHandlePos += node.position;
|
portHandlePos += node.position;
|
||||||
Rect rect = new Rect(portHandlePos.x - 8, portHandlePos.y - 8, 16, 16);
|
Rect rect = new Rect(portHandlePos.x - 8, portHandlePos.y - 8, 16, 16);
|
||||||
@ -514,75 +720,139 @@ namespace XNodeEditor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (selected) GUILayout.EndVertical();
|
if (selected)
|
||||||
|
{
|
||||||
|
GUILayout.EndVertical();
|
||||||
|
}
|
||||||
|
|
||||||
if (e.type != EventType.Layout) {
|
if (e.type != EventType.Layout)
|
||||||
|
{
|
||||||
//Check if we are hovering this node
|
//Check if we are hovering this node
|
||||||
Vector2 nodeSize = GUILayoutUtility.GetLastRect().size;
|
Vector2 nodeSize = GUILayoutUtility.GetLastRect().size;
|
||||||
Rect windowRect = new Rect(nodePos, nodeSize);
|
Rect windowRect = new Rect(nodePos, nodeSize);
|
||||||
if (windowRect.Contains(mousePos)) hoveredNode = node;
|
if (windowRect.Contains(mousePos))
|
||||||
|
{
|
||||||
|
hoveredNode = node;
|
||||||
|
}
|
||||||
|
|
||||||
//If dragging a selection box, add nodes inside to selection
|
//If dragging a selection box, add nodes inside to selection
|
||||||
if (currentActivity == NodeActivity.DragGrid) {
|
if (currentActivity == NodeActivity.DragGrid)
|
||||||
if (windowRect.Overlaps(selectionBox)) preSelection.Add(node);
|
{
|
||||||
|
if (windowRect.Overlaps(selectionBox))
|
||||||
|
{
|
||||||
|
preSelection.Add(node);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//Check if we are hovering any of this nodes ports
|
//Check if we are hovering any of this nodes ports
|
||||||
//Check input ports
|
//Check input ports
|
||||||
foreach (NodePort input in node.Inputs) {
|
foreach (NodePort input in node.Inputs)
|
||||||
|
{
|
||||||
//Check if port rect is available
|
//Check if port rect is available
|
||||||
if (!portConnectionPoints.ContainsKey(input)) continue;
|
if (!portConnectionPoints.ContainsKey(input))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
Rect r = GridToWindowRectNoClipped(portConnectionPoints[input]);
|
Rect r = GridToWindowRectNoClipped(portConnectionPoints[input]);
|
||||||
if (r.Contains(mousePos)) hoveredPort = input;
|
if (r.Contains(mousePos))
|
||||||
|
{
|
||||||
|
hoveredPort = input;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//Check all output ports
|
//Check all output ports
|
||||||
foreach (NodePort output in node.Outputs) {
|
foreach (NodePort output in node.Outputs)
|
||||||
|
{
|
||||||
//Check if port rect is available
|
//Check if port rect is available
|
||||||
if (!portConnectionPoints.ContainsKey(output)) continue;
|
if (!portConnectionPoints.ContainsKey(output))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
Rect r = GridToWindowRectNoClipped(portConnectionPoints[output]);
|
Rect r = GridToWindowRectNoClipped(portConnectionPoints[output]);
|
||||||
if (r.Contains(mousePos)) hoveredPort = output;
|
if (r.Contains(mousePos))
|
||||||
|
{
|
||||||
|
hoveredPort = output;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
GUILayout.EndArea();
|
GUILayout.EndArea();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (e.type != EventType.Layout && currentActivity == NodeActivity.DragGrid) Selection.objects = preSelection.ToArray();
|
if (e.type != EventType.Layout && currentActivity == NodeActivity.DragGrid)
|
||||||
|
{
|
||||||
|
Selection.objects = preSelection.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
EndZoomed(position, zoom, topPadding);
|
EndZoomed(position, zoom, topPadding);
|
||||||
|
|
||||||
//If a change in is detected in the selected node, call OnValidate method.
|
//If a change in is detected in the selected node, call OnValidate method.
|
||||||
//This is done through reflection because OnValidate is only relevant in editor,
|
//This is done through reflection because OnValidate is only relevant in editor,
|
||||||
//and thus, the code should not be included in build.
|
//and thus, the code should not be included in build.
|
||||||
if (onValidate != null && EditorGUI.EndChangeCheck()) onValidate.Invoke(Selection.activeObject, null);
|
if (onValidate != null && EditorGUI.EndChangeCheck())
|
||||||
|
{
|
||||||
|
onValidate.Invoke(Selection.activeObject, null);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private bool ShouldBeCulled(Node node) {
|
private bool ShouldBeCulled(Node node)
|
||||||
|
{
|
||||||
Vector2 nodePos = GridToWindowPositionNoClipped(node.position);
|
Vector2 nodePos = GridToWindowPositionNoClipped(node.position);
|
||||||
if (nodePos.x / _zoom > position.width) return true; // Right
|
if (nodePos.x / _zoom > position.width)
|
||||||
else if (nodePos.y / _zoom > position.height) return true; // Bottom
|
{
|
||||||
else if (nodeSizes.ContainsKey(node)) {
|
return true; // Right
|
||||||
Vector2 size = nodeSizes[node];
|
|
||||||
if (nodePos.x + size.x < 0) return true; // Left
|
|
||||||
else if (nodePos.y + size.y < 0) return true; // Top
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (nodePos.y / _zoom > position.height)
|
||||||
|
{
|
||||||
|
return true; // Bottom
|
||||||
|
}
|
||||||
|
|
||||||
|
if (nodeSizes.ContainsKey(node))
|
||||||
|
{
|
||||||
|
Vector2 size = nodeSizes[node];
|
||||||
|
if (nodePos.x + size.x < 0)
|
||||||
|
{
|
||||||
|
return true; // Left
|
||||||
|
}
|
||||||
|
|
||||||
|
if (nodePos.y + size.y < 0)
|
||||||
|
{
|
||||||
|
return true; // Top
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void DrawTooltip() {
|
private void DrawTooltip()
|
||||||
|
{
|
||||||
if (!NodeEditorPreferences.GetSettings().portTooltips || graphEditor == null)
|
if (!NodeEditorPreferences.GetSettings().portTooltips || graphEditor == null)
|
||||||
|
{
|
||||||
return;
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
string tooltip = null;
|
string tooltip = null;
|
||||||
if (hoveredPort != null) {
|
if (hoveredPort != null)
|
||||||
|
{
|
||||||
tooltip = graphEditor.GetPortTooltip(hoveredPort);
|
tooltip = graphEditor.GetPortTooltip(hoveredPort);
|
||||||
} else if (hoveredNode != null && IsHoveringNode && IsHoveringTitle(hoveredNode)) {
|
}
|
||||||
|
else if (hoveredNode != null && IsHoveringNode && IsHoveringTitle(hoveredNode))
|
||||||
|
{
|
||||||
tooltip = NodeEditor.GetEditor(hoveredNode, this).GetHeaderTooltip();
|
tooltip = NodeEditor.GetEditor(hoveredNode, this).GetHeaderTooltip();
|
||||||
}
|
}
|
||||||
if (string.IsNullOrEmpty(tooltip)) return;
|
|
||||||
|
if (string.IsNullOrEmpty(tooltip))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
GUIContent content = new GUIContent(tooltip);
|
GUIContent content = new GUIContent(tooltip);
|
||||||
Vector2 size = NodeEditorResources.styles.tooltip.CalcSize(content);
|
Vector2 size = NodeEditorResources.styles.tooltip.CalcSize(content);
|
||||||
size.x += 8;
|
size.x += 8;
|
||||||
Rect rect = new Rect(Event.current.mousePosition - (size), size);
|
Rect rect = new Rect(Event.current.mousePosition - size, size);
|
||||||
EditorGUI.LabelField(rect, content, NodeEditorResources.styles.tooltip);
|
EditorGUI.LabelField(rect, content, NodeEditorResources.styles.tooltip);
|
||||||
Repaint();
|
Repaint();
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,98 +1,159 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections;
|
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Reflection;
|
using System.Reflection;
|
||||||
using UnityEditor;
|
using UnityEditor;
|
||||||
using UnityEditorInternal;
|
using UnityEditorInternal;
|
||||||
using UnityEngine;
|
using UnityEngine;
|
||||||
|
using XNode;
|
||||||
|
using Object = UnityEngine.Object;
|
||||||
|
|
||||||
namespace XNodeEditor {
|
namespace XNodeEditor
|
||||||
/// <summary> xNode-specific version of <see cref="EditorGUILayout"/> </summary>
|
{
|
||||||
public static class NodeEditorGUILayout {
|
/// <summary> xNode-specific version of <see cref="EditorGUILayout" /> </summary>
|
||||||
|
public static class NodeEditorGUILayout
|
||||||
private static readonly Dictionary<UnityEngine.Object, Dictionary<string, ReorderableList>> reorderableListCache = new Dictionary<UnityEngine.Object, Dictionary<string, ReorderableList>>();
|
{
|
||||||
|
private static readonly Dictionary<Object, Dictionary<string, ReorderableList>> reorderableListCache =
|
||||||
|
new Dictionary<Object, Dictionary<string, ReorderableList>>();
|
||||||
private static int reorderableListIndex = -1;
|
private static int reorderableListIndex = -1;
|
||||||
|
|
||||||
/// <summary> Make a field for a serialized property. Automatically displays relevant node port. </summary>
|
/// <summary> Make a field for a serialized property. Automatically displays relevant node port. </summary>
|
||||||
public static void PropertyField(SerializedProperty property, bool includeChildren = true, params GUILayoutOption[] options) {
|
public static void PropertyField(SerializedProperty property, bool includeChildren = true,
|
||||||
|
params GUILayoutOption[] options)
|
||||||
|
{
|
||||||
PropertyField(property, (GUIContent)null, includeChildren, options);
|
PropertyField(property, (GUIContent)null, includeChildren, options);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Make a field for a serialized property. Automatically displays relevant node port. </summary>
|
/// <summary> Make a field for a serialized property. Automatically displays relevant node port. </summary>
|
||||||
public static void PropertyField(SerializedProperty property, GUIContent label, bool includeChildren = true, params GUILayoutOption[] options) {
|
public static void PropertyField(SerializedProperty property, GUIContent label, bool includeChildren = true,
|
||||||
if (property == null) throw new NullReferenceException();
|
params GUILayoutOption[] options)
|
||||||
|
{
|
||||||
|
if (property == null)
|
||||||
|
{
|
||||||
|
throw new NullReferenceException();
|
||||||
|
}
|
||||||
|
|
||||||
Node node = property.serializedObject.targetObject as Node;
|
Node node = property.serializedObject.targetObject as Node;
|
||||||
NodePort port = node.GetPort(property.name);
|
NodePort port = node.GetPort(property.name);
|
||||||
PropertyField(property, label, port, includeChildren);
|
PropertyField(property, label, port, includeChildren);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Make a field for a serialized property. Manual node port override. </summary>
|
/// <summary> Make a field for a serialized property. Manual node port override. </summary>
|
||||||
public static void PropertyField(SerializedProperty property, NodePort port, bool includeChildren = true, params GUILayoutOption[] options) {
|
public static void PropertyField(SerializedProperty property, NodePort port, bool includeChildren = true,
|
||||||
|
params GUILayoutOption[] options)
|
||||||
|
{
|
||||||
PropertyField(property, null, port, includeChildren, options);
|
PropertyField(property, null, port, includeChildren, options);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Make a field for a serialized property. Manual node port override. </summary>
|
/// <summary> Make a field for a serialized property. Manual node port override. </summary>
|
||||||
public static void PropertyField(SerializedProperty property, GUIContent label, NodePort port, bool includeChildren = true, params GUILayoutOption[] options) {
|
public static void PropertyField(SerializedProperty property, GUIContent label, NodePort port,
|
||||||
if (property == null) throw new NullReferenceException();
|
bool includeChildren = true, params GUILayoutOption[] options)
|
||||||
|
{
|
||||||
|
if (property == null)
|
||||||
|
{
|
||||||
|
throw new NullReferenceException();
|
||||||
|
}
|
||||||
|
|
||||||
// If property is not a port, display a regular property field
|
// If property is not a port, display a regular property field
|
||||||
if (port == null) EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
|
if (port == null)
|
||||||
else {
|
{
|
||||||
|
EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
Rect rect = new Rect();
|
Rect rect = new Rect();
|
||||||
|
|
||||||
List<PropertyAttribute> propertyAttributes = NodeEditorUtilities.GetCachedPropertyAttribs(port.node.GetType(), property.name);
|
var propertyAttributes =
|
||||||
|
NodeEditorUtilities.GetCachedPropertyAttribs(port.node.GetType(), property.name);
|
||||||
|
|
||||||
// If property is an input, display a regular property field and put a port handle on the left side
|
// If property is an input, display a regular property field and put a port handle on the left side
|
||||||
if (port.direction == NodePort.IO.Input) {
|
if (port.direction == NodePort.IO.Input)
|
||||||
|
{
|
||||||
// Get data from [Input] attribute
|
// Get data from [Input] attribute
|
||||||
Node.ShowBackingValue showBacking = Node.ShowBackingValue.Unconnected;
|
Node.ShowBackingValue showBacking = Node.ShowBackingValue.Unconnected;
|
||||||
Node.InputAttribute inputAttribute;
|
Node.InputAttribute inputAttribute;
|
||||||
bool dynamicPortList = false;
|
bool dynamicPortList = false;
|
||||||
if (NodeEditorUtilities.GetCachedAttrib(port.node.GetType(), property.name, out inputAttribute)) {
|
if (NodeEditorUtilities.GetCachedAttrib(port.node.GetType(), property.name, out inputAttribute))
|
||||||
|
{
|
||||||
dynamicPortList = inputAttribute.dynamicPortList;
|
dynamicPortList = inputAttribute.dynamicPortList;
|
||||||
showBacking = inputAttribute.backingValue;
|
showBacking = inputAttribute.backingValue;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool usePropertyAttributes = dynamicPortList ||
|
bool usePropertyAttributes = dynamicPortList ||
|
||||||
showBacking == Node.ShowBackingValue.Never ||
|
showBacking == Node.ShowBackingValue.Never ||
|
||||||
(showBacking == Node.ShowBackingValue.Unconnected && port.IsConnected);
|
showBacking == Node.ShowBackingValue.Unconnected && port.IsConnected;
|
||||||
|
|
||||||
float spacePadding = 0;
|
float spacePadding = 0;
|
||||||
string tooltip = null;
|
string tooltip = null;
|
||||||
foreach (var attr in propertyAttributes) {
|
foreach (PropertyAttribute attr in propertyAttributes)
|
||||||
if (attr is SpaceAttribute) {
|
{
|
||||||
if (usePropertyAttributes) GUILayout.Space((attr as SpaceAttribute).height);
|
if (attr is SpaceAttribute)
|
||||||
else spacePadding += (attr as SpaceAttribute).height;
|
{
|
||||||
} else if (attr is HeaderAttribute) {
|
if (usePropertyAttributes)
|
||||||
if (usePropertyAttributes) {
|
{
|
||||||
|
GUILayout.Space((attr as SpaceAttribute).height);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
spacePadding += (attr as SpaceAttribute).height;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (attr is HeaderAttribute)
|
||||||
|
{
|
||||||
|
if (usePropertyAttributes)
|
||||||
|
{
|
||||||
//GUI Values are from https://github.com/Unity-Technologies/UnityCsReference/blob/master/Editor/Mono/ScriptAttributeGUI/Implementations/DecoratorDrawers.cs
|
//GUI Values are from https://github.com/Unity-Technologies/UnityCsReference/blob/master/Editor/Mono/ScriptAttributeGUI/Implementations/DecoratorDrawers.cs
|
||||||
Rect position = GUILayoutUtility.GetRect(0, (EditorGUIUtility.singleLineHeight * 1.5f) - EditorGUIUtility.standardVerticalSpacing); //Layout adds standardVerticalSpacing after rect so we subtract it.
|
Rect position = GUILayoutUtility.GetRect(0,
|
||||||
|
EditorGUIUtility.singleLineHeight * 1.5f -
|
||||||
|
EditorGUIUtility
|
||||||
|
.standardVerticalSpacing); //Layout adds standardVerticalSpacing after rect so we subtract it.
|
||||||
position.yMin += EditorGUIUtility.singleLineHeight * 0.5f;
|
position.yMin += EditorGUIUtility.singleLineHeight * 0.5f;
|
||||||
position = EditorGUI.IndentedRect(position);
|
position = EditorGUI.IndentedRect(position);
|
||||||
GUI.Label(position, (attr as HeaderAttribute).header, EditorStyles.boldLabel);
|
GUI.Label(position, (attr as HeaderAttribute).header, EditorStyles.boldLabel);
|
||||||
} else spacePadding += EditorGUIUtility.singleLineHeight * 1.5f;
|
}
|
||||||
} else if (attr is TooltipAttribute) {
|
else
|
||||||
|
{
|
||||||
|
spacePadding += EditorGUIUtility.singleLineHeight * 1.5f;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (attr is TooltipAttribute)
|
||||||
|
{
|
||||||
tooltip = (attr as TooltipAttribute).tooltip;
|
tooltip = (attr as TooltipAttribute).tooltip;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (dynamicPortList) {
|
if (dynamicPortList)
|
||||||
|
{
|
||||||
Type type = GetType(property);
|
Type type = GetType(property);
|
||||||
Node.ConnectionType connectionType = inputAttribute != null ? inputAttribute.connectionType : Node.ConnectionType.Multiple;
|
Node.ConnectionType connectionType = inputAttribute != null
|
||||||
|
? inputAttribute.connectionType
|
||||||
|
: Node.ConnectionType.Multiple;
|
||||||
DynamicPortList(property.name, type, property.serializedObject, port.direction, connectionType);
|
DynamicPortList(property.name, type, property.serializedObject, port.direction, connectionType);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
switch (showBacking) {
|
|
||||||
|
switch (showBacking)
|
||||||
|
{
|
||||||
case Node.ShowBackingValue.Unconnected:
|
case Node.ShowBackingValue.Unconnected:
|
||||||
// Display a label if port is connected
|
// Display a label if port is connected
|
||||||
if (port.IsConnected) EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName, tooltip));
|
if (port.IsConnected)
|
||||||
|
{
|
||||||
|
EditorGUILayout.LabelField(label != null
|
||||||
|
? label
|
||||||
|
: new GUIContent(property.displayName, tooltip));
|
||||||
|
}
|
||||||
// Display an editable property field if port is not connected
|
// Display an editable property field if port is not connected
|
||||||
else EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
|
else
|
||||||
|
{
|
||||||
|
EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
|
||||||
|
}
|
||||||
|
|
||||||
break;
|
break;
|
||||||
case Node.ShowBackingValue.Never:
|
case Node.ShowBackingValue.Never:
|
||||||
// Display a label
|
// Display a label
|
||||||
EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName, tooltip));
|
EditorGUILayout.LabelField(label != null
|
||||||
|
? label
|
||||||
|
: new GUIContent(property.displayName, tooltip));
|
||||||
break;
|
break;
|
||||||
case Node.ShowBackingValue.Always:
|
case Node.ShowBackingValue.Always:
|
||||||
// Display an editable property field
|
// Display an editable property field
|
||||||
@ -104,55 +165,94 @@ namespace XNodeEditor {
|
|||||||
float paddingLeft = NodeEditorWindow.current.graphEditor.GetPortStyle(port).padding.left;
|
float paddingLeft = NodeEditorWindow.current.graphEditor.GetPortStyle(port).padding.left;
|
||||||
rect.position = rect.position - new Vector2(16 + paddingLeft, -spacePadding);
|
rect.position = rect.position - new Vector2(16 + paddingLeft, -spacePadding);
|
||||||
// If property is an output, display a text label and put a port handle on the right side
|
// If property is an output, display a text label and put a port handle on the right side
|
||||||
} else if (port.direction == NodePort.IO.Output) {
|
}
|
||||||
|
else if (port.direction == NodePort.IO.Output)
|
||||||
|
{
|
||||||
// Get data from [Output] attribute
|
// Get data from [Output] attribute
|
||||||
Node.ShowBackingValue showBacking = Node.ShowBackingValue.Unconnected;
|
Node.ShowBackingValue showBacking = Node.ShowBackingValue.Unconnected;
|
||||||
Node.OutputAttribute outputAttribute;
|
Node.OutputAttribute outputAttribute;
|
||||||
bool dynamicPortList = false;
|
bool dynamicPortList = false;
|
||||||
if (NodeEditorUtilities.GetCachedAttrib(port.node.GetType(), property.name, out outputAttribute)) {
|
if (NodeEditorUtilities.GetCachedAttrib(port.node.GetType(), property.name, out outputAttribute))
|
||||||
|
{
|
||||||
dynamicPortList = outputAttribute.dynamicPortList;
|
dynamicPortList = outputAttribute.dynamicPortList;
|
||||||
showBacking = outputAttribute.backingValue;
|
showBacking = outputAttribute.backingValue;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool usePropertyAttributes = dynamicPortList ||
|
bool usePropertyAttributes = dynamicPortList ||
|
||||||
showBacking == Node.ShowBackingValue.Never ||
|
showBacking == Node.ShowBackingValue.Never ||
|
||||||
(showBacking == Node.ShowBackingValue.Unconnected && port.IsConnected);
|
showBacking == Node.ShowBackingValue.Unconnected && port.IsConnected;
|
||||||
|
|
||||||
float spacePadding = 0;
|
float spacePadding = 0;
|
||||||
string tooltip = null;
|
string tooltip = null;
|
||||||
foreach (var attr in propertyAttributes) {
|
foreach (PropertyAttribute attr in propertyAttributes)
|
||||||
if (attr is SpaceAttribute) {
|
{
|
||||||
if (usePropertyAttributes) GUILayout.Space((attr as SpaceAttribute).height);
|
if (attr is SpaceAttribute)
|
||||||
else spacePadding += (attr as SpaceAttribute).height;
|
{
|
||||||
} else if (attr is HeaderAttribute) {
|
if (usePropertyAttributes)
|
||||||
if (usePropertyAttributes) {
|
{
|
||||||
|
GUILayout.Space((attr as SpaceAttribute).height);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
spacePadding += (attr as SpaceAttribute).height;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (attr is HeaderAttribute)
|
||||||
|
{
|
||||||
|
if (usePropertyAttributes)
|
||||||
|
{
|
||||||
//GUI Values are from https://github.com/Unity-Technologies/UnityCsReference/blob/master/Editor/Mono/ScriptAttributeGUI/Implementations/DecoratorDrawers.cs
|
//GUI Values are from https://github.com/Unity-Technologies/UnityCsReference/blob/master/Editor/Mono/ScriptAttributeGUI/Implementations/DecoratorDrawers.cs
|
||||||
Rect position = GUILayoutUtility.GetRect(0, (EditorGUIUtility.singleLineHeight * 1.5f) - EditorGUIUtility.standardVerticalSpacing); //Layout adds standardVerticalSpacing after rect so we subtract it.
|
Rect position = GUILayoutUtility.GetRect(0,
|
||||||
|
EditorGUIUtility.singleLineHeight * 1.5f -
|
||||||
|
EditorGUIUtility
|
||||||
|
.standardVerticalSpacing); //Layout adds standardVerticalSpacing after rect so we subtract it.
|
||||||
position.yMin += EditorGUIUtility.singleLineHeight * 0.5f;
|
position.yMin += EditorGUIUtility.singleLineHeight * 0.5f;
|
||||||
position = EditorGUI.IndentedRect(position);
|
position = EditorGUI.IndentedRect(position);
|
||||||
GUI.Label(position, (attr as HeaderAttribute).header, EditorStyles.boldLabel);
|
GUI.Label(position, (attr as HeaderAttribute).header, EditorStyles.boldLabel);
|
||||||
} else spacePadding += EditorGUIUtility.singleLineHeight * 1.5f;
|
}
|
||||||
} else if (attr is TooltipAttribute) {
|
else
|
||||||
|
{
|
||||||
|
spacePadding += EditorGUIUtility.singleLineHeight * 1.5f;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (attr is TooltipAttribute)
|
||||||
|
{
|
||||||
tooltip = (attr as TooltipAttribute).tooltip;
|
tooltip = (attr as TooltipAttribute).tooltip;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (dynamicPortList) {
|
if (dynamicPortList)
|
||||||
|
{
|
||||||
Type type = GetType(property);
|
Type type = GetType(property);
|
||||||
Node.ConnectionType connectionType = outputAttribute != null ? outputAttribute.connectionType : Node.ConnectionType.Multiple;
|
Node.ConnectionType connectionType = outputAttribute != null
|
||||||
|
? outputAttribute.connectionType
|
||||||
|
: Node.ConnectionType.Multiple;
|
||||||
DynamicPortList(property.name, type, property.serializedObject, port.direction, connectionType);
|
DynamicPortList(property.name, type, property.serializedObject, port.direction, connectionType);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
switch (showBacking) {
|
|
||||||
|
switch (showBacking)
|
||||||
|
{
|
||||||
case Node.ShowBackingValue.Unconnected:
|
case Node.ShowBackingValue.Unconnected:
|
||||||
// Display a label if port is connected
|
// Display a label if port is connected
|
||||||
if (port.IsConnected) EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName, tooltip), NodeEditorResources.OutputPort, GUILayout.MinWidth(30));
|
if (port.IsConnected)
|
||||||
|
{
|
||||||
|
EditorGUILayout.LabelField(
|
||||||
|
label != null ? label : new GUIContent(property.displayName, tooltip),
|
||||||
|
NodeEditorResources.OutputPort, GUILayout.MinWidth(30));
|
||||||
|
}
|
||||||
// Display an editable property field if port is not connected
|
// Display an editable property field if port is not connected
|
||||||
else EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
|
else
|
||||||
|
{
|
||||||
|
EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
|
||||||
|
}
|
||||||
|
|
||||||
break;
|
break;
|
||||||
case Node.ShowBackingValue.Never:
|
case Node.ShowBackingValue.Never:
|
||||||
// Display a label
|
// Display a label
|
||||||
EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName, tooltip), NodeEditorResources.OutputPort, GUILayout.MinWidth(30));
|
EditorGUILayout.LabelField(
|
||||||
|
label != null ? label : new GUIContent(property.displayName, tooltip),
|
||||||
|
NodeEditorResources.OutputPort, GUILayout.MinWidth(30));
|
||||||
break;
|
break;
|
||||||
case Node.ShowBackingValue.Always:
|
case Node.ShowBackingValue.Always:
|
||||||
// Display an editable property field
|
// Display an editable property field
|
||||||
@ -178,26 +278,38 @@ namespace XNodeEditor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static System.Type GetType(SerializedProperty property) {
|
private static Type GetType(SerializedProperty property)
|
||||||
System.Type parentType = property.serializedObject.targetObject.GetType();
|
{
|
||||||
System.Reflection.FieldInfo fi = parentType.GetFieldInfo(property.name);
|
Type parentType = property.serializedObject.targetObject.GetType();
|
||||||
|
FieldInfo fi = parentType.GetFieldInfo(property.name);
|
||||||
return fi.FieldType;
|
return fi.FieldType;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Make a simple port field. </summary>
|
/// <summary> Make a simple port field. </summary>
|
||||||
public static void PortField(NodePort port, params GUILayoutOption[] options) {
|
public static void PortField(NodePort port, params GUILayoutOption[] options)
|
||||||
|
{
|
||||||
PortField(null, port, options);
|
PortField(null, port, options);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Make a simple port field. </summary>
|
/// <summary> Make a simple port field. </summary>
|
||||||
public static void PortField(GUIContent label, NodePort port, params GUILayoutOption[] options) {
|
public static void PortField(GUIContent label, NodePort port, params GUILayoutOption[] options)
|
||||||
if (port == null) return;
|
{
|
||||||
if (options == null) options = new GUILayoutOption[] { GUILayout.MinWidth(30) };
|
if (port == null)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options == null)
|
||||||
|
{
|
||||||
|
options = new[] { GUILayout.MinWidth(30) };
|
||||||
|
}
|
||||||
|
|
||||||
Vector2 position = Vector3.zero;
|
Vector2 position = Vector3.zero;
|
||||||
GUIContent content = label != null ? label : new GUIContent(ObjectNames.NicifyVariableName(port.fieldName));
|
GUIContent content = label != null ? label : new GUIContent(ObjectNames.NicifyVariableName(port.fieldName));
|
||||||
|
|
||||||
// If property is an input, display a regular property field and put a port handle on the left side
|
// If property is an input, display a regular property field and put a port handle on the left side
|
||||||
if (port.direction == NodePort.IO.Input) {
|
if (port.direction == NodePort.IO.Input)
|
||||||
|
{
|
||||||
// Display a label
|
// Display a label
|
||||||
EditorGUILayout.LabelField(content, options);
|
EditorGUILayout.LabelField(content, options);
|
||||||
|
|
||||||
@ -206,7 +318,8 @@ namespace XNodeEditor {
|
|||||||
position = rect.position - new Vector2(16 + paddingLeft, 0);
|
position = rect.position - new Vector2(16 + paddingLeft, 0);
|
||||||
}
|
}
|
||||||
// If property is an output, display a text label and put a port handle on the right side
|
// If property is an output, display a text label and put a port handle on the right side
|
||||||
else if (port.direction == NodePort.IO.Output) {
|
else if (port.direction == NodePort.IO.Output)
|
||||||
|
{
|
||||||
// Display a label
|
// Display a label
|
||||||
EditorGUILayout.LabelField(content, NodeEditorResources.OutputPort, options);
|
EditorGUILayout.LabelField(content, NodeEditorResources.OutputPort, options);
|
||||||
|
|
||||||
@ -214,12 +327,17 @@ namespace XNodeEditor {
|
|||||||
rect.width += NodeEditorWindow.current.graphEditor.GetPortStyle(port).padding.right;
|
rect.width += NodeEditorWindow.current.graphEditor.GetPortStyle(port).padding.right;
|
||||||
position = rect.position + new Vector2(rect.width, 0);
|
position = rect.position + new Vector2(rect.width, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
PortField(position, port);
|
PortField(position, port);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Make a simple port field. </summary>
|
/// <summary> Make a simple port field. </summary>
|
||||||
public static void PortField(Vector2 position, NodePort port) {
|
public static void PortField(Vector2 position, NodePort port)
|
||||||
if (port == null) return;
|
{
|
||||||
|
if (port == null)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
Rect rect = new Rect(position, new Vector2(16, 16));
|
Rect rect = new Rect(position, new Vector2(16, 16));
|
||||||
|
|
||||||
@ -235,17 +353,25 @@ namespace XNodeEditor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Add a port field to previous layout element. </summary>
|
/// <summary> Add a port field to previous layout element. </summary>
|
||||||
public static void AddPortField(NodePort port) {
|
public static void AddPortField(NodePort port)
|
||||||
if (port == null) return;
|
{
|
||||||
|
if (port == null)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
Rect rect = new Rect();
|
Rect rect = new Rect();
|
||||||
|
|
||||||
// If property is an input, display a regular property field and put a port handle on the left side
|
// If property is an input, display a regular property field and put a port handle on the left side
|
||||||
if (port.direction == NodePort.IO.Input) {
|
if (port.direction == NodePort.IO.Input)
|
||||||
|
{
|
||||||
rect = GUILayoutUtility.GetLastRect();
|
rect = GUILayoutUtility.GetLastRect();
|
||||||
float paddingLeft = NodeEditorWindow.current.graphEditor.GetPortStyle(port).padding.left;
|
float paddingLeft = NodeEditorWindow.current.graphEditor.GetPortStyle(port).padding.left;
|
||||||
rect.position = rect.position - new Vector2(16 + paddingLeft, 0);
|
rect.position = rect.position - new Vector2(16 + paddingLeft, 0);
|
||||||
// If property is an output, display a text label and put a port handle on the right side
|
// If property is an output, display a text label and put a port handle on the right side
|
||||||
} else if (port.direction == NodePort.IO.Output) {
|
}
|
||||||
|
else if (port.direction == NodePort.IO.Output)
|
||||||
|
{
|
||||||
rect = GUILayoutUtility.GetLastRect();
|
rect = GUILayoutUtility.GetLastRect();
|
||||||
rect.width += NodeEditorWindow.current.graphEditor.GetPortStyle(port).padding.right;
|
rect.width += NodeEditorWindow.current.graphEditor.GetPortStyle(port).padding.right;
|
||||||
rect.position = rect.position + new Vector2(rect.width, 0);
|
rect.position = rect.position + new Vector2(rect.width, 0);
|
||||||
@ -265,22 +391,25 @@ namespace XNodeEditor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Draws an input and an output port on the same line </summary>
|
/// <summary> Draws an input and an output port on the same line </summary>
|
||||||
public static void PortPair(NodePort input, NodePort output) {
|
public static void PortPair(NodePort input, NodePort output)
|
||||||
|
{
|
||||||
GUILayout.BeginHorizontal();
|
GUILayout.BeginHorizontal();
|
||||||
NodeEditorGUILayout.PortField(input, GUILayout.MinWidth(0));
|
PortField(input, GUILayout.MinWidth(0));
|
||||||
NodeEditorGUILayout.PortField(output, GUILayout.MinWidth(0));
|
PortField(output, GUILayout.MinWidth(0));
|
||||||
GUILayout.EndHorizontal();
|
GUILayout.EndHorizontal();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Draw the port
|
/// Draw the port
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="rect">position and size</param>
|
/// <param name="rect">position and size</param>
|
||||||
/// <param name="backgroundColor">color for background texture of the port. Normaly used to Border</param>
|
/// <param name="backgroundColor">color for background texture of the port. Normaly used to Border</param>
|
||||||
/// <param name="typeColor"></param>
|
/// <param name="typeColor"></param>
|
||||||
/// <param name="border">texture for border of the dot port</param>
|
/// <param name="border">texture for border of the dot port</param>
|
||||||
/// <param name="dot">texture for the dot port</param>
|
/// <param name="dot">texture for the dot port</param>
|
||||||
public static void DrawPortHandle(Rect rect, Color backgroundColor, Color typeColor, Texture2D border, Texture2D dot) {
|
public static void DrawPortHandle(Rect rect, Color backgroundColor, Color typeColor, Texture2D border,
|
||||||
|
Texture2D dot)
|
||||||
|
{
|
||||||
Color col = GUI.color;
|
Color col = GUI.color;
|
||||||
GUI.color = backgroundColor;
|
GUI.color = backgroundColor;
|
||||||
GUI.DrawTexture(rect, border);
|
GUI.DrawTexture(rect, border);
|
||||||
@ -291,26 +420,42 @@ namespace XNodeEditor {
|
|||||||
|
|
||||||
|
|
||||||
#region Obsolete
|
#region Obsolete
|
||||||
|
|
||||||
[Obsolete("Use IsDynamicPortListPort instead")]
|
[Obsolete("Use IsDynamicPortListPort instead")]
|
||||||
public static bool IsInstancePortListPort(NodePort port) {
|
public static bool IsInstancePortListPort(NodePort port)
|
||||||
|
{
|
||||||
return IsDynamicPortListPort(port);
|
return IsDynamicPortListPort(port);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Obsolete("Use DynamicPortList instead")]
|
[Obsolete("Use DynamicPortList instead")]
|
||||||
public static void InstancePortList(string fieldName, Type type, SerializedObject serializedObject, NodePort.IO io, Node.ConnectionType connectionType = Node.ConnectionType.Multiple, Node.TypeConstraint typeConstraint = Node.TypeConstraint.None, Action<ReorderableList> onCreation = null) {
|
public static void InstancePortList(string fieldName, Type type, SerializedObject serializedObject,
|
||||||
|
NodePort.IO io, Node.ConnectionType connectionType = Node.ConnectionType.Multiple,
|
||||||
|
Node.TypeConstraint typeConstraint = Node.TypeConstraint.None, Action<ReorderableList> onCreation = null)
|
||||||
|
{
|
||||||
DynamicPortList(fieldName, type, serializedObject, io, connectionType, typeConstraint, onCreation);
|
DynamicPortList(fieldName, type, serializedObject, io, connectionType, typeConstraint, onCreation);
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
/// <summary> Is this port part of a DynamicPortList? </summary>
|
/// <summary> Is this port part of a DynamicPortList? </summary>
|
||||||
public static bool IsDynamicPortListPort(NodePort port) {
|
public static bool IsDynamicPortListPort(NodePort port)
|
||||||
|
{
|
||||||
string[] parts = port.fieldName.Split(' ');
|
string[] parts = port.fieldName.Split(' ');
|
||||||
if (parts.Length != 2) return false;
|
if (parts.Length != 2)
|
||||||
Dictionary<string, ReorderableList> cache;
|
{
|
||||||
if (reorderableListCache.TryGetValue(port.node, out cache)) {
|
return false;
|
||||||
ReorderableList list;
|
|
||||||
if (cache.TryGetValue(parts[0], out list)) return true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Dictionary<string, ReorderableList> cache;
|
||||||
|
if (reorderableListCache.TryGetValue(port.node, out cache))
|
||||||
|
{
|
||||||
|
ReorderableList list;
|
||||||
|
if (cache.TryGetValue(parts[0], out list))
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -320,119 +465,167 @@ namespace XNodeEditor {
|
|||||||
/// <param name="serializedObject">The serializedObject of the node</param>
|
/// <param name="serializedObject">The serializedObject of the node</param>
|
||||||
/// <param name="connectionType">Connection type of added dynamic ports</param>
|
/// <param name="connectionType">Connection type of added dynamic ports</param>
|
||||||
/// <param name="onCreation">Called on the list on creation. Use this if you want to customize the created ReorderableList</param>
|
/// <param name="onCreation">Called on the list on creation. Use this if you want to customize the created ReorderableList</param>
|
||||||
public static void DynamicPortList(string fieldName, Type type, SerializedObject serializedObject, NodePort.IO io, Node.ConnectionType connectionType = Node.ConnectionType.Multiple, Node.TypeConstraint typeConstraint = Node.TypeConstraint.None, Action<ReorderableList> onCreation = null) {
|
public static void DynamicPortList(string fieldName, Type type, SerializedObject serializedObject,
|
||||||
|
NodePort.IO io, Node.ConnectionType connectionType = Node.ConnectionType.Multiple,
|
||||||
|
Node.TypeConstraint typeConstraint = Node.TypeConstraint.None, Action<ReorderableList> onCreation = null)
|
||||||
|
{
|
||||||
Node node = serializedObject.targetObject as Node;
|
Node node = serializedObject.targetObject as Node;
|
||||||
|
|
||||||
var indexedPorts = node.DynamicPorts.Select(x => {
|
var indexedPorts = node.DynamicPorts.Select(x =>
|
||||||
|
{
|
||||||
string[] split = x.fieldName.Split(' ');
|
string[] split = x.fieldName.Split(' ');
|
||||||
if (split != null && split.Length == 2 && split[0] == fieldName) {
|
if (split != null && split.Length == 2 && split[0] == fieldName)
|
||||||
|
{
|
||||||
int i = -1;
|
int i = -1;
|
||||||
if (int.TryParse(split[1], out i)) {
|
if (int.TryParse(split[1], out i))
|
||||||
|
{
|
||||||
return new { index = i, port = x };
|
return new { index = i, port = x };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return new { index = -1, port = (NodePort)null };
|
return new { index = -1, port = (NodePort)null };
|
||||||
}).Where(x => x.port != null);
|
}).Where(x => x.port != null);
|
||||||
List<NodePort> dynamicPorts = indexedPorts.OrderBy(x => x.index).Select(x => x.port).ToList();
|
var dynamicPorts = indexedPorts.OrderBy(x => x.index).Select(x => x.port).ToList();
|
||||||
|
|
||||||
node.UpdatePorts();
|
node.UpdatePorts();
|
||||||
|
|
||||||
ReorderableList list = null;
|
ReorderableList list = null;
|
||||||
Dictionary<string, ReorderableList> rlc;
|
Dictionary<string, ReorderableList> rlc;
|
||||||
if (reorderableListCache.TryGetValue(serializedObject.targetObject, out rlc)) {
|
if (reorderableListCache.TryGetValue(serializedObject.targetObject, out rlc))
|
||||||
if (!rlc.TryGetValue(fieldName, out list)) list = null;
|
{
|
||||||
|
if (!rlc.TryGetValue(fieldName, out list))
|
||||||
|
{
|
||||||
|
list = null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// If a ReorderableList isn't cached for this array, do so.
|
// If a ReorderableList isn't cached for this array, do so.
|
||||||
if (list == null) {
|
if (list == null)
|
||||||
|
{
|
||||||
SerializedProperty arrayData = serializedObject.FindProperty(fieldName);
|
SerializedProperty arrayData = serializedObject.FindProperty(fieldName);
|
||||||
list = CreateReorderableList(fieldName, dynamicPorts, arrayData, type, serializedObject, io, connectionType, typeConstraint, onCreation);
|
list = CreateReorderableList(fieldName, dynamicPorts, arrayData, type, serializedObject, io,
|
||||||
if (reorderableListCache.TryGetValue(serializedObject.targetObject, out rlc)) rlc.Add(fieldName, list);
|
connectionType, typeConstraint, onCreation);
|
||||||
else reorderableListCache.Add(serializedObject.targetObject, new Dictionary<string, ReorderableList>() { { fieldName, list } });
|
if (reorderableListCache.TryGetValue(serializedObject.targetObject, out rlc))
|
||||||
|
{
|
||||||
|
rlc.Add(fieldName, list);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
reorderableListCache.Add(serializedObject.targetObject,
|
||||||
|
new Dictionary<string, ReorderableList> { { fieldName, list } });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
list.list = dynamicPorts;
|
list.list = dynamicPorts;
|
||||||
list.DoLayoutList();
|
list.DoLayoutList();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static ReorderableList CreateReorderableList(string fieldName, List<NodePort> dynamicPorts, SerializedProperty arrayData, Type type, SerializedObject serializedObject, NodePort.IO io, Node.ConnectionType connectionType, Node.TypeConstraint typeConstraint, Action<ReorderableList> onCreation) {
|
private static ReorderableList CreateReorderableList(string fieldName, List<NodePort> dynamicPorts,
|
||||||
|
SerializedProperty arrayData, Type type, SerializedObject serializedObject, NodePort.IO io,
|
||||||
|
Node.ConnectionType connectionType, Node.TypeConstraint typeConstraint, Action<ReorderableList> onCreation)
|
||||||
|
{
|
||||||
bool hasArrayData = arrayData != null && arrayData.isArray;
|
bool hasArrayData = arrayData != null && arrayData.isArray;
|
||||||
Node node = serializedObject.targetObject as Node;
|
Node node = serializedObject.targetObject as Node;
|
||||||
ReorderableList list = new ReorderableList(dynamicPorts, null, true, true, true, true);
|
ReorderableList list = new ReorderableList(dynamicPorts, null, true, true, true, true);
|
||||||
string label = arrayData != null ? arrayData.displayName : ObjectNames.NicifyVariableName(fieldName);
|
string label = arrayData != null ? arrayData.displayName : ObjectNames.NicifyVariableName(fieldName);
|
||||||
|
|
||||||
list.drawElementCallback =
|
list.drawElementCallback =
|
||||||
(Rect rect, int index, bool isActive, bool isFocused) => {
|
(rect, index, isActive, isFocused) =>
|
||||||
|
{
|
||||||
NodePort port = node.GetPort(fieldName + " " + index);
|
NodePort port = node.GetPort(fieldName + " " + index);
|
||||||
if (hasArrayData && arrayData.propertyType != SerializedPropertyType.String) {
|
if (hasArrayData && arrayData.propertyType != SerializedPropertyType.String)
|
||||||
if (arrayData.arraySize <= index) {
|
{
|
||||||
|
if (arrayData.arraySize <= index)
|
||||||
|
{
|
||||||
EditorGUI.LabelField(rect, "Array[" + index + "] data out of range");
|
EditorGUI.LabelField(rect, "Array[" + index + "] data out of range");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
SerializedProperty itemData = arrayData.GetArrayElementAtIndex(index);
|
SerializedProperty itemData = arrayData.GetArrayElementAtIndex(index);
|
||||||
EditorGUI.PropertyField(rect, itemData, true);
|
EditorGUI.PropertyField(rect, itemData, true);
|
||||||
} else EditorGUI.LabelField(rect, port != null ? port.fieldName : "");
|
}
|
||||||
if (port != null) {
|
else
|
||||||
Vector2 pos = rect.position + (port.IsOutput ? new Vector2(rect.width + 6, 0) : new Vector2(-36, 0));
|
{
|
||||||
NodeEditorGUILayout.PortField(pos, port);
|
EditorGUI.LabelField(rect, port != null ? port.fieldName : "");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (port != null)
|
||||||
|
{
|
||||||
|
Vector2 pos = rect.position +
|
||||||
|
(port.IsOutput ? new Vector2(rect.width + 6, 0) : new Vector2(-36, 0));
|
||||||
|
PortField(pos, port);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
list.elementHeightCallback =
|
list.elementHeightCallback =
|
||||||
(int index) => {
|
index =>
|
||||||
if (hasArrayData) {
|
{
|
||||||
if (arrayData.arraySize <= index) return EditorGUIUtility.singleLineHeight;
|
if (hasArrayData)
|
||||||
|
{
|
||||||
|
if (arrayData.arraySize <= index)
|
||||||
|
{
|
||||||
|
return EditorGUIUtility.singleLineHeight;
|
||||||
|
}
|
||||||
|
|
||||||
SerializedProperty itemData = arrayData.GetArrayElementAtIndex(index);
|
SerializedProperty itemData = arrayData.GetArrayElementAtIndex(index);
|
||||||
return EditorGUI.GetPropertyHeight(itemData);
|
return EditorGUI.GetPropertyHeight(itemData);
|
||||||
} else return EditorGUIUtility.singleLineHeight;
|
}
|
||||||
|
|
||||||
|
return EditorGUIUtility.singleLineHeight;
|
||||||
};
|
};
|
||||||
list.drawHeaderCallback =
|
list.drawHeaderCallback =
|
||||||
(Rect rect) => {
|
rect => { EditorGUI.LabelField(rect, label); };
|
||||||
EditorGUI.LabelField(rect, label);
|
|
||||||
};
|
|
||||||
list.onSelectCallback =
|
list.onSelectCallback =
|
||||||
(ReorderableList rl) => {
|
rl => { reorderableListIndex = rl.index; };
|
||||||
reorderableListIndex = rl.index;
|
|
||||||
};
|
|
||||||
list.onReorderCallback =
|
list.onReorderCallback =
|
||||||
(ReorderableList rl) => {
|
rl =>
|
||||||
|
{
|
||||||
serializedObject.Update();
|
serializedObject.Update();
|
||||||
bool hasRect = false;
|
bool hasRect = false;
|
||||||
bool hasNewRect = false;
|
bool hasNewRect = false;
|
||||||
Rect rect = Rect.zero;
|
Rect rect = Rect.zero;
|
||||||
Rect newRect = Rect.zero;
|
Rect newRect = Rect.zero;
|
||||||
// Move up
|
// Move up
|
||||||
if (rl.index > reorderableListIndex) {
|
if (rl.index > reorderableListIndex)
|
||||||
for (int i = reorderableListIndex; i < rl.index; ++i) {
|
{
|
||||||
|
for (int i = reorderableListIndex; i < rl.index; ++i)
|
||||||
|
{
|
||||||
NodePort port = node.GetPort(fieldName + " " + i);
|
NodePort port = node.GetPort(fieldName + " " + i);
|
||||||
NodePort nextPort = node.GetPort(fieldName + " " + (i + 1));
|
NodePort nextPort = node.GetPort(fieldName + " " + (i + 1));
|
||||||
port.SwapConnections(nextPort);
|
port.SwapConnections(nextPort);
|
||||||
|
|
||||||
// Swap cached positions to mitigate twitching
|
// Swap cached positions to mitigate twitching
|
||||||
hasRect = NodeEditorWindow.current.portConnectionPoints.TryGetValue(port, out rect);
|
hasRect = NodeEditorWindow.current.portConnectionPoints.TryGetValue(port, out rect);
|
||||||
hasNewRect = NodeEditorWindow.current.portConnectionPoints.TryGetValue(nextPort, out newRect);
|
hasNewRect =
|
||||||
|
NodeEditorWindow.current.portConnectionPoints.TryGetValue(nextPort, out newRect);
|
||||||
NodeEditorWindow.current.portConnectionPoints[port] = hasNewRect ? newRect : rect;
|
NodeEditorWindow.current.portConnectionPoints[port] = hasNewRect ? newRect : rect;
|
||||||
NodeEditorWindow.current.portConnectionPoints[nextPort] = hasRect ? rect : newRect;
|
NodeEditorWindow.current.portConnectionPoints[nextPort] = hasRect ? rect : newRect;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Move down
|
// Move down
|
||||||
else {
|
else
|
||||||
for (int i = reorderableListIndex; i > rl.index; --i) {
|
{
|
||||||
|
for (int i = reorderableListIndex; i > rl.index; --i)
|
||||||
|
{
|
||||||
NodePort port = node.GetPort(fieldName + " " + i);
|
NodePort port = node.GetPort(fieldName + " " + i);
|
||||||
NodePort nextPort = node.GetPort(fieldName + " " + (i - 1));
|
NodePort nextPort = node.GetPort(fieldName + " " + (i - 1));
|
||||||
port.SwapConnections(nextPort);
|
port.SwapConnections(nextPort);
|
||||||
|
|
||||||
// Swap cached positions to mitigate twitching
|
// Swap cached positions to mitigate twitching
|
||||||
hasRect = NodeEditorWindow.current.portConnectionPoints.TryGetValue(port, out rect);
|
hasRect = NodeEditorWindow.current.portConnectionPoints.TryGetValue(port, out rect);
|
||||||
hasNewRect = NodeEditorWindow.current.portConnectionPoints.TryGetValue(nextPort, out newRect);
|
hasNewRect =
|
||||||
|
NodeEditorWindow.current.portConnectionPoints.TryGetValue(nextPort, out newRect);
|
||||||
NodeEditorWindow.current.portConnectionPoints[port] = hasNewRect ? newRect : rect;
|
NodeEditorWindow.current.portConnectionPoints[port] = hasNewRect ? newRect : rect;
|
||||||
NodeEditorWindow.current.portConnectionPoints[nextPort] = hasRect ? rect : newRect;
|
NodeEditorWindow.current.portConnectionPoints[nextPort] = hasRect ? rect : newRect;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Apply changes
|
// Apply changes
|
||||||
serializedObject.ApplyModifiedProperties();
|
serializedObject.ApplyModifiedProperties();
|
||||||
serializedObject.Update();
|
serializedObject.Update();
|
||||||
|
|
||||||
// Move array data if there is any
|
// Move array data if there is any
|
||||||
if (hasArrayData) {
|
if (hasArrayData)
|
||||||
|
{
|
||||||
arrayData.MoveArrayElement(reorderableListIndex, rl.index);
|
arrayData.MoveArrayElement(reorderableListIndex, rl.index);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -443,98 +636,152 @@ namespace XNodeEditor {
|
|||||||
EditorApplication.delayCall += NodeEditorWindow.current.Repaint;
|
EditorApplication.delayCall += NodeEditorWindow.current.Repaint;
|
||||||
};
|
};
|
||||||
list.onAddCallback =
|
list.onAddCallback =
|
||||||
(ReorderableList rl) => {
|
rl =>
|
||||||
|
{
|
||||||
// Add dynamic port postfixed with an index number
|
// Add dynamic port postfixed with an index number
|
||||||
string newName = fieldName + " 0";
|
string newName = fieldName + " 0";
|
||||||
int i = 0;
|
int i = 0;
|
||||||
while (node.HasPort(newName)) newName = fieldName + " " + (++i);
|
while (node.HasPort(newName))
|
||||||
|
{
|
||||||
|
newName = fieldName + " " + ++i;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (io == NodePort.IO.Output)
|
||||||
|
{
|
||||||
|
node.AddDynamicOutput(type, connectionType, Node.TypeConstraint.None, newName);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
node.AddDynamicInput(type, connectionType, typeConstraint, newName);
|
||||||
|
}
|
||||||
|
|
||||||
if (io == NodePort.IO.Output) node.AddDynamicOutput(type, connectionType, Node.TypeConstraint.None, newName);
|
|
||||||
else node.AddDynamicInput(type, connectionType, typeConstraint, newName);
|
|
||||||
serializedObject.Update();
|
serializedObject.Update();
|
||||||
EditorUtility.SetDirty(node);
|
EditorUtility.SetDirty(node);
|
||||||
if (hasArrayData) {
|
if (hasArrayData)
|
||||||
|
{
|
||||||
arrayData.InsertArrayElementAtIndex(arrayData.arraySize);
|
arrayData.InsertArrayElementAtIndex(arrayData.arraySize);
|
||||||
}
|
}
|
||||||
|
|
||||||
serializedObject.ApplyModifiedProperties();
|
serializedObject.ApplyModifiedProperties();
|
||||||
};
|
};
|
||||||
list.onRemoveCallback =
|
list.onRemoveCallback =
|
||||||
(ReorderableList rl) => {
|
rl =>
|
||||||
|
{
|
||||||
var indexedPorts = node.DynamicPorts.Select(x => {
|
var indexedPorts = node.DynamicPorts.Select(x =>
|
||||||
|
{
|
||||||
string[] split = x.fieldName.Split(' ');
|
string[] split = x.fieldName.Split(' ');
|
||||||
if (split != null && split.Length == 2 && split[0] == fieldName) {
|
if (split != null && split.Length == 2 && split[0] == fieldName)
|
||||||
|
{
|
||||||
int i = -1;
|
int i = -1;
|
||||||
if (int.TryParse(split[1], out i)) {
|
if (int.TryParse(split[1], out i))
|
||||||
|
{
|
||||||
return new { index = i, port = x };
|
return new { index = i, port = x };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return new { index = -1, port = (NodePort)null };
|
return new { index = -1, port = (NodePort)null };
|
||||||
}).Where(x => x.port != null);
|
}).Where(x => x.port != null);
|
||||||
dynamicPorts = indexedPorts.OrderBy(x => x.index).Select(x => x.port).ToList();
|
dynamicPorts = indexedPorts.OrderBy(x => x.index).Select(x => x.port).ToList();
|
||||||
|
|
||||||
int index = rl.index;
|
int index = rl.index;
|
||||||
|
|
||||||
if (dynamicPorts[index] == null) {
|
if (dynamicPorts[index] == null)
|
||||||
|
{
|
||||||
Debug.LogWarning("No port found at index " + index + " - Skipped");
|
Debug.LogWarning("No port found at index " + index + " - Skipped");
|
||||||
} else if (dynamicPorts.Count <= index) {
|
}
|
||||||
Debug.LogWarning("DynamicPorts[" + index + "] out of range. Length was " + dynamicPorts.Count + " - Skipped");
|
else if (dynamicPorts.Count <= index)
|
||||||
} else {
|
{
|
||||||
|
Debug.LogWarning("DynamicPorts[" + index + "] out of range. Length was " + dynamicPorts.Count +
|
||||||
|
" - Skipped");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
// Clear the removed ports connections
|
// Clear the removed ports connections
|
||||||
dynamicPorts[index].ClearConnections();
|
dynamicPorts[index].ClearConnections();
|
||||||
// Move following connections one step up to replace the missing connection
|
// Move following connections one step up to replace the missing connection
|
||||||
for (int k = index + 1; k < dynamicPorts.Count(); k++) {
|
for (int k = index + 1; k < dynamicPorts.Count(); k++)
|
||||||
for (int j = 0; j < dynamicPorts[k].ConnectionCount; j++) {
|
{
|
||||||
|
for (int j = 0; j < dynamicPorts[k].ConnectionCount; j++)
|
||||||
|
{
|
||||||
NodePort other = dynamicPorts[k].GetConnection(j);
|
NodePort other = dynamicPorts[k].GetConnection(j);
|
||||||
dynamicPorts[k].Disconnect(other);
|
dynamicPorts[k].Disconnect(other);
|
||||||
dynamicPorts[k - 1].Connect(other);
|
dynamicPorts[k - 1].Connect(other);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Remove the last dynamic port, to avoid messing up the indexing
|
// Remove the last dynamic port, to avoid messing up the indexing
|
||||||
node.RemoveDynamicPort(dynamicPorts[dynamicPorts.Count() - 1].fieldName);
|
node.RemoveDynamicPort(dynamicPorts[dynamicPorts.Count() - 1].fieldName);
|
||||||
serializedObject.Update();
|
serializedObject.Update();
|
||||||
EditorUtility.SetDirty(node);
|
EditorUtility.SetDirty(node);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (hasArrayData && arrayData.propertyType != SerializedPropertyType.String) {
|
if (hasArrayData && arrayData.propertyType != SerializedPropertyType.String)
|
||||||
if (arrayData.arraySize <= index) {
|
{
|
||||||
Debug.LogWarning("Attempted to remove array index " + index + " where only " + arrayData.arraySize + " exist - Skipped");
|
if (arrayData.arraySize <= index)
|
||||||
|
{
|
||||||
|
Debug.LogWarning("Attempted to remove array index " + index + " where only " +
|
||||||
|
arrayData.arraySize + " exist - Skipped");
|
||||||
Debug.Log(rl.list[0]);
|
Debug.Log(rl.list[0]);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
arrayData.DeleteArrayElementAtIndex(index);
|
arrayData.DeleteArrayElementAtIndex(index);
|
||||||
// Error handling. If the following happens too often, file a bug report at https://github.com/Siccity/xNode/issues
|
// Error handling. If the following happens too often, file a bug report at https://github.com/Siccity/xNode/issues
|
||||||
if (dynamicPorts.Count <= arrayData.arraySize) {
|
if (dynamicPorts.Count <= arrayData.arraySize)
|
||||||
while (dynamicPorts.Count <= arrayData.arraySize) {
|
{
|
||||||
|
while (dynamicPorts.Count <= arrayData.arraySize)
|
||||||
|
{
|
||||||
arrayData.DeleteArrayElementAtIndex(arrayData.arraySize - 1);
|
arrayData.DeleteArrayElementAtIndex(arrayData.arraySize - 1);
|
||||||
}
|
}
|
||||||
UnityEngine.Debug.LogWarning("Array size exceeded dynamic ports size. Excess items removed.");
|
|
||||||
|
Debug.LogWarning("Array size exceeded dynamic ports size. Excess items removed.");
|
||||||
}
|
}
|
||||||
|
|
||||||
serializedObject.ApplyModifiedProperties();
|
serializedObject.ApplyModifiedProperties();
|
||||||
serializedObject.Update();
|
serializedObject.Update();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
if (hasArrayData) {
|
if (hasArrayData)
|
||||||
|
{
|
||||||
int dynamicPortCount = dynamicPorts.Count;
|
int dynamicPortCount = dynamicPorts.Count;
|
||||||
while (dynamicPortCount < arrayData.arraySize) {
|
while (dynamicPortCount < arrayData.arraySize)
|
||||||
|
{
|
||||||
// Add dynamic port postfixed with an index number
|
// Add dynamic port postfixed with an index number
|
||||||
string newName = arrayData.name + " 0";
|
string newName = arrayData.name + " 0";
|
||||||
int i = 0;
|
int i = 0;
|
||||||
while (node.HasPort(newName)) newName = arrayData.name + " " + (++i);
|
while (node.HasPort(newName))
|
||||||
if (io == NodePort.IO.Output) node.AddDynamicOutput(type, connectionType, typeConstraint, newName);
|
{
|
||||||
else node.AddDynamicInput(type, connectionType, typeConstraint, newName);
|
newName = arrayData.name + " " + ++i;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (io == NodePort.IO.Output)
|
||||||
|
{
|
||||||
|
node.AddDynamicOutput(type, connectionType, typeConstraint, newName);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
node.AddDynamicInput(type, connectionType, typeConstraint, newName);
|
||||||
|
}
|
||||||
|
|
||||||
EditorUtility.SetDirty(node);
|
EditorUtility.SetDirty(node);
|
||||||
dynamicPortCount++;
|
dynamicPortCount++;
|
||||||
}
|
}
|
||||||
while (arrayData.arraySize < dynamicPortCount) {
|
|
||||||
|
while (arrayData.arraySize < dynamicPortCount)
|
||||||
|
{
|
||||||
arrayData.InsertArrayElementAtIndex(arrayData.arraySize);
|
arrayData.InsertArrayElementAtIndex(arrayData.arraySize);
|
||||||
}
|
}
|
||||||
|
|
||||||
serializedObject.ApplyModifiedProperties();
|
serializedObject.ApplyModifiedProperties();
|
||||||
serializedObject.Update();
|
serializedObject.Update();
|
||||||
}
|
}
|
||||||
if (onCreation != null) onCreation(list);
|
|
||||||
|
if (onCreation != null)
|
||||||
|
{
|
||||||
|
onCreation(list);
|
||||||
|
}
|
||||||
|
|
||||||
return list;
|
return list;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -3,33 +3,67 @@ using System.Collections.Generic;
|
|||||||
using UnityEditor;
|
using UnityEditor;
|
||||||
using UnityEngine;
|
using UnityEngine;
|
||||||
using UnityEngine.Serialization;
|
using UnityEngine.Serialization;
|
||||||
|
using Random = UnityEngine.Random;
|
||||||
|
|
||||||
namespace XNodeEditor {
|
namespace XNodeEditor
|
||||||
public enum NoodlePath { Curvy, Straight, Angled, ShaderLab }
|
{
|
||||||
public enum NoodleStroke { Full, Dashed }
|
public enum NoodlePath
|
||||||
|
{
|
||||||
public static class NodeEditorPreferences {
|
Curvy,
|
||||||
|
Straight,
|
||||||
|
Angled,
|
||||||
|
ShaderLab
|
||||||
|
}
|
||||||
|
public enum NoodleStroke
|
||||||
|
{
|
||||||
|
Full,
|
||||||
|
Dashed
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class NodeEditorPreferences
|
||||||
|
{
|
||||||
/// <summary> The last editor we checked. This should be the one we modify </summary>
|
/// <summary> The last editor we checked. This should be the one we modify </summary>
|
||||||
private static XNodeEditor.NodeGraphEditor lastEditor;
|
private static NodeGraphEditor lastEditor;
|
||||||
/// <summary> The last key we checked. This should be the one we modify </summary>
|
/// <summary> The last key we checked. This should be the one we modify </summary>
|
||||||
private static string lastKey = "xNode.Settings";
|
private static string lastKey = "xNode.Settings";
|
||||||
|
|
||||||
private static Dictionary<Type, Color> typeColors = new Dictionary<Type, Color>();
|
private static Dictionary<Type, Color> typeColors = new Dictionary<Type, Color>();
|
||||||
private static Dictionary<string, Settings> settings = new Dictionary<string, Settings>();
|
private static readonly Dictionary<string, Settings> settings = new Dictionary<string, Settings>();
|
||||||
|
|
||||||
[System.Serializable]
|
[Serializable]
|
||||||
public class Settings : ISerializationCallbackReceiver {
|
public class Settings : ISerializationCallbackReceiver
|
||||||
|
{
|
||||||
[SerializeField] private Color32 _gridLineColor = new Color(.23f, .23f, .23f);
|
[SerializeField] private Color32 _gridLineColor = new Color(.23f, .23f, .23f);
|
||||||
public Color32 gridLineColor { get { return _gridLineColor; } set { _gridLineColor = value; _gridTexture = null; _crossTexture = null; } }
|
public Color32 gridLineColor
|
||||||
|
{
|
||||||
|
get => _gridLineColor;
|
||||||
|
set
|
||||||
|
{
|
||||||
|
_gridLineColor = value;
|
||||||
|
_gridTexture = null;
|
||||||
|
_crossTexture = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
[SerializeField] private Color32 _gridBgColor = new Color(.19f, .19f, .19f);
|
[SerializeField] private Color32 _gridBgColor = new Color(.19f, .19f, .19f);
|
||||||
public Color32 gridBgColor { get { return _gridBgColor; } set { _gridBgColor = value; _gridTexture = null; } }
|
public Color32 gridBgColor
|
||||||
|
{
|
||||||
|
get => _gridBgColor;
|
||||||
|
set
|
||||||
|
{
|
||||||
|
_gridBgColor = value;
|
||||||
|
_gridTexture = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
[Obsolete("Use maxZoom instead")]
|
[Obsolete("Use maxZoom instead")]
|
||||||
public float zoomOutLimit { get { return maxZoom; } set { maxZoom = value; } }
|
public float zoomOutLimit
|
||||||
|
{
|
||||||
|
get => maxZoom;
|
||||||
|
set => maxZoom = value;
|
||||||
|
}
|
||||||
|
|
||||||
[UnityEngine.Serialization.FormerlySerializedAs("zoomOutLimit")]
|
[FormerlySerializedAs("zoomOutLimit")]
|
||||||
public float maxZoom = 5f;
|
public float maxZoom = 5f;
|
||||||
public float minZoom = 1f;
|
public float minZoom = 1f;
|
||||||
public Color32 tintColor = new Color32(90, 97, 105, 255);
|
public Color32 tintColor = new Color32(90, 97, 105, 255);
|
||||||
@ -49,63 +83,100 @@ namespace XNodeEditor {
|
|||||||
public NoodleStroke noodleStroke = NoodleStroke.Full;
|
public NoodleStroke noodleStroke = NoodleStroke.Full;
|
||||||
|
|
||||||
private Texture2D _gridTexture;
|
private Texture2D _gridTexture;
|
||||||
public Texture2D gridTexture {
|
public Texture2D gridTexture
|
||||||
get {
|
{
|
||||||
if (_gridTexture == null) _gridTexture = NodeEditorResources.GenerateGridTexture(gridLineColor, gridBgColor);
|
get
|
||||||
|
{
|
||||||
|
if (_gridTexture == null)
|
||||||
|
{
|
||||||
|
_gridTexture = NodeEditorResources.GenerateGridTexture(gridLineColor, gridBgColor);
|
||||||
|
}
|
||||||
|
|
||||||
return _gridTexture;
|
return _gridTexture;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
private Texture2D _crossTexture;
|
private Texture2D _crossTexture;
|
||||||
public Texture2D crossTexture {
|
public Texture2D crossTexture
|
||||||
get {
|
{
|
||||||
if (_crossTexture == null) _crossTexture = NodeEditorResources.GenerateCrossTexture(gridLineColor);
|
get
|
||||||
|
{
|
||||||
|
if (_crossTexture == null)
|
||||||
|
{
|
||||||
|
_crossTexture = NodeEditorResources.GenerateCrossTexture(gridLineColor);
|
||||||
|
}
|
||||||
|
|
||||||
return _crossTexture;
|
return _crossTexture;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void OnAfterDeserialize() {
|
public void OnAfterDeserialize()
|
||||||
|
{
|
||||||
// Deserialize typeColorsData
|
// Deserialize typeColorsData
|
||||||
typeColors = new Dictionary<string, Color>();
|
typeColors = new Dictionary<string, Color>();
|
||||||
string[] data = typeColorsData.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
|
string[] data = typeColorsData.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
|
||||||
for (int i = 0; i < data.Length; i += 2) {
|
for (int i = 0; i < data.Length; i += 2)
|
||||||
|
{
|
||||||
Color col;
|
Color col;
|
||||||
if (ColorUtility.TryParseHtmlString("#" + data[i + 1], out col)) {
|
if (ColorUtility.TryParseHtmlString("#" + data[i + 1], out col))
|
||||||
|
{
|
||||||
typeColors.Add(data[i], col);
|
typeColors.Add(data[i], col);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void OnBeforeSerialize() {
|
public void OnBeforeSerialize()
|
||||||
|
{
|
||||||
// Serialize typeColors
|
// Serialize typeColors
|
||||||
typeColorsData = "";
|
typeColorsData = "";
|
||||||
foreach (var item in typeColors) {
|
foreach (var item in typeColors)
|
||||||
|
{
|
||||||
typeColorsData += item.Key + "," + ColorUtility.ToHtmlStringRGB(item.Value) + ",";
|
typeColorsData += item.Key + "," + ColorUtility.ToHtmlStringRGB(item.Value) + ",";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Get settings of current active editor </summary>
|
/// <summary> Get settings of current active editor </summary>
|
||||||
public static Settings GetSettings() {
|
public static Settings GetSettings()
|
||||||
if (XNodeEditor.NodeEditorWindow.current == null) return new Settings();
|
{
|
||||||
|
if (NodeEditorWindow.current == null)
|
||||||
if (lastEditor != XNodeEditor.NodeEditorWindow.current.graphEditor) {
|
{
|
||||||
object[] attribs = XNodeEditor.NodeEditorWindow.current.graphEditor.GetType().GetCustomAttributes(typeof(XNodeEditor.NodeGraphEditor.CustomNodeGraphEditorAttribute), true);
|
return new Settings();
|
||||||
if (attribs.Length == 1) {
|
|
||||||
XNodeEditor.NodeGraphEditor.CustomNodeGraphEditorAttribute attrib = attribs[0] as XNodeEditor.NodeGraphEditor.CustomNodeGraphEditorAttribute;
|
|
||||||
lastEditor = XNodeEditor.NodeEditorWindow.current.graphEditor;
|
|
||||||
lastKey = attrib.editorPrefsKey;
|
|
||||||
} else return null;
|
|
||||||
}
|
}
|
||||||
if (!settings.ContainsKey(lastKey)) VerifyLoaded();
|
|
||||||
|
if (lastEditor != NodeEditorWindow.current.graphEditor)
|
||||||
|
{
|
||||||
|
object[] attribs = NodeEditorWindow.current.graphEditor.GetType()
|
||||||
|
.GetCustomAttributes(typeof(NodeGraphEditor.CustomNodeGraphEditorAttribute), true);
|
||||||
|
if (attribs.Length == 1)
|
||||||
|
{
|
||||||
|
NodeGraphEditor.CustomNodeGraphEditorAttribute attrib =
|
||||||
|
attribs[0] as NodeGraphEditor.CustomNodeGraphEditorAttribute;
|
||||||
|
lastEditor = NodeEditorWindow.current.graphEditor;
|
||||||
|
lastKey = attrib.editorPrefsKey;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!settings.ContainsKey(lastKey))
|
||||||
|
{
|
||||||
|
VerifyLoaded();
|
||||||
|
}
|
||||||
|
|
||||||
return settings[lastKey];
|
return settings[lastKey];
|
||||||
}
|
}
|
||||||
|
|
||||||
#if UNITY_2019_1_OR_NEWER
|
#if UNITY_2019_1_OR_NEWER
|
||||||
[SettingsProvider]
|
[SettingsProvider]
|
||||||
public static SettingsProvider CreateXNodeSettingsProvider() {
|
public static SettingsProvider CreateXNodeSettingsProvider()
|
||||||
SettingsProvider provider = new SettingsProvider("Preferences/Node Editor", SettingsScope.User) {
|
{
|
||||||
guiHandler = (searchContext) => { XNodeEditor.NodeEditorPreferences.PreferencesGUI(); },
|
SettingsProvider provider = new SettingsProvider("Preferences/Node Editor", SettingsScope.User)
|
||||||
keywords = new HashSet<string>(new [] { "xNode", "node", "editor", "graph", "connections", "noodles", "ports" })
|
{
|
||||||
|
guiHandler = searchContext => { PreferencesGUI(); },
|
||||||
|
keywords = new HashSet<string>(new[]
|
||||||
|
{ "xNode", "node", "editor", "graph", "connections", "noodles", "ports" })
|
||||||
};
|
};
|
||||||
return provider;
|
return provider;
|
||||||
}
|
}
|
||||||
@ -114,72 +185,110 @@ namespace XNodeEditor {
|
|||||||
#if !UNITY_2019_1_OR_NEWER
|
#if !UNITY_2019_1_OR_NEWER
|
||||||
[PreferenceItem("Node Editor")]
|
[PreferenceItem("Node Editor")]
|
||||||
#endif
|
#endif
|
||||||
private static void PreferencesGUI() {
|
private static void PreferencesGUI()
|
||||||
|
{
|
||||||
VerifyLoaded();
|
VerifyLoaded();
|
||||||
Settings settings = NodeEditorPreferences.settings[lastKey];
|
Settings settings = NodeEditorPreferences.settings[lastKey];
|
||||||
|
|
||||||
if (GUILayout.Button(new GUIContent("Documentation", "https://github.com/Siccity/xNode/wiki"), GUILayout.Width(100))) Application.OpenURL("https://github.com/Siccity/xNode/wiki");
|
if (GUILayout.Button(new GUIContent("Documentation", "https://github.com/Siccity/xNode/wiki"),
|
||||||
|
GUILayout.Width(100)))
|
||||||
|
{
|
||||||
|
Application.OpenURL("https://github.com/Siccity/xNode/wiki");
|
||||||
|
}
|
||||||
|
|
||||||
EditorGUILayout.Space();
|
EditorGUILayout.Space();
|
||||||
|
|
||||||
NodeSettingsGUI(lastKey, settings);
|
NodeSettingsGUI(lastKey, settings);
|
||||||
GridSettingsGUI(lastKey, settings);
|
GridSettingsGUI(lastKey, settings);
|
||||||
SystemSettingsGUI(lastKey, settings);
|
SystemSettingsGUI(lastKey, settings);
|
||||||
TypeColorsGUI(lastKey, settings);
|
TypeColorsGUI(lastKey, settings);
|
||||||
if (GUILayout.Button(new GUIContent("Set Default", "Reset all values to default"), GUILayout.Width(120))) {
|
if (GUILayout.Button(new GUIContent("Set Default", "Reset all values to default"), GUILayout.Width(120)))
|
||||||
|
{
|
||||||
ResetPrefs();
|
ResetPrefs();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void GridSettingsGUI(string key, Settings settings) {
|
private static void GridSettingsGUI(string key, Settings settings)
|
||||||
|
{
|
||||||
//Label
|
//Label
|
||||||
EditorGUILayout.LabelField("Grid", EditorStyles.boldLabel);
|
EditorGUILayout.LabelField("Grid", EditorStyles.boldLabel);
|
||||||
settings.gridSnap = EditorGUILayout.Toggle(new GUIContent("Snap", "Hold CTRL in editor to invert"), settings.gridSnap);
|
settings.gridSnap = EditorGUILayout.Toggle(new GUIContent("Snap", "Hold CTRL in editor to invert"),
|
||||||
settings.zoomToMouse = EditorGUILayout.Toggle(new GUIContent("Zoom to Mouse", "Zooms towards mouse position"), settings.zoomToMouse);
|
settings.gridSnap);
|
||||||
|
settings.zoomToMouse =
|
||||||
|
EditorGUILayout.Toggle(new GUIContent("Zoom to Mouse", "Zooms towards mouse position"),
|
||||||
|
settings.zoomToMouse);
|
||||||
EditorGUILayout.LabelField("Zoom");
|
EditorGUILayout.LabelField("Zoom");
|
||||||
EditorGUI.indentLevel++;
|
EditorGUI.indentLevel++;
|
||||||
settings.maxZoom = EditorGUILayout.FloatField(new GUIContent("Max", "Upper limit to zoom"), settings.maxZoom);
|
settings.maxZoom =
|
||||||
settings.minZoom = EditorGUILayout.FloatField(new GUIContent("Min", "Lower limit to zoom"), settings.minZoom);
|
EditorGUILayout.FloatField(new GUIContent("Max", "Upper limit to zoom"), settings.maxZoom);
|
||||||
|
settings.minZoom =
|
||||||
|
EditorGUILayout.FloatField(new GUIContent("Min", "Lower limit to zoom"), settings.minZoom);
|
||||||
EditorGUI.indentLevel--;
|
EditorGUI.indentLevel--;
|
||||||
settings.gridLineColor = EditorGUILayout.ColorField("Color", settings.gridLineColor);
|
settings.gridLineColor = EditorGUILayout.ColorField("Color", settings.gridLineColor);
|
||||||
settings.gridBgColor = EditorGUILayout.ColorField(" ", settings.gridBgColor);
|
settings.gridBgColor = EditorGUILayout.ColorField(" ", settings.gridBgColor);
|
||||||
if (GUI.changed) {
|
if (GUI.changed)
|
||||||
|
{
|
||||||
SavePrefs(key, settings);
|
SavePrefs(key, settings);
|
||||||
|
|
||||||
NodeEditorWindow.RepaintAll();
|
NodeEditorWindow.RepaintAll();
|
||||||
}
|
}
|
||||||
|
|
||||||
EditorGUILayout.Space();
|
EditorGUILayout.Space();
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void SystemSettingsGUI(string key, Settings settings) {
|
private static void SystemSettingsGUI(string key, Settings settings)
|
||||||
|
{
|
||||||
//Label
|
//Label
|
||||||
EditorGUILayout.LabelField("System", EditorStyles.boldLabel);
|
EditorGUILayout.LabelField("System", EditorStyles.boldLabel);
|
||||||
settings.autoSave = EditorGUILayout.Toggle(new GUIContent("Autosave", "Disable for better editor performance"), settings.autoSave);
|
settings.autoSave =
|
||||||
settings.openOnCreate = EditorGUILayout.Toggle(new GUIContent("Open Editor on Create", "Disable to prevent openening the editor when creating a new graph"), settings.openOnCreate);
|
EditorGUILayout.Toggle(new GUIContent("Autosave", "Disable for better editor performance"),
|
||||||
if (GUI.changed) SavePrefs(key, settings);
|
settings.autoSave);
|
||||||
|
settings.openOnCreate =
|
||||||
|
EditorGUILayout.Toggle(
|
||||||
|
new GUIContent("Open Editor on Create",
|
||||||
|
"Disable to prevent openening the editor when creating a new graph"), settings.openOnCreate);
|
||||||
|
if (GUI.changed)
|
||||||
|
{
|
||||||
|
SavePrefs(key, settings);
|
||||||
|
}
|
||||||
|
|
||||||
EditorGUILayout.Space();
|
EditorGUILayout.Space();
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void NodeSettingsGUI(string key, Settings settings) {
|
private static void NodeSettingsGUI(string key, Settings settings)
|
||||||
|
{
|
||||||
//Label
|
//Label
|
||||||
EditorGUILayout.LabelField("Node", EditorStyles.boldLabel);
|
EditorGUILayout.LabelField("Node", EditorStyles.boldLabel);
|
||||||
settings.tintColor = EditorGUILayout.ColorField("Tint", settings.tintColor);
|
settings.tintColor = EditorGUILayout.ColorField("Tint", settings.tintColor);
|
||||||
settings.highlightColor = EditorGUILayout.ColorField("Selection", settings.highlightColor);
|
settings.highlightColor = EditorGUILayout.ColorField("Selection", settings.highlightColor);
|
||||||
settings.noodlePath = (NoodlePath) EditorGUILayout.EnumPopup("Noodle path", (Enum) settings.noodlePath);
|
settings.noodlePath = (NoodlePath)EditorGUILayout.EnumPopup("Noodle path", settings.noodlePath);
|
||||||
settings.noodleThickness = EditorGUILayout.FloatField(new GUIContent("Noodle thickness", "Noodle Thickness of the node connections"), settings.noodleThickness);
|
settings.noodleThickness = EditorGUILayout.FloatField(
|
||||||
settings.noodleStroke = (NoodleStroke) EditorGUILayout.EnumPopup("Noodle stroke", (Enum) settings.noodleStroke);
|
new GUIContent("Noodle thickness", "Noodle Thickness of the node connections"),
|
||||||
|
settings.noodleThickness);
|
||||||
|
settings.noodleStroke = (NoodleStroke)EditorGUILayout.EnumPopup("Noodle stroke", settings.noodleStroke);
|
||||||
settings.portTooltips = EditorGUILayout.Toggle("Port Tooltips", settings.portTooltips);
|
settings.portTooltips = EditorGUILayout.Toggle("Port Tooltips", settings.portTooltips);
|
||||||
settings.dragToCreate = EditorGUILayout.Toggle(new GUIContent("Drag to Create", "Drag a port connection anywhere on the grid to create and connect a node"), settings.dragToCreate);
|
settings.dragToCreate =
|
||||||
settings.createFilter = EditorGUILayout.Toggle(new GUIContent("Create Filter", "Only show nodes that are compatible with the selected port"), settings.createFilter);
|
EditorGUILayout.Toggle(
|
||||||
|
new GUIContent("Drag to Create",
|
||||||
|
"Drag a port connection anywhere on the grid to create and connect a node"),
|
||||||
|
settings.dragToCreate);
|
||||||
|
settings.createFilter =
|
||||||
|
EditorGUILayout.Toggle(
|
||||||
|
new GUIContent("Create Filter", "Only show nodes that are compatible with the selected port"),
|
||||||
|
settings.createFilter);
|
||||||
|
|
||||||
//END
|
//END
|
||||||
if (GUI.changed) {
|
if (GUI.changed)
|
||||||
|
{
|
||||||
SavePrefs(key, settings);
|
SavePrefs(key, settings);
|
||||||
NodeEditorWindow.RepaintAll();
|
NodeEditorWindow.RepaintAll();
|
||||||
}
|
}
|
||||||
|
|
||||||
EditorGUILayout.Space();
|
EditorGUILayout.Space();
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void TypeColorsGUI(string key, Settings settings) {
|
private static void TypeColorsGUI(string key, Settings settings)
|
||||||
|
{
|
||||||
//Label
|
//Label
|
||||||
EditorGUILayout.LabelField("Types", EditorStyles.boldLabel);
|
EditorGUILayout.LabelField("Types", EditorStyles.boldLabel);
|
||||||
|
|
||||||
@ -187,17 +296,26 @@ namespace XNodeEditor {
|
|||||||
var typeColorKeys = new List<Type>(typeColors.Keys);
|
var typeColorKeys = new List<Type>(typeColors.Keys);
|
||||||
|
|
||||||
//Display type colors. Save them if they are edited by the user
|
//Display type colors. Save them if they are edited by the user
|
||||||
foreach (var type in typeColorKeys) {
|
foreach (Type type in typeColorKeys)
|
||||||
string typeColorKey = NodeEditorUtilities.PrettyName(type);
|
{
|
||||||
|
string typeColorKey = type.PrettyName();
|
||||||
Color col = typeColors[type];
|
Color col = typeColors[type];
|
||||||
EditorGUI.BeginChangeCheck();
|
EditorGUI.BeginChangeCheck();
|
||||||
EditorGUILayout.BeginHorizontal();
|
EditorGUILayout.BeginHorizontal();
|
||||||
col = EditorGUILayout.ColorField(typeColorKey, col);
|
col = EditorGUILayout.ColorField(typeColorKey, col);
|
||||||
EditorGUILayout.EndHorizontal();
|
EditorGUILayout.EndHorizontal();
|
||||||
if (EditorGUI.EndChangeCheck()) {
|
if (EditorGUI.EndChangeCheck())
|
||||||
|
{
|
||||||
typeColors[type] = col;
|
typeColors[type] = col;
|
||||||
if (settings.typeColors.ContainsKey(typeColorKey)) settings.typeColors[typeColorKey] = col;
|
if (settings.typeColors.ContainsKey(typeColorKey))
|
||||||
else settings.typeColors.Add(typeColorKey, col);
|
{
|
||||||
|
settings.typeColors[typeColorKey] = col;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
settings.typeColors.Add(typeColorKey, col);
|
||||||
|
}
|
||||||
|
|
||||||
SavePrefs(key, settings);
|
SavePrefs(key, settings);
|
||||||
NodeEditorWindow.RepaintAll();
|
NodeEditorWindow.RepaintAll();
|
||||||
}
|
}
|
||||||
@ -205,59 +323,93 @@ namespace XNodeEditor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Load prefs if they exist. Create if they don't </summary>
|
/// <summary> Load prefs if they exist. Create if they don't </summary>
|
||||||
private static Settings LoadPrefs() {
|
private static Settings LoadPrefs()
|
||||||
|
{
|
||||||
// Create settings if it doesn't exist
|
// Create settings if it doesn't exist
|
||||||
if (!EditorPrefs.HasKey(lastKey)) {
|
if (!EditorPrefs.HasKey(lastKey))
|
||||||
if (lastEditor != null) EditorPrefs.SetString(lastKey, JsonUtility.ToJson(lastEditor.GetDefaultPreferences()));
|
{
|
||||||
else EditorPrefs.SetString(lastKey, JsonUtility.ToJson(new Settings()));
|
if (lastEditor != null)
|
||||||
|
{
|
||||||
|
EditorPrefs.SetString(lastKey, JsonUtility.ToJson(lastEditor.GetDefaultPreferences()));
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
EditorPrefs.SetString(lastKey, JsonUtility.ToJson(new Settings()));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return JsonUtility.FromJson<Settings>(EditorPrefs.GetString(lastKey));
|
return JsonUtility.FromJson<Settings>(EditorPrefs.GetString(lastKey));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Delete all prefs </summary>
|
/// <summary> Delete all prefs </summary>
|
||||||
public static void ResetPrefs() {
|
public static void ResetPrefs()
|
||||||
if (EditorPrefs.HasKey(lastKey)) EditorPrefs.DeleteKey(lastKey);
|
{
|
||||||
if (settings.ContainsKey(lastKey)) settings.Remove(lastKey);
|
if (EditorPrefs.HasKey(lastKey))
|
||||||
|
{
|
||||||
|
EditorPrefs.DeleteKey(lastKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (settings.ContainsKey(lastKey))
|
||||||
|
{
|
||||||
|
settings.Remove(lastKey);
|
||||||
|
}
|
||||||
|
|
||||||
typeColors = new Dictionary<Type, Color>();
|
typeColors = new Dictionary<Type, Color>();
|
||||||
VerifyLoaded();
|
VerifyLoaded();
|
||||||
NodeEditorWindow.RepaintAll();
|
NodeEditorWindow.RepaintAll();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Save preferences in EditorPrefs </summary>
|
/// <summary> Save preferences in EditorPrefs </summary>
|
||||||
private static void SavePrefs(string key, Settings settings) {
|
private static void SavePrefs(string key, Settings settings)
|
||||||
|
{
|
||||||
EditorPrefs.SetString(key, JsonUtility.ToJson(settings));
|
EditorPrefs.SetString(key, JsonUtility.ToJson(settings));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Check if we have loaded settings for given key. If not, load them </summary>
|
/// <summary> Check if we have loaded settings for given key. If not, load them </summary>
|
||||||
private static void VerifyLoaded() {
|
private static void VerifyLoaded()
|
||||||
if (!settings.ContainsKey(lastKey)) settings.Add(lastKey, LoadPrefs());
|
{
|
||||||
|
if (!settings.ContainsKey(lastKey))
|
||||||
|
{
|
||||||
|
settings.Add(lastKey, LoadPrefs());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Return color based on type </summary>
|
/// <summary> Return color based on type </summary>
|
||||||
public static Color GetTypeColor(System.Type type) {
|
public static Color GetTypeColor(Type type)
|
||||||
|
{
|
||||||
VerifyLoaded();
|
VerifyLoaded();
|
||||||
if (type == null) return Color.gray;
|
if (type == null)
|
||||||
|
{
|
||||||
|
return Color.gray;
|
||||||
|
}
|
||||||
|
|
||||||
Color col;
|
Color col;
|
||||||
if (!typeColors.TryGetValue(type, out col)) {
|
if (!typeColors.TryGetValue(type, out col))
|
||||||
|
{
|
||||||
string typeName = type.PrettyName();
|
string typeName = type.PrettyName();
|
||||||
if (settings[lastKey].typeColors.ContainsKey(typeName)) typeColors.Add(type, settings[lastKey].typeColors[typeName]);
|
if (settings[lastKey].typeColors.ContainsKey(typeName))
|
||||||
else {
|
{
|
||||||
|
typeColors.Add(type, settings[lastKey].typeColors[typeName]);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
#if UNITY_5_4_OR_NEWER
|
#if UNITY_5_4_OR_NEWER
|
||||||
UnityEngine.Random.State oldState = UnityEngine.Random.state;
|
Random.State oldState = Random.state;
|
||||||
UnityEngine.Random.InitState(typeName.GetHashCode());
|
Random.InitState(typeName.GetHashCode());
|
||||||
#else
|
#else
|
||||||
int oldSeed = UnityEngine.Random.seed;
|
int oldSeed = UnityEngine.Random.seed;
|
||||||
UnityEngine.Random.seed = typeName.GetHashCode();
|
UnityEngine.Random.seed = typeName.GetHashCode();
|
||||||
#endif
|
#endif
|
||||||
col = new Color(UnityEngine.Random.value, UnityEngine.Random.value, UnityEngine.Random.value);
|
col = new Color(Random.value, Random.value, Random.value);
|
||||||
typeColors.Add(type, col);
|
typeColors.Add(type, col);
|
||||||
#if UNITY_5_4_OR_NEWER
|
#if UNITY_5_4_OR_NEWER
|
||||||
UnityEngine.Random.state = oldState;
|
Random.state = oldState;
|
||||||
#else
|
#else
|
||||||
UnityEngine.Random.seed = oldSeed;
|
UnityEngine.Random.seed = oldSeed;
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return col;
|
return col;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,99 +1,138 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections;
|
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Reflection;
|
using System.Reflection;
|
||||||
using UnityEditor;
|
using UnityEditor;
|
||||||
using UnityEngine;
|
using UnityEngine;
|
||||||
|
using XNode;
|
||||||
|
using Object = UnityEngine.Object;
|
||||||
#if UNITY_2019_1_OR_NEWER && USE_ADVANCED_GENERIC_MENU
|
#if UNITY_2019_1_OR_NEWER && USE_ADVANCED_GENERIC_MENU
|
||||||
using GenericMenu = XNodeEditor.AdvancedGenericMenu;
|
using GenericMenu = XNodeEditor.AdvancedGenericMenu;
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
namespace XNodeEditor {
|
namespace XNodeEditor
|
||||||
|
{
|
||||||
/// <summary> Contains reflection-related extensions built for xNode </summary>
|
/// <summary> Contains reflection-related extensions built for xNode </summary>
|
||||||
public static class NodeEditorReflection {
|
public static class NodeEditorReflection
|
||||||
|
{
|
||||||
[NonSerialized] private static Dictionary<Type, Color> nodeTint;
|
[NonSerialized] private static Dictionary<Type, Color> nodeTint;
|
||||||
[NonSerialized] private static Dictionary<Type, int> nodeWidth;
|
[NonSerialized] private static Dictionary<Type, int> nodeWidth;
|
||||||
/// <summary> All available node types </summary>
|
/// <summary> All available node types </summary>
|
||||||
public static Type[] nodeTypes { get { return _nodeTypes != null ? _nodeTypes : _nodeTypes = GetNodeTypes(); } }
|
public static Type[] nodeTypes => _nodeTypes != null ? _nodeTypes : _nodeTypes = GetNodeTypes();
|
||||||
|
|
||||||
[NonSerialized] private static Type[] _nodeTypes = null;
|
[NonSerialized] private static Type[] _nodeTypes;
|
||||||
|
|
||||||
/// <summary> Return a delegate used to determine whether window is docked or not. It is faster to cache this delegate than run the reflection required each time. </summary>
|
/// <summary> Return a delegate used to determine whether window is docked or not. It is faster to cache this delegate than run the reflection required each time. </summary>
|
||||||
public static Func<bool> GetIsDockedDelegate(this EditorWindow window) {
|
public static Func<bool> GetIsDockedDelegate(this EditorWindow window)
|
||||||
BindingFlags fullBinding = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;
|
{
|
||||||
|
BindingFlags fullBinding = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance |
|
||||||
|
BindingFlags.Static;
|
||||||
MethodInfo isDockedMethod = typeof(EditorWindow).GetProperty("docked", fullBinding).GetGetMethod(true);
|
MethodInfo isDockedMethod = typeof(EditorWindow).GetProperty("docked", fullBinding).GetGetMethod(true);
|
||||||
return (Func<bool>) Delegate.CreateDelegate(typeof(Func<bool>), window, isDockedMethod);
|
return (Func<bool>)Delegate.CreateDelegate(typeof(Func<bool>), window, isDockedMethod);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Type[] GetNodeTypes() {
|
public static Type[] GetNodeTypes()
|
||||||
|
{
|
||||||
//Get all classes deriving from Node via reflection
|
//Get all classes deriving from Node via reflection
|
||||||
return GetDerivedTypes(typeof(Node));
|
return GetDerivedTypes(typeof(Node));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Custom node tint colors defined with [NodeColor(r, g, b)] </summary>
|
/// <summary> Custom node tint colors defined with [NodeColor(r, g, b)] </summary>
|
||||||
public static bool TryGetAttributeTint(this Type nodeType, out Color tint) {
|
public static bool TryGetAttributeTint(this Type nodeType, out Color tint)
|
||||||
if (nodeTint == null) {
|
{
|
||||||
|
if (nodeTint == null)
|
||||||
|
{
|
||||||
CacheAttributes<Color, Node.NodeTintAttribute>(ref nodeTint, x => x.color);
|
CacheAttributes<Color, Node.NodeTintAttribute>(ref nodeTint, x => x.color);
|
||||||
}
|
}
|
||||||
|
|
||||||
return nodeTint.TryGetValue(nodeType, out tint);
|
return nodeTint.TryGetValue(nodeType, out tint);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Get custom node widths defined with [NodeWidth(width)] </summary>
|
/// <summary> Get custom node widths defined with [NodeWidth(width)] </summary>
|
||||||
public static bool TryGetAttributeWidth(this Type nodeType, out int width) {
|
public static bool TryGetAttributeWidth(this Type nodeType, out int width)
|
||||||
if (nodeWidth == null) {
|
{
|
||||||
|
if (nodeWidth == null)
|
||||||
|
{
|
||||||
CacheAttributes<int, Node.NodeWidthAttribute>(ref nodeWidth, x => x.width);
|
CacheAttributes<int, Node.NodeWidthAttribute>(ref nodeWidth, x => x.width);
|
||||||
}
|
}
|
||||||
|
|
||||||
return nodeWidth.TryGetValue(nodeType, out width);
|
return nodeWidth.TryGetValue(nodeType, out width);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void CacheAttributes<V, A>(ref Dictionary<Type, V> dict, Func<A, V> getter) where A : Attribute {
|
private static void CacheAttributes<V, A>(ref Dictionary<Type, V> dict, Func<A, V> getter) where A : Attribute
|
||||||
|
{
|
||||||
dict = new Dictionary<Type, V>();
|
dict = new Dictionary<Type, V>();
|
||||||
for (int i = 0; i < nodeTypes.Length; i++) {
|
for (int i = 0; i < nodeTypes.Length; i++)
|
||||||
|
{
|
||||||
object[] attribs = nodeTypes[i].GetCustomAttributes(typeof(A), true);
|
object[] attribs = nodeTypes[i].GetCustomAttributes(typeof(A), true);
|
||||||
if (attribs == null || attribs.Length == 0) continue;
|
if (attribs == null || attribs.Length == 0)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
A attrib = attribs[0] as A;
|
A attrib = attribs[0] as A;
|
||||||
dict.Add(nodeTypes[i], getter(attrib));
|
dict.Add(nodeTypes[i], getter(attrib));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Get FieldInfo of a field, including those that are private and/or inherited </summary>
|
/// <summary> Get FieldInfo of a field, including those that are private and/or inherited </summary>
|
||||||
public static FieldInfo GetFieldInfo(this Type type, string fieldName) {
|
public static FieldInfo GetFieldInfo(this Type type, string fieldName)
|
||||||
|
{
|
||||||
// If we can't find field in the first run, it's probably a private field in a base class.
|
// If we can't find field in the first run, it's probably a private field in a base class.
|
||||||
FieldInfo field = type.GetField(fieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
|
FieldInfo field = type.GetField(fieldName,
|
||||||
|
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
|
||||||
// Search base classes for private fields only. Public fields are found above
|
// Search base classes for private fields only. Public fields are found above
|
||||||
while (field == null && (type = type.BaseType) != typeof(Node)) field = type.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);
|
while (field == null && (type = type.BaseType) != typeof(Node))
|
||||||
|
{
|
||||||
|
field = type.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);
|
||||||
|
}
|
||||||
|
|
||||||
return field;
|
return field;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Get all classes deriving from baseType via reflection </summary>
|
/// <summary> Get all classes deriving from baseType via reflection </summary>
|
||||||
public static Type[] GetDerivedTypes(this Type baseType) {
|
public static Type[] GetDerivedTypes(this Type baseType)
|
||||||
List<System.Type> types = new List<System.Type>();
|
{
|
||||||
System.Reflection.Assembly[] assemblies = System.AppDomain.CurrentDomain.GetAssemblies();
|
var types = new List<Type>();
|
||||||
foreach (Assembly assembly in assemblies) {
|
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
|
||||||
try {
|
foreach (Assembly assembly in assemblies)
|
||||||
types.AddRange(assembly.GetTypes().Where(t => !t.IsAbstract && baseType.IsAssignableFrom(t)).ToArray());
|
{
|
||||||
} catch (ReflectionTypeLoadException) { }
|
try
|
||||||
|
{
|
||||||
|
types.AddRange(assembly.GetTypes().Where(t => !t.IsAbstract && baseType.IsAssignableFrom(t))
|
||||||
|
.ToArray());
|
||||||
|
}
|
||||||
|
catch (ReflectionTypeLoadException) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
return types.ToArray();
|
return types.ToArray();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Find methods marked with the [ContextMenu] attribute and add them to the context menu </summary>
|
/// <summary> Find methods marked with the [ContextMenu] attribute and add them to the context menu </summary>
|
||||||
public static void AddCustomContextMenuItems(this GenericMenu contextMenu, object obj) {
|
public static void AddCustomContextMenuItems(this GenericMenu contextMenu, object obj)
|
||||||
KeyValuePair<ContextMenu, MethodInfo>[] items = GetContextMenuMethods(obj);
|
{
|
||||||
if (items.Length != 0) {
|
var items = GetContextMenuMethods(obj);
|
||||||
|
if (items.Length != 0)
|
||||||
|
{
|
||||||
contextMenu.AddSeparator("");
|
contextMenu.AddSeparator("");
|
||||||
List<string> invalidatedEntries = new List<string>();
|
var invalidatedEntries = new List<string>();
|
||||||
foreach (KeyValuePair<ContextMenu, MethodInfo> checkValidate in items) {
|
foreach (var checkValidate in items)
|
||||||
if (checkValidate.Key.validate && !(bool) checkValidate.Value.Invoke(obj, null)) {
|
{
|
||||||
|
if (checkValidate.Key.validate && !(bool)checkValidate.Value.Invoke(obj, null))
|
||||||
|
{
|
||||||
invalidatedEntries.Add(checkValidate.Key.menuItem);
|
invalidatedEntries.Add(checkValidate.Key.menuItem);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (int i = 0; i < items.Length; i++) {
|
|
||||||
KeyValuePair<ContextMenu, MethodInfo> kvp = items[i];
|
for (int i = 0; i < items.Length; i++)
|
||||||
if (invalidatedEntries.Contains(kvp.Key.menuItem)) {
|
{
|
||||||
|
var kvp = items[i];
|
||||||
|
if (invalidatedEntries.Contains(kvp.Key.menuItem))
|
||||||
|
{
|
||||||
contextMenu.AddDisabledItem(new GUIContent(kvp.Key.menuItem));
|
contextMenu.AddDisabledItem(new GUIContent(kvp.Key.menuItem));
|
||||||
} else {
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
contextMenu.AddItem(new GUIContent(kvp.Key.menuItem), false, () => kvp.Value.Invoke(obj, null));
|
contextMenu.AddItem(new GUIContent(kvp.Key.menuItem), false, () => kvp.Value.Invoke(obj, null));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -101,31 +140,51 @@ namespace XNodeEditor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Call OnValidate on target </summary>
|
/// <summary> Call OnValidate on target </summary>
|
||||||
public static void TriggerOnValidate(this UnityEngine.Object target) {
|
public static void TriggerOnValidate(this Object target)
|
||||||
System.Reflection.MethodInfo onValidate = null;
|
{
|
||||||
if (target != null) {
|
MethodInfo onValidate = null;
|
||||||
onValidate = target.GetType().GetMethod("OnValidate", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
|
if (target != null)
|
||||||
if (onValidate != null) onValidate.Invoke(target, null);
|
{
|
||||||
|
onValidate = target.GetType().GetMethod("OnValidate",
|
||||||
|
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
|
||||||
|
if (onValidate != null)
|
||||||
|
{
|
||||||
|
onValidate.Invoke(target, null);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static KeyValuePair<ContextMenu, MethodInfo>[] GetContextMenuMethods(object obj) {
|
public static KeyValuePair<ContextMenu, MethodInfo>[] GetContextMenuMethods(object obj)
|
||||||
|
{
|
||||||
Type type = obj.GetType();
|
Type type = obj.GetType();
|
||||||
MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
|
var methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public |
|
||||||
List<KeyValuePair<ContextMenu, MethodInfo>> kvp = new List<KeyValuePair<ContextMenu, MethodInfo>>();
|
BindingFlags.NonPublic);
|
||||||
for (int i = 0; i < methods.Length; i++) {
|
var kvp = new List<KeyValuePair<ContextMenu, MethodInfo>>();
|
||||||
ContextMenu[] attribs = methods[i].GetCustomAttributes(typeof(ContextMenu), true).Select(x => x as ContextMenu).ToArray();
|
for (int i = 0; i < methods.Length; i++)
|
||||||
if (attribs == null || attribs.Length == 0) continue;
|
{
|
||||||
if (methods[i].GetParameters().Length != 0) {
|
var attribs = methods[i].GetCustomAttributes(typeof(ContextMenu), true).Select(x => x as ContextMenu)
|
||||||
Debug.LogWarning("Method " + methods[i].DeclaringType.Name + "." + methods[i].Name + " has parameters and cannot be used for context menu commands.");
|
.ToArray();
|
||||||
continue;
|
if (attribs == null || attribs.Length == 0)
|
||||||
}
|
{
|
||||||
if (methods[i].IsStatic) {
|
|
||||||
Debug.LogWarning("Method " + methods[i].DeclaringType.Name + "." + methods[i].Name + " is static and cannot be used for context menu commands.");
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
for (int k = 0; k < attribs.Length; k++) {
|
if (methods[i].GetParameters().Length != 0)
|
||||||
|
{
|
||||||
|
Debug.LogWarning("Method " + methods[i].DeclaringType.Name + "." + methods[i].Name +
|
||||||
|
" has parameters and cannot be used for context menu commands.");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (methods[i].IsStatic)
|
||||||
|
{
|
||||||
|
Debug.LogWarning("Method " + methods[i].DeclaringType.Name + "." + methods[i].Name +
|
||||||
|
" is static and cannot be used for context menu commands.");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int k = 0; k < attribs.Length; k++)
|
||||||
|
{
|
||||||
kvp.Add(new KeyValuePair<ContextMenu, MethodInfo>(attribs[k], methods[i]));
|
kvp.Add(new KeyValuePair<ContextMenu, MethodInfo>(attribs[k], methods[i]));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -137,8 +196,10 @@ namespace XNodeEditor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Very crude. Uses a lot of reflection. </summary>
|
/// <summary> Very crude. Uses a lot of reflection. </summary>
|
||||||
public static void OpenPreferences() {
|
public static void OpenPreferences()
|
||||||
try {
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
#if UNITY_2018_3_OR_NEWER
|
#if UNITY_2018_3_OR_NEWER
|
||||||
SettingsService.OpenUserPreferences("Preferences/Node Editor");
|
SettingsService.OpenUserPreferences("Preferences/Node Editor");
|
||||||
#else
|
#else
|
||||||
@ -151,8 +212,10 @@ namespace XNodeEditor {
|
|||||||
EditorWindow window = EditorWindow.GetWindow(type);
|
EditorWindow window = EditorWindow.GetWindow(type);
|
||||||
|
|
||||||
//Make sure custom sections are added (because waiting for it to happen automatically is too slow)
|
//Make sure custom sections are added (because waiting for it to happen automatically is too slow)
|
||||||
FieldInfo refreshField = type.GetField("m_RefreshCustomPreferences", BindingFlags.NonPublic | BindingFlags.Instance);
|
FieldInfo refreshField =
|
||||||
if ((bool) refreshField.GetValue(window)) {
|
type.GetField("m_RefreshCustomPreferences", BindingFlags.NonPublic | BindingFlags.Instance);
|
||||||
|
if ((bool)refreshField.GetValue(window))
|
||||||
|
{
|
||||||
type.GetMethod("AddCustomSections", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(window, null);
|
type.GetMethod("AddCustomSections", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(window, null);
|
||||||
refreshField.SetValue(window, false);
|
refreshField.SetValue(window, false);
|
||||||
}
|
}
|
||||||
@ -162,21 +225,28 @@ namespace XNodeEditor {
|
|||||||
IList sections = sectionsField.GetValue(window) as IList;
|
IList sections = sectionsField.GetValue(window) as IList;
|
||||||
|
|
||||||
//Iterate through sections and check contents
|
//Iterate through sections and check contents
|
||||||
Type sectionType = sectionsField.FieldType.GetGenericArguments() [0];
|
Type sectionType = sectionsField.FieldType.GetGenericArguments()[0];
|
||||||
FieldInfo sectionContentField = sectionType.GetField("content", BindingFlags.Instance | BindingFlags.Public);
|
FieldInfo sectionContentField =
|
||||||
for (int i = 0; i < sections.Count; i++) {
|
sectionType.GetField("content", BindingFlags.Instance | BindingFlags.Public);
|
||||||
|
for (int i = 0; i < sections.Count; i++)
|
||||||
|
{
|
||||||
GUIContent sectionContent = sectionContentField.GetValue(sections[i]) as GUIContent;
|
GUIContent sectionContent = sectionContentField.GetValue(sections[i]) as GUIContent;
|
||||||
if (sectionContent.text == "Node Editor") {
|
if (sectionContent.text == "Node Editor")
|
||||||
|
{
|
||||||
//Found contents - Set index
|
//Found contents - Set index
|
||||||
FieldInfo sectionIndexField = type.GetField("m_SelectedSectionIndex", BindingFlags.Instance | BindingFlags.NonPublic);
|
FieldInfo sectionIndexField =
|
||||||
|
type.GetField("m_SelectedSectionIndex", BindingFlags.Instance | BindingFlags.NonPublic);
|
||||||
sectionIndexField.SetValue(window, i);
|
sectionIndexField.SetValue(window, i);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
} catch (Exception e) {
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
Debug.LogError(e);
|
Debug.LogError(e);
|
||||||
Debug.LogWarning("Unity has changed around internally. Can't open properties through reflection. Please contact xNode developer and supply unity version number.");
|
Debug.LogWarning(
|
||||||
|
"Unity has changed around internally. Can't open properties through reflection. Please contact xNode developer and supply unity version number.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,26 +1,34 @@
|
|||||||
using UnityEditor;
|
using UnityEditor;
|
||||||
using UnityEngine;
|
using UnityEngine;
|
||||||
|
|
||||||
namespace XNodeEditor {
|
namespace XNodeEditor
|
||||||
public static class NodeEditorResources {
|
{
|
||||||
|
public static class NodeEditorResources
|
||||||
|
{
|
||||||
// Textures
|
// Textures
|
||||||
public static Texture2D dot { get { return _dot != null ? _dot : _dot = Resources.Load<Texture2D>("xnode_dot"); } }
|
public static Texture2D dot => _dot != null ? _dot : _dot = Resources.Load<Texture2D>("xnode_dot");
|
||||||
private static Texture2D _dot;
|
private static Texture2D _dot;
|
||||||
public static Texture2D dotOuter { get { return _dotOuter != null ? _dotOuter : _dotOuter = Resources.Load<Texture2D>("xnode_dot_outer"); } }
|
public static Texture2D dotOuter =>
|
||||||
|
_dotOuter != null ? _dotOuter : _dotOuter = Resources.Load<Texture2D>("xnode_dot_outer");
|
||||||
private static Texture2D _dotOuter;
|
private static Texture2D _dotOuter;
|
||||||
public static Texture2D nodeBody { get { return _nodeBody != null ? _nodeBody : _nodeBody = Resources.Load<Texture2D>("xnode_node"); } }
|
public static Texture2D nodeBody =>
|
||||||
|
_nodeBody != null ? _nodeBody : _nodeBody = Resources.Load<Texture2D>("xnode_node");
|
||||||
private static Texture2D _nodeBody;
|
private static Texture2D _nodeBody;
|
||||||
public static Texture2D nodeHighlight { get { return _nodeHighlight != null ? _nodeHighlight : _nodeHighlight = Resources.Load<Texture2D>("xnode_node_highlight"); } }
|
public static Texture2D nodeHighlight => _nodeHighlight != null
|
||||||
|
? _nodeHighlight
|
||||||
|
: _nodeHighlight = Resources.Load<Texture2D>("xnode_node_highlight");
|
||||||
private static Texture2D _nodeHighlight;
|
private static Texture2D _nodeHighlight;
|
||||||
|
|
||||||
// Styles
|
// Styles
|
||||||
public static Styles styles { get { return _styles != null ? _styles : _styles = new Styles(); } }
|
public static Styles styles => _styles != null ? _styles : _styles = new Styles();
|
||||||
public static Styles _styles = null;
|
public static Styles _styles;
|
||||||
public static GUIStyle OutputPort { get { return new GUIStyle(EditorStyles.label) { alignment = TextAnchor.UpperRight }; } }
|
public static GUIStyle OutputPort => new GUIStyle(EditorStyles.label) { alignment = TextAnchor.UpperRight };
|
||||||
public class Styles {
|
public class Styles
|
||||||
|
{
|
||||||
public GUIStyle inputPort, outputPort, nodeHeader, nodeBody, tooltip, nodeHighlight;
|
public GUIStyle inputPort, outputPort, nodeHeader, nodeBody, tooltip, nodeHighlight;
|
||||||
|
|
||||||
public Styles() {
|
public Styles()
|
||||||
|
{
|
||||||
GUIStyle baseStyle = new GUIStyle("Label");
|
GUIStyle baseStyle = new GUIStyle("Label");
|
||||||
baseStyle.fixedHeight = 18;
|
baseStyle.fixedHeight = 18;
|
||||||
|
|
||||||
@ -55,17 +63,29 @@ namespace XNodeEditor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Texture2D GenerateGridTexture(Color line, Color bg) {
|
public static Texture2D GenerateGridTexture(Color line, Color bg)
|
||||||
|
{
|
||||||
Texture2D tex = new Texture2D(64, 64);
|
Texture2D tex = new Texture2D(64, 64);
|
||||||
Color[] cols = new Color[64 * 64];
|
var cols = new Color[64 * 64];
|
||||||
for (int y = 0; y < 64; y++) {
|
for (int y = 0; y < 64; y++)
|
||||||
for (int x = 0; x < 64; x++) {
|
{
|
||||||
|
for (int x = 0; x < 64; x++)
|
||||||
|
{
|
||||||
Color col = bg;
|
Color col = bg;
|
||||||
if (y % 16 == 0 || x % 16 == 0) col = Color.Lerp(line, bg, 0.65f);
|
if (y % 16 == 0 || x % 16 == 0)
|
||||||
if (y == 63 || x == 63) col = Color.Lerp(line, bg, 0.35f);
|
{
|
||||||
cols[(y * 64) + x] = col;
|
col = Color.Lerp(line, bg, 0.65f);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (y == 63 || x == 63)
|
||||||
|
{
|
||||||
|
col = Color.Lerp(line, bg, 0.35f);
|
||||||
|
}
|
||||||
|
|
||||||
|
cols[y * 64 + x] = col;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
tex.SetPixels(cols);
|
tex.SetPixels(cols);
|
||||||
tex.wrapMode = TextureWrapMode.Repeat;
|
tex.wrapMode = TextureWrapMode.Repeat;
|
||||||
tex.filterMode = FilterMode.Bilinear;
|
tex.filterMode = FilterMode.Bilinear;
|
||||||
@ -74,16 +94,24 @@ namespace XNodeEditor {
|
|||||||
return tex;
|
return tex;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Texture2D GenerateCrossTexture(Color line) {
|
public static Texture2D GenerateCrossTexture(Color line)
|
||||||
|
{
|
||||||
Texture2D tex = new Texture2D(64, 64);
|
Texture2D tex = new Texture2D(64, 64);
|
||||||
Color[] cols = new Color[64 * 64];
|
var cols = new Color[64 * 64];
|
||||||
for (int y = 0; y < 64; y++) {
|
for (int y = 0; y < 64; y++)
|
||||||
for (int x = 0; x < 64; x++) {
|
{
|
||||||
|
for (int x = 0; x < 64; x++)
|
||||||
|
{
|
||||||
Color col = line;
|
Color col = line;
|
||||||
if (y != 31 && x != 31) col.a = 0;
|
if (y != 31 && x != 31)
|
||||||
cols[(y * 64) + x] = col;
|
{
|
||||||
|
col.a = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
cols[y * 64 + x] = col;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
tex.SetPixels(cols);
|
tex.SetPixels(cols);
|
||||||
tex.wrapMode = TextureWrapMode.Clamp;
|
tex.wrapMode = TextureWrapMode.Clamp;
|
||||||
tex.filterMode = FilterMode.Bilinear;
|
tex.filterMode = FilterMode.Bilinear;
|
||||||
|
|||||||
@ -5,82 +5,108 @@ using System.Linq;
|
|||||||
using System.Reflection;
|
using System.Reflection;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using UnityEditor;
|
using UnityEditor;
|
||||||
|
using UnityEditor.ProjectWindowCallback;
|
||||||
using UnityEngine;
|
using UnityEngine;
|
||||||
|
using XNode;
|
||||||
using Object = UnityEngine.Object;
|
using Object = UnityEngine.Object;
|
||||||
|
|
||||||
namespace XNodeEditor {
|
namespace XNodeEditor
|
||||||
|
{
|
||||||
/// <summary> A set of editor-only utilities and extensions for xNode </summary>
|
/// <summary> A set of editor-only utilities and extensions for xNode </summary>
|
||||||
public static class NodeEditorUtilities {
|
public static class NodeEditorUtilities
|
||||||
|
{
|
||||||
/// <summary>C#'s Script Icon [The one MonoBhevaiour Scripts have].</summary>
|
/// <summary>C#'s Script Icon [The one MonoBhevaiour Scripts have].</summary>
|
||||||
private static Texture2D scriptIcon = (EditorGUIUtility.IconContent("cs Script Icon").image as Texture2D);
|
private static readonly Texture2D
|
||||||
|
scriptIcon = EditorGUIUtility.IconContent("cs Script Icon").image as Texture2D;
|
||||||
|
|
||||||
/// Saves Attribute from Type+Field for faster lookup. Resets on recompiles.
|
/// Saves Attribute from Type+Field for faster lookup. Resets on recompiles.
|
||||||
private static Dictionary<Type, Dictionary<string, Dictionary<Type, Attribute>>> typeAttributes = new Dictionary<Type, Dictionary<string, Dictionary<Type, Attribute>>>();
|
private static readonly Dictionary<Type, Dictionary<string, Dictionary<Type, Attribute>>> typeAttributes =
|
||||||
|
new Dictionary<Type, Dictionary<string, Dictionary<Type, Attribute>>>();
|
||||||
|
|
||||||
/// Saves ordered PropertyAttribute from Type+Field for faster lookup. Resets on recompiles.
|
/// Saves ordered PropertyAttribute from Type+Field for faster lookup. Resets on recompiles.
|
||||||
private static Dictionary<Type, Dictionary<string, List<PropertyAttribute>>> typeOrderedPropertyAttributes = new Dictionary<Type, Dictionary<string, List<PropertyAttribute>>>();
|
private static readonly Dictionary<Type, Dictionary<string, List<PropertyAttribute>>>
|
||||||
|
typeOrderedPropertyAttributes = new Dictionary<Type, Dictionary<string, List<PropertyAttribute>>>();
|
||||||
|
|
||||||
public static bool GetAttrib<T>(Type classType, out T attribOut) where T : Attribute {
|
public static bool GetAttrib<T>(Type classType, out T attribOut) where T : Attribute
|
||||||
|
{
|
||||||
object[] attribs = classType.GetCustomAttributes(typeof(T), false);
|
object[] attribs = classType.GetCustomAttributes(typeof(T), false);
|
||||||
return GetAttrib(attribs, out attribOut);
|
return GetAttrib(attribs, out attribOut);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static bool GetAttrib<T>(object[] attribs, out T attribOut) where T : Attribute {
|
public static bool GetAttrib<T>(object[] attribs, out T attribOut) where T : Attribute
|
||||||
for (int i = 0; i < attribs.Length; i++) {
|
{
|
||||||
if (attribs[i] is T) {
|
for (int i = 0; i < attribs.Length; i++)
|
||||||
|
{
|
||||||
|
if (attribs[i] is T)
|
||||||
|
{
|
||||||
attribOut = attribs[i] as T;
|
attribOut = attribs[i] as T;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
attribOut = null;
|
attribOut = null;
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static bool GetAttrib<T>(Type classType, string fieldName, out T attribOut) where T : Attribute {
|
public static bool GetAttrib<T>(Type classType, string fieldName, out T attribOut) where T : Attribute
|
||||||
|
{
|
||||||
// If we can't find field in the first run, it's probably a private field in a base class.
|
// If we can't find field in the first run, it's probably a private field in a base class.
|
||||||
FieldInfo field = classType.GetFieldInfo(fieldName);
|
FieldInfo field = classType.GetFieldInfo(fieldName);
|
||||||
// This shouldn't happen. Ever.
|
// This shouldn't happen. Ever.
|
||||||
if (field == null) {
|
if (field == null)
|
||||||
|
{
|
||||||
Debug.LogWarning("Field " + fieldName + " couldnt be found");
|
Debug.LogWarning("Field " + fieldName + " couldnt be found");
|
||||||
attribOut = null;
|
attribOut = null;
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
object[] attribs = field.GetCustomAttributes(typeof(T), true);
|
object[] attribs = field.GetCustomAttributes(typeof(T), true);
|
||||||
return GetAttrib(attribs, out attribOut);
|
return GetAttrib(attribs, out attribOut);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static bool HasAttrib<T>(object[] attribs) where T : Attribute {
|
public static bool HasAttrib<T>(object[] attribs) where T : Attribute
|
||||||
for (int i = 0; i < attribs.Length; i++) {
|
{
|
||||||
if (attribs[i].GetType() == typeof(T)) {
|
for (int i = 0; i < attribs.Length; i++)
|
||||||
|
{
|
||||||
|
if (attribs[i].GetType() == typeof(T))
|
||||||
|
{
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static bool GetCachedAttrib<T>(Type classType, string fieldName, out T attribOut) where T : Attribute {
|
public static bool GetCachedAttrib<T>(Type classType, string fieldName, out T attribOut) where T : Attribute
|
||||||
|
{
|
||||||
Dictionary<string, Dictionary<Type, Attribute>> typeFields;
|
Dictionary<string, Dictionary<Type, Attribute>> typeFields;
|
||||||
if (!typeAttributes.TryGetValue(classType, out typeFields)) {
|
if (!typeAttributes.TryGetValue(classType, out typeFields))
|
||||||
|
{
|
||||||
typeFields = new Dictionary<string, Dictionary<Type, Attribute>>();
|
typeFields = new Dictionary<string, Dictionary<Type, Attribute>>();
|
||||||
typeAttributes.Add(classType, typeFields);
|
typeAttributes.Add(classType, typeFields);
|
||||||
}
|
}
|
||||||
|
|
||||||
Dictionary<Type, Attribute> typeTypes;
|
Dictionary<Type, Attribute> typeTypes;
|
||||||
if (!typeFields.TryGetValue(fieldName, out typeTypes)) {
|
if (!typeFields.TryGetValue(fieldName, out typeTypes))
|
||||||
|
{
|
||||||
typeTypes = new Dictionary<Type, Attribute>();
|
typeTypes = new Dictionary<Type, Attribute>();
|
||||||
typeFields.Add(fieldName, typeTypes);
|
typeFields.Add(fieldName, typeTypes);
|
||||||
}
|
}
|
||||||
|
|
||||||
Attribute attr;
|
Attribute attr;
|
||||||
if (!typeTypes.TryGetValue(typeof(T), out attr)) {
|
if (!typeTypes.TryGetValue(typeof(T), out attr))
|
||||||
if (GetAttrib<T>(classType, fieldName, out attribOut)) {
|
{
|
||||||
|
if (GetAttrib(classType, fieldName, out attribOut))
|
||||||
|
{
|
||||||
typeTypes.Add(typeof(T), attribOut);
|
typeTypes.Add(typeof(T), attribOut);
|
||||||
return true;
|
return true;
|
||||||
} else typeTypes.Add(typeof(T), null);
|
}
|
||||||
|
|
||||||
|
typeTypes.Add(typeof(T), null);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (attr == null) {
|
if (attr == null)
|
||||||
|
{
|
||||||
attribOut = null;
|
attribOut = null;
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@ -89,15 +115,18 @@ namespace XNodeEditor {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static List<PropertyAttribute> GetCachedPropertyAttribs(Type classType, string fieldName) {
|
public static List<PropertyAttribute> GetCachedPropertyAttribs(Type classType, string fieldName)
|
||||||
|
{
|
||||||
Dictionary<string, List<PropertyAttribute>> typeFields;
|
Dictionary<string, List<PropertyAttribute>> typeFields;
|
||||||
if (!typeOrderedPropertyAttributes.TryGetValue(classType, out typeFields)) {
|
if (!typeOrderedPropertyAttributes.TryGetValue(classType, out typeFields))
|
||||||
|
{
|
||||||
typeFields = new Dictionary<string, List<PropertyAttribute>>();
|
typeFields = new Dictionary<string, List<PropertyAttribute>>();
|
||||||
typeOrderedPropertyAttributes.Add(classType, typeFields);
|
typeOrderedPropertyAttributes.Add(classType, typeFields);
|
||||||
}
|
}
|
||||||
|
|
||||||
List<PropertyAttribute> typeAttributes;
|
List<PropertyAttribute> typeAttributes;
|
||||||
if (!typeFields.TryGetValue(fieldName, out typeAttributes)) {
|
if (!typeFields.TryGetValue(fieldName, out typeAttributes))
|
||||||
|
{
|
||||||
FieldInfo field = classType.GetFieldInfo(fieldName);
|
FieldInfo field = classType.GetFieldInfo(fieldName);
|
||||||
object[] attribs = field.GetCustomAttributes(typeof(PropertyAttribute), true);
|
object[] attribs = field.GetCustomAttributes(typeof(PropertyAttribute), true);
|
||||||
typeAttributes = attribs.Cast<PropertyAttribute>().Reverse().ToList(); //Unity draws them in reverse
|
typeAttributes = attribs.Cast<PropertyAttribute>().Reverse().ToList(); //Unity draws them in reverse
|
||||||
@ -107,7 +136,8 @@ namespace XNodeEditor {
|
|||||||
return typeAttributes;
|
return typeAttributes;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static bool IsMac() {
|
public static bool IsMac()
|
||||||
|
{
|
||||||
#if UNITY_2017_1_OR_NEWER
|
#if UNITY_2017_1_OR_NEWER
|
||||||
return SystemInfo.operatingSystemFamily == OperatingSystemFamily.MacOSX;
|
return SystemInfo.operatingSystemFamily == OperatingSystemFamily.MacOSX;
|
||||||
#else
|
#else
|
||||||
@ -115,36 +145,48 @@ namespace XNodeEditor {
|
|||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Returns true if this can be casted to <see cref="Type"/></summary>
|
/// <summary> Returns true if this can be casted to <see cref="Type" /></summary>
|
||||||
public static bool IsCastableTo(this Type from, Type to) {
|
public static bool IsCastableTo(this Type from, Type to)
|
||||||
if (to.IsAssignableFrom(from)) return true;
|
{
|
||||||
|
if (to.IsAssignableFrom(from))
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
var methods = from.GetMethods(BindingFlags.Public | BindingFlags.Static)
|
var methods = from.GetMethods(BindingFlags.Public | BindingFlags.Static)
|
||||||
.Where(
|
.Where(
|
||||||
m => m.ReturnType == to &&
|
m => m.ReturnType == to &&
|
||||||
(m.Name == "op_Implicit" ||
|
(m.Name == "op_Implicit" ||
|
||||||
m.Name == "op_Explicit")
|
m.Name == "op_Explicit")
|
||||||
);
|
);
|
||||||
return methods.Count() > 0;
|
return methods.Count() > 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Looking for ports with value Type compatible with a given type.
|
/// Looking for ports with value Type compatible with a given type.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="nodeType">Node to search</param>
|
/// <param name="nodeType">Node to search</param>
|
||||||
/// <param name="compatibleType">Type to find compatiblities</param>
|
/// <param name="compatibleType">Type to find compatiblities</param>
|
||||||
/// <param name="direction"></param>
|
/// <param name="direction"></param>
|
||||||
/// <returns>True if NodeType has some port with value type compatible</returns>
|
/// <returns>True if NodeType has some port with value type compatible</returns>
|
||||||
public static bool HasCompatiblePortType(Type nodeType, Type compatibleType, NodePort.IO direction = NodePort.IO.Input) {
|
public static bool HasCompatiblePortType(Type nodeType, Type compatibleType,
|
||||||
|
NodePort.IO direction = NodePort.IO.Input)
|
||||||
|
{
|
||||||
Type findType = typeof(Node.InputAttribute);
|
Type findType = typeof(Node.InputAttribute);
|
||||||
if (direction == NodePort.IO.Output)
|
if (direction == NodePort.IO.Output)
|
||||||
|
{
|
||||||
findType = typeof(Node.OutputAttribute);
|
findType = typeof(Node.OutputAttribute);
|
||||||
|
}
|
||||||
|
|
||||||
//Get All fields from node type and we go filter only field with portAttribute.
|
//Get All fields from node type and we go filter only field with portAttribute.
|
||||||
//This way is possible to know the values of the all ports and if have some with compatible value tue
|
//This way is possible to know the values of the all ports and if have some with compatible value tue
|
||||||
foreach (FieldInfo f in NodeDataCache.GetNodeFields(nodeType)) {
|
foreach (FieldInfo f in NodeDataCache.GetNodeFields(nodeType))
|
||||||
var portAttribute = f.GetCustomAttributes(findType, false).FirstOrDefault();
|
{
|
||||||
if (portAttribute != null) {
|
object portAttribute = f.GetCustomAttributes(findType, false).FirstOrDefault();
|
||||||
if (IsCastableTo(f.FieldType, compatibleType)) {
|
if (portAttribute != null)
|
||||||
|
{
|
||||||
|
if (IsCastableTo(f.FieldType, compatibleType))
|
||||||
|
{
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -154,22 +196,33 @@ namespace XNodeEditor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Filter only node types that contains some port value type compatible with an given type
|
/// Filter only node types that contains some port value type compatible with an given type
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="nodeTypes">List with all nodes type to filter</param>
|
/// <param name="nodeTypes">List with all nodes type to filter</param>
|
||||||
/// <param name="compatibleType">Compatible Type to Filter</param>
|
/// <param name="compatibleType">Compatible Type to Filter</param>
|
||||||
/// <returns>Return Only Node Types with ports compatible, or an empty list</returns>
|
/// <returns>Return Only Node Types with ports compatible, or an empty list</returns>
|
||||||
public static List<Type> GetCompatibleNodesTypes(Type[] nodeTypes, Type compatibleType, NodePort.IO direction = NodePort.IO.Input) {
|
public static List<Type> GetCompatibleNodesTypes(Type[] nodeTypes, Type compatibleType,
|
||||||
|
NodePort.IO direction = NodePort.IO.Input)
|
||||||
|
{
|
||||||
//Result List
|
//Result List
|
||||||
List<Type> filteredTypes = new List<Type>();
|
var filteredTypes = new List<Type>();
|
||||||
|
|
||||||
//Return empty list
|
//Return empty list
|
||||||
if (nodeTypes == null) { return filteredTypes; }
|
if (nodeTypes == null)
|
||||||
if (compatibleType == null) { return filteredTypes; }
|
{
|
||||||
|
return filteredTypes;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (compatibleType == null)
|
||||||
|
{
|
||||||
|
return filteredTypes;
|
||||||
|
}
|
||||||
|
|
||||||
//Find compatiblity
|
//Find compatiblity
|
||||||
foreach (Type findType in nodeTypes) {
|
foreach (Type findType in nodeTypes)
|
||||||
if (HasCompatiblePortType(findType, compatibleType, direction)) {
|
{
|
||||||
|
if (HasCompatiblePortType(findType, compatibleType, direction))
|
||||||
|
{
|
||||||
filteredTypes.Add(findType);
|
filteredTypes.Add(findType);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -179,68 +232,134 @@ namespace XNodeEditor {
|
|||||||
|
|
||||||
|
|
||||||
/// <summary> Return a prettiefied type name. </summary>
|
/// <summary> Return a prettiefied type name. </summary>
|
||||||
public static string PrettyName(this Type type) {
|
public static string PrettyName(this Type type)
|
||||||
if (type == null) return "null";
|
{
|
||||||
if (type == typeof(System.Object)) return "object";
|
if (type == null)
|
||||||
if (type == typeof(float)) return "float";
|
{
|
||||||
else if (type == typeof(int)) return "int";
|
return "null";
|
||||||
else if (type == typeof(long)) return "long";
|
}
|
||||||
else if (type == typeof(double)) return "double";
|
|
||||||
else if (type == typeof(string)) return "string";
|
if (type == typeof(object))
|
||||||
else if (type == typeof(bool)) return "bool";
|
{
|
||||||
else if (type.IsGenericType) {
|
return "object";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type == typeof(float))
|
||||||
|
{
|
||||||
|
return "float";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type == typeof(int))
|
||||||
|
{
|
||||||
|
return "int";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type == typeof(long))
|
||||||
|
{
|
||||||
|
return "long";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type == typeof(double))
|
||||||
|
{
|
||||||
|
return "double";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type == typeof(string))
|
||||||
|
{
|
||||||
|
return "string";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type == typeof(bool))
|
||||||
|
{
|
||||||
|
return "bool";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type.IsGenericType)
|
||||||
|
{
|
||||||
string s = "";
|
string s = "";
|
||||||
Type genericType = type.GetGenericTypeDefinition();
|
Type genericType = type.GetGenericTypeDefinition();
|
||||||
if (genericType == typeof(List<>)) s = "List";
|
if (genericType == typeof(List<>))
|
||||||
else s = type.GetGenericTypeDefinition().ToString();
|
{
|
||||||
|
s = "List";
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
s = type.GetGenericTypeDefinition().ToString();
|
||||||
|
}
|
||||||
|
|
||||||
Type[] types = type.GetGenericArguments();
|
var types = type.GetGenericArguments();
|
||||||
string[] stypes = new string[types.Length];
|
string[] stypes = new string[types.Length];
|
||||||
for (int i = 0; i < types.Length; i++) {
|
for (int i = 0; i < types.Length; i++)
|
||||||
|
{
|
||||||
stypes[i] = types[i].PrettyName();
|
stypes[i] = types[i].PrettyName();
|
||||||
}
|
}
|
||||||
|
|
||||||
return s + "<" + string.Join(", ", stypes) + ">";
|
return s + "<" + string.Join(", ", stypes) + ">";
|
||||||
} else if (type.IsArray) {
|
}
|
||||||
|
|
||||||
|
if (type.IsArray)
|
||||||
|
{
|
||||||
string rank = "";
|
string rank = "";
|
||||||
for (int i = 1; i < type.GetArrayRank(); i++) {
|
for (int i = 1; i < type.GetArrayRank(); i++)
|
||||||
|
{
|
||||||
rank += ",";
|
rank += ",";
|
||||||
}
|
}
|
||||||
|
|
||||||
Type elementType = type.GetElementType();
|
Type elementType = type.GetElementType();
|
||||||
if (!elementType.IsArray) return elementType.PrettyName() + "[" + rank + "]";
|
if (!elementType.IsArray)
|
||||||
else {
|
{
|
||||||
|
return elementType.PrettyName() + "[" + rank + "]";
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
string s = elementType.PrettyName();
|
string s = elementType.PrettyName();
|
||||||
int i = s.IndexOf('[');
|
int i = s.IndexOf('[');
|
||||||
return s.Substring(0, i) + "[" + rank + "]" + s.Substring(i);
|
return s.Substring(0, i) + "[" + rank + "]" + s.Substring(i);
|
||||||
}
|
}
|
||||||
} else return type.ToString();
|
}
|
||||||
|
|
||||||
|
return type.ToString();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Returns the default name for the node type. </summary>
|
/// <summary> Returns the default name for the node type. </summary>
|
||||||
public static string NodeDefaultName(Type type) {
|
public static string NodeDefaultName(Type type)
|
||||||
|
{
|
||||||
string typeName = type.Name;
|
string typeName = type.Name;
|
||||||
// Automatically remove redundant 'Node' postfix
|
// Automatically remove redundant 'Node' postfix
|
||||||
if (typeName.EndsWith("Node")) typeName = typeName.Substring(0, typeName.LastIndexOf("Node"));
|
if (typeName.EndsWith("Node"))
|
||||||
typeName = UnityEditor.ObjectNames.NicifyVariableName(typeName);
|
{
|
||||||
|
typeName = typeName.Substring(0, typeName.LastIndexOf("Node"));
|
||||||
|
}
|
||||||
|
|
||||||
|
typeName = ObjectNames.NicifyVariableName(typeName);
|
||||||
return typeName;
|
return typeName;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Returns the default creation path for the node type. </summary>
|
/// <summary> Returns the default creation path for the node type. </summary>
|
||||||
public static string NodeDefaultPath(Type type) {
|
public static string NodeDefaultPath(Type type)
|
||||||
|
{
|
||||||
string typePath = type.ToString().Replace('.', '/');
|
string typePath = type.ToString().Replace('.', '/');
|
||||||
// Automatically remove redundant 'Node' postfix
|
// Automatically remove redundant 'Node' postfix
|
||||||
if (typePath.EndsWith("Node")) typePath = typePath.Substring(0, typePath.LastIndexOf("Node"));
|
if (typePath.EndsWith("Node"))
|
||||||
typePath = UnityEditor.ObjectNames.NicifyVariableName(typePath);
|
{
|
||||||
|
typePath = typePath.Substring(0, typePath.LastIndexOf("Node"));
|
||||||
|
}
|
||||||
|
|
||||||
|
typePath = ObjectNames.NicifyVariableName(typePath);
|
||||||
return typePath;
|
return typePath;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Creates a new C# Class.</summary>
|
/// <summary>Creates a new C# Class.</summary>
|
||||||
[MenuItem("Assets/Create/xNode/Node C# Script", false, 89)]
|
[MenuItem("Assets/Create/xNode/Node C# Script", false, 89)]
|
||||||
private static void CreateNode() {
|
private static void CreateNode()
|
||||||
|
{
|
||||||
string[] guids = AssetDatabase.FindAssets("xNode_NodeTemplate.cs");
|
string[] guids = AssetDatabase.FindAssets("xNode_NodeTemplate.cs");
|
||||||
if (guids.Length == 0) {
|
if (guids.Length == 0)
|
||||||
|
{
|
||||||
Debug.LogWarning("xNode_NodeTemplate.cs.txt not found in asset database");
|
Debug.LogWarning("xNode_NodeTemplate.cs.txt not found in asset database");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
string path = AssetDatabase.GUIDToAssetPath(guids[0]);
|
string path = AssetDatabase.GUIDToAssetPath(guids[0]);
|
||||||
CreateFromTemplate(
|
CreateFromTemplate(
|
||||||
"NewNode.cs",
|
"NewNode.cs",
|
||||||
@ -250,12 +369,15 @@ namespace XNodeEditor {
|
|||||||
|
|
||||||
/// <summary>Creates a new C# Class.</summary>
|
/// <summary>Creates a new C# Class.</summary>
|
||||||
[MenuItem("Assets/Create/xNode/NodeGraph C# Script", false, 89)]
|
[MenuItem("Assets/Create/xNode/NodeGraph C# Script", false, 89)]
|
||||||
private static void CreateGraph() {
|
private static void CreateGraph()
|
||||||
|
{
|
||||||
string[] guids = AssetDatabase.FindAssets("xNode_NodeGraphTemplate.cs");
|
string[] guids = AssetDatabase.FindAssets("xNode_NodeGraphTemplate.cs");
|
||||||
if (guids.Length == 0) {
|
if (guids.Length == 0)
|
||||||
|
{
|
||||||
Debug.LogWarning("xNode_NodeGraphTemplate.cs.txt not found in asset database");
|
Debug.LogWarning("xNode_NodeGraphTemplate.cs.txt not found in asset database");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
string path = AssetDatabase.GUIDToAssetPath(guids[0]);
|
string path = AssetDatabase.GUIDToAssetPath(guids[0]);
|
||||||
CreateFromTemplate(
|
CreateFromTemplate(
|
||||||
"NewNodeGraph.cs",
|
"NewNodeGraph.cs",
|
||||||
@ -263,7 +385,8 @@ namespace XNodeEditor {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void CreateFromTemplate(string initialName, string templatePath) {
|
public static void CreateFromTemplate(string initialName, string templatePath)
|
||||||
|
{
|
||||||
ProjectWindowUtil.StartNameEditingIfProjectWindowExists(
|
ProjectWindowUtil.StartNameEditingIfProjectWindowExists(
|
||||||
0,
|
0,
|
||||||
ScriptableObject.CreateInstance<DoCreateCodeFile>(),
|
ScriptableObject.CreateInstance<DoCreateCodeFile>(),
|
||||||
@ -274,21 +397,25 @@ namespace XNodeEditor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Inherits from EndNameAction, must override EndNameAction.Action
|
/// Inherits from EndNameAction, must override EndNameAction.Action
|
||||||
public class DoCreateCodeFile : UnityEditor.ProjectWindowCallback.EndNameEditAction {
|
public class DoCreateCodeFile : EndNameEditAction
|
||||||
public override void Action(int instanceId, string pathName, string resourceFile) {
|
{
|
||||||
|
public override void Action(int instanceId, string pathName, string resourceFile)
|
||||||
|
{
|
||||||
Object o = CreateScript(pathName, resourceFile);
|
Object o = CreateScript(pathName, resourceFile);
|
||||||
ProjectWindowUtil.ShowCreatedAsset(o);
|
ProjectWindowUtil.ShowCreatedAsset(o);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Creates Script from Template's path.</summary>
|
/// <summary>Creates Script from Template's path.</summary>
|
||||||
internal static UnityEngine.Object CreateScript(string pathName, string templatePath) {
|
internal static Object CreateScript(string pathName, string templatePath)
|
||||||
|
{
|
||||||
string className = Path.GetFileNameWithoutExtension(pathName).Replace(" ", string.Empty);
|
string className = Path.GetFileNameWithoutExtension(pathName).Replace(" ", string.Empty);
|
||||||
string templateText = string.Empty;
|
string templateText = string.Empty;
|
||||||
|
|
||||||
UTF8Encoding encoding = new UTF8Encoding(true, false);
|
UTF8Encoding encoding = new UTF8Encoding(true, false);
|
||||||
|
|
||||||
if (File.Exists(templatePath)) {
|
if (File.Exists(templatePath))
|
||||||
|
{
|
||||||
/// Read procedures.
|
/// Read procedures.
|
||||||
StreamReader reader = new StreamReader(templatePath);
|
StreamReader reader = new StreamReader(templatePath);
|
||||||
templateText = reader.ReadToEnd();
|
templateText = reader.ReadToEnd();
|
||||||
@ -308,10 +435,10 @@ namespace XNodeEditor {
|
|||||||
|
|
||||||
AssetDatabase.ImportAsset(pathName);
|
AssetDatabase.ImportAsset(pathName);
|
||||||
return AssetDatabase.LoadAssetAtPath(pathName, typeof(Object));
|
return AssetDatabase.LoadAssetAtPath(pathName, typeof(Object));
|
||||||
} else {
|
|
||||||
Debug.LogError(string.Format("The template file was not found: {0}", templatePath));
|
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Debug.LogError(string.Format("The template file was not found: {0}", templatePath));
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -1,119 +1,173 @@
|
|||||||
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using UnityEditor;
|
using UnityEditor;
|
||||||
using UnityEditor.Callbacks;
|
using UnityEditor.Callbacks;
|
||||||
using UnityEngine;
|
using UnityEngine;
|
||||||
using System;
|
using XNode;
|
||||||
using Object = UnityEngine.Object;
|
using Object = UnityEngine.Object;
|
||||||
|
|
||||||
namespace XNodeEditor {
|
namespace XNodeEditor
|
||||||
|
{
|
||||||
[InitializeOnLoad]
|
[InitializeOnLoad]
|
||||||
public partial class NodeEditorWindow : EditorWindow {
|
public partial class NodeEditorWindow : EditorWindow
|
||||||
|
{
|
||||||
public static NodeEditorWindow current;
|
public static NodeEditorWindow current;
|
||||||
|
|
||||||
/// <summary> Stores node positions for all nodePorts. </summary>
|
/// <summary> Stores node positions for all nodePorts. </summary>
|
||||||
public Dictionary<NodePort, Rect> portConnectionPoints { get { return _portConnectionPoints; } }
|
public Dictionary<NodePort, Rect> portConnectionPoints { get; } = new Dictionary<NodePort, Rect>();
|
||||||
private Dictionary<NodePort, Rect> _portConnectionPoints = new Dictionary<NodePort, Rect>();
|
|
||||||
[SerializeField] private NodePortReference[] _references = new NodePortReference[0];
|
[SerializeField] private NodePortReference[] _references = new NodePortReference[0];
|
||||||
[SerializeField] private Rect[] _rects = new Rect[0];
|
[SerializeField] private Rect[] _rects = new Rect[0];
|
||||||
|
|
||||||
private Func<bool> isDocked {
|
private Func<bool> isDocked
|
||||||
get {
|
{
|
||||||
if (_isDocked == null) _isDocked = this.GetIsDockedDelegate();
|
get
|
||||||
|
{
|
||||||
|
if (_isDocked == null)
|
||||||
|
{
|
||||||
|
_isDocked = this.GetIsDockedDelegate();
|
||||||
|
}
|
||||||
|
|
||||||
return _isDocked;
|
return _isDocked;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
private Func<bool> _isDocked;
|
private Func<bool> _isDocked;
|
||||||
|
|
||||||
[System.Serializable] private class NodePortReference {
|
[Serializable] private class NodePortReference
|
||||||
|
{
|
||||||
[SerializeField] private Node _node;
|
[SerializeField] private Node _node;
|
||||||
[SerializeField] private string _name;
|
[SerializeField] private string _name;
|
||||||
|
|
||||||
public NodePortReference(NodePort nodePort) {
|
public NodePortReference(NodePort nodePort)
|
||||||
|
{
|
||||||
_node = nodePort.node;
|
_node = nodePort.node;
|
||||||
_name = nodePort.fieldName;
|
_name = nodePort.fieldName;
|
||||||
}
|
}
|
||||||
|
|
||||||
public NodePort GetNodePort() {
|
public NodePort GetNodePort()
|
||||||
if (_node == null) {
|
{
|
||||||
|
if (_node == null)
|
||||||
|
{
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return _node.GetPort(_name);
|
return _node.GetPort(_name);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void OnDisable() {
|
private void OnDisable()
|
||||||
|
{
|
||||||
// Cache portConnectionPoints before serialization starts
|
// Cache portConnectionPoints before serialization starts
|
||||||
int count = portConnectionPoints.Count;
|
int count = portConnectionPoints.Count;
|
||||||
_references = new NodePortReference[count];
|
_references = new NodePortReference[count];
|
||||||
_rects = new Rect[count];
|
_rects = new Rect[count];
|
||||||
int index = 0;
|
int index = 0;
|
||||||
foreach (var portConnectionPoint in portConnectionPoints) {
|
foreach (var portConnectionPoint in portConnectionPoints)
|
||||||
|
{
|
||||||
_references[index] = new NodePortReference(portConnectionPoint.Key);
|
_references[index] = new NodePortReference(portConnectionPoint.Key);
|
||||||
_rects[index] = portConnectionPoint.Value;
|
_rects[index] = portConnectionPoint.Value;
|
||||||
index++;
|
index++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void OnEnable() {
|
private void OnEnable()
|
||||||
|
{
|
||||||
// Reload portConnectionPoints if there are any
|
// Reload portConnectionPoints if there are any
|
||||||
int length = _references.Length;
|
int length = _references.Length;
|
||||||
if (length == _rects.Length) {
|
if (length == _rects.Length)
|
||||||
for (int i = 0; i < length; i++) {
|
{
|
||||||
|
for (int i = 0; i < length; i++)
|
||||||
|
{
|
||||||
NodePort nodePort = _references[i].GetNodePort();
|
NodePort nodePort = _references[i].GetNodePort();
|
||||||
if (nodePort != null)
|
if (nodePort != null)
|
||||||
_portConnectionPoints.Add(nodePort, _rects[i]);
|
{
|
||||||
|
portConnectionPoints.Add(nodePort, _rects[i]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public Dictionary<Node, Vector2> nodeSizes { get { return _nodeSizes; } }
|
public Dictionary<Node, Vector2> nodeSizes { get; } = new Dictionary<Node, Vector2>();
|
||||||
private Dictionary<Node, Vector2> _nodeSizes = new Dictionary<Node, Vector2>();
|
|
||||||
public NodeGraph graph;
|
public NodeGraph graph;
|
||||||
public Vector2 panOffset { get { return _panOffset; } set { _panOffset = value; Repaint(); } }
|
public Vector2 panOffset
|
||||||
|
{
|
||||||
|
get => _panOffset;
|
||||||
|
set
|
||||||
|
{
|
||||||
|
_panOffset = value;
|
||||||
|
Repaint();
|
||||||
|
}
|
||||||
|
}
|
||||||
private Vector2 _panOffset;
|
private Vector2 _panOffset;
|
||||||
public float zoom { get { return _zoom; } set { _zoom = Mathf.Clamp(value, NodeEditorPreferences.GetSettings().minZoom, NodeEditorPreferences.GetSettings().maxZoom); Repaint(); } }
|
public float zoom
|
||||||
|
{
|
||||||
|
get => _zoom;
|
||||||
|
set
|
||||||
|
{
|
||||||
|
_zoom = Mathf.Clamp(value, NodeEditorPreferences.GetSettings().minZoom,
|
||||||
|
NodeEditorPreferences.GetSettings().maxZoom);
|
||||||
|
Repaint();
|
||||||
|
}
|
||||||
|
}
|
||||||
private float _zoom = 1;
|
private float _zoom = 1;
|
||||||
|
|
||||||
void OnFocus() {
|
private void OnFocus()
|
||||||
|
{
|
||||||
current = this;
|
current = this;
|
||||||
ValidateGraphEditor();
|
ValidateGraphEditor();
|
||||||
if (graphEditor != null) {
|
if (graphEditor != null)
|
||||||
|
{
|
||||||
graphEditor.OnWindowFocus();
|
graphEditor.OnWindowFocus();
|
||||||
if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets();
|
if (NodeEditorPreferences.GetSettings().autoSave)
|
||||||
|
{
|
||||||
|
AssetDatabase.SaveAssets();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
dragThreshold = Math.Max(1f, Screen.width / 1000f);
|
dragThreshold = Math.Max(1f, Screen.width / 1000f);
|
||||||
}
|
}
|
||||||
|
|
||||||
void OnLostFocus() {
|
private void OnLostFocus()
|
||||||
if (graphEditor != null) graphEditor.OnWindowFocusLost();
|
{
|
||||||
|
if (graphEditor != null)
|
||||||
|
{
|
||||||
|
graphEditor.OnWindowFocusLost();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
[InitializeOnLoadMethod]
|
[InitializeOnLoadMethod]
|
||||||
private static void OnLoad() {
|
private static void OnLoad()
|
||||||
|
{
|
||||||
Selection.selectionChanged -= OnSelectionChanged;
|
Selection.selectionChanged -= OnSelectionChanged;
|
||||||
Selection.selectionChanged += OnSelectionChanged;
|
Selection.selectionChanged += OnSelectionChanged;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Handle Selection Change events</summary>
|
/// <summary> Handle Selection Change events</summary>
|
||||||
private static void OnSelectionChanged() {
|
private static void OnSelectionChanged()
|
||||||
|
{
|
||||||
NodeGraph nodeGraph = Selection.activeObject as NodeGraph;
|
NodeGraph nodeGraph = Selection.activeObject as NodeGraph;
|
||||||
if (nodeGraph && !AssetDatabase.Contains(nodeGraph)) {
|
if (nodeGraph && !AssetDatabase.Contains(nodeGraph))
|
||||||
if (NodeEditorPreferences.GetSettings().openOnCreate) Open(nodeGraph);
|
{
|
||||||
|
if (NodeEditorPreferences.GetSettings().openOnCreate)
|
||||||
|
{
|
||||||
|
Open(nodeGraph);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Make sure the graph editor is assigned and to the right object </summary>
|
/// <summary> Make sure the graph editor is assigned and to the right object </summary>
|
||||||
private void ValidateGraphEditor() {
|
private void ValidateGraphEditor()
|
||||||
|
{
|
||||||
NodeGraphEditor graphEditor = NodeGraphEditor.GetEditor(graph, this);
|
NodeGraphEditor graphEditor = NodeGraphEditor.GetEditor(graph, this);
|
||||||
if (this.graphEditor != graphEditor && graphEditor != null) {
|
if (this.graphEditor != graphEditor && graphEditor != null)
|
||||||
|
{
|
||||||
this.graphEditor = graphEditor;
|
this.graphEditor = graphEditor;
|
||||||
graphEditor.OnOpen();
|
graphEditor.OnOpen();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Create editor window </summary>
|
/// <summary> Create editor window </summary>
|
||||||
public static NodeEditorWindow Init() {
|
public static NodeEditorWindow Init()
|
||||||
|
{
|
||||||
NodeEditorWindow w = CreateInstance<NodeEditorWindow>();
|
NodeEditorWindow w = CreateInstance<NodeEditorWindow>();
|
||||||
w.titleContent = new GUIContent("xNode");
|
w.titleContent = new GUIContent("xNode");
|
||||||
w.wantsMouseMove = true;
|
w.wantsMouseMove = true;
|
||||||
@ -121,49 +175,74 @@ namespace XNodeEditor {
|
|||||||
return w;
|
return w;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Save() {
|
public void Save()
|
||||||
if (AssetDatabase.Contains(graph)) {
|
{
|
||||||
|
if (AssetDatabase.Contains(graph))
|
||||||
|
{
|
||||||
EditorUtility.SetDirty(graph);
|
EditorUtility.SetDirty(graph);
|
||||||
if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets();
|
if (NodeEditorPreferences.GetSettings().autoSave)
|
||||||
} else SaveAs();
|
{
|
||||||
}
|
AssetDatabase.SaveAssets();
|
||||||
|
}
|
||||||
public void SaveAs() {
|
}
|
||||||
string path = EditorUtility.SaveFilePanelInProject("Save NodeGraph", "NewNodeGraph", "asset", "");
|
else
|
||||||
if (string.IsNullOrEmpty(path)) return;
|
{
|
||||||
else {
|
SaveAs();
|
||||||
NodeGraph existingGraph = AssetDatabase.LoadAssetAtPath<NodeGraph>(path);
|
|
||||||
if (existingGraph != null) AssetDatabase.DeleteAsset(path);
|
|
||||||
AssetDatabase.CreateAsset(graph, path);
|
|
||||||
EditorUtility.SetDirty(graph);
|
|
||||||
if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void DraggableWindow(int windowID) {
|
public void SaveAs()
|
||||||
|
{
|
||||||
|
string path = EditorUtility.SaveFilePanelInProject("Save NodeGraph", "NewNodeGraph", "asset", "");
|
||||||
|
if (string.IsNullOrEmpty(path))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
NodeGraph existingGraph = AssetDatabase.LoadAssetAtPath<NodeGraph>(path);
|
||||||
|
if (existingGraph != null)
|
||||||
|
{
|
||||||
|
AssetDatabase.DeleteAsset(path);
|
||||||
|
}
|
||||||
|
|
||||||
|
AssetDatabase.CreateAsset(graph, path);
|
||||||
|
EditorUtility.SetDirty(graph);
|
||||||
|
if (NodeEditorPreferences.GetSettings().autoSave)
|
||||||
|
{
|
||||||
|
AssetDatabase.SaveAssets();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void DraggableWindow(int windowID)
|
||||||
|
{
|
||||||
GUI.DragWindow();
|
GUI.DragWindow();
|
||||||
}
|
}
|
||||||
|
|
||||||
public Vector2 WindowToGridPosition(Vector2 windowPosition) {
|
public Vector2 WindowToGridPosition(Vector2 windowPosition)
|
||||||
return (windowPosition - (position.size * 0.5f) - (panOffset / zoom)) * zoom;
|
{
|
||||||
|
return (windowPosition - position.size * 0.5f - panOffset / zoom) * zoom;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Vector2 GridToWindowPosition(Vector2 gridPosition) {
|
public Vector2 GridToWindowPosition(Vector2 gridPosition)
|
||||||
return (position.size * 0.5f) + (panOffset / zoom) + (gridPosition / zoom);
|
{
|
||||||
|
return position.size * 0.5f + panOffset / zoom + gridPosition / zoom;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Rect GridToWindowRectNoClipped(Rect gridRect) {
|
public Rect GridToWindowRectNoClipped(Rect gridRect)
|
||||||
|
{
|
||||||
gridRect.position = GridToWindowPositionNoClipped(gridRect.position);
|
gridRect.position = GridToWindowPositionNoClipped(gridRect.position);
|
||||||
return gridRect;
|
return gridRect;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Rect GridToWindowRect(Rect gridRect) {
|
public Rect GridToWindowRect(Rect gridRect)
|
||||||
|
{
|
||||||
gridRect.position = GridToWindowPosition(gridRect.position);
|
gridRect.position = GridToWindowPosition(gridRect.position);
|
||||||
gridRect.size /= zoom;
|
gridRect.size /= zoom;
|
||||||
return gridRect;
|
return gridRect;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Vector2 GridToWindowPositionNoClipped(Vector2 gridPosition) {
|
public Vector2 GridToWindowPositionNoClipped(Vector2 gridPosition)
|
||||||
|
{
|
||||||
Vector2 center = position.size * 0.5f;
|
Vector2 center = position.size * 0.5f;
|
||||||
// UI Sharpness complete fix - Round final offset not panOffset
|
// UI Sharpness complete fix - Round final offset not panOffset
|
||||||
float xOffset = Mathf.Round(center.x * zoom + (panOffset.x + gridPosition.x));
|
float xOffset = Mathf.Round(center.x * zoom + (panOffset.x + gridPosition.x));
|
||||||
@ -171,33 +250,47 @@ namespace XNodeEditor {
|
|||||||
return new Vector2(xOffset, yOffset);
|
return new Vector2(xOffset, yOffset);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void SelectNode(Node node, bool add) {
|
public void SelectNode(Node node, bool add)
|
||||||
if (add) {
|
{
|
||||||
List<Object> selection = new List<Object>(Selection.objects);
|
if (add)
|
||||||
|
{
|
||||||
|
var selection = new List<Object>(Selection.objects);
|
||||||
selection.Add(node);
|
selection.Add(node);
|
||||||
Selection.objects = selection.ToArray();
|
Selection.objects = selection.ToArray();
|
||||||
} else Selection.objects = new Object[] { node };
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Selection.objects = new Object[] { node };
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void DeselectNode(Node node) {
|
public void DeselectNode(Node node)
|
||||||
List<Object> selection = new List<Object>(Selection.objects);
|
{
|
||||||
|
var selection = new List<Object>(Selection.objects);
|
||||||
selection.Remove(node);
|
selection.Remove(node);
|
||||||
Selection.objects = selection.ToArray();
|
Selection.objects = selection.ToArray();
|
||||||
}
|
}
|
||||||
|
|
||||||
[OnOpenAsset(0)]
|
[OnOpenAsset(0)]
|
||||||
public static bool OnOpen(int instanceID, int line) {
|
public static bool OnOpen(int instanceID, int line)
|
||||||
|
{
|
||||||
NodeGraph nodeGraph = EditorUtility.InstanceIDToObject(instanceID) as NodeGraph;
|
NodeGraph nodeGraph = EditorUtility.InstanceIDToObject(instanceID) as NodeGraph;
|
||||||
if (nodeGraph != null) {
|
if (nodeGraph != null)
|
||||||
|
{
|
||||||
Open(nodeGraph);
|
Open(nodeGraph);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Open the provided graph in the NodeEditor</summary>
|
/// <summary>Open the provided graph in the NodeEditor</summary>
|
||||||
public static NodeEditorWindow Open(NodeGraph graph) {
|
public static NodeEditorWindow Open(NodeGraph graph)
|
||||||
if (!graph) return null;
|
{
|
||||||
|
if (!graph)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
NodeEditorWindow w = GetWindow(typeof(NodeEditorWindow), false, "xNode", true) as NodeEditorWindow;
|
NodeEditorWindow w = GetWindow(typeof(NodeEditorWindow), false, "xNode", true) as NodeEditorWindow;
|
||||||
w.wantsMouseMove = true;
|
w.wantsMouseMove = true;
|
||||||
@ -206,9 +299,11 @@ namespace XNodeEditor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Repaint all open NodeEditorWindows. </summary>
|
/// <summary> Repaint all open NodeEditorWindows. </summary>
|
||||||
public static void RepaintAll() {
|
public static void RepaintAll()
|
||||||
NodeEditorWindow[] windows = Resources.FindObjectsOfTypeAll<NodeEditorWindow>();
|
{
|
||||||
for (int i = 0; i < windows.Length; i++) {
|
var windows = Resources.FindObjectsOfTypeAll<NodeEditorWindow>();
|
||||||
|
for (int i = 0; i < windows.Length; i++)
|
||||||
|
{
|
||||||
windows[i].Repaint();
|
windows[i].Repaint();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -2,113 +2,167 @@
|
|||||||
using System.Linq;
|
using System.Linq;
|
||||||
using UnityEditor;
|
using UnityEditor;
|
||||||
using UnityEngine;
|
using UnityEngine;
|
||||||
|
using XNode;
|
||||||
|
using XNodeEditor.Internal;
|
||||||
|
using Object = UnityEngine.Object;
|
||||||
#if UNITY_2019_1_OR_NEWER && USE_ADVANCED_GENERIC_MENU
|
#if UNITY_2019_1_OR_NEWER && USE_ADVANCED_GENERIC_MENU
|
||||||
using GenericMenu = XNodeEditor.AdvancedGenericMenu;
|
using GenericMenu = XNodeEditor.AdvancedGenericMenu;
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
namespace XNodeEditor {
|
namespace XNodeEditor
|
||||||
|
{
|
||||||
/// <summary> Base class to derive custom Node Graph editors from. Use this to override how graphs are drawn in the editor. </summary>
|
/// <summary> Base class to derive custom Node Graph editors from. Use this to override how graphs are drawn in the editor. </summary>
|
||||||
[CustomNodeGraphEditor(typeof(NodeGraph))]
|
[CustomNodeGraphEditor(typeof(NodeGraph))]
|
||||||
public class NodeGraphEditor : XNodeEditor.Internal.NodeEditorBase<NodeGraphEditor, NodeGraphEditor.CustomNodeGraphEditorAttribute, NodeGraph> {
|
public class
|
||||||
|
NodeGraphEditor : NodeEditorBase<NodeGraphEditor, NodeGraphEditor.CustomNodeGraphEditorAttribute, NodeGraph>
|
||||||
|
{
|
||||||
[Obsolete("Use window.position instead")]
|
[Obsolete("Use window.position instead")]
|
||||||
public Rect position { get { return window.position; } set { window.position = value; } }
|
public Rect position
|
||||||
|
{
|
||||||
|
get => window.position;
|
||||||
|
set => window.position = value;
|
||||||
|
}
|
||||||
/// <summary> Are we currently renaming a node? </summary>
|
/// <summary> Are we currently renaming a node? </summary>
|
||||||
protected bool isRenaming;
|
protected bool isRenaming;
|
||||||
|
|
||||||
public virtual void OnGUI() { }
|
public virtual void OnGUI() {}
|
||||||
|
|
||||||
/// <summary> Called when opened by NodeEditorWindow </summary>
|
/// <summary> Called when opened by NodeEditorWindow </summary>
|
||||||
public virtual void OnOpen() { }
|
public virtual void OnOpen() {}
|
||||||
|
|
||||||
/// <summary> Called when NodeEditorWindow gains focus </summary>
|
/// <summary> Called when NodeEditorWindow gains focus </summary>
|
||||||
public virtual void OnWindowFocus() { }
|
public virtual void OnWindowFocus() {}
|
||||||
|
|
||||||
/// <summary> Called when NodeEditorWindow loses focus </summary>
|
/// <summary> Called when NodeEditorWindow loses focus </summary>
|
||||||
public virtual void OnWindowFocusLost() { }
|
public virtual void OnWindowFocusLost() {}
|
||||||
|
|
||||||
public virtual Texture2D GetGridTexture() {
|
public virtual Texture2D GetGridTexture()
|
||||||
|
{
|
||||||
return NodeEditorPreferences.GetSettings().gridTexture;
|
return NodeEditorPreferences.GetSettings().gridTexture;
|
||||||
}
|
}
|
||||||
|
|
||||||
public virtual Texture2D GetSecondaryGridTexture() {
|
public virtual Texture2D GetSecondaryGridTexture()
|
||||||
|
{
|
||||||
return NodeEditorPreferences.GetSettings().crossTexture;
|
return NodeEditorPreferences.GetSettings().crossTexture;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Return default settings for this graph type. This is the settings the user will load if no previous settings have been saved. </summary>
|
/// <summary> Return default settings for this graph type. This is the settings the user will load if no previous settings have been saved. </summary>
|
||||||
public virtual NodeEditorPreferences.Settings GetDefaultPreferences() {
|
public virtual NodeEditorPreferences.Settings GetDefaultPreferences()
|
||||||
|
{
|
||||||
return new NodeEditorPreferences.Settings();
|
return new NodeEditorPreferences.Settings();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Returns context node menu path. Null or empty strings for hidden nodes. </summary>
|
/// <summary> Returns context node menu path. Null or empty strings for hidden nodes. </summary>
|
||||||
public virtual string GetNodeMenuName(Type type) {
|
public virtual string GetNodeMenuName(Type type)
|
||||||
|
{
|
||||||
//Check if type has the CreateNodeMenuAttribute
|
//Check if type has the CreateNodeMenuAttribute
|
||||||
Node.CreateNodeMenuAttribute attrib;
|
Node.CreateNodeMenuAttribute attrib;
|
||||||
if (NodeEditorUtilities.GetAttrib(type, out attrib)) // Return custom path
|
if (NodeEditorUtilities.GetAttrib(type, out attrib)) // Return custom path
|
||||||
|
{
|
||||||
return attrib.menuName;
|
return attrib.menuName;
|
||||||
else // Return generated path
|
}
|
||||||
return NodeEditorUtilities.NodeDefaultPath(type);
|
|
||||||
|
// Return generated path
|
||||||
|
return NodeEditorUtilities.NodeDefaultPath(type);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> The order by which the menu items are displayed. </summary>
|
/// <summary> The order by which the menu items are displayed. </summary>
|
||||||
public virtual int GetNodeMenuOrder(Type type) {
|
public virtual int GetNodeMenuOrder(Type type)
|
||||||
|
{
|
||||||
//Check if type has the CreateNodeMenuAttribute
|
//Check if type has the CreateNodeMenuAttribute
|
||||||
Node.CreateNodeMenuAttribute attrib;
|
Node.CreateNodeMenuAttribute attrib;
|
||||||
if (NodeEditorUtilities.GetAttrib(type, out attrib)) // Return custom path
|
if (NodeEditorUtilities.GetAttrib(type, out attrib)) // Return custom path
|
||||||
|
{
|
||||||
return attrib.order;
|
return attrib.order;
|
||||||
else
|
}
|
||||||
return 0;
|
|
||||||
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Called before connecting two ports in the graph view to see if the output port is compatible with the input port
|
/// Called before connecting two ports in the graph view to see if the output port is compatible with the input port
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public virtual bool CanConnect(NodePort output, NodePort input) {
|
public virtual bool CanConnect(NodePort output, NodePort input)
|
||||||
|
{
|
||||||
return output.CanConnectTo(input);
|
return output.CanConnectTo(input);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Add items for the context menu when right-clicking this node.
|
/// Add items for the context menu when right-clicking this node.
|
||||||
/// Override to add custom menu items.
|
/// Override to add custom menu items.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="menu"></param>
|
/// <param name="menu"></param>
|
||||||
/// <param name="compatibleType">Use it to filter only nodes with ports value type, compatible with this type</param>
|
/// <param name="compatibleType">Use it to filter only nodes with ports value type, compatible with this type</param>
|
||||||
/// <param name="direction">Direction of the compatiblity</param>
|
/// <param name="direction">Direction of the compatiblity</param>
|
||||||
public virtual void AddContextMenuItems(GenericMenu menu, Type compatibleType = null, NodePort.IO direction = NodePort.IO.Input) {
|
public virtual void AddContextMenuItems(GenericMenu menu, Type compatibleType = null,
|
||||||
|
NodePort.IO direction = NodePort.IO.Input)
|
||||||
|
{
|
||||||
Vector2 pos = NodeEditorWindow.current.WindowToGridPosition(Event.current.mousePosition);
|
Vector2 pos = NodeEditorWindow.current.WindowToGridPosition(Event.current.mousePosition);
|
||||||
|
|
||||||
Type[] nodeTypes;
|
Type[] nodeTypes;
|
||||||
|
|
||||||
if (compatibleType != null && NodeEditorPreferences.GetSettings().createFilter) {
|
if (compatibleType != null && NodeEditorPreferences.GetSettings().createFilter)
|
||||||
nodeTypes = NodeEditorUtilities.GetCompatibleNodesTypes(NodeEditorReflection.nodeTypes, compatibleType, direction).OrderBy(GetNodeMenuOrder).ToArray();
|
{
|
||||||
} else {
|
nodeTypes = NodeEditorUtilities
|
||||||
|
.GetCompatibleNodesTypes(NodeEditorReflection.nodeTypes, compatibleType, direction)
|
||||||
|
.OrderBy(GetNodeMenuOrder).ToArray();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
nodeTypes = NodeEditorReflection.nodeTypes.OrderBy(GetNodeMenuOrder).ToArray();
|
nodeTypes = NodeEditorReflection.nodeTypes.OrderBy(GetNodeMenuOrder).ToArray();
|
||||||
}
|
}
|
||||||
|
|
||||||
for (int i = 0; i < nodeTypes.Length; i++) {
|
for (int i = 0; i < nodeTypes.Length; i++)
|
||||||
|
{
|
||||||
Type type = nodeTypes[i];
|
Type type = nodeTypes[i];
|
||||||
|
|
||||||
//Get node context menu path
|
//Get node context menu path
|
||||||
string path = GetNodeMenuName(type);
|
string path = GetNodeMenuName(type);
|
||||||
if (string.IsNullOrEmpty(path)) continue;
|
if (string.IsNullOrEmpty(path))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
// Check if user is allowed to add more of given node type
|
// Check if user is allowed to add more of given node type
|
||||||
Node.DisallowMultipleNodesAttribute disallowAttrib;
|
Node.DisallowMultipleNodesAttribute disallowAttrib;
|
||||||
bool disallowed = false;
|
bool disallowed = false;
|
||||||
if (NodeEditorUtilities.GetAttrib(type, out disallowAttrib)) {
|
if (NodeEditorUtilities.GetAttrib(type, out disallowAttrib))
|
||||||
|
{
|
||||||
int typeCount = target.nodes.Count(x => x.GetType() == type);
|
int typeCount = target.nodes.Count(x => x.GetType() == type);
|
||||||
if (typeCount >= disallowAttrib.max) disallowed = true;
|
if (typeCount >= disallowAttrib.max)
|
||||||
|
{
|
||||||
|
disallowed = true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add node entry to context menu
|
// Add node entry to context menu
|
||||||
if (disallowed) menu.AddItem(new GUIContent(path), false, null);
|
if (disallowed)
|
||||||
else menu.AddItem(new GUIContent(path), false, () => {
|
{
|
||||||
Node node = CreateNode(type, pos);
|
menu.AddItem(new GUIContent(path), false, null);
|
||||||
if (node != null) NodeEditorWindow.current.AutoConnect(node); // handle null nodes to avoid nullref exceptions
|
}
|
||||||
});
|
else
|
||||||
|
{
|
||||||
|
menu.AddItem(new GUIContent(path), false, () =>
|
||||||
|
{
|
||||||
|
Node node = CreateNode(type, pos);
|
||||||
|
if (node != null)
|
||||||
|
{
|
||||||
|
NodeEditorWindow.current.AutoConnect(node); // handle null nodes to avoid nullref exceptions
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
menu.AddSeparator("");
|
menu.AddSeparator("");
|
||||||
if (NodeEditorWindow.copyBuffer != null && NodeEditorWindow.copyBuffer.Length > 0) menu.AddItem(new GUIContent("Paste"), false, () => NodeEditorWindow.current.PasteNodes(pos));
|
if (NodeEditorWindow.copyBuffer != null && NodeEditorWindow.copyBuffer.Length > 0)
|
||||||
else menu.AddDisabledItem(new GUIContent("Paste"));
|
{
|
||||||
|
menu.AddItem(new GUIContent("Paste"), false, () => NodeEditorWindow.current.PasteNodes(pos));
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
menu.AddDisabledItem(new GUIContent("Paste"));
|
||||||
|
}
|
||||||
|
|
||||||
menu.AddItem(new GUIContent("Preferences"), false, () => NodeEditorReflection.OpenPreferences());
|
menu.AddItem(new GUIContent("Preferences"), false, () => NodeEditorReflection.OpenPreferences());
|
||||||
menu.AddCustomContextMenuItems(target);
|
menu.AddCustomContextMenuItems(target);
|
||||||
}
|
}
|
||||||
@ -116,167 +170,235 @@ namespace XNodeEditor {
|
|||||||
/// <summary> Returned gradient is used to color noodles </summary>
|
/// <summary> Returned gradient is used to color noodles </summary>
|
||||||
/// <param name="output"> The output this noodle comes from. Never null. </param>
|
/// <param name="output"> The output this noodle comes from. Never null. </param>
|
||||||
/// <param name="input"> The output this noodle comes from. Can be null if we are dragging the noodle. </param>
|
/// <param name="input"> The output this noodle comes from. Can be null if we are dragging the noodle. </param>
|
||||||
public virtual Gradient GetNoodleGradient(NodePort output, NodePort input) {
|
public virtual Gradient GetNoodleGradient(NodePort output, NodePort input)
|
||||||
|
{
|
||||||
Gradient grad = new Gradient();
|
Gradient grad = new Gradient();
|
||||||
|
|
||||||
// If dragging the noodle, draw solid, slightly transparent
|
// If dragging the noodle, draw solid, slightly transparent
|
||||||
if (input == null) {
|
if (input == null)
|
||||||
|
{
|
||||||
Color a = GetTypeColor(output.ValueType);
|
Color a = GetTypeColor(output.ValueType);
|
||||||
grad.SetKeys(
|
grad.SetKeys(
|
||||||
new GradientColorKey[] { new GradientColorKey(a, 0f) },
|
new[] { new GradientColorKey(a, 0f) },
|
||||||
new GradientAlphaKey[] { new GradientAlphaKey(0.6f, 0f) }
|
new[] { new GradientAlphaKey(0.6f, 0f) }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
// If normal, draw gradient fading from one input color to the other
|
// If normal, draw gradient fading from one input color to the other
|
||||||
else {
|
else
|
||||||
|
{
|
||||||
Color a = GetTypeColor(output.ValueType);
|
Color a = GetTypeColor(output.ValueType);
|
||||||
Color b = GetTypeColor(input.ValueType);
|
Color b = GetTypeColor(input.ValueType);
|
||||||
// If any port is hovered, tint white
|
// If any port is hovered, tint white
|
||||||
if (window.hoveredPort == output || window.hoveredPort == input) {
|
if (window.hoveredPort == output || window.hoveredPort == input)
|
||||||
|
{
|
||||||
a = Color.Lerp(a, Color.white, 0.8f);
|
a = Color.Lerp(a, Color.white, 0.8f);
|
||||||
b = Color.Lerp(b, Color.white, 0.8f);
|
b = Color.Lerp(b, Color.white, 0.8f);
|
||||||
}
|
}
|
||||||
|
|
||||||
grad.SetKeys(
|
grad.SetKeys(
|
||||||
new GradientColorKey[] { new GradientColorKey(a, 0f), new GradientColorKey(b, 1f) },
|
new[] { new GradientColorKey(a, 0f), new GradientColorKey(b, 1f) },
|
||||||
new GradientAlphaKey[] { new GradientAlphaKey(1f, 0f), new GradientAlphaKey(1f, 1f) }
|
new[] { new GradientAlphaKey(1f, 0f), new GradientAlphaKey(1f, 1f) }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return grad;
|
return grad;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Returned float is used for noodle thickness </summary>
|
/// <summary> Returned float is used for noodle thickness </summary>
|
||||||
/// <param name="output"> The output this noodle comes from. Never null. </param>
|
/// <param name="output"> The output this noodle comes from. Never null. </param>
|
||||||
/// <param name="input"> The output this noodle comes from. Can be null if we are dragging the noodle. </param>
|
/// <param name="input"> The output this noodle comes from. Can be null if we are dragging the noodle. </param>
|
||||||
public virtual float GetNoodleThickness(NodePort output, NodePort input) {
|
public virtual float GetNoodleThickness(NodePort output, NodePort input)
|
||||||
|
{
|
||||||
return NodeEditorPreferences.GetSettings().noodleThickness;
|
return NodeEditorPreferences.GetSettings().noodleThickness;
|
||||||
}
|
}
|
||||||
|
|
||||||
public virtual NoodlePath GetNoodlePath(NodePort output, NodePort input) {
|
public virtual NoodlePath GetNoodlePath(NodePort output, NodePort input)
|
||||||
|
{
|
||||||
return NodeEditorPreferences.GetSettings().noodlePath;
|
return NodeEditorPreferences.GetSettings().noodlePath;
|
||||||
}
|
}
|
||||||
|
|
||||||
public virtual NoodleStroke GetNoodleStroke(NodePort output, NodePort input) {
|
public virtual NoodleStroke GetNoodleStroke(NodePort output, NodePort input)
|
||||||
|
{
|
||||||
return NodeEditorPreferences.GetSettings().noodleStroke;
|
return NodeEditorPreferences.GetSettings().noodleStroke;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Returned color is used to color ports </summary>
|
/// <summary> Returned color is used to color ports </summary>
|
||||||
public virtual Color GetPortColor(NodePort port) {
|
public virtual Color GetPortColor(NodePort port)
|
||||||
|
{
|
||||||
return GetTypeColor(port.ValueType);
|
return GetTypeColor(port.ValueType);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The returned Style is used to configure the paddings and icon texture of the ports.
|
/// The returned Style is used to configure the paddings and icon texture of the ports.
|
||||||
/// Use these properties to customize your port style.
|
/// Use these properties to customize your port style.
|
||||||
///
|
/// The properties used is:
|
||||||
/// The properties used is:
|
/// <see cref="GUIStyle.padding" />[Left and Right], <see cref="GUIStyle.normal" /> [Background] = border texture,
|
||||||
/// <see cref="GUIStyle.padding"/>[Left and Right], <see cref="GUIStyle.normal"/> [Background] = border texture,
|
/// and <seealso cref="GUIStyle.active" /> [Background] = dot texture;
|
||||||
/// and <seealso cref="GUIStyle.active"/> [Background] = dot texture;
|
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="port">the owner of the style</param>
|
/// <param name="port">the owner of the style</param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public virtual GUIStyle GetPortStyle(NodePort port) {
|
public virtual GUIStyle GetPortStyle(NodePort port)
|
||||||
|
{
|
||||||
if (port.direction == NodePort.IO.Input)
|
if (port.direction == NodePort.IO.Input)
|
||||||
|
{
|
||||||
return NodeEditorResources.styles.inputPort;
|
return NodeEditorResources.styles.inputPort;
|
||||||
|
}
|
||||||
|
|
||||||
return NodeEditorResources.styles.outputPort;
|
return NodeEditorResources.styles.outputPort;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> The returned color is used to color the background of the door.
|
/// <summary>
|
||||||
/// Usually used for outer edge effect </summary>
|
/// The returned color is used to color the background of the door.
|
||||||
public virtual Color GetPortBackgroundColor(NodePort port) {
|
/// Usually used for outer edge effect
|
||||||
|
/// </summary>
|
||||||
|
public virtual Color GetPortBackgroundColor(NodePort port)
|
||||||
|
{
|
||||||
return Color.gray;
|
return Color.gray;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Returns generated color for a type. This color is editable in preferences </summary>
|
/// <summary> Returns generated color for a type. This color is editable in preferences </summary>
|
||||||
public virtual Color GetTypeColor(Type type) {
|
public virtual Color GetTypeColor(Type type)
|
||||||
|
{
|
||||||
return NodeEditorPreferences.GetTypeColor(type);
|
return NodeEditorPreferences.GetTypeColor(type);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Override to display custom tooltips </summary>
|
/// <summary> Override to display custom tooltips </summary>
|
||||||
public virtual string GetPortTooltip(NodePort port) {
|
public virtual string GetPortTooltip(NodePort port)
|
||||||
|
{
|
||||||
Type portType = port.ValueType;
|
Type portType = port.ValueType;
|
||||||
string tooltip = "";
|
string tooltip = "";
|
||||||
tooltip = portType.PrettyName();
|
tooltip = portType.PrettyName();
|
||||||
if (port.IsOutput) {
|
if (port.IsOutput)
|
||||||
|
{
|
||||||
object obj = port.node.GetValue(port);
|
object obj = port.node.GetValue(port);
|
||||||
tooltip += " = " + (obj != null ? obj.ToString() : "null");
|
tooltip += " = " + (obj != null ? obj.ToString() : "null");
|
||||||
}
|
}
|
||||||
|
|
||||||
return tooltip;
|
return tooltip;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Deal with objects dropped into the graph through DragAndDrop </summary>
|
/// <summary> Deal with objects dropped into the graph through DragAndDrop </summary>
|
||||||
public virtual void OnDropObjects(UnityEngine.Object[] objects) {
|
public virtual void OnDropObjects(Object[] objects)
|
||||||
if (GetType() != typeof(NodeGraphEditor)) Debug.Log("No OnDropObjects override defined for " + GetType());
|
{
|
||||||
|
if (GetType() != typeof(NodeGraphEditor))
|
||||||
|
{
|
||||||
|
Debug.Log("No OnDropObjects override defined for " + GetType());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Create a node and save it in the graph asset </summary>
|
/// <summary> Create a node and save it in the graph asset </summary>
|
||||||
public virtual Node CreateNode(Type type, Vector2 position) {
|
public virtual Node CreateNode(Type type, Vector2 position)
|
||||||
|
{
|
||||||
Undo.RecordObject(target, "Create Node");
|
Undo.RecordObject(target, "Create Node");
|
||||||
Node node = target.AddNode(type);
|
Node node = target.AddNode(type);
|
||||||
if (node == null) return null; // handle null nodes to avoid nullref exceptions
|
if (node == null)
|
||||||
|
{
|
||||||
|
return null; // handle null nodes to avoid nullref exceptions
|
||||||
|
}
|
||||||
|
|
||||||
Undo.RegisterCreatedObjectUndo(node, "Create Node");
|
Undo.RegisterCreatedObjectUndo(node, "Create Node");
|
||||||
node.position = position;
|
node.position = position;
|
||||||
if (node.name == null || node.name.Trim() == "") node.name = NodeEditorUtilities.NodeDefaultName(type);
|
if (node.name == null || node.name.Trim() == "")
|
||||||
if (!string.IsNullOrEmpty(AssetDatabase.GetAssetPath(target))) AssetDatabase.AddObjectToAsset(node, target);
|
{
|
||||||
if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets();
|
node.name = NodeEditorUtilities.NodeDefaultName(type);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!string.IsNullOrEmpty(AssetDatabase.GetAssetPath(target)))
|
||||||
|
{
|
||||||
|
AssetDatabase.AddObjectToAsset(node, target);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (NodeEditorPreferences.GetSettings().autoSave)
|
||||||
|
{
|
||||||
|
AssetDatabase.SaveAssets();
|
||||||
|
}
|
||||||
|
|
||||||
NodeEditorWindow.RepaintAll();
|
NodeEditorWindow.RepaintAll();
|
||||||
return node;
|
return node;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Creates a copy of the original node in the graph </summary>
|
/// <summary> Creates a copy of the original node in the graph </summary>
|
||||||
public virtual Node CopyNode(Node original) {
|
public virtual Node CopyNode(Node original)
|
||||||
|
{
|
||||||
Undo.RecordObject(target, "Duplicate Node");
|
Undo.RecordObject(target, "Duplicate Node");
|
||||||
Node node = target.CopyNode(original);
|
Node node = target.CopyNode(original);
|
||||||
Undo.RegisterCreatedObjectUndo(node, "Duplicate Node");
|
Undo.RegisterCreatedObjectUndo(node, "Duplicate Node");
|
||||||
node.name = original.name;
|
node.name = original.name;
|
||||||
if (!string.IsNullOrEmpty(AssetDatabase.GetAssetPath(target))) AssetDatabase.AddObjectToAsset(node, target);
|
if (!string.IsNullOrEmpty(AssetDatabase.GetAssetPath(target)))
|
||||||
if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets();
|
{
|
||||||
|
AssetDatabase.AddObjectToAsset(node, target);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (NodeEditorPreferences.GetSettings().autoSave)
|
||||||
|
{
|
||||||
|
AssetDatabase.SaveAssets();
|
||||||
|
}
|
||||||
|
|
||||||
return node;
|
return node;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Return false for nodes that can't be removed </summary>
|
/// <summary> Return false for nodes that can't be removed </summary>
|
||||||
public virtual bool CanRemove(Node node) {
|
public virtual bool CanRemove(Node node)
|
||||||
|
{
|
||||||
// Check graph attributes to see if this node is required
|
// Check graph attributes to see if this node is required
|
||||||
Type graphType = target.GetType();
|
Type graphType = target.GetType();
|
||||||
NodeGraph.RequireNodeAttribute[] attribs = Array.ConvertAll(
|
var attribs = Array.ConvertAll(
|
||||||
graphType.GetCustomAttributes(typeof(NodeGraph.RequireNodeAttribute), true), x => x as NodeGraph.RequireNodeAttribute);
|
graphType.GetCustomAttributes(typeof(NodeGraph.RequireNodeAttribute), true),
|
||||||
if (attribs.Any(x => x.Requires(node.GetType()))) {
|
x => x as NodeGraph.RequireNodeAttribute);
|
||||||
if (target.nodes.Count(x => x.GetType() == node.GetType()) <= 1) {
|
if (attribs.Any(x => x.Requires(node.GetType())))
|
||||||
|
{
|
||||||
|
if (target.nodes.Count(x => x.GetType() == node.GetType()) <= 1)
|
||||||
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Safely remove a node and all its connections. </summary>
|
/// <summary> Safely remove a node and all its connections. </summary>
|
||||||
public virtual void RemoveNode(Node node) {
|
public virtual void RemoveNode(Node node)
|
||||||
if (!CanRemove(node)) return;
|
{
|
||||||
|
if (!CanRemove(node))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// Remove the node
|
// Remove the node
|
||||||
Undo.RecordObject(node, "Delete Node");
|
Undo.RecordObject(node, "Delete Node");
|
||||||
Undo.RecordObject(target, "Delete Node");
|
Undo.RecordObject(target, "Delete Node");
|
||||||
foreach (var port in node.Ports)
|
foreach (NodePort port in node.Ports)
|
||||||
foreach (var conn in port.GetConnections())
|
foreach (NodePort conn in port.GetConnections())
|
||||||
Undo.RecordObject(conn.node, "Delete Node");
|
{
|
||||||
|
Undo.RecordObject(conn.node, "Delete Node");
|
||||||
|
}
|
||||||
|
|
||||||
target.RemoveNode(node);
|
target.RemoveNode(node);
|
||||||
Undo.DestroyObjectImmediate(node);
|
Undo.DestroyObjectImmediate(node);
|
||||||
if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets();
|
if (NodeEditorPreferences.GetSettings().autoSave)
|
||||||
|
{
|
||||||
|
AssetDatabase.SaveAssets();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
[AttributeUsage(AttributeTargets.Class)]
|
[AttributeUsage(AttributeTargets.Class)]
|
||||||
public class CustomNodeGraphEditorAttribute : Attribute,
|
public class CustomNodeGraphEditorAttribute : Attribute,
|
||||||
XNodeEditor.Internal.NodeEditorBase<NodeGraphEditor, NodeGraphEditor.CustomNodeGraphEditorAttribute, NodeGraph>.INodeEditorAttrib {
|
INodeEditorAttrib
|
||||||
private Type inspectedType;
|
{
|
||||||
|
private readonly Type inspectedType;
|
||||||
public string editorPrefsKey;
|
public string editorPrefsKey;
|
||||||
|
|
||||||
/// <summary> Tells a NodeGraphEditor which Graph type it is an editor for </summary>
|
/// <summary> Tells a NodeGraphEditor which Graph type it is an editor for </summary>
|
||||||
/// <param name="inspectedType">Type that this editor can edit</param>
|
/// <param name="inspectedType">Type that this editor can edit</param>
|
||||||
/// <param name="editorPrefsKey">Define unique key for unique layout settings instance</param>
|
/// <param name="editorPrefsKey">Define unique key for unique layout settings instance</param>
|
||||||
public CustomNodeGraphEditorAttribute(Type inspectedType, string editorPrefsKey = "xNode.Settings") {
|
public CustomNodeGraphEditorAttribute(Type inspectedType, string editorPrefsKey = "xNode.Settings")
|
||||||
|
{
|
||||||
this.inspectedType = inspectedType;
|
this.inspectedType = inspectedType;
|
||||||
this.editorPrefsKey = editorPrefsKey;
|
this.editorPrefsKey = editorPrefsKey;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Type GetInspectedType() {
|
public Type GetInspectedType()
|
||||||
|
{
|
||||||
return inspectedType;
|
return inspectedType;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -2,42 +2,75 @@
|
|||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using UnityEditor;
|
using UnityEditor;
|
||||||
using UnityEditor.Experimental.AssetImporters;
|
|
||||||
using UnityEngine;
|
using UnityEngine;
|
||||||
|
using XNode;
|
||||||
|
|
||||||
namespace XNodeEditor {
|
namespace XNodeEditor
|
||||||
|
{
|
||||||
/// <summary> Deals with modified assets </summary>
|
/// <summary> Deals with modified assets </summary>
|
||||||
class NodeGraphImporter : AssetPostprocessor {
|
internal class NodeGraphImporter : AssetPostprocessor
|
||||||
private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) {
|
{
|
||||||
foreach (string path in importedAssets) {
|
private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets,
|
||||||
|
string[] movedAssets, string[] movedFromAssetPaths)
|
||||||
|
{
|
||||||
|
foreach (string path in importedAssets)
|
||||||
|
{
|
||||||
// Skip processing anything without the .asset extension
|
// Skip processing anything without the .asset extension
|
||||||
if (Path.GetExtension(path) != ".asset") continue;
|
if (Path.GetExtension(path) != ".asset")
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
// Get the object that is requested for deletion
|
// Get the object that is requested for deletion
|
||||||
NodeGraph graph = AssetDatabase.LoadAssetAtPath<NodeGraph>(path);
|
NodeGraph graph = AssetDatabase.LoadAssetAtPath<NodeGraph>(path);
|
||||||
if (graph == null) continue;
|
if (graph == null)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
// Get attributes
|
// Get attributes
|
||||||
Type graphType = graph.GetType();
|
Type graphType = graph.GetType();
|
||||||
NodeGraph.RequireNodeAttribute[] attribs = Array.ConvertAll(
|
var attribs = Array.ConvertAll(
|
||||||
graphType.GetCustomAttributes(typeof(NodeGraph.RequireNodeAttribute), true), x => x as NodeGraph.RequireNodeAttribute);
|
graphType.GetCustomAttributes(typeof(NodeGraph.RequireNodeAttribute), true),
|
||||||
|
x => x as NodeGraph.RequireNodeAttribute);
|
||||||
|
|
||||||
Vector2 position = Vector2.zero;
|
Vector2 position = Vector2.zero;
|
||||||
foreach (NodeGraph.RequireNodeAttribute attrib in attribs) {
|
foreach (NodeGraph.RequireNodeAttribute attrib in attribs)
|
||||||
if (attrib.type0 != null) AddRequired(graph, attrib.type0, ref position);
|
{
|
||||||
if (attrib.type1 != null) AddRequired(graph, attrib.type1, ref position);
|
if (attrib.type0 != null)
|
||||||
if (attrib.type2 != null) AddRequired(graph, attrib.type2, ref position);
|
{
|
||||||
|
AddRequired(graph, attrib.type0, ref position);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (attrib.type1 != null)
|
||||||
|
{
|
||||||
|
AddRequired(graph, attrib.type1, ref position);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (attrib.type2 != null)
|
||||||
|
{
|
||||||
|
AddRequired(graph, attrib.type2, ref position);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void AddRequired(NodeGraph graph, Type type, ref Vector2 position) {
|
private static void AddRequired(NodeGraph graph, Type type, ref Vector2 position)
|
||||||
if (!graph.nodes.Any(x => x.GetType() == type)) {
|
{
|
||||||
|
if (!graph.nodes.Any(x => x.GetType() == type))
|
||||||
|
{
|
||||||
Node node = graph.AddNode(type);
|
Node node = graph.AddNode(type);
|
||||||
node.position = position;
|
node.position = position;
|
||||||
position.x += 200;
|
position.x += 200;
|
||||||
if (node.name == null || node.name.Trim() == "") node.name = NodeEditorUtilities.NodeDefaultName(type);
|
if (node.name == null || node.name.Trim() == "")
|
||||||
if (!string.IsNullOrEmpty(AssetDatabase.GetAssetPath(graph))) AssetDatabase.AddObjectToAsset(node, graph);
|
{
|
||||||
|
node.name = NodeEditorUtilities.NodeDefaultName(type);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!string.IsNullOrEmpty(AssetDatabase.GetAssetPath(graph)))
|
||||||
|
{
|
||||||
|
AssetDatabase.AddObjectToAsset(node, graph);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,6 +1,7 @@
|
|||||||
using System.Linq;
|
using System.Linq;
|
||||||
using UnityEditor;
|
using UnityEditor;
|
||||||
using UnityEngine;
|
using UnityEngine;
|
||||||
|
using XNode;
|
||||||
using XNodeEditor.Internal;
|
using XNodeEditor.Internal;
|
||||||
|
|
||||||
namespace XNodeEditor.NodeGroups
|
namespace XNodeEditor.NodeGroups
|
||||||
@ -10,8 +11,13 @@ namespace XNodeEditor.NodeGroups
|
|||||||
{
|
{
|
||||||
private NodeGroup group => _group != null ? _group : _group = target as NodeGroup;
|
private NodeGroup group => _group != null ? _group : _group = target as NodeGroup;
|
||||||
private NodeGroup _group;
|
private NodeGroup _group;
|
||||||
private bool isDragging;
|
private bool _isDragging;
|
||||||
private Vector2 size;
|
private Vector2 _size;
|
||||||
|
|
||||||
|
public override void OnHeaderGUI()
|
||||||
|
{
|
||||||
|
GUILayout.Label(target.name, NodeEditorResources.styles.nodeHeader, GUILayout.Height(30));
|
||||||
|
}
|
||||||
|
|
||||||
public override void OnBodyGUI()
|
public override void OnBodyGUI()
|
||||||
{
|
{
|
||||||
@ -19,7 +25,7 @@ namespace XNodeEditor.NodeGroups
|
|||||||
switch (e.type)
|
switch (e.type)
|
||||||
{
|
{
|
||||||
case EventType.MouseDrag:
|
case EventType.MouseDrag:
|
||||||
if (isDragging)
|
if (_isDragging)
|
||||||
{
|
{
|
||||||
group.width = Mathf.Max(200, (int)e.mousePosition.x + 16);
|
group.width = Mathf.Max(200, (int)e.mousePosition.x + 16);
|
||||||
group.height = Mathf.Max(100, (int)e.mousePosition.y - 34);
|
group.height = Mathf.Max(100, (int)e.mousePosition.y - 34);
|
||||||
@ -34,19 +40,19 @@ namespace XNodeEditor.NodeGroups
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (NodeEditorWindow.current.nodeSizes.TryGetValue(target, out size))
|
if (NodeEditorWindow.current.nodeSizes.TryGetValue(target, out _size))
|
||||||
{
|
{
|
||||||
// Mouse position checking is in node local space
|
// Mouse position checking is in node local space
|
||||||
Rect lowerRight = new Rect(size.x - 34, size.y - 34, 30, 30);
|
Rect lowerRight = new Rect(_size.x - 34, _size.y - 34, 30, 30);
|
||||||
if (lowerRight.Contains(e.mousePosition))
|
if (lowerRight.Contains(e.mousePosition))
|
||||||
{
|
{
|
||||||
isDragging = true;
|
_isDragging = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
break;
|
break;
|
||||||
case EventType.MouseUp:
|
case EventType.MouseUp:
|
||||||
isDragging = false;
|
_isDragging = false;
|
||||||
// Select nodes inside the group
|
// Select nodes inside the group
|
||||||
if (Selection.Contains(target))
|
if (Selection.Contains(target))
|
||||||
{
|
{
|
||||||
@ -114,11 +120,11 @@ namespace XNodeEditor.NodeGroups
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Add scale cursors
|
// Add scale cursors
|
||||||
if (NodeEditorWindow.current.nodeSizes.TryGetValue(target, out size))
|
if (NodeEditorWindow.current.nodeSizes.TryGetValue(target, out _size))
|
||||||
{
|
{
|
||||||
Rect lowerRight = new Rect(target.position, new Vector2(30, 30));
|
Rect lowerRight = new Rect(target.position, new Vector2(30, 30));
|
||||||
lowerRight.y += size.y - 34;
|
lowerRight.y += _size.y - 34;
|
||||||
lowerRight.x += size.x - 34;
|
lowerRight.x += _size.x - 34;
|
||||||
lowerRight = NodeEditorWindow.current.GridToWindowRect(lowerRight);
|
lowerRight = NodeEditorWindow.current.GridToWindowRect(lowerRight);
|
||||||
NodeEditorWindow.current.onLateGUI += () => AddMouseRect(lowerRight);
|
NodeEditorWindow.current.onLateGUI += () => AddMouseRect(lowerRight);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,9 +1,12 @@
|
|||||||
using UnityEditor;
|
using UnityEditor;
|
||||||
using UnityEngine;
|
using UnityEngine;
|
||||||
|
using XNode;
|
||||||
|
|
||||||
namespace XNodeEditor {
|
namespace XNodeEditor
|
||||||
|
{
|
||||||
/// <summary> Utility for renaming assets </summary>
|
/// <summary> Utility for renaming assets </summary>
|
||||||
public class RenamePopup : EditorWindow {
|
public class RenamePopup : EditorWindow
|
||||||
|
{
|
||||||
private const string inputControlName = "nameInput";
|
private const string inputControlName = "nameInput";
|
||||||
|
|
||||||
public static RenamePopup current { get; private set; }
|
public static RenamePopup current { get; private set; }
|
||||||
@ -13,9 +16,14 @@ namespace XNodeEditor {
|
|||||||
private bool firstFrame = true;
|
private bool firstFrame = true;
|
||||||
|
|
||||||
/// <summary> Show a rename popup for an asset at mouse position. Will trigger reimport of the asset on apply.
|
/// <summary> Show a rename popup for an asset at mouse position. Will trigger reimport of the asset on apply.
|
||||||
public static RenamePopup Show(Object target, float width = 200) {
|
public static RenamePopup Show(Object target, float width = 200)
|
||||||
RenamePopup window = EditorWindow.GetWindow<RenamePopup>(true, "Rename " + target.name, true);
|
{
|
||||||
if (current != null) current.Close();
|
RenamePopup window = GetWindow<RenamePopup>(true, "Rename " + target.name, true);
|
||||||
|
if (current != null)
|
||||||
|
{
|
||||||
|
current.Close();
|
||||||
|
}
|
||||||
|
|
||||||
current = window;
|
current = window;
|
||||||
window.target = target;
|
window.target = target;
|
||||||
window.input = target.name;
|
window.input = target.name;
|
||||||
@ -25,8 +33,13 @@ namespace XNodeEditor {
|
|||||||
return window;
|
return window;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void UpdatePositionToMouse() {
|
private void UpdatePositionToMouse()
|
||||||
if (Event.current == null) return;
|
{
|
||||||
|
if (Event.current == null)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
Vector3 mousePoint = GUIUtility.GUIToScreenPoint(Event.current.mousePosition);
|
Vector3 mousePoint = GUIUtility.GUIToScreenPoint(Event.current.mousePosition);
|
||||||
Rect pos = position;
|
Rect pos = position;
|
||||||
pos.x = mousePoint.x - position.width * 0.5f;
|
pos.x = mousePoint.x - position.width * 0.5f;
|
||||||
@ -34,53 +47,67 @@ namespace XNodeEditor {
|
|||||||
position = pos;
|
position = pos;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void OnLostFocus() {
|
private void OnLostFocus()
|
||||||
|
{
|
||||||
// Make the popup close on lose focus
|
// Make the popup close on lose focus
|
||||||
Close();
|
Close();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void OnGUI() {
|
private void OnGUI()
|
||||||
if (firstFrame) {
|
{
|
||||||
|
if (firstFrame)
|
||||||
|
{
|
||||||
UpdatePositionToMouse();
|
UpdatePositionToMouse();
|
||||||
firstFrame = false;
|
firstFrame = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
GUI.SetNextControlName(inputControlName);
|
GUI.SetNextControlName(inputControlName);
|
||||||
input = EditorGUILayout.TextField(input);
|
input = EditorGUILayout.TextField(input);
|
||||||
EditorGUI.FocusTextInControl(inputControlName);
|
EditorGUI.FocusTextInControl(inputControlName);
|
||||||
Event e = Event.current;
|
Event e = Event.current;
|
||||||
// If input is empty, revert name to default instead
|
// If input is empty, revert name to default instead
|
||||||
if (input == null || input.Trim() == "") {
|
if (input == null || input.Trim() == "")
|
||||||
if (GUILayout.Button("Revert to default") || (e.isKey && e.keyCode == KeyCode.Return)) {
|
{
|
||||||
|
if (GUILayout.Button("Revert to default") || e.isKey && e.keyCode == KeyCode.Return)
|
||||||
|
{
|
||||||
target.name = NodeEditorUtilities.NodeDefaultName(target.GetType());
|
target.name = NodeEditorUtilities.NodeDefaultName(target.GetType());
|
||||||
NodeEditor.GetEditor((Node)target, NodeEditorWindow.current).OnRename();
|
NodeEditor.GetEditor((Node)target, NodeEditorWindow.current).OnRename();
|
||||||
if (!string.IsNullOrEmpty(AssetDatabase.GetAssetPath(target))) {
|
if (!string.IsNullOrEmpty(AssetDatabase.GetAssetPath(target)))
|
||||||
|
{
|
||||||
AssetDatabase.SetMainObject((target as Node).graph, AssetDatabase.GetAssetPath(target));
|
AssetDatabase.SetMainObject((target as Node).graph, AssetDatabase.GetAssetPath(target));
|
||||||
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(target));
|
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(target));
|
||||||
}
|
}
|
||||||
|
|
||||||
Close();
|
Close();
|
||||||
target.TriggerOnValidate();
|
target.TriggerOnValidate();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Rename asset to input text
|
// Rename asset to input text
|
||||||
else {
|
else
|
||||||
if (GUILayout.Button("Apply") || (e.isKey && e.keyCode == KeyCode.Return)) {
|
{
|
||||||
|
if (GUILayout.Button("Apply") || e.isKey && e.keyCode == KeyCode.Return)
|
||||||
|
{
|
||||||
target.name = input;
|
target.name = input;
|
||||||
NodeEditor.GetEditor((Node)target, NodeEditorWindow.current).OnRename();
|
NodeEditor.GetEditor((Node)target, NodeEditorWindow.current).OnRename();
|
||||||
if (!string.IsNullOrEmpty(AssetDatabase.GetAssetPath(target))) {
|
if (!string.IsNullOrEmpty(AssetDatabase.GetAssetPath(target)))
|
||||||
|
{
|
||||||
AssetDatabase.SetMainObject((target as Node).graph, AssetDatabase.GetAssetPath(target));
|
AssetDatabase.SetMainObject((target as Node).graph, AssetDatabase.GetAssetPath(target));
|
||||||
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(target));
|
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(target));
|
||||||
}
|
}
|
||||||
|
|
||||||
Close();
|
Close();
|
||||||
target.TriggerOnValidate();
|
target.TriggerOnValidate();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (e.isKey && e.keyCode == KeyCode.Escape) {
|
if (e.isKey && e.keyCode == KeyCode.Escape)
|
||||||
|
{
|
||||||
Close();
|
Close();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void OnDestroy() {
|
private void OnDestroy()
|
||||||
|
{
|
||||||
EditorGUIUtility.editingTextField = false;
|
EditorGUIUtility.editingTextField = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,76 +1,105 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections;
|
|
||||||
using System.Collections.Generic;
|
|
||||||
using UnityEditor;
|
using UnityEditor;
|
||||||
using UnityEngine;
|
using UnityEngine;
|
||||||
|
using XNode;
|
||||||
|
|
||||||
namespace XNodeEditor {
|
namespace XNodeEditor
|
||||||
|
{
|
||||||
[CustomEditor(typeof(SceneGraph), true)]
|
[CustomEditor(typeof(SceneGraph), true)]
|
||||||
public class SceneGraphEditor : Editor {
|
public class SceneGraphEditor : Editor
|
||||||
|
{
|
||||||
private SceneGraph sceneGraph;
|
private SceneGraph sceneGraph;
|
||||||
private bool removeSafely;
|
private bool removeSafely;
|
||||||
private Type graphType;
|
private Type graphType;
|
||||||
|
|
||||||
public override void OnInspectorGUI() {
|
public override void OnInspectorGUI()
|
||||||
if (sceneGraph.graph == null) {
|
{
|
||||||
if (GUILayout.Button("New graph", GUILayout.Height(40))) {
|
if (sceneGraph.graph == null)
|
||||||
if (graphType == null) {
|
{
|
||||||
Type[] graphTypes = NodeEditorReflection.GetDerivedTypes(typeof(NodeGraph));
|
if (GUILayout.Button("New graph", GUILayout.Height(40)))
|
||||||
|
{
|
||||||
|
if (graphType == null)
|
||||||
|
{
|
||||||
|
var graphTypes = typeof(NodeGraph).GetDerivedTypes();
|
||||||
GenericMenu menu = new GenericMenu();
|
GenericMenu menu = new GenericMenu();
|
||||||
for (int i = 0; i < graphTypes.Length; i++) {
|
for (int i = 0; i < graphTypes.Length; i++)
|
||||||
|
{
|
||||||
Type graphType = graphTypes[i];
|
Type graphType = graphTypes[i];
|
||||||
menu.AddItem(new GUIContent(graphType.Name), false, () => CreateGraph(graphType));
|
menu.AddItem(new GUIContent(graphType.Name), false, () => CreateGraph(graphType));
|
||||||
}
|
}
|
||||||
|
|
||||||
menu.ShowAsContext();
|
menu.ShowAsContext();
|
||||||
} else {
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
CreateGraph(graphType);
|
CreateGraph(graphType);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
}
|
||||||
if (GUILayout.Button("Open graph", GUILayout.Height(40))) {
|
else
|
||||||
|
{
|
||||||
|
if (GUILayout.Button("Open graph", GUILayout.Height(40)))
|
||||||
|
{
|
||||||
NodeEditorWindow.Open(sceneGraph.graph);
|
NodeEditorWindow.Open(sceneGraph.graph);
|
||||||
}
|
}
|
||||||
if (removeSafely) {
|
|
||||||
|
if (removeSafely)
|
||||||
|
{
|
||||||
GUILayout.BeginHorizontal();
|
GUILayout.BeginHorizontal();
|
||||||
GUILayout.Label("Really remove graph?");
|
GUILayout.Label("Really remove graph?");
|
||||||
GUI.color = new Color(1, 0.8f, 0.8f);
|
GUI.color = new Color(1, 0.8f, 0.8f);
|
||||||
if (GUILayout.Button("Remove")) {
|
if (GUILayout.Button("Remove"))
|
||||||
|
{
|
||||||
removeSafely = false;
|
removeSafely = false;
|
||||||
Undo.RecordObject(sceneGraph, "Removed graph");
|
Undo.RecordObject(sceneGraph, "Removed graph");
|
||||||
sceneGraph.graph = null;
|
sceneGraph.graph = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
GUI.color = Color.white;
|
GUI.color = Color.white;
|
||||||
if (GUILayout.Button("Cancel")) {
|
if (GUILayout.Button("Cancel"))
|
||||||
|
{
|
||||||
removeSafely = false;
|
removeSafely = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
GUILayout.EndHorizontal();
|
GUILayout.EndHorizontal();
|
||||||
} else {
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
GUI.color = new Color(1, 0.8f, 0.8f);
|
GUI.color = new Color(1, 0.8f, 0.8f);
|
||||||
if (GUILayout.Button("Remove graph")) {
|
if (GUILayout.Button("Remove graph"))
|
||||||
|
{
|
||||||
removeSafely = true;
|
removeSafely = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
GUI.color = Color.white;
|
GUI.color = Color.white;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
DrawDefaultInspector();
|
|
||||||
|
DrawDefaultInspector();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void OnEnable() {
|
private void OnEnable()
|
||||||
|
{
|
||||||
sceneGraph = target as SceneGraph;
|
sceneGraph = target as SceneGraph;
|
||||||
Type sceneGraphType = sceneGraph.GetType();
|
Type sceneGraphType = sceneGraph.GetType();
|
||||||
if (sceneGraphType == typeof(SceneGraph)) {
|
if (sceneGraphType == typeof(SceneGraph))
|
||||||
|
{
|
||||||
graphType = null;
|
graphType = null;
|
||||||
} else {
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
Type baseType = sceneGraphType.BaseType;
|
Type baseType = sceneGraphType.BaseType;
|
||||||
if (baseType.IsGenericType) {
|
if (baseType.IsGenericType)
|
||||||
graphType = sceneGraphType = baseType.GetGenericArguments() [0];
|
{
|
||||||
|
graphType = sceneGraphType = baseType.GetGenericArguments()[0];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void CreateGraph(Type type) {
|
public void CreateGraph(Type type)
|
||||||
|
{
|
||||||
Undo.RecordObject(sceneGraph, "Create graph");
|
Undo.RecordObject(sceneGraph, "Create graph");
|
||||||
sceneGraph.graph = ScriptableObject.CreateInstance(type) as NodeGraph;
|
sceneGraph.graph = CreateInstance(type) as NodeGraph;
|
||||||
sceneGraph.graph.name = sceneGraph.name + "-graph";
|
sceneGraph.graph.name = sceneGraph.name + "-graph";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
1007
Scripts/Node.cs
1007
Scripts/Node.cs
File diff suppressed because it is too large
Load Diff
@ -1,224 +1,338 @@
|
|||||||
using System.Collections.Generic;
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Reflection;
|
using System.Reflection;
|
||||||
using UnityEngine;
|
using UnityEngine;
|
||||||
|
using UnityEngine.Serialization;
|
||||||
|
|
||||||
/// <summary> Precaches reflection data in editor so we won't have to do it runtime </summary>
|
namespace XNode
|
||||||
public static class NodeDataCache {
|
{
|
||||||
private static PortDataCache portDataCache;
|
/// <summary> Precaches reflection data in editor so we won't have to do it runtime </summary>
|
||||||
private static Dictionary<System.Type, Dictionary<string, string>> formerlySerializedAsCache;
|
public static class NodeDataCache
|
||||||
private static Dictionary<System.Type, string> typeQualifiedNameCache;
|
{
|
||||||
private static bool Initialized { get { return portDataCache != null; } }
|
private static PortDataCache portDataCache;
|
||||||
|
private static Dictionary<Type, Dictionary<string, string>> formerlySerializedAsCache;
|
||||||
|
private static Dictionary<Type, string> typeQualifiedNameCache;
|
||||||
|
private static bool Initialized => portDataCache != null;
|
||||||
|
|
||||||
public static string GetTypeQualifiedName(System.Type type) {
|
public static string GetTypeQualifiedName(Type type)
|
||||||
if(typeQualifiedNameCache == null) typeQualifiedNameCache = new Dictionary<System.Type, string>();
|
{
|
||||||
|
if (typeQualifiedNameCache == null)
|
||||||
|
{
|
||||||
|
typeQualifiedNameCache = new Dictionary<Type, string>();
|
||||||
|
}
|
||||||
|
|
||||||
string name;
|
string name;
|
||||||
if (!typeQualifiedNameCache.TryGetValue(type, out name)) {
|
if (!typeQualifiedNameCache.TryGetValue(type, out name))
|
||||||
name = type.AssemblyQualifiedName;
|
{
|
||||||
typeQualifiedNameCache.Add(type, name);
|
name = type.AssemblyQualifiedName;
|
||||||
}
|
typeQualifiedNameCache.Add(type, name);
|
||||||
return name;
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Update static ports and dynamic ports managed by DynamicPortLists to reflect class fields. </summary>
|
return name;
|
||||||
public static void UpdatePorts(Node node, Dictionary<string, NodePort> ports) {
|
|
||||||
if (!Initialized) BuildCache();
|
|
||||||
|
|
||||||
Dictionary<string, List<NodePort>> removedPorts = new Dictionary<string, List<NodePort>>();
|
|
||||||
System.Type nodeType = node.GetType();
|
|
||||||
|
|
||||||
Dictionary<string, string> formerlySerializedAs = null;
|
|
||||||
if (formerlySerializedAsCache != null) formerlySerializedAsCache.TryGetValue(nodeType, out formerlySerializedAs);
|
|
||||||
|
|
||||||
List<NodePort> dynamicListPorts = new List<NodePort>();
|
|
||||||
|
|
||||||
Dictionary<string, NodePort> staticPorts;
|
|
||||||
if (!portDataCache.TryGetValue(nodeType, out staticPorts)) {
|
|
||||||
staticPorts = new Dictionary<string, NodePort>();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Cleanup port dict - Remove nonexisting static ports - update static port types
|
/// <summary> Update static ports and dynamic ports managed by DynamicPortLists to reflect class fields. </summary>
|
||||||
// AND update dynamic ports (albeit only those in lists) too, in order to enforce proper serialisation.
|
public static void UpdatePorts(Node node, Dictionary<string, NodePort> ports)
|
||||||
// Loop through current node ports
|
{
|
||||||
foreach (NodePort port in ports.Values.ToArray()) {
|
if (!Initialized)
|
||||||
// If port still exists, check it it has been changed
|
{
|
||||||
NodePort staticPort;
|
BuildCache();
|
||||||
if (staticPorts.TryGetValue(port.fieldName, out staticPort)) {
|
|
||||||
// If port exists but with wrong settings, remove it. Re-add it later.
|
|
||||||
if (port.IsDynamic || port.direction != staticPort.direction || port.connectionType != staticPort.connectionType || port.typeConstraint != staticPort.typeConstraint) {
|
|
||||||
// If port is not dynamic and direction hasn't changed, add it to the list so we can try reconnecting the ports connections.
|
|
||||||
if (!port.IsDynamic && port.direction == staticPort.direction) removedPorts.Add(port.fieldName, port.GetConnections());
|
|
||||||
port.ClearConnections();
|
|
||||||
ports.Remove(port.fieldName);
|
|
||||||
} else port.ValueType = staticPort.ValueType;
|
|
||||||
}
|
}
|
||||||
// If port doesn't exist anymore, remove it
|
|
||||||
else if (port.IsStatic) {
|
|
||||||
//See if the field is tagged with FormerlySerializedAs, if so add the port with its new field name to removedPorts
|
|
||||||
// so it can be reconnected in missing ports stage.
|
|
||||||
string newName = null;
|
|
||||||
if (formerlySerializedAs != null && formerlySerializedAs.TryGetValue(port.fieldName, out newName)) removedPorts.Add(newName, port.GetConnections());
|
|
||||||
|
|
||||||
port.ClearConnections();
|
var removedPorts = new Dictionary<string, List<NodePort>>();
|
||||||
ports.Remove(port.fieldName);
|
Type nodeType = node.GetType();
|
||||||
|
|
||||||
|
Dictionary<string, string> formerlySerializedAs = null;
|
||||||
|
if (formerlySerializedAsCache != null)
|
||||||
|
{
|
||||||
|
formerlySerializedAsCache.TryGetValue(nodeType, out formerlySerializedAs);
|
||||||
}
|
}
|
||||||
// If the port is dynamic and is managed by a dynamic port list, flag it for reference updates
|
|
||||||
else if (IsDynamicListPort(port)) {
|
var dynamicListPorts = new List<NodePort>();
|
||||||
dynamicListPorts.Add(port);
|
|
||||||
|
Dictionary<string, NodePort> staticPorts;
|
||||||
|
if (!portDataCache.TryGetValue(nodeType, out staticPorts))
|
||||||
|
{
|
||||||
|
staticPorts = new Dictionary<string, NodePort>();
|
||||||
}
|
}
|
||||||
}
|
|
||||||
// Add missing ports
|
// Cleanup port dict - Remove nonexisting static ports - update static port types
|
||||||
foreach (NodePort staticPort in staticPorts.Values) {
|
// AND update dynamic ports (albeit only those in lists) too, in order to enforce proper serialisation.
|
||||||
if (!ports.ContainsKey(staticPort.fieldName)) {
|
// Loop through current node ports
|
||||||
NodePort port = new NodePort(staticPort, node);
|
foreach (NodePort port in ports.Values.ToArray())
|
||||||
//If we just removed the port, try re-adding the connections
|
{
|
||||||
List<NodePort> reconnectConnections;
|
// If port still exists, check it it has been changed
|
||||||
if (removedPorts.TryGetValue(staticPort.fieldName, out reconnectConnections)) {
|
NodePort staticPort;
|
||||||
for (int i = 0; i < reconnectConnections.Count; i++) {
|
if (staticPorts.TryGetValue(port.fieldName, out staticPort))
|
||||||
NodePort connection = reconnectConnections[i];
|
{
|
||||||
if (connection == null) continue;
|
// If port exists but with wrong settings, remove it. Re-add it later.
|
||||||
// CAVEAT: Ports connected under special conditions defined in graphEditor.CanConnect overrides will not auto-connect.
|
if (port.IsDynamic || port.direction != staticPort.direction ||
|
||||||
// To fix this, this code would need to be moved to an editor script and call graphEditor.CanConnect instead of port.CanConnectTo.
|
port.connectionType != staticPort.connectionType ||
|
||||||
// This is only a problem in the rare edge case where user is using non-standard CanConnect overrides and changes port type of an already connected port
|
port.typeConstraint != staticPort.typeConstraint)
|
||||||
if (port.CanConnectTo(connection)) port.Connect(connection);
|
{
|
||||||
|
// If port is not dynamic and direction hasn't changed, add it to the list so we can try reconnecting the ports connections.
|
||||||
|
if (!port.IsDynamic && port.direction == staticPort.direction)
|
||||||
|
{
|
||||||
|
removedPorts.Add(port.fieldName, port.GetConnections());
|
||||||
|
}
|
||||||
|
|
||||||
|
port.ClearConnections();
|
||||||
|
ports.Remove(port.fieldName);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
port.ValueType = staticPort.ValueType;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ports.Add(staticPort.fieldName, port);
|
// If port doesn't exist anymore, remove it
|
||||||
|
else if (port.IsStatic)
|
||||||
|
{
|
||||||
|
//See if the field is tagged with FormerlySerializedAs, if so add the port with its new field name to removedPorts
|
||||||
|
// so it can be reconnected in missing ports stage.
|
||||||
|
string newName = null;
|
||||||
|
if (formerlySerializedAs != null && formerlySerializedAs.TryGetValue(port.fieldName, out newName))
|
||||||
|
{
|
||||||
|
removedPorts.Add(newName, port.GetConnections());
|
||||||
|
}
|
||||||
|
|
||||||
|
port.ClearConnections();
|
||||||
|
ports.Remove(port.fieldName);
|
||||||
|
}
|
||||||
|
// If the port is dynamic and is managed by a dynamic port list, flag it for reference updates
|
||||||
|
else if (IsDynamicListPort(port))
|
||||||
|
{
|
||||||
|
dynamicListPorts.Add(port);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add missing ports
|
||||||
|
foreach (NodePort staticPort in staticPorts.Values)
|
||||||
|
{
|
||||||
|
if (!ports.ContainsKey(staticPort.fieldName))
|
||||||
|
{
|
||||||
|
NodePort port = new NodePort(staticPort, node);
|
||||||
|
//If we just removed the port, try re-adding the connections
|
||||||
|
List<NodePort> reconnectConnections;
|
||||||
|
if (removedPorts.TryGetValue(staticPort.fieldName, out reconnectConnections))
|
||||||
|
{
|
||||||
|
for (int i = 0; i < reconnectConnections.Count; i++)
|
||||||
|
{
|
||||||
|
NodePort connection = reconnectConnections[i];
|
||||||
|
if (connection == null)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// CAVEAT: Ports connected under special conditions defined in graphEditor.CanConnect overrides will not auto-connect.
|
||||||
|
// To fix this, this code would need to be moved to an editor script and call graphEditor.CanConnect instead of port.CanConnectTo.
|
||||||
|
// This is only a problem in the rare edge case where user is using non-standard CanConnect overrides and changes port type of an already connected port
|
||||||
|
if (port.CanConnectTo(connection))
|
||||||
|
{
|
||||||
|
port.Connect(connection);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ports.Add(staticPort.fieldName, port);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Finally, make sure dynamic list port settings correspond to the settings of their "backing port"
|
||||||
|
foreach (NodePort listPort in dynamicListPorts)
|
||||||
|
{
|
||||||
|
// At this point we know that ports here are dynamic list ports
|
||||||
|
// which have passed name/"backing port" checks, ergo we can proceed more safely.
|
||||||
|
string backingPortName = listPort.fieldName.Substring(0, listPort.fieldName.IndexOf(' '));
|
||||||
|
NodePort backingPort = staticPorts[backingPortName];
|
||||||
|
|
||||||
|
// Update port constraints. Creating a new port instead will break the editor, mandating the need for setters.
|
||||||
|
listPort.ValueType = GetBackingValueType(backingPort.ValueType);
|
||||||
|
listPort.direction = backingPort.direction;
|
||||||
|
listPort.connectionType = backingPort.connectionType;
|
||||||
|
listPort.typeConstraint = backingPort.typeConstraint;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Finally, make sure dynamic list port settings correspond to the settings of their "backing port"
|
/// <summary>
|
||||||
foreach (NodePort listPort in dynamicListPorts) {
|
/// Extracts the underlying types from arrays and lists, the only collections for dynamic port lists
|
||||||
// At this point we know that ports here are dynamic list ports
|
/// currently supported. If the given type is not applicable (i.e. if the dynamic list port was not
|
||||||
// which have passed name/"backing port" checks, ergo we can proceed more safely.
|
/// defined as an array or a list), returns the given type itself.
|
||||||
string backingPortName = listPort.fieldName.Substring(0, listPort.fieldName.IndexOf(' '));
|
/// </summary>
|
||||||
NodePort backingPort = staticPorts[backingPortName];
|
private static Type GetBackingValueType(Type portValType)
|
||||||
|
{
|
||||||
|
if (portValType.HasElementType)
|
||||||
|
{
|
||||||
|
return portValType.GetElementType();
|
||||||
|
}
|
||||||
|
|
||||||
// Update port constraints. Creating a new port instead will break the editor, mandating the need for setters.
|
if (portValType.IsGenericType && portValType.GetGenericTypeDefinition() == typeof(List<>))
|
||||||
listPort.ValueType = GetBackingValueType(backingPort.ValueType);
|
{
|
||||||
listPort.direction = backingPort.direction;
|
return portValType.GetGenericArguments()[0];
|
||||||
listPort.connectionType = backingPort.connectionType;
|
}
|
||||||
listPort.typeConstraint = backingPort.typeConstraint;
|
|
||||||
|
return portValType;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>Returns true if the given port is in a dynamic port list.</summary>
|
||||||
/// Extracts the underlying types from arrays and lists, the only collections for dynamic port lists
|
private static bool IsDynamicListPort(NodePort port)
|
||||||
/// currently supported. If the given type is not applicable (i.e. if the dynamic list port was not
|
{
|
||||||
/// defined as an array or a list), returns the given type itself.
|
// Ports flagged as "dynamicPortList = true" end up having a "backing port" and a name with an index, but we have
|
||||||
/// </summary>
|
// no guarantee that a dynamic port called "output 0" is an element in a list backed by a static "output" port.
|
||||||
private static System.Type GetBackingValueType(System.Type portValType) {
|
// Thus, we need to check for attributes... (but at least we don't need to look at all fields this time)
|
||||||
if (portValType.HasElementType) {
|
string[] fieldNameParts = port.fieldName.Split(' ');
|
||||||
return portValType.GetElementType();
|
if (fieldNameParts.Length != 2)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
FieldInfo backingPortInfo = port.node.GetType().GetField(fieldNameParts[0]);
|
||||||
|
if (backingPortInfo == null)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
object[] attribs = backingPortInfo.GetCustomAttributes(true);
|
||||||
|
return attribs.Any(x =>
|
||||||
|
{
|
||||||
|
Node.InputAttribute inputAttribute = x as Node.InputAttribute;
|
||||||
|
Node.OutputAttribute outputAttribute = x as Node.OutputAttribute;
|
||||||
|
return inputAttribute != null && inputAttribute.dynamicPortList ||
|
||||||
|
outputAttribute != null && outputAttribute.dynamicPortList;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
if (portValType.IsGenericType && portValType.GetGenericTypeDefinition() == typeof(List<>)) {
|
|
||||||
return portValType.GetGenericArguments()[0];
|
/// <summary> Cache node types </summary>
|
||||||
|
private static void BuildCache()
|
||||||
|
{
|
||||||
|
portDataCache = new PortDataCache();
|
||||||
|
Type baseType = typeof(Node);
|
||||||
|
var nodeTypes = new List<Type>();
|
||||||
|
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
|
||||||
|
|
||||||
|
// Loop through assemblies and add node types to list
|
||||||
|
foreach (Assembly assembly in assemblies)
|
||||||
|
{
|
||||||
|
// Skip certain dlls to improve performance
|
||||||
|
string assemblyName = assembly.GetName().Name;
|
||||||
|
int index = assemblyName.IndexOf('.');
|
||||||
|
if (index != -1)
|
||||||
|
{
|
||||||
|
assemblyName = assemblyName.Substring(0, index);
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (assemblyName)
|
||||||
|
{
|
||||||
|
// The following assemblies, and sub-assemblies (eg. UnityEngine.UI) are skipped
|
||||||
|
case "UnityEditor":
|
||||||
|
case "UnityEngine":
|
||||||
|
case "Unity":
|
||||||
|
case "System":
|
||||||
|
case "mscorlib":
|
||||||
|
case "Microsoft":
|
||||||
|
continue;
|
||||||
|
default:
|
||||||
|
nodeTypes.AddRange(assembly.GetTypes().Where(t => !t.IsAbstract && baseType.IsAssignableFrom(t))
|
||||||
|
.ToArray());
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int i = 0; i < nodeTypes.Count; i++)
|
||||||
|
{
|
||||||
|
CachePorts(nodeTypes[i]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return portValType;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>Returns true if the given port is in a dynamic port list.</summary>
|
public static List<FieldInfo> GetNodeFields(Type nodeType)
|
||||||
private static bool IsDynamicListPort(NodePort port) {
|
{
|
||||||
// Ports flagged as "dynamicPortList = true" end up having a "backing port" and a name with an index, but we have
|
var fieldInfo =
|
||||||
// no guarantee that a dynamic port called "output 0" is an element in a list backed by a static "output" port.
|
new List<FieldInfo>(
|
||||||
// Thus, we need to check for attributes... (but at least we don't need to look at all fields this time)
|
nodeType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance));
|
||||||
string[] fieldNameParts = port.fieldName.Split(' ');
|
|
||||||
if (fieldNameParts.Length != 2) return false;
|
|
||||||
|
|
||||||
FieldInfo backingPortInfo = port.node.GetType().GetField(fieldNameParts[0]);
|
// GetFields doesnt return inherited private fields, so walk through base types and pick those up
|
||||||
if (backingPortInfo == null) return false;
|
Type tempType = nodeType;
|
||||||
|
while ((tempType = tempType.BaseType) != typeof(Node))
|
||||||
|
{
|
||||||
|
var parentFields = tempType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
|
||||||
|
for (int i = 0; i < parentFields.Length; i++)
|
||||||
|
{
|
||||||
|
// Ensure that we do not already have a member with this type and name
|
||||||
|
FieldInfo parentField = parentFields[i];
|
||||||
|
if (fieldInfo.TrueForAll(x => x.Name != parentField.Name))
|
||||||
|
{
|
||||||
|
fieldInfo.Add(parentField);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
object[] attribs = backingPortInfo.GetCustomAttributes(true);
|
return fieldInfo;
|
||||||
return attribs.Any(x => {
|
}
|
||||||
Node.InputAttribute inputAttribute = x as Node.InputAttribute;
|
|
||||||
Node.OutputAttribute outputAttribute = x as Node.OutputAttribute;
|
|
||||||
return inputAttribute != null && inputAttribute.dynamicPortList ||
|
|
||||||
outputAttribute != null && outputAttribute.dynamicPortList;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Cache node types </summary>
|
private static void CachePorts(Type nodeType)
|
||||||
private static void BuildCache() {
|
{
|
||||||
portDataCache = new PortDataCache();
|
var fieldInfo = GetNodeFields(nodeType);
|
||||||
System.Type baseType = typeof(Node);
|
|
||||||
List<System.Type> nodeTypes = new List<System.Type>();
|
|
||||||
System.Reflection.Assembly[] assemblies = System.AppDomain.CurrentDomain.GetAssemblies();
|
|
||||||
|
|
||||||
// Loop through assemblies and add node types to list
|
for (int i = 0; i < fieldInfo.Count; i++)
|
||||||
foreach (Assembly assembly in assemblies) {
|
{
|
||||||
// Skip certain dlls to improve performance
|
//Get InputAttribute and OutputAttribute
|
||||||
string assemblyName = assembly.GetName().Name;
|
object[] attribs = fieldInfo[i].GetCustomAttributes(true);
|
||||||
int index = assemblyName.IndexOf('.');
|
Node.InputAttribute inputAttrib =
|
||||||
if (index != -1) assemblyName = assemblyName.Substring(0, index);
|
attribs.FirstOrDefault(x => x is Node.InputAttribute) as Node.InputAttribute;
|
||||||
switch (assemblyName) {
|
Node.OutputAttribute outputAttrib =
|
||||||
// The following assemblies, and sub-assemblies (eg. UnityEngine.UI) are skipped
|
attribs.FirstOrDefault(x => x is Node.OutputAttribute) as Node.OutputAttribute;
|
||||||
case "UnityEditor":
|
FormerlySerializedAsAttribute formerlySerializedAsAttribute =
|
||||||
case "UnityEngine":
|
attribs.FirstOrDefault(x => x is FormerlySerializedAsAttribute) as
|
||||||
case "Unity":
|
FormerlySerializedAsAttribute;
|
||||||
case "System":
|
|
||||||
case "mscorlib":
|
if (inputAttrib == null && outputAttrib == null)
|
||||||
case "Microsoft":
|
{
|
||||||
continue;
|
continue;
|
||||||
default:
|
}
|
||||||
nodeTypes.AddRange(assembly.GetTypes().Where(t => !t.IsAbstract && baseType.IsAssignableFrom(t)).ToArray());
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for (int i = 0; i < nodeTypes.Count; i++) {
|
if (inputAttrib != null && outputAttrib != null)
|
||||||
CachePorts(nodeTypes[i]);
|
{
|
||||||
}
|
Debug.LogError("Field " + fieldInfo[i].Name + " of type " + nodeType.FullName +
|
||||||
}
|
" cannot be both input and output.");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
if (!portDataCache.ContainsKey(nodeType))
|
||||||
|
{
|
||||||
|
portDataCache.Add(nodeType, new Dictionary<string, NodePort>());
|
||||||
|
}
|
||||||
|
|
||||||
public static List<FieldInfo> GetNodeFields(System.Type nodeType) {
|
NodePort port = new NodePort(fieldInfo[i]);
|
||||||
List<System.Reflection.FieldInfo> fieldInfo = new List<System.Reflection.FieldInfo>(nodeType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance));
|
portDataCache[nodeType].Add(port.fieldName, port);
|
||||||
|
}
|
||||||
|
|
||||||
// GetFields doesnt return inherited private fields, so walk through base types and pick those up
|
if (formerlySerializedAsAttribute != null)
|
||||||
System.Type tempType = nodeType;
|
{
|
||||||
while ((tempType = tempType.BaseType) != typeof(Node)) {
|
if (formerlySerializedAsCache == null)
|
||||||
FieldInfo[] parentFields = tempType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
|
{
|
||||||
for (int i = 0; i < parentFields.Length; i++) {
|
formerlySerializedAsCache = new Dictionary<Type, Dictionary<string, string>>();
|
||||||
// Ensure that we do not already have a member with this type and name
|
}
|
||||||
FieldInfo parentField = parentFields[i];
|
|
||||||
if (fieldInfo.TrueForAll(x => x.Name != parentField.Name)) {
|
if (!formerlySerializedAsCache.ContainsKey(nodeType))
|
||||||
fieldInfo.Add(parentField);
|
{
|
||||||
|
formerlySerializedAsCache.Add(nodeType, new Dictionary<string, string>());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (formerlySerializedAsCache[nodeType].ContainsKey(formerlySerializedAsAttribute.oldName))
|
||||||
|
{
|
||||||
|
Debug.LogError("Another FormerlySerializedAs with value '" +
|
||||||
|
formerlySerializedAsAttribute.oldName + "' already exist on this node.");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
formerlySerializedAsCache[nodeType]
|
||||||
|
.Add(formerlySerializedAsAttribute.oldName, fieldInfo[i].Name);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return fieldInfo;
|
|
||||||
|
[Serializable]
|
||||||
|
private class PortDataCache : Dictionary<Type, Dictionary<string, NodePort>> {}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void CachePorts(System.Type nodeType) {
|
|
||||||
List<System.Reflection.FieldInfo> fieldInfo = GetNodeFields(nodeType);
|
|
||||||
|
|
||||||
for (int i = 0; i < fieldInfo.Count; i++) {
|
|
||||||
|
|
||||||
//Get InputAttribute and OutputAttribute
|
|
||||||
object[] attribs = fieldInfo[i].GetCustomAttributes(true);
|
|
||||||
Node.InputAttribute inputAttrib = attribs.FirstOrDefault(x => x is Node.InputAttribute) as Node.InputAttribute;
|
|
||||||
Node.OutputAttribute outputAttrib = attribs.FirstOrDefault(x => x is Node.OutputAttribute) as Node.OutputAttribute;
|
|
||||||
UnityEngine.Serialization.FormerlySerializedAsAttribute formerlySerializedAsAttribute = attribs.FirstOrDefault(x => x is UnityEngine.Serialization.FormerlySerializedAsAttribute) as UnityEngine.Serialization.FormerlySerializedAsAttribute;
|
|
||||||
|
|
||||||
if (inputAttrib == null && outputAttrib == null) continue;
|
|
||||||
|
|
||||||
if (inputAttrib != null && outputAttrib != null) Debug.LogError("Field " + fieldInfo[i].Name + " of type " + nodeType.FullName + " cannot be both input and output.");
|
|
||||||
else {
|
|
||||||
if (!portDataCache.ContainsKey(nodeType)) portDataCache.Add(nodeType, new Dictionary<string, NodePort>());
|
|
||||||
NodePort port = new NodePort(fieldInfo[i]);
|
|
||||||
portDataCache[nodeType].Add(port.fieldName, port);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (formerlySerializedAsAttribute != null) {
|
|
||||||
if (formerlySerializedAsCache == null) formerlySerializedAsCache = new Dictionary<System.Type, Dictionary<string, string>>();
|
|
||||||
if (!formerlySerializedAsCache.ContainsKey(nodeType)) formerlySerializedAsCache.Add(nodeType, new Dictionary<string, string>());
|
|
||||||
|
|
||||||
if (formerlySerializedAsCache[nodeType].ContainsKey(formerlySerializedAsAttribute.oldName)) Debug.LogError("Another FormerlySerializedAs with value '" + formerlySerializedAsAttribute.oldName + "' already exist on this node.");
|
|
||||||
else formerlySerializedAsCache[nodeType].Add(formerlySerializedAsAttribute.oldName, fieldInfo[i].Name);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[System.Serializable]
|
|
||||||
private class PortDataCache : Dictionary<System.Type, Dictionary<string, NodePort>> { }
|
|
||||||
}
|
}
|
||||||
@ -2,121 +2,177 @@
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using UnityEngine;
|
using UnityEngine;
|
||||||
|
|
||||||
/// <summary> Base class for all node graphs </summary>
|
namespace XNode
|
||||||
[Serializable]
|
{
|
||||||
public abstract class NodeGraph : ScriptableObject {
|
/// <summary> Base class for all node graphs </summary>
|
||||||
|
[Serializable]
|
||||||
|
public abstract class NodeGraph : ScriptableObject
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// All nodes in the graph.
|
||||||
|
/// <para />
|
||||||
|
/// See: <see cref="AddNode{T}" />
|
||||||
|
/// </summary>
|
||||||
|
[SerializeField] public List<Node> nodes = new List<Node>();
|
||||||
|
|
||||||
/// <summary> All nodes in the graph. <para/>
|
/// <summary> Add a node to the graph by type (convenience method - will call the System.Type version) </summary>
|
||||||
/// See: <see cref="AddNode{T}"/> </summary>
|
public T AddNode<T>() where T : Node
|
||||||
[SerializeField] public List<Node> nodes = new List<Node>();
|
{
|
||||||
|
return AddNode(typeof(T)) as T;
|
||||||
/// <summary> Add a node to the graph by type (convenience method - will call the System.Type version) </summary>
|
|
||||||
public T AddNode<T>() where T : Node {
|
|
||||||
return AddNode(typeof(T)) as T;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Add a node to the graph by type </summary>
|
|
||||||
public virtual Node AddNode(Type type) {
|
|
||||||
Node.graphHotfix = this;
|
|
||||||
Node node = ScriptableObject.CreateInstance(type) as Node;
|
|
||||||
node.graph = this;
|
|
||||||
nodes.Add(node);
|
|
||||||
return node;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Creates a copy of the original node in the graph </summary>
|
|
||||||
public virtual Node CopyNode(Node original) {
|
|
||||||
Node.graphHotfix = this;
|
|
||||||
Node node = ScriptableObject.Instantiate(original);
|
|
||||||
node.graph = this;
|
|
||||||
node.ClearConnections();
|
|
||||||
nodes.Add(node);
|
|
||||||
return node;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Safely remove a node and all its connections </summary>
|
|
||||||
/// <param name="node"> The node to remove </param>
|
|
||||||
public virtual void RemoveNode(Node node) {
|
|
||||||
node.ClearConnections();
|
|
||||||
nodes.Remove(node);
|
|
||||||
if (Application.isPlaying) Destroy(node);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Remove all nodes and connections from the graph </summary>
|
|
||||||
public virtual void Clear() {
|
|
||||||
if (Application.isPlaying) {
|
|
||||||
for (int i = 0; i < nodes.Count; i++) {
|
|
||||||
if (nodes[i] != null) Destroy(nodes[i]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
nodes.Clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Create a new deep copy of this graph </summary>
|
|
||||||
public virtual NodeGraph Copy() {
|
|
||||||
// Instantiate a new nodegraph instance
|
|
||||||
NodeGraph graph = Instantiate(this);
|
|
||||||
// Instantiate all nodes inside the graph
|
|
||||||
for (int i = 0; i < nodes.Count; i++) {
|
|
||||||
if (nodes[i] == null) continue;
|
|
||||||
Node.graphHotfix = graph;
|
|
||||||
Node node = Instantiate(nodes[i]) as Node;
|
|
||||||
node.graph = graph;
|
|
||||||
graph.nodes[i] = node;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Redirect all connections
|
/// <summary> Add a node to the graph by type </summary>
|
||||||
for (int i = 0; i < graph.nodes.Count; i++) {
|
public virtual Node AddNode(Type type)
|
||||||
if (graph.nodes[i] == null) continue;
|
{
|
||||||
foreach (NodePort port in graph.nodes[i].Ports) {
|
Node.graphHotfix = this;
|
||||||
port.Redirect(nodes, graph.nodes);
|
Node node = CreateInstance(type) as Node;
|
||||||
|
node.graph = this;
|
||||||
|
nodes.Add(node);
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary> Creates a copy of the original node in the graph </summary>
|
||||||
|
public virtual Node CopyNode(Node original)
|
||||||
|
{
|
||||||
|
Node.graphHotfix = this;
|
||||||
|
Node node = Instantiate(original);
|
||||||
|
node.graph = this;
|
||||||
|
node.ClearConnections();
|
||||||
|
nodes.Add(node);
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary> Safely remove a node and all its connections </summary>
|
||||||
|
/// <param name="node"> The node to remove </param>
|
||||||
|
public virtual void RemoveNode(Node node)
|
||||||
|
{
|
||||||
|
node.ClearConnections();
|
||||||
|
nodes.Remove(node);
|
||||||
|
if (Application.isPlaying)
|
||||||
|
{
|
||||||
|
Destroy(node);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return graph;
|
/// <summary> Remove all nodes and connections from the graph </summary>
|
||||||
|
public virtual void Clear()
|
||||||
|
{
|
||||||
|
if (Application.isPlaying)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < nodes.Count; i++)
|
||||||
|
{
|
||||||
|
if (nodes[i] != null)
|
||||||
|
{
|
||||||
|
Destroy(nodes[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
nodes.Clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary> Create a new deep copy of this graph </summary>
|
||||||
|
public virtual NodeGraph Copy()
|
||||||
|
{
|
||||||
|
// Instantiate a new nodegraph instance
|
||||||
|
NodeGraph graph = Instantiate(this);
|
||||||
|
// Instantiate all nodes inside the graph
|
||||||
|
for (int i = 0; i < nodes.Count; i++)
|
||||||
|
{
|
||||||
|
if (nodes[i] == null)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
Node.graphHotfix = graph;
|
||||||
|
Node node = Instantiate(nodes[i]);
|
||||||
|
node.graph = graph;
|
||||||
|
graph.nodes[i] = node;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Redirect all connections
|
||||||
|
for (int i = 0; i < graph.nodes.Count; i++)
|
||||||
|
{
|
||||||
|
if (graph.nodes[i] == null)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (NodePort port in graph.nodes[i].Ports)
|
||||||
|
{
|
||||||
|
port.Redirect(nodes, graph.nodes);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return graph;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected virtual void OnDestroy()
|
||||||
|
{
|
||||||
|
// Remove all nodes prior to graph destruction
|
||||||
|
Clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
#region Attributes
|
||||||
|
|
||||||
|
/// <summary> Automatically ensures the existance of a certain node type, and prevents it from being deleted. </summary>
|
||||||
|
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
|
||||||
|
public class RequireNodeAttribute : Attribute
|
||||||
|
{
|
||||||
|
public Type type0;
|
||||||
|
public Type type1;
|
||||||
|
public Type type2;
|
||||||
|
|
||||||
|
/// <summary> Automatically ensures the existance of a certain node type, and prevents it from being deleted </summary>
|
||||||
|
public RequireNodeAttribute(Type type)
|
||||||
|
{
|
||||||
|
type0 = type;
|
||||||
|
type1 = null;
|
||||||
|
type2 = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary> Automatically ensures the existance of a certain node type, and prevents it from being deleted </summary>
|
||||||
|
public RequireNodeAttribute(Type type, Type type2)
|
||||||
|
{
|
||||||
|
type0 = type;
|
||||||
|
type1 = type2;
|
||||||
|
this.type2 = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary> Automatically ensures the existance of a certain node type, and prevents it from being deleted </summary>
|
||||||
|
public RequireNodeAttribute(Type type, Type type2, Type type3)
|
||||||
|
{
|
||||||
|
type0 = type;
|
||||||
|
type1 = type2;
|
||||||
|
this.type2 = type3;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool Requires(Type type)
|
||||||
|
{
|
||||||
|
if (type == null)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type == type0)
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type == type1)
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type == type2)
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
}
|
}
|
||||||
|
|
||||||
protected virtual void OnDestroy() {
|
|
||||||
// Remove all nodes prior to graph destruction
|
|
||||||
Clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
#region Attributes
|
|
||||||
/// <summary> Automatically ensures the existance of a certain node type, and prevents it from being deleted. </summary>
|
|
||||||
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
|
|
||||||
public class RequireNodeAttribute : Attribute {
|
|
||||||
public Type type0;
|
|
||||||
public Type type1;
|
|
||||||
public Type type2;
|
|
||||||
|
|
||||||
/// <summary> Automatically ensures the existance of a certain node type, and prevents it from being deleted </summary>
|
|
||||||
public RequireNodeAttribute(Type type) {
|
|
||||||
this.type0 = type;
|
|
||||||
this.type1 = null;
|
|
||||||
this.type2 = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Automatically ensures the existance of a certain node type, and prevents it from being deleted </summary>
|
|
||||||
public RequireNodeAttribute(Type type, Type type2) {
|
|
||||||
this.type0 = type;
|
|
||||||
this.type1 = type2;
|
|
||||||
this.type2 = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Automatically ensures the existance of a certain node type, and prevents it from being deleted </summary>
|
|
||||||
public RequireNodeAttribute(Type type, Type type2, Type type3) {
|
|
||||||
this.type0 = type;
|
|
||||||
this.type1 = type2;
|
|
||||||
this.type2 = type3;
|
|
||||||
}
|
|
||||||
|
|
||||||
public bool Requires(Type type) {
|
|
||||||
if (type == null) return false;
|
|
||||||
if (type == type0) return true;
|
|
||||||
else if (type == type1) return true;
|
|
||||||
else if (type == type2) return true;
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#endregion
|
|
||||||
}
|
}
|
||||||
@ -1,28 +1,60 @@
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using UnityEngine;
|
using UnityEngine;
|
||||||
|
|
||||||
[CreateNodeMenu("Group")]
|
namespace XNode
|
||||||
public class NodeGroup : Node {
|
{
|
||||||
public int width = 400;
|
[CreateNodeMenu("Group")]
|
||||||
public int height = 400;
|
public class NodeGroup : Node
|
||||||
public Color color = new Color(1f, 1f, 1f, 0.1f);
|
{
|
||||||
|
public int width = 400;
|
||||||
|
public int height = 400;
|
||||||
|
public Color color = new Color(1f, 1f, 1f, 0.1f);
|
||||||
|
|
||||||
public override object GetValue(NodePort port) {
|
public override object GetValue(NodePort port)
|
||||||
return null;
|
{
|
||||||
}
|
return null;
|
||||||
|
}
|
||||||
/// <summary> Gets nodes in this group </summary>
|
|
||||||
public List<Node> GetNodes() {
|
/// <summary> Gets nodes in this group </summary>
|
||||||
List<Node> result = new List<Node>();
|
public List<Node> GetNodes()
|
||||||
foreach (Node node in graph.nodes) {
|
{
|
||||||
if (node == this) continue;
|
var result = new List<Node>();
|
||||||
if (node == null) continue;
|
foreach (Node node in graph.nodes)
|
||||||
if (node.position.x < this.position.x) continue;
|
{
|
||||||
if (node.position.y < this.position.y) continue;
|
if (node == this)
|
||||||
if (node.position.x > this.position.x + width) continue;
|
{
|
||||||
if (node.position.y > this.position.y + height + 30) continue;
|
continue;
|
||||||
result.Add(node);
|
}
|
||||||
|
|
||||||
|
if (node == null)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (node.position.x < position.x)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (node.position.y < position.y)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (node.position.x > position.x + width)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (node.position.y > position.y + height + 30)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
result.Add(node);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
return result;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
1057
Scripts/NodePort.cs
1057
Scripts/NodePort.cs
File diff suppressed because it is too large
Load Diff
@ -1,18 +1,27 @@
|
|||||||
using UnityEngine;
|
using UnityEngine;
|
||||||
|
|
||||||
/// <summary> Lets you instantiate a node graph in the scene. This allows you to reference in-scene objects. </summary>
|
namespace XNode
|
||||||
public class SceneGraph : MonoBehaviour {
|
{
|
||||||
public NodeGraph graph;
|
/// <summary> Lets you instantiate a node graph in the scene. This allows you to reference in-scene objects. </summary>
|
||||||
}
|
public class SceneGraph : MonoBehaviour
|
||||||
|
{
|
||||||
|
public NodeGraph graph;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary> Derive from this class to create a SceneGraph with a specific graph type. </summary>
|
/// <summary> Derive from this class to create a SceneGraph with a specific graph type. </summary>
|
||||||
/// <example>
|
/// <example>
|
||||||
/// <code>
|
/// <code>
|
||||||
/// public class MySceneGraph : SceneGraph<MyGraph> {
|
/// public class MySceneGraph : SceneGraph<MyGraph>
|
||||||
///
|
/// {
|
||||||
/// }
|
/// }
|
||||||
/// </code>
|
/// </code>
|
||||||
/// </example>
|
/// </example>
|
||||||
public class SceneGraph<T> : SceneGraph where T : NodeGraph {
|
public class SceneGraph<T> : SceneGraph where T : NodeGraph
|
||||||
public new T graph { get { return base.graph as T; } set { base.graph = value; } }
|
{
|
||||||
|
public new T graph
|
||||||
|
{
|
||||||
|
get => base.graph as T;
|
||||||
|
set => base.graph = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Loading…
x
Reference in New Issue
Block a user