1
0
mirror of https://github.com/Siccity/xNode.git synced 2025-12-21 09:46:03 +08:00

Made NodeEditorReflection static, merged NodeEditorWindow and NodeGraphEditor into NodeGraphWindow

This commit is contained in:
Thor Brigsted 2019-07-24 00:28:43 +02:00
parent 93fa101af8
commit aef8073896
14 changed files with 382 additions and 413 deletions

View File

@ -29,7 +29,7 @@ namespace XNodeEditor {
if (EditorGUI.DropdownButton(position, new GUIContent(enumName), FocusType.Passive)) { if (EditorGUI.DropdownButton(position, new GUIContent(enumName), FocusType.Passive)) {
// Position is all wrong if we show the dropdown during the node draw phase. // Position is all wrong if we show the dropdown during the node draw phase.
// Instead, add it to onLateGUI to display it later. // Instead, add it to onLateGUI to display it later.
NodeEditorWindow.current.onLateGUI += () => ShowContextMenuAtMouse(property); NodeGraphWindow.current.onLateGUI += () => ShowContextMenuAtMouse(property);
} }
#else #else
// Display dropdown // Display dropdown

View File

@ -49,7 +49,7 @@ namespace XNodeEditor {
public virtual int GetWidth() { public virtual int GetWidth() {
Type type = target.GetType(); Type type = target.GetType();
int width; int width;
if (NodeEditorWindow.nodeWidth.TryGetValue(type, out width)) return width; if (NodeEditorReflection.nodeWidth.TryGetValue(type, out width)) return width;
else return 208; else return 208;
} }
@ -58,7 +58,7 @@ namespace XNodeEditor {
// 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 (NodeEditorWindow.nodeTint.TryGetValue(type, out color)) return color; if (NodeEditorReflection.nodeTint.TryGetValue(type, out color)) return color;
// Return default color (grey) // Return default color (grey)
else return DEFAULTCOLOR; else return DEFAULTCOLOR;
} }
@ -72,19 +72,19 @@ namespace XNodeEditor {
// Actions if only one node is selected // Actions if only one node is selected
if (Selection.objects.Length == 1 && Selection.activeObject is XNode.Node) { if (Selection.objects.Length == 1 && Selection.activeObject is XNode.Node) {
XNode.Node node = Selection.activeObject as XNode.Node; XNode.Node node = Selection.activeObject as XNode.Node;
menu.AddItem(new GUIContent("Move To Top"), false, () => NodeEditorWindow.current.MoveNodeToTop(node)); menu.AddItem(new GUIContent("Move To Top"), false, () => NodeGraphWindow.current.MoveNodeToTop(node));
menu.AddItem(new GUIContent("Rename"), false, NodeEditorWindow.current.RenameSelectedNode); menu.AddItem(new GUIContent("Rename"), false, NodeGraphWindow.current.RenameSelectedNode);
} }
// Add actions to any number of selected nodes // Add actions to any number of selected nodes
menu.AddItem(new GUIContent("Copy"), false, NodeEditorWindow.current.CopySelectedNodes); menu.AddItem(new GUIContent("Copy"), false, NodeGraphWindow.current.CopySelectedNodes);
menu.AddItem(new GUIContent("Duplicate"), false, NodeEditorWindow.current.DuplicateSelectedNodes); menu.AddItem(new GUIContent("Duplicate"), false, NodeGraphWindow.current.DuplicateSelectedNodes);
menu.AddItem(new GUIContent("Remove"), false, NodeEditorWindow.current.RemoveSelectedNodes); menu.AddItem(new GUIContent("Remove"), false, NodeGraphWindow.current.RemoveSelectedNodes);
// Custom sctions if only one node is selected // Custom sctions if only one node is selected
if (Selection.objects.Length == 1 && Selection.activeObject is XNode.Node) { if (Selection.objects.Length == 1 && Selection.activeObject is XNode.Node) {
XNode.Node node = Selection.activeObject as XNode.Node; XNode.Node node = Selection.activeObject as XNode.Node;
NodeEditorWindow.AddCustomContextMenuItems(menu, node); NodeEditorReflection.AddCustomContextMenuItems(menu, node);
} }
} }
@ -96,8 +96,7 @@ namespace XNodeEditor {
} }
[AttributeUsage(AttributeTargets.Class)] [AttributeUsage(AttributeTargets.Class)]
public class CustomNodeEditorAttribute : Attribute, public class CustomNodeEditorAttribute : Attribute, XNodeEditor.Internal.INodeEditorAttrib {
XNodeEditor.Internal.NodeEditorBase<NodeEditor, NodeEditor.CustomNodeEditorAttribute, XNode.Node>.INodeEditorAttrib {
private Type inspectedType; private 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>

View File

@ -5,7 +5,7 @@ using UnityEditor;
using UnityEngine; using UnityEngine;
namespace XNodeEditor { namespace XNodeEditor {
public partial class NodeEditorWindow { public partial class NodeGraphWindow {
public enum NodeActivity { Idle, HoldNode, DragNode, HoldGrid, DragGrid } public enum NodeActivity { Idle, HoldNode, DragNode, HoldGrid, DragGrid }
public static NodeActivity currentActivity = NodeActivity.Idle; public static NodeActivity currentActivity = NodeActivity.Idle;
public static bool isPanning { get; private set; } public static bool isPanning { get; private set; }
@ -57,7 +57,7 @@ namespace XNodeEditor {
DragAndDrop.visualMode = DragAndDropVisualMode.Generic; DragAndDrop.visualMode = DragAndDropVisualMode.Generic;
if (e.type == EventType.DragPerform) { if (e.type == EventType.DragPerform) {
DragAndDrop.AcceptDrag(); DragAndDrop.AcceptDrag();
graphEditor.OnDropObjects(DragAndDrop.objectReferences); OnDropObjects(DragAndDrop.objectReferences);
} }
break; break;
case EventType.MouseMove: case EventType.MouseMove:
@ -287,7 +287,7 @@ namespace XNodeEditor {
e.Use(); // Fixes copy/paste context menu appearing in Unity 5.6.6f2 - doesn't occur in 2018.3.2f1 Probably needs to be used in other places. e.Use(); // Fixes copy/paste context menu appearing in Unity 5.6.6f2 - doesn't occur in 2018.3.2f1 Probably needs to be used in other places.
} else if (!IsHoveringNode) { } else if (!IsHoveringNode) {
GenericMenu menu = new GenericMenu(); GenericMenu menu = new GenericMenu();
graphEditor.AddContextMenuItems(menu); AddContextMenuItems(menu);
menu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero)); menu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero));
} }
} }
@ -376,7 +376,7 @@ namespace XNodeEditor {
foreach (UnityEngine.Object item in Selection.objects) { foreach (UnityEngine.Object item in Selection.objects) {
if (item is XNode.Node) { if (item is XNode.Node) {
XNode.Node node = item as XNode.Node; XNode.Node node = item as XNode.Node;
graphEditor.RemoveNode(node); RemoveNode(node);
} }
} }
} }
@ -432,7 +432,7 @@ namespace XNodeEditor {
for (int i = 0; i < nodes.Length; i++) { for (int i = 0; i < nodes.Length; i++) {
XNode.Node srcNode = nodes[i]; XNode.Node srcNode = nodes[i];
if (srcNode == null) continue; if (srcNode == null) continue;
XNode.Node newNode = graphEditor.CopyNode(srcNode); XNode.Node newNode = CopyNode(srcNode);
substitutes.Add(srcNode, newNode); substitutes.Add(srcNode, newNode);
newNode.position = srcNode.position + offset; newNode.position = srcNode.position + offset;
newNodes[i] = newNode; newNodes[i] = newNode;

View File

@ -10,15 +10,15 @@ namespace XNodeEditor.Internal {
/// <typeparam name="T">Editor Type. Should be the type of the deriving script itself (eg. NodeEditor) </typeparam> /// <typeparam name="T">Editor Type. Should be the type of the deriving script itself (eg. NodeEditor) </typeparam>
/// <typeparam name="A">Attribute Type. The attribute used to connect with the runtime type (eg. CustomNodeEditorAttribute) </typeparam> /// <typeparam name="A">Attribute Type. The attribute used to connect with the runtime type (eg. CustomNodeEditorAttribute) </typeparam>
/// <typeparam name="K">Runtime Type. The ScriptableObject this can be an editor for (eg. Node) </typeparam> /// <typeparam name="K">Runtime Type. The ScriptableObject this can be an editor for (eg. Node) </typeparam>
public abstract class NodeEditorBase<T, A, K> where A : Attribute, NodeEditorBase<T, A, K>.INodeEditorAttrib where T : NodeEditorBase<T, A, K> where K : ScriptableObject { public abstract class NodeEditorBase<T, A, K> where A : Attribute, INodeEditorAttrib where T : NodeEditorBase<T, A, K> where K : ScriptableObject {
/// <summary> Custom editors defined with [CustomNodeEditor] </summary> /// <summary> Custom editors defined with [CustomNodeEditor] </summary>
private static Dictionary<Type, Type> editorTypes; private static Dictionary<Type, Type> editorTypes;
private static Dictionary<K, T> editors = new Dictionary<K, T>(); private static Dictionary<K, T> editors = new Dictionary<K, T>();
public NodeEditorWindow window; public NodeGraphWindow window;
public K target; public K target;
public SerializedObject serializedObject; public SerializedObject serializedObject;
public static T GetEditor(K target, NodeEditorWindow window) { public static T GetEditor(K target, NodeGraphWindow window) {
if (target == null) return null; if (target == null) return null;
T editor; T editor;
if (!editors.TryGetValue(target, out editor)) { if (!editors.TryGetValue(target, out editor)) {
@ -50,7 +50,7 @@ namespace XNodeEditor.Internal {
editorTypes = new Dictionary<Type, Type>(); editorTypes = new Dictionary<Type, Type>();
//Get all classes deriving from NodeEditor via reflection //Get all classes deriving from NodeEditor via reflection
Type[] nodeEditors = XNodeEditor.NodeEditorWindow.GetDerivedTypes(typeof(T)); Type[] nodeEditors = XNodeEditor.NodeEditorReflection.GetDerivedTypes(typeof(T));
for (int i = 0; i < nodeEditors.Length; i++) { for (int i = 0; i < nodeEditors.Length; i++) {
if (nodeEditors[i].IsAbstract) continue; if (nodeEditors[i].IsAbstract) continue;
var attribs = nodeEditors[i].GetCustomAttributes(typeof(A), false); var attribs = nodeEditors[i].GetCustomAttributes(typeof(A), false);
@ -62,9 +62,9 @@ namespace XNodeEditor.Internal {
/// <summary> Called on creation, after references have been set </summary> /// <summary> Called on creation, after references have been set </summary>
public virtual void OnCreate() { } public virtual void OnCreate() { }
}
public interface INodeEditorAttrib { public interface INodeEditorAttrib {
Type GetInspectedType(); Type GetInspectedType();
} }
} }
}

View File

@ -6,8 +6,7 @@ using UnityEngine;
namespace XNodeEditor { namespace XNodeEditor {
/// <summary> Contains GUI methods </summary> /// <summary> Contains GUI methods </summary>
public partial class NodeEditorWindow { public partial class NodeGraphWindow {
public NodeGraphEditor graphEditor;
private List<UnityEngine.Object> selectionCache; private List<UnityEngine.Object> selectionCache;
private List<XNode.Node> culledNodes; private List<XNode.Node> culledNodes;
/// <summary> 19 if docked, 22 if not </summary> /// <summary> 19 if docked, 22 if not </summary>
@ -23,7 +22,6 @@ namespace XNodeEditor {
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();
Controls(); Controls();
DrawGrid(position, zoom, panOffset); DrawGrid(position, zoom, panOffset);
@ -71,7 +69,7 @@ namespace XNodeEditor {
GUI.EndGroup(); GUI.EndGroup();
Rect rect = new Rect(new Vector2(leftPadding, topPadding), new Vector2(Screen.width, Screen.height)); Rect rect = new Rect(new Vector2(leftPadding, topPadding), new Vector2(Screen.width, Screen.height));
GUI.BeginGroup(rect); GUI.BeginGroup(rect);
graphEditor.OnGUI(); OnOverlayGUI();
GUI.EndGroup(); GUI.EndGroup();
GUI.BeginGroup(new Rect(0.0f, topPadding - (topPadding * zoom), Screen.width, Screen.height)); GUI.BeginGroup(new Rect(0.0f, topPadding - (topPadding * zoom), Screen.width, Screen.height));
} }
@ -94,8 +92,8 @@ namespace XNodeEditor {
rect.position = Vector2.zero; rect.position = Vector2.zero;
Vector2 center = rect.size / 2f; Vector2 center = rect.size / 2f;
Texture2D gridTex = graphEditor.GetGridTexture(); Texture2D gridTex = GetGridTexture();
Texture2D crossTex = graphEditor.GetSecondaryGridTexture(); Texture2D crossTex = GetSecondaryGridTexture();
// Offset from origin in tile units // Offset from origin in tile units
float xOffset = -(center.x * zoom + panOffset.x) / gridTex.width; float xOffset = -(center.x * zoom + panOffset.x) / gridTex.width;
@ -230,7 +228,7 @@ namespace XNodeEditor {
Rect fromRect; Rect fromRect;
if (!_portConnectionPoints.TryGetValue(output, out fromRect)) continue; if (!_portConnectionPoints.TryGetValue(output, out fromRect)) continue;
Color connectionColor = graphEditor.GetPortColor(output); Color connectionColor = GetPortColor(output);
for (int k = 0; k < output.ConnectionCount; k++) { for (int k = 0; k < output.ConnectionCount; k++) {
XNode.NodePort input = output.GetConnection(k); XNode.NodePort input = output.GetConnection(k);
@ -430,8 +428,8 @@ namespace XNodeEditor {
} }
private void DrawTooltip() { private void DrawTooltip() {
if (hoveredPort != null && NodeEditorPreferences.GetSettings().portTooltips && graphEditor != null) { if (hoveredPort != null && NodeEditorPreferences.GetSettings().portTooltips) {
string tooltip = graphEditor.GetPortTooltip(hoveredPort); string tooltip = GetPortTooltip(hoveredPort);
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);

View File

@ -141,8 +141,8 @@ namespace XNodeEditor {
Color backgroundColor = new Color32(90, 97, 105, 255); Color backgroundColor = new Color32(90, 97, 105, 255);
Color tint; Color tint;
if (NodeEditorWindow.nodeTint.TryGetValue(port.node.GetType(), out tint)) backgroundColor *= tint; if (NodeEditorReflection.nodeTint.TryGetValue(port.node.GetType(), out tint)) backgroundColor *= tint;
Color col = NodeEditorWindow.current.graphEditor.GetPortColor(port); Color col = NodeGraphWindow.current.GetPortColor(port);
DrawPortHandle(rect, backgroundColor, col); DrawPortHandle(rect, backgroundColor, col);
// Register the handle position // Register the handle position
@ -153,7 +153,7 @@ namespace XNodeEditor {
private static System.Type GetType(SerializedProperty property) { private static System.Type GetType(SerializedProperty property) {
System.Type parentType = property.serializedObject.targetObject.GetType(); System.Type parentType = property.serializedObject.targetObject.GetType();
System.Reflection.FieldInfo fi = NodeEditorWindow.GetFieldInfo(parentType, property.name); System.Reflection.FieldInfo fi = NodeEditorReflection.GetFieldInfo(parentType, property.name);
return fi.FieldType; return fi.FieldType;
} }
@ -197,8 +197,8 @@ namespace XNodeEditor {
Color backgroundColor = new Color32(90, 97, 105, 255); Color backgroundColor = new Color32(90, 97, 105, 255);
Color tint; Color tint;
if (NodeEditorWindow.nodeTint.TryGetValue(port.node.GetType(), out tint)) backgroundColor *= tint; if (NodeEditorReflection.nodeTint.TryGetValue(port.node.GetType(), out tint)) backgroundColor *= tint;
Color col = NodeEditorWindow.current.graphEditor.GetPortColor(port); Color col = NodeGraphWindow.current.GetPortColor(port);
DrawPortHandle(rect, backgroundColor, col); DrawPortHandle(rect, backgroundColor, col);
// Register the handle position // Register the handle position
@ -225,8 +225,8 @@ namespace XNodeEditor {
Color backgroundColor = new Color32(90, 97, 105, 255); Color backgroundColor = new Color32(90, 97, 105, 255);
Color tint; Color tint;
if (NodeEditorWindow.nodeTint.TryGetValue(port.node.GetType(), out tint)) backgroundColor *= tint; if (NodeEditorReflection.nodeTint.TryGetValue(port.node.GetType(), out tint)) backgroundColor *= tint;
Color col = NodeEditorWindow.current.graphEditor.GetPortColor(port); Color col = NodeGraphWindow.current.GetPortColor(port);
DrawPortHandle(rect, backgroundColor, col); DrawPortHandle(rect, backgroundColor, col);
// Register the handle position // Register the handle position
@ -362,9 +362,9 @@ namespace XNodeEditor {
port.SwapConnections(nextPort); port.SwapConnections(nextPort);
// Swap cached positions to mitigate twitching // Swap cached positions to mitigate twitching
Rect rect = NodeEditorWindow.current.portConnectionPoints[port]; Rect rect = NodeGraphWindow.current.portConnectionPoints[port];
NodeEditorWindow.current.portConnectionPoints[port] = NodeEditorWindow.current.portConnectionPoints[nextPort]; NodeGraphWindow.current.portConnectionPoints[port] = NodeGraphWindow.current.portConnectionPoints[nextPort];
NodeEditorWindow.current.portConnectionPoints[nextPort] = rect; NodeGraphWindow.current.portConnectionPoints[nextPort] = rect;
} }
} }
// Move down // Move down
@ -375,9 +375,9 @@ namespace XNodeEditor {
port.SwapConnections(nextPort); port.SwapConnections(nextPort);
// Swap cached positions to mitigate twitching // Swap cached positions to mitigate twitching
Rect rect = NodeEditorWindow.current.portConnectionPoints[port]; Rect rect = NodeGraphWindow.current.portConnectionPoints[port];
NodeEditorWindow.current.portConnectionPoints[port] = NodeEditorWindow.current.portConnectionPoints[nextPort]; NodeGraphWindow.current.portConnectionPoints[port] = NodeGraphWindow.current.portConnectionPoints[nextPort];
NodeEditorWindow.current.portConnectionPoints[nextPort] = rect; NodeGraphWindow.current.portConnectionPoints[nextPort] = rect;
} }
} }
// Apply changes // Apply changes
@ -392,8 +392,8 @@ namespace XNodeEditor {
// Apply changes // Apply changes
serializedObject.ApplyModifiedProperties(); serializedObject.ApplyModifiedProperties();
serializedObject.Update(); serializedObject.Update();
NodeEditorWindow.current.Repaint(); NodeGraphWindow.current.Repaint();
EditorApplication.delayCall += NodeEditorWindow.current.Repaint; EditorApplication.delayCall += NodeGraphWindow.current.Repaint;
}; };
list.onAddCallback = list.onAddCallback =
(ReorderableList rl) => { (ReorderableList rl) => {

View File

@ -8,7 +8,7 @@ namespace XNodeEditor {
public enum NoodleType { Curve, Line, Angled } public enum NoodleType { Curve, Line, Angled }
/// <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 XNodeEditor.NodeGraphWindow 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";
@ -76,11 +76,11 @@ namespace XNodeEditor {
/// <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 (lastEditor != XNodeEditor.NodeEditorWindow.current.graphEditor) { if (lastEditor != XNodeEditor.NodeGraphWindow.current) {
object[] attribs = XNodeEditor.NodeEditorWindow.current.graphEditor.GetType().GetCustomAttributes(typeof(XNodeEditor.NodeGraphEditor.CustomNodeGraphEditorAttribute), true); object[] attribs = XNodeEditor.NodeGraphWindow.current.GetType().GetCustomAttributes(typeof(XNodeEditor.NodeGraphWindow.CustomNodeGraphWindowAttribute), true);
if (attribs.Length == 1) { if (attribs.Length == 1) {
XNodeEditor.NodeGraphEditor.CustomNodeGraphEditorAttribute attrib = attribs[0] as XNodeEditor.NodeGraphEditor.CustomNodeGraphEditorAttribute; XNodeEditor.NodeGraphWindow.CustomNodeGraphWindowAttribute attrib = attribs[0] as XNodeEditor.NodeGraphWindow.CustomNodeGraphWindowAttribute;
lastEditor = XNodeEditor.NodeEditorWindow.current.graphEditor; lastEditor = XNodeEditor.NodeGraphWindow.current;
lastKey = attrib.editorPrefsKey; lastKey = attrib.editorPrefsKey;
} else return null; } else return null;
} }
@ -130,7 +130,7 @@ namespace XNodeEditor {
if (GUI.changed) { if (GUI.changed) {
SavePrefs(key, settings); SavePrefs(key, settings);
NodeEditorWindow.RepaintAll(); NodeGraphWindow.RepaintAll();
} }
EditorGUILayout.Space(); EditorGUILayout.Space();
} }
@ -151,7 +151,7 @@ namespace XNodeEditor {
settings.portTooltips = EditorGUILayout.Toggle("Port Tooltips", settings.portTooltips); settings.portTooltips = EditorGUILayout.Toggle("Port Tooltips", settings.portTooltips);
if (GUI.changed) { if (GUI.changed) {
SavePrefs(key, settings); SavePrefs(key, settings);
NodeEditorWindow.RepaintAll(); NodeGraphWindow.RepaintAll();
} }
EditorGUILayout.Space(); EditorGUILayout.Space();
} }
@ -176,7 +176,7 @@ namespace XNodeEditor {
if (settings.typeColors.ContainsKey(typeColorKey)) settings.typeColors[typeColorKey] = col; if (settings.typeColors.ContainsKey(typeColorKey)) settings.typeColors[typeColorKey] = col;
else settings.typeColors.Add(typeColorKey, col); else settings.typeColors.Add(typeColorKey, col);
SavePrefs(key, settings); SavePrefs(key, settings);
NodeEditorWindow.RepaintAll(); NodeGraphWindow.RepaintAll();
} }
} }
} }
@ -197,7 +197,7 @@ namespace XNodeEditor {
if (settings.ContainsKey(lastKey)) settings.Remove(lastKey); if (settings.ContainsKey(lastKey)) settings.Remove(lastKey);
typeColors = new Dictionary<Type, Color>(); typeColors = new Dictionary<Type, Color>();
VerifyLoaded(); VerifyLoaded();
NodeEditorWindow.RepaintAll(); NodeGraphWindow.RepaintAll();
} }
/// <summary> Save preferences in EditorPrefs </summary> /// <summary> Save preferences in EditorPrefs </summary>

View File

@ -8,7 +8,7 @@ using UnityEngine;
namespace XNodeEditor { namespace XNodeEditor {
/// <summary> Contains reflection-related info </summary> /// <summary> Contains reflection-related info </summary>
public partial class NodeEditorWindow { public static class NodeEditorReflection {
/// <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 Dictionary<Type, Color> nodeTint { get { return _nodeTint != null ? _nodeTint : _nodeTint = GetNodeTint(); } } public static Dictionary<Type, Color> nodeTint { get { return _nodeTint != null ? _nodeTint : _nodeTint = GetNodeTint(); } }
@ -22,23 +22,18 @@ namespace XNodeEditor {
[NonSerialized] private static Type[] _nodeTypes = null; [NonSerialized] private static Type[] _nodeTypes = null;
private Func<bool> isDocked {
get {
if (_isDocked == null) {
BindingFlags fullBinding = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;
MethodInfo isDockedMethod = typeof(NodeEditorWindow).GetProperty("docked", fullBinding).GetGetMethod(true);
_isDocked = (Func<bool>) Delegate.CreateDelegate(typeof(Func<bool>), this, isDockedMethod);
}
return _isDocked;
}
}
private Func<bool> _isDocked;
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(XNode.Node)); return GetDerivedTypes(typeof(XNode.Node));
} }
/// <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) {
BindingFlags fullBinding = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;
MethodInfo isDockedMethod = typeof(NodeGraphWindow).GetProperty("docked", fullBinding).GetGetMethod(true);
return (Func<bool>) Delegate.CreateDelegate(typeof(Func<bool>), window, isDockedMethod);
}
public static Dictionary<Type, Color> GetNodeTint() { public static Dictionary<Type, Color> GetNodeTint() {
Dictionary<Type, Color> tints = new Dictionary<Type, Color>(); Dictionary<Type, Color> tints = new Dictionary<Type, Color>();
for (int i = 0; i < nodeTypes.Length; i++) { for (int i = 0; i < nodeTypes.Length; i++) {

View File

@ -36,7 +36,7 @@ namespace XNodeEditor {
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 = NodeEditorWindow.GetFieldInfo(classType, fieldName); FieldInfo field = NodeEditorReflection.GetFieldInfo(classType, 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");

View File

@ -1,133 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
namespace XNodeEditor {
/// <summary> Base class to derive custom Node Graph editors from. Use this to override how graphs are drawn in the editor. </summary>
[CustomNodeGraphEditor(typeof(XNode.NodeGraph))]
public class NodeGraphEditor : XNodeEditor.Internal.NodeEditorBase<NodeGraphEditor, NodeGraphEditor.CustomNodeGraphEditorAttribute, XNode.NodeGraph> {
[Obsolete("Use window.position instead")]
public Rect position { get { return window.position; } set { window.position = value; } }
/// <summary> Are we currently renaming a node? </summary>
protected bool isRenaming;
public virtual void OnGUI() { }
/// <summary> Called when opened by NodeEditorWindow </summary>
public virtual void OnOpen() { }
public virtual Texture2D GetGridTexture() {
return NodeEditorPreferences.GetSettings().gridTexture;
}
public virtual Texture2D GetSecondaryGridTexture() {
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>
public virtual NodeEditorPreferences.Settings GetDefaultPreferences() {
return new NodeEditorPreferences.Settings();
}
/// <summary> Returns context node menu path. Null or empty strings for hidden nodes. </summary>
public virtual string GetNodeMenuName(Type type) {
//Check if type has the CreateNodeMenuAttribute
XNode.Node.CreateNodeMenuAttribute attrib;
if (NodeEditorUtilities.GetAttrib(type, out attrib)) // Return custom path
return attrib.menuName;
else // Return generated path
return ObjectNames.NicifyVariableName(type.ToString().Replace('.', '/'));
}
/// <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) {
Vector2 pos = NodeEditorWindow.current.WindowToGridPosition(Event.current.mousePosition);
for (int i = 0; i < NodeEditorWindow.nodeTypes.Length; i++) {
Type type = NodeEditorWindow.nodeTypes[i];
//Get node context menu path
string path = GetNodeMenuName(type);
if (string.IsNullOrEmpty(path)) continue;
menu.AddItem(new GUIContent(path), false, () => {
CreateNode(type, pos);
});
}
menu.AddSeparator("");
if (NodeEditorWindow.copyBuffer != null && NodeEditorWindow.copyBuffer.Length > 0) menu.AddItem(new GUIContent("Paste"), false, () => NodeEditorWindow.current.PasteNodes(pos));
else menu.AddDisabledItem(new GUIContent("Paste"));
menu.AddItem(new GUIContent("Preferences"), false, () => NodeEditorWindow.OpenPreferences());
NodeEditorWindow.AddCustomContextMenuItems(menu, target);
}
public virtual Color GetPortColor(XNode.NodePort port) {
return GetTypeColor(port.ValueType);
}
public virtual Color GetTypeColor(Type type) {
return NodeEditorPreferences.GetTypeColor(type);
}
public virtual string GetPortTooltip(XNode.NodePort port) {
Type portType = port.ValueType;
string tooltip = "";
tooltip = portType.PrettyName();
if (port.IsOutput) {
object obj = port.node.GetValue(port);
tooltip += " = " + (obj != null ? obj.ToString() : "null");
}
return tooltip;
}
/// <summary> Deal with objects dropped into the graph through DragAndDrop </summary>
public virtual void OnDropObjects(UnityEngine.Object[] objects) {
Debug.Log("No OnDropItems override defined for " + GetType());
}
/// <summary> Create a node and save it in the graph asset </summary>
public virtual void CreateNode(Type type, Vector2 position) {
XNode.Node node = target.AddNode(type);
node.position = position;
if (node.name == null || node.name.Trim() == "") node.name = NodeEditorUtilities.NodeDefaultName(type);
AssetDatabase.AddObjectToAsset(node, target);
if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets();
NodeEditorWindow.RepaintAll();
}
/// <summary> Creates a copy of the original node in the graph </summary>
public XNode.Node CopyNode(XNode.Node original) {
XNode.Node node = target.CopyNode(original);
node.name = original.name;
AssetDatabase.AddObjectToAsset(node, target);
if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets();
return node;
}
/// <summary> Safely remove a node and all its connections. </summary>
public virtual void RemoveNode(XNode.Node node) {
target.RemoveNode(node);
UnityEngine.Object.DestroyImmediate(node, true);
if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets();
}
[AttributeUsage(AttributeTargets.Class)]
public class CustomNodeGraphEditorAttribute : Attribute,
XNodeEditor.Internal.NodeEditorBase<NodeGraphEditor, NodeGraphEditor.CustomNodeGraphEditorAttribute, XNode.NodeGraph>.INodeEditorAttrib {
private Type inspectedType;
public string editorPrefsKey;
/// <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="editorPrefsKey">Define unique key for unique layout settings instance</param>
public CustomNodeGraphEditorAttribute(Type inspectedType, string editorPrefsKey = "xNode.Settings") {
this.inspectedType = inspectedType;
this.editorPrefsKey = editorPrefsKey;
}
public Type GetInspectedType() {
return inspectedType;
}
}
}
}

View File

@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: ddcbb5432255d3247a0718b15a9c193c
timeCreated: 1505462176
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -1,12 +1,13 @@
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 Object = UnityEngine.Object;
namespace XNodeEditor { namespace XNodeEditor {
[InitializeOnLoad] [InitializeOnLoad, CustomNodeGraphWindow(typeof(XNode.NodeGraph))]
public partial class NodeEditorWindow : EditorWindow { public partial class NodeGraphWindow : EditorWindow {
public static NodeEditorWindow current;
/// <summary> Stores node positions for all nodePorts. </summary> /// <summary> Stores node positions for all nodePorts. </summary>
public Dictionary<XNode.NodePort, Rect> portConnectionPoints { get { return _portConnectionPoints; } } public Dictionary<XNode.NodePort, Rect> portConnectionPoints { get { return _portConnectionPoints; } }
@ -14,6 +15,14 @@ namespace XNodeEditor {
[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 {
get {
if (_isDocked == null) _isDocked = this.GetIsDockedDelegate();
return _isDocked;
}
}
private Func<bool> _isDocked;
[System.Serializable] private class NodePortReference { [System.Serializable] private class NodePortReference {
[SerializeField] private XNode.Node _node; [SerializeField] private XNode.Node _node;
[SerializeField] private string _name; [SerializeField] private string _name;
@ -31,6 +40,129 @@ namespace XNodeEditor {
} }
} }
public static NodeGraphWindow current;
public XNode.NodeGraph target;
/// <summary> Are we currently renaming a node? </summary>
protected bool isRenaming;
/// <summary> Called when opened by NodeEditorWindow </summary>
public virtual void OnOpen() { }
public virtual void OnOverlayGUI() { }
public virtual Texture2D GetGridTexture() {
return NodeEditorPreferences.GetSettings().gridTexture;
}
public virtual Texture2D GetSecondaryGridTexture() {
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>
public virtual NodeEditorPreferences.Settings GetDefaultPreferences() {
return new NodeEditorPreferences.Settings();
}
/// <summary> Returns context node menu path. Null or empty strings for hidden nodes. </summary>
public virtual string GetNodeMenuName(Type type) {
//Check if type has the CreateNodeMenuAttribute
XNode.Node.CreateNodeMenuAttribute attrib;
if (NodeEditorUtilities.GetAttrib(type, out attrib)) // Return custom path
return attrib.menuName;
else // Return generated path
return ObjectNames.NicifyVariableName(type.ToString().Replace('.', '/'));
}
/// <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) {
Vector2 pos = WindowToGridPosition(Event.current.mousePosition);
for (int i = 0; i < NodeEditorReflection.nodeTypes.Length; i++) {
Type type = NodeEditorReflection.nodeTypes[i];
//Get node context menu path
string path = GetNodeMenuName(type);
if (string.IsNullOrEmpty(path)) continue;
menu.AddItem(new GUIContent(path), false, () => {
CreateNode(type, pos);
});
}
menu.AddSeparator("");
if (NodeGraphWindow.copyBuffer != null && NodeGraphWindow.copyBuffer.Length > 0) menu.AddItem(new GUIContent("Paste"), false, () => PasteNodes(pos));
else menu.AddDisabledItem(new GUIContent("Paste"));
menu.AddItem(new GUIContent("Preferences"), false, () => NodeEditorReflection.OpenPreferences());
NodeEditorReflection.AddCustomContextMenuItems(menu, target);
}
public virtual Color GetPortColor(XNode.NodePort port) {
return GetTypeColor(port.ValueType);
}
public virtual Color GetTypeColor(Type type) {
return NodeEditorPreferences.GetTypeColor(type);
}
public virtual string GetPortTooltip(XNode.NodePort port) {
Type portType = port.ValueType;
string tooltip = "";
tooltip = portType.PrettyName();
if (port.IsOutput) {
object obj = port.node.GetValue(port);
tooltip += " = " + (obj != null ? obj.ToString() : "null");
}
return tooltip;
}
/// <summary> Deal with objects dropped into the graph through DragAndDrop </summary>
public virtual void OnDropObjects(UnityEngine.Object[] objects) {
Debug.Log("No OnDropItems override defined for " + GetType());
}
/// <summary> Create a node and save it in the graph asset </summary>
public virtual void CreateNode(Type type, Vector2 position) {
XNode.Node node = target.AddNode(type);
node.position = position;
if (node.name == null || node.name.Trim() == "") node.name = NodeEditorUtilities.NodeDefaultName(type);
AssetDatabase.AddObjectToAsset(node, target);
if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets();
NodeGraphWindow.RepaintAll();
}
/// <summary> Creates a copy of the original node in the graph </summary>
public XNode.Node CopyNode(XNode.Node original) {
XNode.Node node = target.CopyNode(original);
node.name = original.name;
AssetDatabase.AddObjectToAsset(node, target);
if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets();
return node;
}
/// <summary> Safely remove a node and all its connections. </summary>
public virtual void RemoveNode(XNode.Node node) {
target.RemoveNode(node);
UnityEngine.Object.DestroyImmediate(node, true);
if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets();
}
[AttributeUsage(AttributeTargets.Class)]
public class CustomNodeGraphWindowAttribute : Attribute, XNodeEditor.Internal.INodeEditorAttrib {
private Type inspectedType;
public string editorPrefsKey;
/// <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="editorPrefsKey">Define unique key for unique layout settings instance</param>
public CustomNodeGraphWindowAttribute(Type inspectedType, string editorPrefsKey = "xNode.Settings") {
this.inspectedType = inspectedType;
this.editorPrefsKey = editorPrefsKey;
}
public Type GetInspectedType() {
return inspectedType;
}
}
private void OnDisable() { private void OnDisable() {
// Cache portConnectionPoints before serialization starts // Cache portConnectionPoints before serialization starts
int count = portConnectionPoints.Count; int count = portConnectionPoints.Count;
@ -66,8 +198,7 @@ namespace XNodeEditor {
void OnFocus() { void OnFocus() {
current = this; current = this;
ValidateGraphEditor(); if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets();
if (graphEditor != null && NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets();
} }
[InitializeOnLoadMethod] [InitializeOnLoadMethod]
@ -84,18 +215,9 @@ namespace XNodeEditor {
} }
} }
/// <summary> Make sure the graph editor is assigned and to the right object </summary>
private void ValidateGraphEditor() {
NodeGraphEditor graphEditor = NodeGraphEditor.GetEditor(graph, this);
if (this.graphEditor != graphEditor) {
this.graphEditor = graphEditor;
graphEditor.OnOpen();
}
}
/// <summary> Create editor window </summary> /// <summary> Create editor window </summary>
public static NodeEditorWindow Init() { public static NodeGraphWindow Init() {
NodeEditorWindow w = CreateInstance<NodeEditorWindow>(); NodeGraphWindow w = CreateInstance<NodeGraphWindow>();
w.titleContent = new GUIContent("xNode"); w.titleContent = new GUIContent("xNode");
w.wantsMouseMove = true; w.wantsMouseMove = true;
w.Show(); w.Show();
@ -180,14 +302,14 @@ namespace XNodeEditor {
public static void Open(XNode.NodeGraph graph) { public static void Open(XNode.NodeGraph graph) {
if (!graph) return; if (!graph) return;
NodeEditorWindow w = GetWindow(typeof(NodeEditorWindow), false, "xNode", true) as NodeEditorWindow; NodeGraphWindow w = GetWindow(typeof(NodeGraphWindow), false, "xNode", true) as NodeGraphWindow;
w.wantsMouseMove = true; w.wantsMouseMove = true;
w.graph = graph; w.graph = graph;
} }
/// <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>(); NodeGraphWindow[] windows = Resources.FindObjectsOfTypeAll<NodeGraphWindow>();
for (int i = 0; i < windows.Length; i++) { for (int i = 0; i < windows.Length; i++) {
windows[i].Repaint(); windows[i].Repaint();
} }

View File

@ -51,7 +51,7 @@ namespace XNodeEditor {
target.name = NodeEditorUtilities.NodeDefaultName(target.GetType()); target.name = NodeEditorUtilities.NodeDefaultName(target.GetType());
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(target)); AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(target));
Close(); Close();
NodeEditorWindow.TriggerOnValidate(target); NodeEditorReflection.TriggerOnValidate(target);
} }
} }
// Rename asset to input text // Rename asset to input text
@ -60,7 +60,7 @@ namespace XNodeEditor {
target.name = input; target.name = input;
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(target)); AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(target));
Close(); Close();
NodeEditorWindow.TriggerOnValidate(target); NodeEditorReflection.TriggerOnValidate(target);
} }
} }
} }