コード例 #1
0
ファイル: NodeEditorAction.cs プロジェクト: jfranmora/xNode
        private void InsertDuplicateNodes(XNode.Node[] nodes, Vector2 topLeft)
        {
            if (nodes == null || nodes.Length == 0)
            {
                return;
            }

            // Get top-left node
            Vector2 topLeftNode = nodes.Select(x => x.position).Aggregate((x, y) => new Vector2(Mathf.Min(x.x, y.x), Mathf.Min(x.y, y.y)));
            Vector2 offset      = topLeft - topLeftNode;

            UnityEngine.Object[] newNodes = new UnityEngine.Object[nodes.Length];
            Dictionary <XNode.Node, XNode.Node> substitutes = new Dictionary <XNode.Node, XNode.Node>();

            for (int i = 0; i < nodes.Length; i++)
            {
                XNode.Node srcNode = nodes[i];
                if (srcNode == null)
                {
                    continue;
                }

                // Check if user is allowed to add more of given node type
                XNode.Node.DisallowMultipleNodesAttribute disallowAttrib;
                Type nodeType = srcNode.GetType();
                if (NodeEditorUtilities.GetAttrib(nodeType, out disallowAttrib))
                {
                    int typeCount = graph.nodes.Count(x => x.GetType() == nodeType);
                    if (typeCount >= disallowAttrib.max)
                    {
                        continue;
                    }
                }

                XNode.Node newNode = graphEditor.CopyNode(srcNode);
                substitutes.Add(srcNode, newNode);
                newNode.position = srcNode.position + offset;
                newNodes[i]      = newNode;
            }

            // Walk through the selected nodes again, recreate connections, using the new nodes
            for (int i = 0; i < nodes.Length; i++)
            {
                XNode.Node srcNode = nodes[i];
                if (srcNode == null)
                {
                    continue;
                }
                foreach (XNode.NodePort port in srcNode.Ports)
                {
                    for (int c = 0; c < port.ConnectionCount; c++)
                    {
                        XNode.NodePort inputPort  = port.direction == XNode.NodePort.IO.Input ? port : port.GetConnection(c);
                        XNode.NodePort outputPort = port.direction == XNode.NodePort.IO.Output ? port : port.GetConnection(c);

                        XNode.Node newNodeIn, newNodeOut;
                        if (substitutes.TryGetValue(inputPort.node, out newNodeIn) && substitutes.TryGetValue(outputPort.node, out newNodeOut))
                        {
                            newNodeIn.UpdatePorts();
                            newNodeOut.UpdatePorts();
                            inputPort  = newNodeIn.GetInputPort(inputPort.fieldName);
                            outputPort = newNodeOut.GetOutputPort(outputPort.fieldName);
                        }
                        if (!inputPort.IsConnectedTo(outputPort))
                        {
                            inputPort.Connect(outputPort);
                        }
                    }
                }
            }
            EditorUtility.SetDirty(graph);
            // Select the new nodes
            Selection.objects = newNodes;
        }
