1
0
mirror of https://github.com/Siccity/xNode.git synced 2026-03-26 22:49:02 +08:00

Merge 31aa42141320cb9b1f7c30dd349ca5049bb00e56 into 60a8e89cdbf728519c8e615fcf261624a02de7c7

This commit is contained in:
Daniel Steegmüller 2020-08-10 09:53:23 +02:00 committed by GitHub
commit 97d540ecac
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 310 additions and 229 deletions

2
Scripts/Editor/NodeEditor.cs Normal file → Executable file
View File

@ -18,7 +18,7 @@ namespace XNodeEditor {
/// <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<XNode.Node> onUpdateNode; public static Action<XNode.Node> onUpdateNode;
public readonly static Dictionary<XNode.NodePort, Vector2> portPositions = new Dictionary<XNode.NodePort, Vector2>(); public static readonly Dictionary<XNode.NodePort, Vector2> portPositions = new Dictionary<XNode.NodePort, Vector2>();
#if ODIN_INSPECTOR #if ODIN_INSPECTOR
protected internal static bool inNodeEditor = false; protected internal static bool inNodeEditor = false;

16
Scripts/Editor/NodeEditorAction.cs Normal file → Executable file
View File

@ -18,23 +18,23 @@ namespace XNodeEditor {
private bool IsHoveringPort { get { return hoveredPort != null; } } private bool IsHoveringPort { get { return hoveredPort != null; } }
private bool IsHoveringNode { get { return hoveredNode != null; } } private bool IsHoveringNode { get { return hoveredNode != null; } }
private bool IsHoveringReroute { get { return hoveredReroute.port != null; } } private bool IsHoveringReroute { get { return hoveredReroute.port != null; } }
private XNode.Node hoveredNode = null; protected XNode.Node hoveredNode = null;
[NonSerialized] public XNode.NodePort hoveredPort = null; [NonSerialized] public XNode.NodePort hoveredPort = null;
[NonSerialized] private XNode.NodePort draggedOutput = null; [NonSerialized] private XNode.NodePort draggedOutput = null;
[NonSerialized] private XNode.NodePort draggedOutputTarget = null; [NonSerialized] private XNode.NodePort draggedOutputTarget = null;
[NonSerialized] private XNode.NodePort autoConnectOutput = null; [NonSerialized] private XNode.NodePort autoConnectOutput = null;
[NonSerialized] private List<Vector2> draggedOutputReroutes = new List<Vector2>(); [NonSerialized] private List<Vector2> draggedOutputReroutes = new List<Vector2>();
private RerouteReference hoveredReroute = new RerouteReference(); protected RerouteReference hoveredReroute = new RerouteReference();
public List<RerouteReference> selectedReroutes = new List<RerouteReference>(); public List<RerouteReference> selectedReroutes = new List<RerouteReference>();
private Vector2 dragBoxStart; protected Vector2 dragBoxStart;
private UnityEngine.Object[] preBoxSelection; protected UnityEngine.Object[] preBoxSelection;
private RerouteReference[] preBoxSelectionReroute; protected RerouteReference[] preBoxSelectionReroute;
private Rect selectionBox; protected Rect selectionBox;
private bool isDoubleClick = false; private bool isDoubleClick = false;
private Vector2 lastMousePosition; private Vector2 lastMousePosition;
private float dragThreshold = 1f; private float dragThreshold = 1f;
public void Controls() { protected virtual void Controls() {
wantsMouseMove = true; wantsMouseMove = true;
Event e = Event.current; Event e = Event.current;
switch (e.type) { switch (e.type) {
@ -483,7 +483,7 @@ namespace XNodeEditor {
} }
/// <summary> Draw a connection as we are dragging it </summary> /// <summary> Draw a connection as we are dragging it </summary>
public void DrawDraggedConnection() { protected virtual void DrawDraggedConnection() {
if (IsDraggingPort) { if (IsDraggingPort) {
Gradient gradient = graphEditor.GetNoodleGradient(draggedOutput, null); Gradient gradient = graphEditor.GetNoodleGradient(draggedOutput, null);
float thickness = graphEditor.GetNoodleThickness(draggedOutput, null); float thickness = graphEditor.GetNoodleThickness(draggedOutput, null);

View File

@ -3,16 +3,18 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using UnityEditor; using UnityEditor;
using UnityEngine; using UnityEngine;
using XNode;
using XNodeEditor.Internal; using XNodeEditor.Internal;
using Object = UnityEngine.Object;
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; protected List<UnityEngine.Object> selectionCache;
private List<XNode.Node> culledNodes; protected List<XNode.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; } } protected int topPadding { get { return 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];
@ -32,15 +34,19 @@ namespace XNodeEditor {
DrawTooltip(); DrawTooltip();
graphEditor.OnGUI(); graphEditor.OnGUI();
RunAndResetOnLateGui();
GUI.matrix = m;
}
protected void RunAndResetOnLateGui()
{
// Run and reset onLateGUI // Run and reset onLateGUI
if (onLateGUI != null) { if (onLateGUI != null) {
onLateGUI(); onLateGUI();
onLateGUI = null; onLateGUI = null;
} }
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();
@ -61,7 +67,7 @@ namespace XNodeEditor {
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) { protected virtual void DrawGrid(Rect rect, float zoom, Vector2 panOffset) {
rect.position = Vector2.zero; rect.position = Vector2.zero;
@ -86,7 +92,7 @@ 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() { protected virtual 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;
@ -137,22 +143,27 @@ 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, string connectionLabel = null) {
// 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;
Vector2 point_a = Vector2.zero;
Vector2 point_b = Vector2.zero;
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]; point_a = gridPoints[i];
Vector2 point_b = gridPoints[i + 1]; 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) outputTangent = zoom * dist_ab * 0.01f * Vector2.right;
if (i < length - 2) { if (i < length - 2) {
@ -161,6 +172,7 @@ namespace XNodeEditor {
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)));
@ -187,7 +199,7 @@ namespace XNodeEditor {
if (draw == 0) bezierPrevious = CalculateBezierPoint(point_a, tangent_a, tangent_b, point_b, (j - 1f) / (float) division); if (draw == 0) bezierPrevious = CalculateBezierPoint(point_a, tangent_a, tangent_b, point_b, (j - 1f) / (float) division);
} }
if (i == length - 2) if (i == length - 2)
Handles.color = gradient.Evaluate((j + 1f) / division); Handles.color = gradient.Evaluate(Time.time + (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;
@ -197,8 +209,8 @@ namespace XNodeEditor {
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]; point_a = gridPoints[i];
Vector2 point_b = gridPoints[i + 1]; 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
@ -224,20 +236,20 @@ namespace XNodeEditor {
if (i == length - 1) continue; // Skip last index if (i == length - 1) continue; // Skip last index
if (gridPoints[i].x <= gridPoints[i + 1].x - (50 / zoom)) { 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]; point_a = gridPoints[i];
Vector2 end_1 = gridPoints[i + 1]; point_b = gridPoints[i + 1];
start_1.x = midpoint; point_a.x = midpoint;
end_1.x = midpoint; point_b.x = midpoint;
if (i == length - 2) { if (i == length - 2) {
DrawAAPolyLineNonAlloc(thickness, gridPoints[i], start_1); DrawAAPolyLineNonAlloc(thickness, gridPoints[i], point_a);
Handles.color = gradient.Evaluate(0.5f); Handles.color = gradient.Evaluate(0.5f);
DrawAAPolyLineNonAlloc(thickness, start_1, end_1); DrawAAPolyLineNonAlloc(thickness, point_a, point_b);
Handles.color = gradient.Evaluate(1f); Handles.color = gradient.Evaluate(1f);
DrawAAPolyLineNonAlloc(thickness, end_1, gridPoints[i + 1]); DrawAAPolyLineNonAlloc(thickness, point_b, gridPoints[i + 1]);
} else { } else {
DrawAAPolyLineNonAlloc(thickness, gridPoints[i], start_1); DrawAAPolyLineNonAlloc(thickness, gridPoints[i], point_a);
DrawAAPolyLineNonAlloc(thickness, start_1, end_1); DrawAAPolyLineNonAlloc(thickness, point_a, point_b);
DrawAAPolyLineNonAlloc(thickness, end_1, gridPoints[i + 1]); DrawAAPolyLineNonAlloc(thickness, point_b, 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;
@ -281,8 +293,8 @@ namespace XNodeEditor {
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]; point_a = gridPoints[i];
Vector2 point_b = gridPoints[i + 1]; 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
@ -306,79 +318,108 @@ namespace XNodeEditor {
gridPoints[length - 1] = end; gridPoints[length - 1] = end;
break; break;
} }
if (zoom < 2f)
{
NodeEditorResources.styles.connectionLabel.fontSize = (int)(12 / zoom);
var labelSize = (NodeEditorResources.styles.connectionLabel.CalcSize(new GUIContent(connectionLabel)) + Vector2.one * 5 )/ zoom ;
Vector2 noodleCenter = (point_a + point_b) * 0.5f;
EditorGUI.LabelField(new Rect(noodleCenter - labelSize * 0.5f, labelSize), new GUIContent(connectionLabel), NodeEditorResources.styles.connectionLabel);
}
Handles.color = originalHandlesColor; Handles.color = originalHandlesColor;
} }
/// <summary> Draws all connections </summary> /// <summary> Draws all connections </summary>
public void DrawConnections() { protected virtual void DrawConnections() {
Vector2 mousePos = Event.current.mousePosition;
List<RerouteReference> selection = preBoxSelectionReroute != null ? new List<RerouteReference>(preBoxSelectionReroute) : new List<RerouteReference>(); List<RerouteReference> selection = preBoxSelectionReroute != null ? new List<RerouteReference>(preBoxSelectionReroute) : new List<RerouteReference>();
hoveredReroute = new RerouteReference(); hoveredReroute = new RerouteReference();
List<Vector2> gridPoints = new List<Vector2>(2);
Color col = GUI.color; Color col = GUI.color;
foreach (XNode.Node node in graph.nodes) { foreach (XNode.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 (node == null) continue; DrawNodeConnections(node, selection);
// Draw full connections and output > reroute
foreach (XNode.NodePort output in node.Outputs) {
//Needs cleanup. Null checks are ugly
Rect fromRect;
if (!_portConnectionPoints.TryGetValue(output, out fromRect)) continue;
Color portColor = graphEditor.GetPortColor(output);
for (int k = 0; k < output.ConnectionCount; k++) {
XNode.NodePort input = output.GetConnection(k);
Gradient noodleGradient = graphEditor.GetNoodleGradient(output, input);
float noodleThickness = graphEditor.GetNoodleThickness(output, input);
NoodlePath noodlePath = graphEditor.GetNoodlePath(output, input);
NoodleStroke noodleStroke = graphEditor.GetNoodleStroke(output, input);
// 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.IsConnectedTo(output)) input.Connect(output);
Rect toRect;
if (!_portConnectionPoints.TryGetValue(input, out toRect)) continue;
List<Vector2> reroutePoints = output.GetReroutePoints(k);
gridPoints.Clear();
gridPoints.Add(fromRect.center);
gridPoints.AddRange(reroutePoints);
gridPoints.Add(toRect.center);
DrawNoodle(noodleGradient, noodlePath, noodleStroke, noodleThickness, gridPoints);
// Loop through reroute points again and draw the points
for (int i = 0; i < reroutePoints.Count; i++) {
RerouteReference rerouteRef = new RerouteReference(output, k, i);
// Draw reroute point at position
Rect rect = new Rect(reroutePoints[i], new Vector2(12, 12));
rect.position = new Vector2(rect.position.x - 6, rect.position.y - 6);
rect = GridToWindowRect(rect);
// Draw selected reroute points with an outline
if (selectedReroutes.Contains(rerouteRef)) {
GUI.color = NodeEditorPreferences.GetSettings().highlightColor;
GUI.DrawTexture(rect, NodeEditorResources.dotOuter);
}
GUI.color = portColor;
GUI.DrawTexture(rect, NodeEditorResources.dot);
if (rect.Overlaps(selectionBox)) 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() { protected virtual void DrawNodeConnections(Node node, List<RerouteReference> selection)
{
//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) return;
// Draw full connections and output > reroute
foreach (XNode.NodePort output in node.Outputs)
{
//Needs cleanup. Null checks are ugly
Rect fromRect;
if (!_portConnectionPoints.TryGetValue(output, out fromRect)) return;
Color portColor = graphEditor.GetPortColor(output);
for (int k = 0; k < output.ConnectionCount; k++)
{
XNode.NodePort input = output.GetConnection(k);
DrawConnection( selection, output, input, k, fromRect, portColor);
}
}
}
protected virtual void DrawConnection(List<RerouteReference> selection, NodePort output,
NodePort input, int k, Rect fromRect, Color portColor)
{
Gradient noodleGradient = graphEditor.GetNoodleGradient(output, input);
float noodleThickness = graphEditor.GetNoodleThickness(output, input);
NoodlePath noodlePath = graphEditor.GetNoodlePath(output, input);
NoodleStroke noodleStroke = graphEditor.GetNoodleStroke(output, input);
// Error handling
if (input == null)
return;
if (!input.IsConnectedTo(output)) input.Connect(output);
Rect toRect;
if (!_portConnectionPoints.TryGetValue(input, out toRect)) return;
List<Vector2> reroutePoints = output.GetReroutePoints(k);
List<Vector2> gridPoints = new List<Vector2>(2);
gridPoints.Clear();
gridPoints.Add(fromRect.center);
gridPoints.AddRange(reroutePoints);
gridPoints.Add(toRect.center);
DrawNoodle(noodleGradient, noodlePath, noodleStroke, noodleThickness, gridPoints,
output.GetPortConnection(k).connectionLabel);
Rect r = fromRect;
r.width = 200;
Rect center = new Rect((toRect.center + fromRect.center) / 2f, new Vector2(100, 20));
// Loop through reroute points again and draw the points
for (int i = 0; i < reroutePoints.Count; i++)
{
RerouteReference rerouteRef = new RerouteReference(output, k, i);
// Draw reroute point at position
Rect rect = new Rect(reroutePoints[i], new Vector2(12, 12));
rect.position = new Vector2(rect.position.x - 6, rect.position.y - 6);
rect = GridToWindowRect(rect);
// Draw selected reroute points with an outline
if (selectedReroutes.Contains(rerouteRef))
{
GUI.color = NodeEditorPreferences.GetSettings().highlightColor;
GUI.DrawTexture(rect, NodeEditorResources.dotOuter);
}
Vector2 mousePos = Event.current.mousePosition;
GUI.color = portColor;
GUI.DrawTexture(rect, NodeEditorResources.dot);
if (rect.Overlaps(selectionBox)) selection.Add(rerouteRef);
if (rect.Contains(mousePos)) hoveredReroute = rerouteRef;
}
}
protected virtual 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<UnityEngine.Object>(Selection.objects);
@ -429,103 +470,7 @@ namespace XNodeEditor {
} }
} else if (culledNodes.Contains(node)) continue; } else if (culledNodes.Contains(node)) continue;
if (e.type == EventType.Repaint) { DrawNode(e, removeEntries, node, guiColor, mousePos, selectionBox, preSelection);
removeEntries.Clear();
foreach (var kvp in _portConnectionPoints)
if (kvp.Key.node == node) removeEntries.Add(kvp.Key);
foreach (var k in removeEntries) _portConnectionPoints.Remove(k);
}
NodeEditor nodeEditor = NodeEditor.GetEditor(node, this);
NodeEditor.portPositions.Clear();
// Set default label width. This is potentially overridden in OnBodyGUI
EditorGUIUtility.labelWidth = 84;
//Get node position
Vector2 nodePos = GridToWindowPositionNoClipped(node.position);
GUILayout.BeginArea(new Rect(nodePos, new Vector2(nodeEditor.GetWidth(), 4000)));
bool selected = selectionCache.Contains(graph.nodes[n]);
if (selected) {
GUIStyle style = new GUIStyle(nodeEditor.GetBodyStyle());
GUIStyle highlightStyle = new GUIStyle(nodeEditor.GetBodyHighlightStyle());
highlightStyle.padding = style.padding;
style.padding = new RectOffset();
GUI.color = nodeEditor.GetTint();
GUILayout.BeginVertical(style);
GUI.color = NodeEditorPreferences.GetSettings().highlightColor;
GUILayout.BeginVertical(new GUIStyle(highlightStyle));
} else {
GUIStyle style = new GUIStyle(nodeEditor.GetBodyStyle());
GUI.color = nodeEditor.GetTint();
GUILayout.BeginVertical(style);
}
GUI.color = guiColor;
EditorGUI.BeginChangeCheck();
//Draw node contents
nodeEditor.OnHeaderGUI();
nodeEditor.OnBodyGUI();
//If user changed a value, notify other scripts through onUpdateNode
if (EditorGUI.EndChangeCheck()) {
if (NodeEditor.onUpdateNode != null) NodeEditor.onUpdateNode(node);
EditorUtility.SetDirty(node);
nodeEditor.serializedObject.ApplyModifiedProperties();
}
GUILayout.EndVertical();
//Cache data about the node for next frame
if (e.type == EventType.Repaint) {
Vector2 size = GUILayoutUtility.GetLastRect().size;
if (nodeSizes.ContainsKey(node)) nodeSizes[node] = size;
else nodeSizes.Add(node, size);
foreach (var kvp in NodeEditor.portPositions) {
Vector2 portHandlePos = kvp.Value;
portHandlePos += node.position;
Rect rect = new Rect(portHandlePos.x - 8, portHandlePos.y - 8, 16, 16);
portConnectionPoints[kvp.Key] = rect;
}
}
if (selected) GUILayout.EndVertical();
if (e.type != EventType.Layout) {
//Check if we are hovering this node
Vector2 nodeSize = GUILayoutUtility.GetLastRect().size;
Rect windowRect = new Rect(nodePos, nodeSize);
if (windowRect.Contains(mousePos)) hoveredNode = node;
//If dragging a selection box, add nodes inside to selection
if (currentActivity == NodeActivity.DragGrid) {
if (windowRect.Overlaps(selectionBox)) preSelection.Add(node);
}
//Check if we are hovering any of this nodes ports
//Check input ports
foreach (XNode.NodePort input in node.Inputs) {
//Check if port rect is available
if (!portConnectionPoints.ContainsKey(input)) continue;
Rect r = GridToWindowRectNoClipped(portConnectionPoints[input]);
if (r.Contains(mousePos)) hoveredPort = input;
}
//Check all output ports
foreach (XNode.NodePort output in node.Outputs) {
//Check if port rect is available
if (!portConnectionPoints.ContainsKey(output)) continue;
Rect r = GridToWindowRectNoClipped(portConnectionPoints[output]);
if (r.Contains(mousePos)) hoveredPort = output;
}
}
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();
@ -537,7 +482,122 @@ namespace XNodeEditor {
if (onValidate != null && EditorGUI.EndChangeCheck()) onValidate.Invoke(Selection.activeObject, null); if (onValidate != null && EditorGUI.EndChangeCheck()) onValidate.Invoke(Selection.activeObject, null);
} }
private bool ShouldBeCulled(XNode.Node node) { protected virtual void DrawNode(Event e, List<NodePort> removeEntries, Node node, Color guiColor, Vector2 mousePos,
Rect selectionBox, List<Object> preSelection)
{
if (e.type == EventType.Repaint)
{
removeEntries.Clear();
foreach (var kvp in _portConnectionPoints)
if (kvp.Key.node == node)
removeEntries.Add(kvp.Key);
foreach (var k in removeEntries) _portConnectionPoints.Remove(k);
}
NodeEditor nodeEditor = NodeEditor.GetEditor(node, this);
NodeEditor.portPositions.Clear();
// Set default label width. This is potentially overridden in OnBodyGUI
EditorGUIUtility.labelWidth = 84;
//Get node position
Vector2 nodePos = GridToWindowPositionNoClipped(node.position);
GUILayout.BeginArea(new Rect(nodePos, new Vector2(nodeEditor.GetWidth(), 4000)));
bool selected = selectionCache.Contains(node);
if (selected)
{
GUIStyle style = new GUIStyle(nodeEditor.GetBodyStyle());
GUIStyle highlightStyle = new GUIStyle(nodeEditor.GetBodyHighlightStyle());
highlightStyle.padding = style.padding;
style.padding = new RectOffset();
GUI.color = nodeEditor.GetTint();
GUILayout.BeginVertical(style);
GUI.color = NodeEditorPreferences.GetSettings().highlightColor;
GUILayout.BeginVertical(new GUIStyle(highlightStyle));
}
else
{
GUIStyle style = new GUIStyle(nodeEditor.GetBodyStyle());
GUI.color = nodeEditor.GetTint();
GUILayout.BeginVertical(style);
}
GUI.color = guiColor;
EditorGUI.BeginChangeCheck();
//Draw node contents
nodeEditor.OnHeaderGUI();
nodeEditor.OnBodyGUI();
//If user changed a value, notify other scripts through onUpdateNode
if (EditorGUI.EndChangeCheck())
{
if (NodeEditor.onUpdateNode != null) NodeEditor.onUpdateNode(node);
EditorUtility.SetDirty(node);
nodeEditor.serializedObject.ApplyModifiedProperties();
}
GUILayout.EndVertical();
//Cache data about the node for next frame
if (e.type == EventType.Repaint)
{
Vector2 size = GUILayoutUtility.GetLastRect().size;
if (nodeSizes.ContainsKey(node)) nodeSizes[node] = size;
else nodeSizes.Add(node, size);
foreach (var kvp in NodeEditor.portPositions)
{
Vector2 portHandlePos = kvp.Value;
portHandlePos += node.position;
Rect rect = new Rect(portHandlePos.x - 8, portHandlePos.y - 8, 16, 16);
portConnectionPoints[kvp.Key] = rect;
}
}
if (selected) GUILayout.EndVertical();
if (e.type != EventType.Layout)
{
//Check if we are hovering this node
Vector2 nodeSize = GUILayoutUtility.GetLastRect().size;
Rect windowRect = new Rect(nodePos, nodeSize);
if (windowRect.Contains(mousePos)) hoveredNode = node;
//If dragging a selection box, add nodes inside to selection
if (currentActivity == NodeActivity.DragGrid)
{
if (windowRect.Overlaps(selectionBox)) preSelection.Add(node);
}
//Check if we are hovering any of this nodes ports
//Check input ports
foreach (XNode.NodePort input in node.Inputs)
{
//Check if port rect is available
if (!portConnectionPoints.ContainsKey(input)) continue;
Rect r = GridToWindowRectNoClipped(portConnectionPoints[input]);
if (r.Contains(mousePos)) hoveredPort = input;
}
//Check all output ports
foreach (XNode.NodePort output in node.Outputs)
{
//Check if port rect is available
if (!portConnectionPoints.ContainsKey(output)) continue;
Rect r = GridToWindowRectNoClipped(portConnectionPoints[output]);
if (r.Contains(mousePos)) hoveredPort = output;
}
}
GUILayout.EndArea();
}
protected virtual bool ShouldBeCulled(XNode.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) return true; // Right
@ -550,7 +610,7 @@ namespace XNodeEditor {
return false; return false;
} }
private void DrawTooltip() { protected virtual void DrawTooltip() {
if (hoveredPort != null && NodeEditorPreferences.GetSettings().portTooltips && graphEditor != null) { if (hoveredPort != null && NodeEditorPreferences.GetSettings().portTooltips && graphEditor != null) {
string tooltip = graphEditor.GetPortTooltip(hoveredPort); string tooltip = graphEditor.GetPortTooltip(hoveredPort);
if (string.IsNullOrEmpty(tooltip)) return; if (string.IsNullOrEmpty(tooltip)) return;

6
Scripts/Editor/NodeEditorResources.cs Normal file → Executable file
View File

@ -18,12 +18,16 @@ namespace XNodeEditor {
public static Styles _styles = null; public static Styles _styles = null;
public static GUIStyle OutputPort { get { return new GUIStyle(EditorStyles.label) { alignment = TextAnchor.UpperRight }; } } public static GUIStyle OutputPort { get { return new GUIStyle(EditorStyles.label) { alignment = TextAnchor.UpperRight }; } }
public class Styles { public class Styles {
public GUIStyle inputPort, nodeHeader, nodeBody, tooltip, nodeHighlight; public GUIStyle inputPort, nodeHeader, nodeBody, tooltip, nodeHighlight, connectionLabel;
public Styles() { public Styles() {
GUIStyle baseStyle = new GUIStyle("Label"); GUIStyle baseStyle = new GUIStyle("Label");
baseStyle.fixedHeight = 18; baseStyle.fixedHeight = 18;
connectionLabel = new GUIStyle(EditorStyles.boldLabel);
connectionLabel.richText = true;
connectionLabel.alignment = TextAnchor.MiddleCenter;
inputPort = new GUIStyle(baseStyle); inputPort = new GUIStyle(baseStyle);
inputPort.alignment = TextAnchor.UpperLeft; inputPort.alignment = TextAnchor.UpperLeft;
inputPort.padding.left = 10; inputPort.padding.left = 10;

2
Scripts/Editor/NodeEditorWindow.cs Normal file → Executable file
View File

@ -104,7 +104,7 @@ namespace XNodeEditor {
} }
/// <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() { protected 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;

8
Scripts/Node.cs Normal file → Executable file
View File

@ -111,7 +111,7 @@ namespace XNode {
/// <summary> Position on the <see cref="NodeGraph"/> </summary> /// <summary> Position on the <see cref="NodeGraph"/> </summary>
[SerializeField] public Vector2 position; [SerializeField] public Vector2 position;
/// <summary> It is recommended not to modify these at hand. Instead, see <see cref="InputAttribute"/> and <see cref="OutputAttribute"/> </summary> /// <summary> It is recommended not to modify these at hand. Instead, see <see cref="InputAttribute"/> and <see cref="OutputAttribute"/> </summary>
[SerializeField] private NodePortDictionary ports = new NodePortDictionary(); [SerializeField] protected NodePortDictionary ports = new NodePortDictionary();
/// <summary> Used during node instantiation to fix null/misconfigured graph during OnEnable/Init. Set it before instantiating a node. Will automatically be unset during OnEnable </summary> /// <summary> Used during node instantiation to fix null/misconfigured graph during OnEnable/Init. Set it before instantiating a node. Will automatically be unset during OnEnable </summary>
public static NodeGraph graphHotfix; public static NodeGraph graphHotfix;
@ -140,14 +140,14 @@ namespace XNode {
/// <summary> Convenience function. </summary> /// <summary> Convenience function. </summary>
/// <seealso cref="AddInstancePort"/> /// <seealso cref="AddInstancePort"/>
/// <seealso cref="AddInstanceOutput"/> /// <seealso cref="AddInstanceOutput"/>
public NodePort AddDynamicInput(Type type, Node.ConnectionType connectionType = Node.ConnectionType.Multiple, Node.TypeConstraint typeConstraint = TypeConstraint.None, string fieldName = null) { public virtual NodePort AddDynamicInput(Type type, Node.ConnectionType connectionType = Node.ConnectionType.Multiple, Node.TypeConstraint typeConstraint = TypeConstraint.None, string fieldName = null) {
return AddDynamicPort(type, NodePort.IO.Input, connectionType, typeConstraint, fieldName); return AddDynamicPort(type, NodePort.IO.Input, connectionType, typeConstraint, fieldName);
} }
/// <summary> Convenience function. </summary> /// <summary> Convenience function. </summary>
/// <seealso cref="AddInstancePort"/> /// <seealso cref="AddInstancePort"/>
/// <seealso cref="AddInstanceInput"/> /// <seealso cref="AddInstanceInput"/>
public NodePort AddDynamicOutput(Type type, Node.ConnectionType connectionType = Node.ConnectionType.Multiple, Node.TypeConstraint typeConstraint = TypeConstraint.None, string fieldName = null) { public virtual NodePort AddDynamicOutput(Type type, Node.ConnectionType connectionType = Node.ConnectionType.Multiple, Node.TypeConstraint typeConstraint = TypeConstraint.None, string fieldName = null) {
return AddDynamicPort(type, NodePort.IO.Output, connectionType, typeConstraint, fieldName); return AddDynamicPort(type, NodePort.IO.Output, connectionType, typeConstraint, fieldName);
} }
@ -387,7 +387,7 @@ namespace XNode {
} }
#endregion #endregion
[Serializable] private class NodePortDictionary : Dictionary<string, NodePort>, ISerializationCallbackReceiver { [Serializable] protected class NodePortDictionary : Dictionary<string, NodePort>, ISerializationCallbackReceiver {
[SerializeField] private List<string> keys = new List<string>(); [SerializeField] private List<string> keys = new List<string>();
[SerializeField] private List<NodePort> values = new List<NodePort>(); [SerializeField] private List<NodePort> values = new List<NodePort>();

35
Scripts/NodePort.cs Normal file → Executable file
View File

@ -202,7 +202,8 @@ namespace XNode {
/// <summary> Connect this <see cref="NodePort"/> to another </summary> /// <summary> Connect this <see cref="NodePort"/> to another </summary>
/// <param name="port">The <see cref="NodePort"/> to connect to</param> /// <param name="port">The <see cref="NodePort"/> to connect to</param>
public void Connect(NodePort port) { /// <param name="connectionLabel">The optional label of the connection</param>
public void Connect(NodePort port, string connectionLabel = null) {
if (connections == null) connections = new List<PortConnection>(); if (connections == null) connections = new List<PortConnection>();
if (port == null) { Debug.LogWarning("Cannot connect to null port"); return; } if (port == null) { Debug.LogWarning("Cannot connect to null port"); return; }
if (port == this) { Debug.LogWarning("Cannot connect port to self."); return; } if (port == this) { Debug.LogWarning("Cannot connect port to self."); return; }
@ -214,9 +215,9 @@ namespace XNode {
#endif #endif
if (port.connectionType == Node.ConnectionType.Override && port.ConnectionCount != 0) { port.ClearConnections(); } if (port.connectionType == Node.ConnectionType.Override && port.ConnectionCount != 0) { port.ClearConnections(); }
if (connectionType == Node.ConnectionType.Override && ConnectionCount != 0) { ClearConnections(); } if (connectionType == Node.ConnectionType.Override && ConnectionCount != 0) { ClearConnections(); }
connections.Add(new PortConnection(port)); connections.Add(new PortConnection(port, connectionLabel));
if (port.connections == null) port.connections = new List<PortConnection>(); if (port.connections == null) port.connections = new List<PortConnection>();
if (!port.IsConnectedTo(this)) port.connections.Add(new PortConnection(this)); if (!port.IsConnectedTo(this)) port.connections.Add(new PortConnection(this, connectionLabel));
node.OnCreateConnection(this, port); node.OnCreateConnection(this, port);
port.node.OnCreateConnection(this, port); port.node.OnCreateConnection(this, port);
} }
@ -230,6 +231,11 @@ namespace XNode {
return result; return result;
} }
public PortConnection GetPortConnection(int index)
{
return connections[index];
}
public NodePort GetConnection(int i) { public NodePort GetConnection(int i) {
//If the connection is broken for some reason, remove it. //If the connection is broken for some reason, remove it.
if (connections[i].node == null || string.IsNullOrEmpty(connections[i].fieldName)) { if (connections[i].node == null || string.IsNullOrEmpty(connections[i].fieldName)) {
@ -391,28 +397,5 @@ namespace XNode {
if (index >= 0) connection.node = newNodes[index]; if (index >= 0) connection.node = newNodes[index];
} }
} }
[Serializable]
private class PortConnection {
[SerializeField] public string fieldName;
[SerializeField] public Node node;
public NodePort Port { get { return port != null ? port : port = GetPort(); } }
[NonSerialized] private NodePort port;
/// <summary> Extra connection path points for organization </summary>
[SerializeField] public List<Vector2> reroutePoints = new List<Vector2>();
public PortConnection(NodePort port) {
this.port = port;
node = port.node;
fieldName = port.fieldName;
}
/// <summary> Returns the port that this <see cref="PortConnection"/> points to </summary>
private NodePort GetPort() {
if (node == null || string.IsNullOrEmpty(fieldName)) return null;
return node.GetPort(fieldName);
}
}
} }
} }

31
Scripts/PortConnection.cs Normal file
View File

@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using UnityEngine;
namespace XNode
{
[Serializable]
public class PortConnection {
[SerializeField] public string fieldName;
[SerializeField] public string connectionLabel;
[SerializeField] public Node node;
public NodePort Port { get { return port != null ? port : port = GetPort(); } }
[NonSerialized] protected NodePort port;
/// <summary> Extra connection path points for organization </summary>
[SerializeField] public List<Vector2> reroutePoints = new List<Vector2>();
public PortConnection(NodePort port, string connectionLabel = null) {
this.port = port;
node = port.node;
fieldName = port.fieldName;
this.connectionLabel = connectionLabel;
}
/// <summary> Returns the port that this <see cref="PortConnection"/> points to </summary>
private NodePort GetPort() {
if (node == null || string.IsNullOrEmpty(fieldName)) return null;
return node.GetPort(fieldName);
}
}
}

View File

@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 82f6ec040528431e87c5a15e2092f31e
timeCreated: 1595343084