コード例 #2
0
ファイル: NodeEditorAction.cs プロジェクト: jfranmora/xNode
        public void Controls()
        {
            wantsMouseMove = true;
            Event e = Event.current;

            switch (e.type)
            {
            case EventType.DragUpdated:
            case EventType.DragPerform:
                DragAndDrop.visualMode = DragAndDropVisualMode.Generic;
                if (e.type == EventType.DragPerform)
                {
                    DragAndDrop.AcceptDrag();
                    graphEditor.OnDropObjects(DragAndDrop.objectReferences);
                }
                break;

            case EventType.MouseMove:
                //Keyboard commands will not get correct mouse position from Event
                lastMousePosition = e.mousePosition;
                break;

            case EventType.ScrollWheel:
                float oldZoom = zoom;
                if (e.delta.y > 0)
                {
                    zoom += 0.1f * zoom;
                }
                else
                {
                    zoom -= 0.1f * zoom;
                }
                if (NodeEditorPreferences.GetSettings().zoomToMouse)
                {
                    panOffset += (1 - oldZoom / zoom) * (WindowToGridPosition(e.mousePosition) + panOffset);
                }
                break;

            case EventType.MouseDrag:
                if (e.button == 0)
                {
                    if (IsDraggingPort)
                    {
                        // Set target even if we can't connect, so as to prevent auto-conn menu from opening erroneously
                        if (IsHoveringPort && hoveredPort.IsInput && !draggedOutput.IsConnectedTo(hoveredPort))
                        {
                            draggedOutputTarget = hoveredPort;
                        }
                        else
                        {
                            draggedOutputTarget = null;
                        }
                        Repaint();
                    }
                    else if (currentActivity == NodeActivity.HoldNode)
                    {
                        RecalculateDragOffsets(e);
                        currentActivity = NodeActivity.DragNode;
                        Repaint();
                    }
                    if (currentActivity == NodeActivity.DragNode)
                    {
                        // Holding ctrl inverts grid snap
                        bool gridSnap = NodeEditorPreferences.GetSettings().gridSnap;
                        if (e.control)
                        {
                            gridSnap = !gridSnap;
                        }

                        Vector2 mousePos = WindowToGridPosition(e.mousePosition);
                        // Move selected nodes with offset
                        for (int i = 0; i < Selection.objects.Length; i++)
                        {
                            if (Selection.objects[i] is XNode.Node)
                            {
                                XNode.Node node = Selection.objects[i] as XNode.Node;
                                Undo.RecordObject(node, "Moved Node");
                                Vector2 initial = node.position;
                                node.position = mousePos + dragOffset[i];
                                if (gridSnap)
                                {
                                    node.position.x = (Mathf.Round((node.position.x + 8) / 16) * 16) - 8;
                                    node.position.y = (Mathf.Round((node.position.y + 8) / 16) * 16) - 8;
                                }

                                // Offset portConnectionPoints instantly if a node is dragged so they aren't delayed by a frame.
                                Vector2 offset = node.position - initial;
                                if (offset.sqrMagnitude > 0)
                                {
                                    foreach (XNode.NodePort output in node.Outputs)
                                    {
                                        Rect rect;
                                        if (portConnectionPoints.TryGetValue(output, out rect))
                                        {
                                            rect.position += offset;
                                            portConnectionPoints[output] = rect;
                                        }
                                    }

                                    foreach (XNode.NodePort input in node.Inputs)
                                    {
                                        Rect rect;
                                        if (portConnectionPoints.TryGetValue(input, out rect))
                                        {
                                            rect.position += offset;
                                            portConnectionPoints[input] = rect;
                                        }
                                    }
                                }
                            }
                        }
                        // Move selected reroutes with offset
                        for (int i = 0; i < selectedReroutes.Count; i++)
                        {
                            Vector2 pos = mousePos + dragOffset[Selection.objects.Length + i];
                            if (gridSnap)
                            {
                                pos.x = (Mathf.Round(pos.x / 16) * 16);
                                pos.y = (Mathf.Round(pos.y / 16) * 16);
                            }
                            selectedReroutes[i].SetPoint(pos);
                        }
                        Repaint();
                    }
                    else if (currentActivity == NodeActivity.HoldGrid)
                    {
                        currentActivity        = NodeActivity.DragGrid;
                        preBoxSelection        = Selection.objects;
                        preBoxSelectionReroute = selectedReroutes.ToArray();
                        dragBoxStart           = WindowToGridPosition(e.mousePosition);
                        Repaint();
                    }
                    else if (currentActivity == NodeActivity.DragGrid)
                    {
                        Vector2 boxStartPos = GridToWindowPosition(dragBoxStart);
                        Vector2 boxSize     = e.mousePosition - boxStartPos;
                        if (boxSize.x < 0)
                        {
                            boxStartPos.x += boxSize.x; boxSize.x = Mathf.Abs(boxSize.x);
                        }
                        if (boxSize.y < 0)
                        {
                            boxStartPos.y += boxSize.y; boxSize.y = Mathf.Abs(boxSize.y);
                        }
                        selectionBox = new Rect(boxStartPos, boxSize);
                        Repaint();
                    }
                }
                else if (e.button == 1 || e.button == 2)
                {
                    //check drag threshold for larger screens
                    if (e.delta.magnitude > dragThreshold)
                    {
                        panOffset += e.delta * zoom;
                        isPanning  = true;
                    }
                }
                break;

            case EventType.MouseDown:
                Repaint();
                if (e.button == 0)
                {
                    draggedOutputReroutes.Clear();

                    if (IsHoveringPort)
                    {
                        if (hoveredPort.IsOutput)
                        {
                            draggedOutput     = hoveredPort;
                            autoConnectOutput = hoveredPort;
                        }
                        else
                        {
                            hoveredPort.VerifyConnections();
                            autoConnectOutput = null;
                            if (hoveredPort.IsConnected)
                            {
                                XNode.Node     node   = hoveredPort.node;
                                XNode.NodePort output = hoveredPort.Connection;
                                int            outputConnectionIndex = output.GetConnectionIndex(hoveredPort);
                                draggedOutputReroutes = output.GetReroutePoints(outputConnectionIndex);
                                hoveredPort.Disconnect(output);
                                draggedOutput       = output;
                                draggedOutputTarget = hoveredPort;
                                if (NodeEditor.onUpdateNode != null)
                                {
                                    NodeEditor.onUpdateNode(node);
                                }
                            }
                        }
                    }
                    else if (IsHoveringNode && IsHoveringTitle(hoveredNode))
                    {
                        // If mousedown on node header, select or deselect
                        if (!Selection.Contains(hoveredNode))
                        {
                            SelectNode(hoveredNode, e.control || e.shift);
                            if (!e.control && !e.shift)
                            {
                                selectedReroutes.Clear();
                            }
                        }
                        else if (e.control || e.shift)
                        {
                            DeselectNode(hoveredNode);
                        }

                        // Cache double click state, but only act on it in MouseUp - Except ClickCount only works in mouseDown.
                        isDoubleClick = (e.clickCount == 2);

                        e.Use();
                        currentActivity = NodeActivity.HoldNode;
                    }
                    else if (IsHoveringReroute)
                    {
                        // If reroute isn't selected
                        if (!selectedReroutes.Contains(hoveredReroute))
                        {
                            // Add it
                            if (e.control || e.shift)
                            {
                                selectedReroutes.Add(hoveredReroute);
                            }
                            // Select it
                            else
                            {
                                selectedReroutes = new List <RerouteReference>()
                                {
                                    hoveredReroute
                                };
                                Selection.activeObject = null;
                            }
                        }
                        // Deselect
                        else if (e.control || e.shift)
                        {
                            selectedReroutes.Remove(hoveredReroute);
                        }
                        e.Use();
                        currentActivity = NodeActivity.HoldNode;
                    }
                    // If mousedown on grid background, deselect all
                    else if (!IsHoveringNode)
                    {
                        currentActivity = NodeActivity.HoldGrid;
                        if (!e.control && !e.shift)
                        {
                            selectedReroutes.Clear();
                            Selection.activeObject = null;
                        }
                    }
                }
                break;

            case EventType.MouseUp:
                if (e.button == 0)
                {
                    //Port drag release
                    if (IsDraggingPort)
                    {
                        // If connection is valid, save it
                        if (draggedOutputTarget != null && draggedOutput.CanConnectTo(draggedOutputTarget))
                        {
                            XNode.Node node = draggedOutputTarget.node;
                            if (graph.nodes.Count != 0)
                            {
                                draggedOutput.Connect(draggedOutputTarget);
                            }

                            // ConnectionIndex can be -1 if the connection is removed instantly after creation
                            int connectionIndex = draggedOutput.GetConnectionIndex(draggedOutputTarget);
                            if (connectionIndex != -1)
                            {
                                draggedOutput.GetReroutePoints(connectionIndex).AddRange(draggedOutputReroutes);
                                if (NodeEditor.onUpdateNode != null)
                                {
                                    NodeEditor.onUpdateNode(node);
                                }
                                EditorUtility.SetDirty(graph);
                            }
                        }
                        // Open context menu for auto-connection if there is no target node
                        else if (draggedOutputTarget == null && NodeEditorPreferences.GetSettings().dragToCreate&& autoConnectOutput != null)
                        {
                            GenericMenu menu = new GenericMenu();
                            graphEditor.AddContextMenuItems(menu, draggedOutput.ValueType);
                            menu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero));
                        }
                        //Release dragged connection
                        draggedOutput       = null;
                        draggedOutputTarget = null;
                        EditorUtility.SetDirty(graph);
                        if (NodeEditorPreferences.GetSettings().autoSave)
                        {
                            AssetDatabase.SaveAssets();
                        }
                    }
                    else if (currentActivity == NodeActivity.DragNode)
                    {
                        IEnumerable <XNode.Node> nodes = Selection.objects.Where(x => x is XNode.Node).Select(x => x as XNode.Node);
                        foreach (XNode.Node node in nodes)
                        {
                            EditorUtility.SetDirty(node);
                        }
                        if (NodeEditorPreferences.GetSettings().autoSave)
                        {
                            AssetDatabase.SaveAssets();
                        }
                    }
                    else if (!IsHoveringNode)
                    {
                        // If click outside node, release field focus
                        if (!isPanning)
                        {
                            EditorGUI.FocusTextInControl(null);
                            EditorGUIUtility.editingTextField = false;
                        }
                        if (NodeEditorPreferences.GetSettings().autoSave)
                        {
                            AssetDatabase.SaveAssets();
                        }
                    }

                    // If click node header, select it.
                    if (currentActivity == NodeActivity.HoldNode && !(e.control || e.shift))
                    {
                        selectedReroutes.Clear();
                        SelectNode(hoveredNode, false);

                        // Double click to center node
                        if (isDoubleClick)
                        {
                            Vector2 nodeDimension = nodeSizes.ContainsKey(hoveredNode) ? nodeSizes[hoveredNode] / 2 : Vector2.zero;
                            panOffset = -hoveredNode.position - nodeDimension;
                        }
                    }

                    // If click reroute, select it.
                    if (IsHoveringReroute && !(e.control || e.shift))
                    {
                        selectedReroutes = new List <RerouteReference>()
                        {
                            hoveredReroute
                        };
                        Selection.activeObject = null;
                    }

                    Repaint();
                    currentActivity = NodeActivity.Idle;
                }
                else if (e.button == 1 || e.button == 2)
                {
                    if (!isPanning)
                    {
                        if (IsDraggingPort)
                        {
                            draggedOutputReroutes.Add(WindowToGridPosition(e.mousePosition));
                        }
                        else if (currentActivity == NodeActivity.DragNode && Selection.activeObject == null && selectedReroutes.Count == 1)
                        {
                            selectedReroutes[0].InsertPoint(selectedReroutes[0].GetPoint());
                            selectedReroutes[0] = new RerouteReference(selectedReroutes[0].port, selectedReroutes[0].connectionIndex, selectedReroutes[0].pointIndex + 1);
                        }
                        else if (IsHoveringReroute)
                        {
                            ShowRerouteContextMenu(hoveredReroute);
                        }
                        else if (IsHoveringPort)
                        {
                            ShowPortContextMenu(hoveredPort);
                        }
                        else if (IsHoveringNode && IsHoveringTitle(hoveredNode))
                        {
                            if (!Selection.Contains(hoveredNode))
                            {
                                SelectNode(hoveredNode, false);
                            }
                            autoConnectOutput = null;
                            GenericMenu menu = new GenericMenu();
                            NodeEditor.GetEditor(hoveredNode, this).AddContextMenuItems(menu);
                            menu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero));
                            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)
                        {
                            autoConnectOutput = null;
                            GenericMenu menu = new GenericMenu();
                            graphEditor.AddContextMenuItems(menu);
                            menu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero));
                        }
                    }
                    isPanning = false;
                }
                // Reset DoubleClick
                isDoubleClick = false;
                break;

            case EventType.KeyDown:
                if (EditorGUIUtility.editingTextField || GUIUtility.keyboardControl != 0)
                {
                    break;
                }
                else if (e.keyCode == KeyCode.F)
                {
                    Home();
                }
                if (NodeEditorUtilities.IsMac())
                {
                    if (e.keyCode == KeyCode.Return)
                    {
                        RenameSelectedNode();
                    }
                }
                else
                {
                    if (e.keyCode == KeyCode.F2)
                    {
                        RenameSelectedNode();
                    }
                }
                if (e.keyCode == KeyCode.A)
                {
                    if (Selection.objects.Any(x => graph.nodes.Contains(x as XNode.Node)))
                    {
                        foreach (XNode.Node node in graph.nodes)
                        {
                            DeselectNode(node);
                        }
                    }
                    else
                    {
                        foreach (XNode.Node node in graph.nodes)
                        {
                            SelectNode(node, true);
                        }
                    }
                    Repaint();
                }
                break;

            case EventType.ValidateCommand:
            case EventType.ExecuteCommand:
                if (e.commandName == "SoftDelete")
                {
                    if (e.type == EventType.ExecuteCommand)
                    {
                        RemoveSelectedNodes();
                    }
                    e.Use();
                }
                else if (NodeEditorUtilities.IsMac() && e.commandName == "Delete")
                {
                    if (e.type == EventType.ExecuteCommand)
                    {
                        RemoveSelectedNodes();
                    }
                    e.Use();
                }
                else if (e.commandName == "Duplicate")
                {
                    if (e.type == EventType.ExecuteCommand)
                    {
                        DuplicateSelectedNodes();
                    }
                    e.Use();
                }
                else if (e.commandName == "Copy")
                {
                    if (!EditorGUIUtility.editingTextField)
                    {
                        if (e.type == EventType.ExecuteCommand)
                        {
                            CopySelectedNodes();
                        }
                        e.Use();
                    }
                }
                else if (e.commandName == "Paste")
                {
                    if (!EditorGUIUtility.editingTextField)
                    {
                        if (e.type == EventType.ExecuteCommand)
                        {
                            PasteNodes(WindowToGridPosition(lastMousePosition));
                        }
                        e.Use();
                    }
                }
                Repaint();
                break;

            case EventType.Ignore:
                // If release mouse outside window
                if (e.rawType == EventType.MouseUp && currentActivity == NodeActivity.DragGrid)
                {
                    Repaint();
                    currentActivity = NodeActivity.Idle;
                }
                break;
            }
        }
コード例 #3
0
        /// <summary>
        /// Add items for the context menu when right-clicking this node.
        /// Override to add custom menu items.
        /// </summary>
        /// <param name="menu"></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>
        public virtual void AddContextMenuItems(GenericMenu menu, Type compatibleType = null, XNode.NodePort.IO direction = XNode.NodePort.IO.Input)
        {
            Vector2 pos = NodeEditorWindow.current.WindowToGridPosition(Event.current.mousePosition);

            Type[] nodeTypes;

            if (compatibleType != null && NodeEditorPreferences.GetSettings().createFilter)
            {
                nodeTypes = NodeEditorUtilities.GetCompatibleNodesTypes(NodeEditorReflection.nodeTypes, compatibleType, direction).OrderBy(GetNodeMenuOrder).ToArray();
            }
            else
            {
                nodeTypes = NodeEditorReflection.nodeTypes.OrderBy(GetNodeMenuOrder).ToArray();
            }

            for (int i = 0; i < nodeTypes.Length; i++)
            {
                Type type = nodeTypes[i];

                //Get node context menu path
                string path = GetNodeMenuName(type);
                if (string.IsNullOrEmpty(path))
                {
                    continue;
                }

                // Check if user is allowed to add more of given node type
                XNode.Node.DisallowMultipleNodesAttribute disallowAttrib;
                bool disallowed = false;
                if (NodeEditorUtilities.GetAttrib(type, out disallowAttrib))
                {
                    int typeCount = target.nodes.Count(x => x.GetType() == type);
                    if (typeCount >= disallowAttrib.max)
                    {
                        disallowed = true;
                    }
                }

                // Add node entry to context menu
                if (disallowed)
                {
                    menu.AddItem(new GUIContent(path), false, null);
                }
                else
                {
                    menu.AddItem(new GUIContent(path), false, () => {
                        XNode.Node node = CreateNode(type, pos);
                        NodeEditorWindow.current.AutoConnect(node);
                    });
                }
            }
            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, () => NodeEditorReflection.OpenPreferences());
            menu.AddCustomContextMenuItems(target);
        }
コード例 #4
0
        /// <summary> Make a field for a serialized property. Manual node port override. </summary>
        public static void PropertyField(SerializedProperty property, GUIContent label, XNode.NodePort port, bool includeChildren = true, params GUILayoutOption[] options)
        {
            if (property == null)
            {
                throw new NullReferenceException();
            }

            // If property is not a port, display a regular property field
            if (port == null)
            {
                EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
            }
            else
            {
                Rect rect = new Rect();

                float          spacePadding = 0;
                SpaceAttribute spaceAttribute;
                if (NodeEditorUtilities.GetCachedAttrib(port.node.GetType(), property.name, out spaceAttribute))
                {
                    spacePadding = spaceAttribute.height;
                }

                // If property is an input, display a regular property field and put a port handle on the left side
                if (port.direction == XNode.NodePort.IO.Input)
                {
                    // Get data from [Input] attribute
                    XNode.Node.ShowBackingValue showBacking = XNode.Node.ShowBackingValue.Unconnected;
                    XNode.Node.InputAttribute   inputAttribute;
                    bool instancePortList = false;
                    if (NodeEditorUtilities.GetCachedAttrib(port.node.GetType(), property.name, out inputAttribute))
                    {
                        instancePortList = inputAttribute.instancePortList;
                        showBacking      = inputAttribute.backingValue;
                    }

                    //Call GUILayout.Space if Space attribute is set and we are NOT drawing a PropertyField
                    bool useLayoutSpace = instancePortList ||
                                          showBacking == XNode.Node.ShowBackingValue.Never ||
                                          (showBacking == XNode.Node.ShowBackingValue.Unconnected && port.IsConnected);
                    if (spacePadding > 0 && useLayoutSpace)
                    {
                        GUILayout.Space(spacePadding);
                        spacePadding = 0;
                    }

                    if (instancePortList)
                    {
                        Type type = GetType(property);
                        XNode.Node.ConnectionType connectionType = inputAttribute != null ? inputAttribute.connectionType : XNode.Node.ConnectionType.Multiple;
                        InstancePortList(property.name, type, property.serializedObject, port.direction, connectionType);
                        return;
                    }
                    switch (showBacking)
                    {
                    case XNode.Node.ShowBackingValue.Unconnected:
                        // Display a label if port is connected
                        if (port.IsConnected)
                        {
                            EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName));
                        }
                        // Display an editable property field if port is not connected
                        else
                        {
                            EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
                        }
                        break;

                    case XNode.Node.ShowBackingValue.Never:
                        // Display a label
                        EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName));
                        break;

                    case XNode.Node.ShowBackingValue.Always:
                        // Display an editable property field
                        EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
                        break;
                    }

                    rect          = GUILayoutUtility.GetLastRect();
                    rect.position = rect.position - new Vector2(16, -spacePadding);
                    // If property is an output, display a text label and put a port handle on the right side
                }
                else if (port.direction == XNode.NodePort.IO.Output)
                {
                    // Get data from [Output] attribute
                    XNode.Node.ShowBackingValue showBacking = XNode.Node.ShowBackingValue.Unconnected;
                    XNode.Node.OutputAttribute  outputAttribute;
                    bool instancePortList = false;
                    if (NodeEditorUtilities.GetCachedAttrib(port.node.GetType(), property.name, out outputAttribute))
                    {
                        instancePortList = outputAttribute.instancePortList;
                        showBacking      = outputAttribute.backingValue;
                    }

                    //Call GUILayout.Space if Space attribute is set and we are NOT drawing a PropertyField
                    bool useLayoutSpace = instancePortList ||
                                          showBacking == XNode.Node.ShowBackingValue.Never ||
                                          (showBacking == XNode.Node.ShowBackingValue.Unconnected && port.IsConnected);
                    if (spacePadding > 0 && useLayoutSpace)
                    {
                        GUILayout.Space(spacePadding);
                        spacePadding = 0;
                    }

                    if (instancePortList)
                    {
                        Type type = GetType(property);
                        XNode.Node.ConnectionType connectionType = outputAttribute != null ? outputAttribute.connectionType : XNode.Node.ConnectionType.Multiple;
                        InstancePortList(property.name, type, property.serializedObject, port.direction, connectionType);
                        return;
                    }
                    switch (showBacking)
                    {
                    case XNode.Node.ShowBackingValue.Unconnected:
                        // Display a label if port is connected
                        if (port.IsConnected)
                        {
                            EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName), NodeEditorResources.OutputPort, GUILayout.MinWidth(30));
                        }
                        // Display an editable property field if port is not connected
                        else
                        {
                            EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
                        }
                        break;

                    case XNode.Node.ShowBackingValue.Never:
                        // Display a label
                        EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName), NodeEditorResources.OutputPort, GUILayout.MinWidth(30));
                        break;

                    case XNode.Node.ShowBackingValue.Always:
                        // Display an editable property field
                        EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
                        break;
                    }

                    rect          = GUILayoutUtility.GetLastRect();
                    rect.position = rect.position + new Vector2(rect.width, spacePadding);
                }

                rect.size = new Vector2(16, 16);

                Color backgroundColor = new Color32(90, 97, 105, 255);
                Color tint;
                if (NodeEditorWindow.nodeTint.TryGetValue(port.node.GetType(), out tint))
                {
                    backgroundColor *= tint;
                }
                Color col = NodeEditorWindow.current.graphEditor.GetTypeColor(port.ValueType);
                DrawPortHandle(rect, backgroundColor, col);

                // Register the handle position
                Vector2 portPos = rect.center;
                if (NodeEditor.portPositions.ContainsKey(port))
                {
                    NodeEditor.portPositions[port] = portPos;
                }
                else
                {
                    NodeEditor.portPositions.Add(port, portPos);
                }
            }
        }
コード例 #5
0
        /// <summary> Make a field for a serialized property. Manual node port override. </summary>
        public static void PropertyField(SerializedProperty property, GUIContent label, XNode.NodePort port, bool includeChildren = true, params GUILayoutOption[] options)
        {
            if (property == null)
            {
                throw new NullReferenceException();
            }

            // If property is not a port, display a regular property field
            if (port == null)
            {
                EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
            }
            else
            {
                Rect rect = new Rect();

                // If property is an input, display a regular property field and put a port handle on the left side
                if (port.direction == XNode.NodePort.IO.Input)
                {
                    // Get data from [Input] attribute
                    XNode.Node.ShowBackingValue showBacking = XNode.Node.ShowBackingValue.Unconnected;
                    XNode.Node.InputAttribute   inputAttribute;
                    if (NodeEditorUtilities.GetAttrib(port.node.GetType(), property.name, out inputAttribute))
                    {
                        showBacking = inputAttribute.backingValue;
                    }

                    switch (showBacking)
                    {
                    case XNode.Node.ShowBackingValue.Unconnected:
                        // Display a label if port is connected
                        if (port.IsConnected)
                        {
                            EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName));
                        }
                        // Display an editable property field if port is not connected
                        else
                        {
                            EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
                        }
                        break;

                    case XNode.Node.ShowBackingValue.Never:
                        // Display a label
                        EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName));
                        break;

                    case XNode.Node.ShowBackingValue.Always:
                        // Display an editable property field
                        EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
                        break;
                    }

                    rect          = GUILayoutUtility.GetLastRect();
                    rect.position = rect.position - new Vector2(16, 0);
                    // If property is an output, display a text label and put a port handle on the right side
                }
                else if (port.direction == XNode.NodePort.IO.Output)
                {
                    // Get data from [Output] attribute
                    XNode.Node.ShowBackingValue showBacking = XNode.Node.ShowBackingValue.Unconnected;
                    XNode.Node.OutputAttribute  outputAttribute;
                    if (NodeEditorUtilities.GetAttrib(port.node.GetType(), property.name, out outputAttribute))
                    {
                        showBacking = outputAttribute.backingValue;
                    }

                    switch (showBacking)
                    {
                    case XNode.Node.ShowBackingValue.Unconnected:
                        // Display a label if port is connected
                        if (port.IsConnected)
                        {
                            EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName), NodeEditorResources.OutputPort, GUILayout.MinWidth(30));
                        }
                        // Display an editable property field if port is not connected
                        else
                        {
                            EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
                        }
                        break;

                    case XNode.Node.ShowBackingValue.Never:
                        // Display a label
                        EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName), NodeEditorResources.OutputPort, GUILayout.MinWidth(30));
                        break;

                    case XNode.Node.ShowBackingValue.Always:
                        // Display an editable property field
                        EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
                        break;
                    }

                    rect          = GUILayoutUtility.GetLastRect();
                    rect.position = rect.position + new Vector2(rect.width, 0);
                }

                rect.size = new Vector2(16, 16);

                Color backgroundColor = new Color32(90, 97, 105, 255);
                if (NodeEditorWindow.nodeTint.ContainsKey(port.node.GetType()))
                {
                    backgroundColor *= NodeEditorWindow.nodeTint[port.node.GetType()];
                }
                Color col = NodeEditorWindow.current.graphEditor.GetTypeColor(port.ValueType);
                DrawPortHandle(rect, backgroundColor, col);

                // Register the handle position
                Vector2 portPos = rect.center;
                if (NodeEditor.portPositions.ContainsKey(port))
                {
                    NodeEditor.portPositions[port] = portPos;
                }
                else
                {
                    NodeEditor.portPositions.Add(port, portPos);
                }
            }
        }
コード例 #6
0
ファイル: NodeEditorGUILayout.cs プロジェクト: Your-Die/xNode
        /// <summary> Make a field for a serialized property. Manual node port override. </summary>
        public static void PropertyField(SerializedProperty property, GUIContent label, xNode.NodePort port, bool includeChildren = true, params GUILayoutOption[] options)
        {
            if (property == null)
            {
                throw new NullReferenceException();
            }

            // If property is not a port, display a regular property field
            if (port == null)
            {
                EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
            }
            else
            {
                Rect rect = new Rect();

                List <PropertyAttribute> 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 (port.Direction == xNode.NodePort.IO.Input)
                {
                    // Get data from [Input] attribute
                    xNode.Node.ShowBackingValue showBacking = xNode.Node.ShowBackingValue.Unconnected;
                    xNode.Node.InputAttribute   inputAttribute;
                    bool dynamicPortList = false;
                    if (NodeEditorUtilities.GetCachedAttrib(port.node.GetType(), property.name, out inputAttribute))
                    {
                        dynamicPortList = inputAttribute.dynamicPortList;
                        showBacking     = inputAttribute.backingValue;
                    }

                    bool usePropertyAttributes = dynamicPortList ||
                                                 showBacking == xNode.Node.ShowBackingValue.Never ||
                                                 (showBacking == xNode.Node.ShowBackingValue.Unconnected && port.IsConnected);

                    float  spacePadding = 0;
                    string tooltip      = null;
                    foreach (var attr in propertyAttributes)
                    {
                        if (attr is SpaceAttribute)
                        {
                            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
                                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       = EditorGUI.IndentedRect(position);
                                GUI.Label(position, (attr as HeaderAttribute).header, EditorStyles.boldLabel);
                            }
                            else
                            {
                                spacePadding += EditorGUIUtility.singleLineHeight * 1.5f;
                            }
                        }
                        else if (attr is TooltipAttribute)
                        {
                            tooltip = (attr as TooltipAttribute).tooltip;
                        }
                    }

                    if (dynamicPortList)
                    {
                        Type type = GetType(property);
                        xNode.Node.ConnectionType connectionType = inputAttribute != null ? inputAttribute.connectionType : xNode.Node.ConnectionType.Multiple;
                        DynamicPortList(property.name, type, property.serializedObject, port.Direction, connectionType);
                        return;
                    }
                    switch (showBacking)
                    {
                    case xNode.Node.ShowBackingValue.Unconnected:
                        // Display a label if port is connected
                        if (port.IsConnected)
                        {
                            EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName, tooltip));
                        }
                        // Display an editable property field if port is not connected
                        else
                        {
                            EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
                        }
                        break;

                    case xNode.Node.ShowBackingValue.Never:
                        // Display a label
                        EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName, tooltip));
                        break;

                    case xNode.Node.ShowBackingValue.Always:
                        // Display an editable property field
                        EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
                        break;
                    }

                    rect = GUILayoutUtility.GetLastRect();
                    float paddingLeft = NodeEditorResources.styles.inputPort.padding.left;
                    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
                }
                else if (port.Direction == xNode.NodePort.IO.Output)
                {
                    // Get data from [Output] attribute
                    xNode.Node.ShowBackingValue showBacking = xNode.Node.ShowBackingValue.Unconnected;
                    xNode.Node.OutputAttribute  outputAttribute;
                    bool dynamicPortList = false;
                    if (NodeEditorUtilities.GetCachedAttrib(port.node.GetType(), property.name, out outputAttribute))
                    {
                        dynamicPortList = outputAttribute.dynamicPortList;
                        showBacking     = outputAttribute.backingValue;
                    }

                    bool usePropertyAttributes = dynamicPortList ||
                                                 showBacking == xNode.Node.ShowBackingValue.Never ||
                                                 (showBacking == xNode.Node.ShowBackingValue.Unconnected && port.IsConnected);

                    float  spacePadding = 0;
                    string tooltip      = null;
                    foreach (var attr in propertyAttributes)
                    {
                        if (attr is SpaceAttribute)
                        {
                            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
                                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       = EditorGUI.IndentedRect(position);
                                GUI.Label(position, (attr as HeaderAttribute).header, EditorStyles.boldLabel);
                            }
                            else
                            {
                                spacePadding += EditorGUIUtility.singleLineHeight * 1.5f;
                            }
                        }
                        else if (attr is TooltipAttribute)
                        {
                            tooltip = (attr as TooltipAttribute).tooltip;
                        }
                    }

                    if (dynamicPortList)
                    {
                        Type type = GetType(property);
                        xNode.Node.ConnectionType connectionType = outputAttribute != null ? outputAttribute.connectionType : xNode.Node.ConnectionType.Multiple;
                        DynamicPortList(property.name, type, property.serializedObject, port.Direction, connectionType);
                        return;
                    }
                    switch (showBacking)
                    {
                    case xNode.Node.ShowBackingValue.Unconnected:
                        // 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));
                        }
                        // Display an editable property field if port is not connected
                        else
                        {
                            EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
                        }
                        break;

                    case xNode.Node.ShowBackingValue.Never:
                        // Display a label
                        EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName, tooltip), NodeEditorResources.OutputPort, GUILayout.MinWidth(30));
                        break;

                    case xNode.Node.ShowBackingValue.Always:
                        // Display an editable property field
                        EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
                        break;
                    }

                    rect          = GUILayoutUtility.GetLastRect();
                    rect.width   += NodeEditorResources.styles.outputPort.padding.right;
                    rect.position = rect.position + new Vector2(rect.width, spacePadding);
                }

                rect.size = new Vector2(16, 16);

                Color backgroundColor = NodeEditorWindow.current.graphEditor.GetPortBackgroundColor(port);
                Color col             = NodeEditorWindow.current.graphEditor.GetPortColor(port);
                DrawPortHandle(rect, backgroundColor, col);

                // Register the handle position
                Vector2 portPos = rect.center;
                NodeEditor.portPositions[port] = portPos;
            }
        }