Beispiel #1
0
 static void DoLoadDoc()
 {
     try {
         progress = 0;
         Assembly[] assemblies = EditorReflectionUtility.GetAssemblies();
         int        index      = 0;
         //EditorUtility.DisplayProgressBar("Loading Documentation", "", progress);
         //EditorProgressBar.ShowProgressBar("Loading Documentation", progress);
         foreach (Assembly assembly in assemblies)
         {
             try {
                 if (Thread.CurrentThread.ThreadState == ThreadState.AbortRequested)
                 {
                     break;
                 }
                 //if(uNodePreference.GetPreference().assembly.ContainsKey(assembly.GetName().Name))
                 {
                     XMLFromAssembly(assembly);
                 }
                 Thread.Sleep(1);
             }
             catch {
                 continue;
             }
             index++;
             progress = (float)index / (float)assemblies.Length;
             //EditorProgressBar.ShowProgressBar("Loading Documentation", progress);
             //EditorUtility.DisplayProgressBar("Loading Documentation", "", progress);
         }
     }
     catch { }
     //EditorUtility.ClearProgressBar();
     hasLoadDoc = true;
     isLoadDoc  = false;
 }
Beispiel #2
0
        /// <summary>
        /// Find command pin menu.
        /// </summary>
        /// <returns></returns>
        public static List <ControlFieldAttribute> FindControlsField()
        {
            if (_controlsField == null)
            {
                _controlsField = new List <ControlFieldAttribute>();

                foreach (System.Reflection.Assembly assembly in EditorReflectionUtility.GetAssemblies())
                {
                    foreach (System.Type type in EditorReflectionUtility.GetAssemblyTypes(assembly))
                    {
                        var atts = type.GetCustomAttributes(typeof(ControlFieldAttribute), true);
                        if (atts.Length > 0)
                        {
                            foreach (var a in atts)
                            {
                                var control = a as ControlFieldAttribute;
                                control.classType = type;
                                _controlsField.Add(control);
                            }
                        }
                    }
                }
                _controlsField.Sort((x, y) => Comparer <int> .Default.Compare(x.order, y.order));
            }
            return(_controlsField);
        }
Beispiel #3
0
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            MemberData      variable = PropertyDrawerUtility.GetActualObjectForSerializedProperty <MemberData>(property);
            FilterAttribute filter   = null;

            if (fieldInfo.IsDefined(typeof(ObjectTypeAttribute), true))
            {
                object pVariable       = PropertyDrawerUtility.GetParentObjectFromSerializedProperty <object>(property);
                var    fieldAttributes = fieldInfo.GetCustomAttributes(true);
                if (pVariable != null && ReflectionUtils.TryCorrectingAttribute(pVariable, ref fieldAttributes))
                {
                    filter = ReflectionUtils.GetAttribute <FilterAttribute>(fieldAttributes);
                }
                else
                {
                    return;
                }
            }
            else if (fieldInfo.GetCustomAttributes(typeof(FilterAttribute), false).Length > 0)
            {
                filter = (FilterAttribute)fieldInfo.GetCustomAttributes(typeof(FilterAttribute), false)[0];
            }
            if (fieldInfo.GetCustomAttributes(typeof(TooltipAttribute), false).Length > 0)
            {
                label.tooltip = ((TooltipAttribute)fieldInfo.GetCustomAttributes(typeof(TooltipAttribute), false)[0]).tooltip;
            }
            EditorReflectionUtility.RenderVariable(position, variable, label, property.serializedObject.targetObject, filter);
        }
Beispiel #4
0
 public bool HasDeepMember()
 {
     if (nextValidation != null)
     {
         return(nextValidation());
     }
     return(EditorReflectionUtility.ValidateNextMember(member, FilterAttribute.Default));
 }
Beispiel #5
0
 public static List <HierarchyDrawer> FindHierarchyDrawer()
 {
     if (_drawers == null)
     {
         _drawers = EditorReflectionUtility.GetListOfType <HierarchyDrawer>();
         _drawers.Sort((x, y) => {
             return(CompareUtility.Compare(x.order, y.order));
         });
     }
     return(_drawers);
 }
 public static List <GraphCreator> FindGraphCreators()
 {
     if (_graphCreators == null)
     {
         _graphCreators = EditorReflectionUtility.GetListOfType <GraphCreator>();
         _graphCreators.Sort((x, y) => {
             return(CompareUtility.Compare(x.menuName, x.order, y.menuName, y.order));
         });
     }
     return(_graphCreators);
 }
Beispiel #7
0
        /// <summary>
        /// Get the actual node view type.
        /// </summary>
        /// <param name="nodeType"></param>
        /// <returns></returns>
        public static Type GetNodeViewTypeFromType(Type nodeType)
        {
            if (nodeViewPerType == null)
            {
                nodeViewPerType = new Dictionary <Type, Type>();
                foreach (var asm in EditorReflectionUtility.GetAssemblies())
                {
                    foreach (var type in EditorReflectionUtility.GetAssemblyTypes(asm))
                    {
                        if (type.IsClass && !type.IsAbstract)
                        {
                            if (type.IsSubclassOf(typeof(UNodeView)))
                            {
                                if (type.GetCustomAttributes(typeof(NodeCustomEditor), true) is NodeCustomEditor[] attrs && attrs.Length > 0)
                                {
                                    for (int i = 0; i < attrs.Length; i++)
                                    {
                                        Type nType = attrs[i].nodeType;
                                        nodeViewPerType[nType] = type;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            Type oriType = nodeType;
            Type view    = null;

            while (nodeType != typeof(UNodeView) && nodeType != typeof(object) && nodeType != typeof(BaseNodeView))
            {
                if (nodeViewPerType.TryGetValue(nodeType, out view))
                {
                    if (oriType != nodeType)
                    {
                        nodeViewPerType[oriType] = view;
                    }
                    return(view);
                }
                else
                {
                    nodeType = nodeType.BaseType;
                }
            }
            return(view);
        }
        protected void DrawOverrideMembers(string label = "Override Members")
        {
            Type type = graphInheritFrom.Get <Type>();

            if (type == null)
            {
                return;
            }
            VariableEditorUtility.DrawCustomList(
                graphOverrideMembers,
                label,
                drawElement: (position, index, element) => {
                EditorGUI.LabelField(position, NodeBrowser.GetRichMemberName(element));
            },
                addAction: (pos) => {
                var members      = EditorReflectionUtility.GetOverrideMembers(type);
                GenericMenu menu = new GenericMenu();
                for (int i = 0; i < members.Count; i++)
                {
                    var member = members[i];
                    if (member is PropertyInfo)
                    {
                        menu.AddItem(new GUIContent("Properties/" + NodeBrowser.GetRichMemberName(member)), graphOverrideMembers.Contains(member), () => {
                            graphOverrideMembers.Add(member);
                        });
                    }
                    else
                    {
                        menu.AddItem(new GUIContent("Methods/" + NodeBrowser.GetRichMemberName(member)), graphOverrideMembers.Contains(member), () => {
                            graphOverrideMembers.Add(member);
                        });
                    }
                }
                menu.ShowAsContext();
            },
                removeAction: (index) => {
                graphOverrideMembers.RemoveAt(index);
            }
                );
        }
Beispiel #9
0
        public static string GetRichMemberName(MemberInfo member)
        {
            if (uNodePreference.GetPreference().coloredItem)
            {
                Type type = member as Type;
                if (type != null)
                {
                    if (type.IsEnum)
                    {
                        return(uNodeUtility.WrapTextWithColor(type.PrettyName(), uNodePreference.GetPreference().itemEnumColor, false));
                    }
                    else if (type.IsInterface)
                    {
                        return(uNodeUtility.WrapTextWithColor(type.PrettyName(), uNodePreference.GetPreference().itemInterfaceColor, false));
                    }
                    return(uNodeUtility.WrapTextWithColor(type.PrettyName(), uNodePreference.GetPreference().itemTypeColor, false));
                }
                switch (member.MemberType)
                {
                case MemberTypes.Method:
                    return(GetRichMethodName(member as MethodInfo, false));

                case MemberTypes.Constructor:
                    return(GetRichConstructorNames(member as ConstructorInfo));
                }
            }
            switch (member.MemberType)
            {
            case MemberTypes.Method:
                return(EditorReflectionUtility.GetOverloadingMethodNames(member as MethodInfo, false));

            case MemberTypes.Constructor:
                return(EditorReflectionUtility.GetOverloadingConstructorNames(member as ConstructorInfo));

            case MemberTypes.TypeInfo:
            case MemberTypes.NestedType:
                return((member as Type).PrettyName());
            }
            return(member.Name);
        }
Beispiel #10
0
 public static List <FieldDecorator> FindDecorators()
 {
     if (_fieldDecorators == null)
     {
         _fieldDecorators = new List <FieldDecorator>();
         foreach (var assembly in EditorReflectionUtility.GetAssemblies())
         {
             try {
                 foreach (System.Type type in EditorReflectionUtility.GetAssemblyTypes(assembly))
                 {
                     if (type.IsSubclassOf(typeof(FieldDecorator)) && ReflectionUtils.CanCreateInstance(type))
                     {
                         var control = ReflectionUtils.CreateInstance(type) as FieldDecorator;
                         _fieldDecorators.Add(control);
                     }
                 }
             }
             catch { continue; }
         }
         _fieldDecorators.Sort((x, y) => CompareUtility.Compare(x.order, y.order));
     }
     return(_fieldDecorators);
 }
Beispiel #11
0
 /// <summary>
 /// Find all available graph converters
 /// </summary>
 /// <returns></returns>
 public static List <GraphConverter> FindGraphConverters()
 {
     if (_graphConverters == null)
     {
         _graphConverters = new List <GraphConverter>();
         foreach (var assembly in EditorReflectionUtility.GetAssemblies())
         {
             try {
                 foreach (System.Type type in EditorReflectionUtility.GetAssemblyTypes(assembly))
                 {
                     if (!type.IsAbstract && type.IsSubclassOf(typeof(GraphConverter)))
                     {
                         var converter = System.Activator.CreateInstance(type, true);
                         _graphConverters.Add(converter as GraphConverter);
                     }
                 }
             }
             catch { continue; }
         }
         _graphConverters.Sort((x, y) => Comparer <int> .Default.Compare(x.order, y.order));
     }
     return(_graphConverters);
 }
Beispiel #12
0
 /// <summary>
 /// Find all graph system attributes.
 /// </summary>
 /// <returns></returns>
 public static List <GraphSystemAttribute> FindGraphSystemAttributes()
 {
     if (_graphSystems == null)
     {
         _graphSystems = new List <GraphSystemAttribute>();
         foreach (var assembly in EditorReflectionUtility.GetAssemblies())
         {
             try {
                 foreach (System.Type type in EditorReflectionUtility.GetAssemblyTypes(assembly))
                 {
                     if (type.IsDefined(typeof(GraphSystemAttribute), false))
                     {
                         var menuItem = (GraphSystemAttribute)type.GetCustomAttributes(typeof(GraphSystemAttribute), false)[0];
                         menuItem.type = type;
                         _graphSystems.Add(menuItem);
                     }
                 }
             }
             catch { continue; }
         }
         _graphSystems.Sort((x, y) => CompareUtility.Compare(x.menu, x.order, y.menu, y.order));
     }
     return(_graphSystems);
 }
Beispiel #13
0
        public override void OnInspectorGUI()
        {
            MultiArithmeticNode node = target as MultiArithmeticNode;

            DrawDefaultInspector();
            VariableEditorUtility.DrawMembers(new GUIContent("Targets"), node.targets, node, new FilterAttribute(typeof(object)),
                                              (obj) => {
                node.targets = obj;
            },
                                              () => {
                uNodeEditorUtility.RegisterUndo(node);
                var type = node.ReturnType();
                if (type != typeof(object) && ReflectionUtils.CanCreateInstance(type))
                {
                    node.targets.Add(new MemberData(ReflectionUtils.CreateInstance(type)));
                }
                else if (node.targets.Count > 0)
                {
                    node.targets.Add(new MemberData(node.targets[node.targets.Count - 1]));
                }
                else
                {
                    node.targets.Add(new MemberData());
                }
            });
            if (GUILayout.Button(new GUIContent("Change Operator")))
            {
                var customItems = new List <ItemSelector.CustomItem>();
                {                //Primitives
                    customItems.AddRange(GetCustomItemForPrimitives(node, typeof(int)));
                    customItems.AddRange(GetCustomItemForPrimitives(node, typeof(float)));
                }
                var ns                 = NodeGraph.GetOpenedGraphUsingNamespaces();
                var preference         = uNodePreference.GetPreference();
                var assemblies         = EditorReflectionUtility.GetAssemblies();
                var includedAssemblies = uNodePreference.GetIncludedAssemblies();
                foreach (var assembly in assemblies)
                {
                    if (!includedAssemblies.Contains(assembly.GetName().Name))
                    {
                        continue;
                    }
                    var operators = EditorReflectionUtility.GetOperators(assembly, (op) => {
                        return(ns == null || ns.Contains(op.DeclaringType.Namespace));
                    });
                    if (operators.Count > 0)
                    {
                        foreach (var op in operators)
                        {
                            switch (op.Name)
                            {
                            case "op_Addition": {
                                var parameters = op.GetParameters();
                                customItems.Add(GetCustomItem(node, parameters[0].ParameterType, parameters[1].ParameterType, op.DeclaringType, op.ReturnType, ArithmeticType.Add));
                                break;
                            }

                            case "op_Subtraction": {
                                var parameters = op.GetParameters();
                                customItems.Add(GetCustomItem(node, parameters[0].ParameterType, parameters[1].ParameterType, op.DeclaringType, op.ReturnType, ArithmeticType.Subtract));
                                break;
                            }

                            case "op_Division": {
                                var parameters = op.GetParameters();
                                customItems.Add(GetCustomItem(node, parameters[0].ParameterType, parameters[1].ParameterType, op.DeclaringType, op.ReturnType, ArithmeticType.Divide));
                                break;
                            }

                            case "op_Multiply": {
                                var parameters = op.GetParameters();
                                customItems.Add(GetCustomItem(node, parameters[0].ParameterType, parameters[1].ParameterType, op.DeclaringType, op.ReturnType, ArithmeticType.Multiply));
                                break;
                            }

                            case "op_Modulus": {
                                var parameters = op.GetParameters();
                                customItems.Add(GetCustomItem(node, parameters[0].ParameterType, parameters[1].ParameterType, op.DeclaringType, op.ReturnType, ArithmeticType.Modulo));
                                break;
                            }
                            }
                        }
                    }
                }
                customItems.Sort((x, y) => {
                    if (x.category == y.category)
                    {
                        return(string.Compare(x.name, y.name));
                    }
                    return(string.Compare(x.category, y.category));
                });
                if (customItems.Count > 0)
                {
                    ItemSelector.ShowWindow(null, null, null, false, customItems).
                    ChangePosition(
                        GUIUtility.GUIToScreenRect(GUILayoutUtility.GetLastRect())
                        ).displayDefaultItem = false;
                }
            }
        }
Beispiel #14
0
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            object variable = PropertyDrawerUtility.GetParentObjectFromSerializedProperty <object>(property);

            if (variable != null)
            {
                if (uNodeGUIUtility.IsHide(fieldInfo, variable))
                {
                    return;
                }
            }
            else
            {
                if (fieldInfo.IsDefined(typeof(HideAttribute), true))
                {
                    HideAttribute[] hide = fieldInfo.GetCustomAttributes(typeof(HideAttribute), true) as HideAttribute[];
                    foreach (HideAttribute ha in hide)
                    {
                        if (string.IsNullOrEmpty(ha.targetField))
                        {
                            return;
                        }
                    }
                }
            }
            if (fieldInfo.IsDefined(typeof(TooltipAttribute), true))
            {
                label.tooltip = ((TooltipAttribute)fieldInfo.GetCustomAttributes(typeof(TooltipAttribute), true)[0]).tooltip;
            }
            System.Type type = fieldInfo.FieldType;
            if (fieldInfo.FieldType.IsArray)
            {
                type = fieldInfo.FieldType.GetElementType();
            }
            else if (fieldInfo.FieldType.IsGenericType)
            {
                System.Type[] gType = fieldInfo.FieldType.GetGenericArguments();
                if (gType.Length == 1)
                {
                    type = gType[0];
                }
            }
            if (type == typeof(MemberData))
            {
                MemberData      obj    = PropertyDrawerUtility.GetActualObjectForSerializedProperty <MemberData>(property);
                FilterAttribute filter = null;
                if (fieldInfo.GetCustomAttributes(typeof(FilterAttribute), false).Length > 0)
                {
                    filter = (FilterAttribute)fieldInfo.GetCustomAttributes(typeof(FilterAttribute), false)[0];
                }
                else if (fieldInfo.IsDefined(typeof(ObjectTypeAttribute), true))
                {
                    var    fieldAttributes = fieldInfo.GetCustomAttributes(true);
                    object pVariable       = PropertyDrawerUtility.GetParentObjectFromSerializedProperty <object>(property);
                    if (pVariable != null && ReflectionUtils.TryCorrectingAttribute(pVariable, ref fieldAttributes))
                    {
                        filter = ReflectionUtils.GetAttribute <FilterAttribute>(fieldAttributes);
                    }
                    else
                    {
                        return;
                    }
                }
                EditorReflectionUtility.RenderVariable(position, obj, label, property.serializedObject.targetObject, filter);
            }
            else
            {
                EditorGUI.PropertyField(position, property, label, true);
            }
        }
        void Setup()
        {
            if (reflectionValue == null)
            {
                reflectionValue = MemberData.none;
            }
            if (filter == null)
            {
                filter = new FilterAttribute()
                {
                    UnityReference = false, OnlyGetType = onlyGetType
                };
            }
            if (onlyGetType)
            {
                filter = new FilterAttribute(filter)
                {
                    OnlyGetType = onlyGetType
                }
            }
            ;
            if (filter.OnlyGetType)
            {
                filter.ValidTargetType = MemberData.TargetType.Type | MemberData.TargetType.Null;
            }
            if (targetObject)
            {
                uNodeRoot UNR = null;
                if (targetObject is uNodeRoot)
                {
                    UNR = targetObject as uNodeRoot;
                }
                else if (targetObject is RootObject)
                {
                    UNR = (targetObject as RootObject).owner;
                }
                else if (targetObject is NodeComponent)
                {
                    UNR = (targetObject as NodeComponent).owner;
                }
                else if (targetObject is TransitionEvent)
                {
                    UNR = (targetObject as TransitionEvent).owner;
                }
                if (UNR)
                {
                    uNodeData data = UNR.GetComponent <uNodeData>();
                    if (data)
                    {
                        //Clear the default namespace
                        usingNamespaces.Clear();
                        //Add graph namespaces
                        foreach (var n in data.GetNamespaces())
                        {
                            usingNamespaces.Add(n);
                        }
                    }
                    if (UNR is IIndependentGraph graph)
                    {
                        if (data == null)
                        {
                            //Clear the default namespace
                            usingNamespaces.Clear();
                        }
                        foreach (var n in graph.UsingNamespaces)
                        {
                            usingNamespaces.Add(n);
                        }
                    }
                }
            }
            editorData.manager        = new Manager(new TreeViewState());
            editorData.manager.window = this;
            editorData.searchField    = new SearchField();
            editorData.searchField.downOrUpArrowKeyPressed  += editorData.manager.SetFocusAndEnsureSelectedItem;
            editorData.searchField.autoSetFocusOnFindCommand = true;
            window = this;
            uNodeThreadUtility.Queue(DoSetup);
        }

        void DoSetup()
        {
            editorData.setup.Setup((progress) => {
                if (progress == 1)
                {
                    uNodeThreadUtility.Queue(() => {
                        var categories = new List <TreeViewItem>();
                        if (displayDefaultItem)
                        {
                            var categoryTree = new SelectorCategoryTreeView("#", "", uNodeEditorUtility.GetUIDFromString("[CATEG]#"), -1);
                            categories.Add(categoryTree);
                            var recentTree = new SelectorCategoryTreeView("Recently", "", uNodeEditorUtility.GetUIDFromString("[CATEG]#Recently"), -1);
                            categories.Add(recentTree);
                            if (displayNoneOption && filter.IsValidTarget(MemberData.TargetType.None))
                            {
                                categoryTree.AddChild(new SelectorMemberTreeView(MemberData.none, "None", uNodeEditorUtility.GetUIDFromString("#None"))
                                {
                                    icon = uNodeEditorUtility.GetTypeIcon(typeof(TypeIcons.NullTypeIcon)) as Texture2D
                                });
                            }
                            if (!filter.SetMember)
                            {
                                if (!filter.IsValueTypes() && filter.IsValidTarget(MemberData.TargetType.Null) && !filter.OnlyGetType)
                                {
                                    categoryTree.AddChild(new SelectorMemberTreeView(MemberData.Null, "Null", uNodeEditorUtility.GetUIDFromString("#Null"))
                                    {
                                        icon = uNodeEditorUtility.GetTypeIcon(typeof(TypeIcons.NullTypeIcon)) as Texture2D
                                    });
                                }
                                //if(!filter.OnlyGetType && filter.IsValidTarget(MemberData.TargetType.Values) &&
                                //	(filter.Types == null || filter.Types.Count != 1 || filter.Types[0] != typeof(Type))) {
                                //	categoryTree.AddChild(new SelectorCallbackTreeView((cRect) => {
                                //		var screenRect = cRect.ToScreenRect();
                                //		FilterAttribute F = new FilterAttribute(filter);
                                //		F.OnlyGetType = true;
                                //		ItemSelector w = null;
                                //		Action<MemberData> action = delegate (MemberData m) {
                                //			if(w != null) {
                                //				w.Close();
                                //				//EditorGUIUtility.ExitGUI();
                                //			}
                                //			if(filter.CanManipulateArray()) {
                                //				if(Event.current.button == 0) {
                                //					TypeSelectorWindow.ShowAsNew(Rect.zero, F, delegate (MemberData[] members) {
                                //						Type t = members[0].Get<Type>();
                                //						SelectValues(t);
                                //					}, m).ChangePosition(screenRect);
                                //				} else {
                                //					CommandWindow.CreateWindow(screenRect, (items) => {
                                //						var member = CompletionEvaluator.CompletionsToMemberData(items);
                                //						if(member != null) {
                                //							Type t = member.Get<Type>();
                                //							SelectValues(t);
                                //							return true;
                                //						}
                                //						return false;
                                //					}, new CompletionEvaluator.CompletionSetting() {
                                //						validCompletionKind = CompletionKind.Type | CompletionKind.Namespace | CompletionKind.Keyword,
                                //					});
                                //				}
                                //			} else {
                                //				Type t = m.Get<Type>();
                                //				SelectValues(t);
                                //			}
                                //		};
                                //		w = ShowAsNew(targetObject, F, action, true).ChangePosition(screenRect);
                                //	}, "Values", uNodeEditorUtility.GetUIDFromString("#Values"), -1) {
                                //		icon = uNodeEditorUtility.GetTypeIcon(typeof(TypeIcons.ValueIcon)) as Texture2D
                                //	});
                                //}
                            }
                            if (displayRecentItem)
                            {
                                var listRecentItems = new List <TreeViewItem>();
                                if (uNodeEditor.SavedData.recentItems != null)
                                {
                                    foreach (var recent in uNodeEditor.SavedData.recentItems)
                                    {
                                        if (recent != null && recent.info != null)
                                        {
                                            if (recent.info is Type)
                                            {
                                                listRecentItems.Add(new TypeTreeView(recent.info as Type, recent.GetHashCode(), -1));
                                            }
                                            else if (!filter.OnlyGetType && (recent.isStatic || filter.DisplayInstanceOnStatic))
                                            {
                                                listRecentItems.Add(new MemberTreeView(recent.info, recent.GetHashCode(), -1));
                                            }
                                        }
                                    }
                                }
                                while (listRecentItems.Count > 10)
                                {
                                    listRecentItems.RemoveAt(listRecentItems.Count - 1);
                                }
                                if (listRecentItems.Count > 0)
                                {
                                    foreach (var item in listRecentItems)
                                    {
                                        if (item is MemberTreeView)
                                        {
                                            var tree = item as MemberTreeView;
                                            if (!(tree.member is Type))
                                            {
                                                tree.displayName = tree.member.DeclaringType.Name + "." + tree.displayName;
                                            }
                                        }
                                        recentTree.AddChild(item);
                                    }
                                    recentTree.expanded = false;
                                }
                            }
                            if (!filter.OnlyGetType && filter.UnityReference)
                            {
                                if (reflectionValue != null && reflectionValue.GetInstance() != null && !(reflectionValue.GetInstance() is IGraphSystem) && !(reflectionValue.GetInstance() is INode))
                                {
                                    categories.Add(TreeFunction.CreateTargetItem(reflectionValue.GetInstance(), "Target Reference", filter));
                                }
                                categories.AddRange(TreeFunction.CreateGraphItem(targetObject, reflectionValue, filter));
                            }
                            if (filter.UnityReference)
                            {
                                categories.AddRange(TreeFunction.CreateRootItem(targetObject, filter));
                            }
                            categories.AddRange(TreeFunction.CreateCustomItem(customItems));
                            if (filter.DisplayDefaultStaticType)
                            {
                                categoryTree.AddChild(new SelectorGroupedTreeView(() => {
                                    var result = new List <TreeViewItem>();
                                    result.Add(new SelectorSearchTreeView((prog) => {
                                        var treeResult = new List <TreeViewItem>();
                                        var sp         = new SearchProgress();
                                        prog?.Invoke(sp);
                                        var allTypes = GetAllTypes((currProgress) => {
                                            prog?.Invoke(currProgress);
                                        }, true, true);
                                        sp.info = "Setup Items";
                                        for (int i = 0; i < allTypes.Count; i++)
                                        {
                                            var pair   = allTypes[i];
                                            var nsTree = new SelectorCategoryTreeView(pair.Key, "", uNodeEditorUtility.GetUIDFromString("[CATEG-SEARCH]" + pair.Key), -1);
                                            foreach (var type in pair.Value)
                                            {
                                                nsTree.AddChild(new TypeTreeView(type, type.GetHashCode(), -1));
                                            }
                                            treeResult.Add(nsTree);
                                            sp.progress = (float)i / (float)allTypes.Count;
                                            prog?.Invoke(sp);
                                        }
                                        return(treeResult);
                                    }, "Search All Types", uNodeEditorUtility.GetUIDFromString("[SAT]"), -1));
                                    var nestedNS = new HashSet <string>();
                                    //var excludedNs = uNodePreference.GetExcludedNamespace();
                                    var namespaces = new List <string>(EditorReflectionUtility.GetNamespaces());
                                    namespaces.Sort();
                                    namespaces.RemoveAll(i => /*excludedNs.Contains(i) ||*/ i == null || i.Contains("."));
                                    foreach (var ns in namespaces)
                                    {
                                        result.Add(new NamespaceTreeView(ns, uNodeEditorUtility.GetUIDFromString("[N]" + ns), -1));
                                    }
                                    //var nsTypes = GetNamespaceTypes(namespaces);
                                    //foreach(var pair in nsTypes) {
                                    //	var nsTree = new SelectorCategoryTreeView(pair.Key, "", uNodeEditorUtility.GetUIDFromString("[Nested-NS]" + pair.Key), -1);
                                    //	foreach(var ns in nestedNS) {
                                    //		if(ns.StartsWith(pair.Key)) {
                                    //			nsTree.AddChild(new NamespaceTreeView(ns, uNodeEditorUtility.GetUIDFromString("[N]" + ns), -1));
                                    //		}
                                    //	}
                                    //	foreach(var type in pair.Value) {
                                    //		nsTree.AddChild(new TypeTreeView(type, type.GetHashCode(), -1));
                                    //	}
                                    //	//nsTree.children.Sort((x, y) => string.Compare(x.displayName, y.displayName));
                                    //	nsTree.expanded = false;
                                    //	result.Add(nsTree);
                                    //}
                                    return(result);
                                }, "All Namespaces", uNodeEditorUtility.GetUIDFromString("[ALL-NS]"), -1)
                                {
                                    icon = uNodeEditorUtility.GetTypeIcon(typeof(TypeIcons.NamespaceIcon)) as Texture2D
                                });
                                categoryTree.AddChild(new SelectorGroupedTreeView(() => {
                                    var result    = new List <TreeViewItem>();
                                    var favorites = uNodeEditor.SavedData.favoriteItems;
                                    if (favorites != null)                                     //Favorite Type and Members
                                    {
                                        var typeTrees   = new List <TypeTreeView>();
                                        var memberTrees = new List <MemberTreeView>();
                                        foreach (var fav in favorites)
                                        {
                                            if (fav.info != null && window.filter.IsValidMember(fav.info))
                                            {
                                                if (fav.info is Type type)
                                                {
                                                    typeTrees.Add(new TypeTreeView(type));
                                                }
                                                else
                                                {
                                                    var tree         = new MemberTreeView(fav.info);
                                                    tree.displayName = tree.member.DeclaringType.Name + "." + tree.displayName;
                                                    memberTrees.Add(tree);
                                                }
                                            }
                                        }
                                        typeTrees.Sort((x, y) => string.Compare(x.displayName, y.displayName));
                                        memberTrees.Sort((x, y) => string.Compare(x.displayName, y.displayName));
                                        var typeCategory = new SelectorCategoryTreeView("Types", "", uNodeEditorUtility.GetUIDFromString("[TYPES]"), -1);
                                        foreach (var tree in typeTrees)
                                        {
                                            typeCategory.AddChild(tree);
                                        }
                                        var memberCategory = new SelectorCategoryTreeView("Members", "", uNodeEditorUtility.GetUIDFromString("[MEMBERS]"), -1);
                                        foreach (var tree in memberTrees)
                                        {
                                            memberCategory.AddChild(tree);
                                        }
                                        if (typeCategory.hasChildren)
                                        {
                                            result.Add(typeCategory);
                                        }
                                        if (memberCategory.hasChildren)
                                        {
                                            result.Add(memberCategory);
                                        }
                                    }
                                    {                                    //Favorite Namespaces
                                        var nsTrees = new List <NamespaceTreeView>();
                                        foreach (var fav in uNodeEditor.SavedData.favoriteNamespaces)
                                        {
                                            nsTrees.Add(new NamespaceTreeView(fav, uNodeEditorUtility.GetUIDFromString("[NS-FAV]" + fav), -1));
                                        }
                                        nsTrees.Sort((x, y) => string.Compare(x.displayName, y.displayName));
                                        var nsCategory = new SelectorCategoryTreeView("Namespaces", "", uNodeEditorUtility.GetUIDFromString("[NS]"), -1);
                                        foreach (var tree in nsTrees)
                                        {
                                            nsCategory.AddChild(tree);
                                        }
                                        if (nsCategory.hasChildren)
                                        {
                                            result.Add(nsCategory);
                                        }
                                    }
                                    return(result);
                                }, "Favorites", uNodeEditorUtility.GetUIDFromString("[fav]"), -1)
                                {
                                    icon = uNodeGUIUtility.Styles.favoriteIconOn
                                });
                                var namespaceTrees = new SelectorCategoryTreeView("Types", "", uNodeEditorUtility.GetUIDFromString("[NS]"), -1);
                                if (displayGeneralType)
                                {
                                    var categTree = new SelectorCategoryTreeView("General", "", uNodeEditorUtility.GetUIDFromString("[GENERAL]"), -1);
                                    var items     = TreeFunction.GetGeneralTrees();
                                    items.ForEach(tree => categTree.AddChild(tree));
                                    namespaceTrees.AddChild(categTree);
                                }
                                if (filter.DisplayRuntimeType)
                                {
                                    var runtimeItems = TreeFunction.GetRuntimeItems();
                                    var runtimeTypes = new Dictionary <string, List <TypeTreeView> >();
                                    foreach (var item in runtimeItems)
                                    {
                                        var ns = item.type.Namespace;
                                        if (string.IsNullOrEmpty(ns) || ns == RuntimeType.RuntimeNamespace)
                                        {
                                            ns = "Generated Type";
                                        }
                                        List <TypeTreeView> list;
                                        if (!runtimeTypes.TryGetValue(ns, out list))
                                        {
                                            list             = new List <TypeTreeView>();
                                            runtimeTypes[ns] = list;
                                        }
                                        list.Add(item);
                                    }
                                    foreach (var pair in runtimeTypes)
                                    {
                                        var categTree = new SelectorCategoryTreeView(pair.Key, "", uNodeEditorUtility.GetUIDFromString("[RT]" + pair.Key), -1);
                                        var items     = pair.Value;
                                        items.ForEach(tree => categTree.AddChild(tree));
                                        namespaceTrees.AddChild(categTree);
                                    }
                                }
                                var typeList = editorData.setup.typeList;
                                foreach (var pair in typeList)
                                {
                                    var nsTree = new SelectorCategoryTreeView(pair.Key, "", uNodeEditorUtility.GetUIDFromString("[CATEG]" + pair.Key), -1);
                                    foreach (var type in pair.Value)
                                    {
                                        nsTree.AddChild(new TypeTreeView(type, type.GetHashCode(), -1));
                                    }
                                    namespaceTrees.AddChild(nsTree);
                                }
                                categories.Add(namespaceTrees);
                            }
                        }
Beispiel #16
0
        public static Assembly CompileFromFile(params string[] files)
        {
            var csharpParserType = EditorBinding.csharpParserType;

            if (csharpParserType != null)
            {
                //var method = csharpParserType.GetMethod("CompileScript", new Type[] { typeof(IEnumerable<string>) });
                //if(method != null) {
                //	List<string> scripts = new List<string>();
                //	foreach(var file in files) {
                //		scripts.Add(File.ReadAllText(file));
                //	}
                //	var compileResult = method.Invoke(null, new object[] { scripts as IEnumerable<string> }) as CompileResult;
                //	if(compileResult.assembly == null) {
                //		//compileResult.LogErrors();
                //		throw new Exception(compileResult.GetErrorMessage());
                //	}
                //	return compileResult.assembly;
                //}
                var method = csharpParserType.GetMethod("CompileFiles", new Type[] { typeof(IEnumerable <string>) });
                if (method != null)
                {
                    var compileResult = method.Invoke(null, new object[] { files as IEnumerable <string> }) as CompileResult;
                    if (compileResult.assembly == null)
                    {
                        //compileResult.LogErrors();
                        throw new Exception(compileResult.GetErrorMessage());
                    }
                    return(compileResult.assembly);
                }
            }
#if !NET_STANDARD_2_0
            var provider = new Microsoft.CSharp.CSharpCodeProvider();
            var param    = new System.CodeDom.Compiler.CompilerParameters();
            foreach (var assembly in EditorReflectionUtility.GetAssemblies())
            {
                try {
                    if (!string.IsNullOrEmpty(assembly.Location))
                    {
                        param.ReferencedAssemblies.Add(assembly.Location);
                    }
                } catch { continue; }
            }
            // Generate a dll in memory
            param.GenerateExecutable      = false;
            param.GenerateInMemory        = true;
            param.TreatWarningsAsErrors   = false;
            param.IncludeDebugInformation = true;
            //No Waring
            //param.WarningLevel = 0;
            // Compile the source
            var result = provider.CompileAssemblyFromFile(param, files);
            if (result.Errors.Count > 0)
            {
                var  msg      = new System.Text.StringBuilder();
                bool hasError = false;
                foreach (System.CodeDom.Compiler.CompilerError error in result.Errors)
                {
                    //Debug.LogError("Error (" + error.ErrorNumber + "): " + error.ErrorText + "\n");
                    if (error.IsWarning)
                    {
                        Debug.LogWarningFormat("Warning ({0}): {1}\nin line: {2}",
                                               error.ErrorNumber, error.ErrorText, error.Line);
                    }
                    else
                    {
                        hasError = true;
                        msg.AppendFormat("Error ({0}): {1}\nin line: {2}:{3}\nin file:{4}\n", error.ErrorNumber, error.ErrorText, error.Line, error.Column, error.FileName);
                    }
                }
                if (hasError)
                {
                    throw new Exception(msg.ToString());
                }
            }

            // Return the assembly
            return(result.CompiledAssembly);
#else
            Debug.Log("Compiling script is disable due to unsupported in .NET Standard 2.0, change API compativility level to .NET 4.x to enable it or import CSharp Parser add-ons to compile with Roslyn instead.");
            return(null);
#endif
        }
Beispiel #17
0
        public static CompileResult CompileScript(params string[] source)
        {
            var csharpParserType = EditorBinding.csharpParserType;

            if (csharpParserType != null)
            {
                var method = csharpParserType.GetMethod("CompileScript", new Type[] { typeof(IEnumerable <string>) });
                if (method != null)
                {
                    return(method.Invoke(null, new object[] { source as IEnumerable <string> }) as CompileResult);
                }
            }
#if !NET_STANDARD_2_0
            var provider = new Microsoft.CSharp.CSharpCodeProvider();
            var param    = new System.CodeDom.Compiler.CompilerParameters();
            foreach (var assembly in EditorReflectionUtility.GetAssemblies())
            {
                try {
                    if (!string.IsNullOrEmpty(assembly.Location))
                    {
                        param.ReferencedAssemblies.Add(assembly.Location);
                    }
                } catch { continue; }
            }
            // Generate a dll in memory
            param.GenerateExecutable      = false;
            param.GenerateInMemory        = true;
            param.TreatWarningsAsErrors   = false;
            param.IncludeDebugInformation = true;
            Directory.CreateDirectory(tempGeneratedFolder);
            param.TempFiles = new System.CodeDom.Compiler.TempFileCollection(tempGeneratedFolder, true);
            //No Waring
            //param.WarningLevel = 0;
            // Compile the source
            var result = provider.CompileAssemblyFromSource(param, source);

            List <CompileResult.CompileError> compileErrors = new List <CompileResult.CompileError>();
            if (result.Errors.Count > 0)
            {
                foreach (System.CodeDom.Compiler.CompilerError error in result.Errors)
                {
                    compileErrors.Add(new CompileResult.CompileError()
                    {
                        fileName    = error.FileName,
                        isWarning   = error.IsWarning,
                        errorText   = error.ErrorText,
                        errorNumber = error.ErrorNumber,
                        errorLine   = error.Line,
                        errorColumn = error.Column,
                    });
                }
            }

            // Return the assembly
            return(new CompileResult()
            {
                assembly = result.CompiledAssembly,
                errors = compileErrors,
            });
#else
            Debug.Log("Compiling script is disable due to unsupported in .NET Standard 2.0, change API compativility level to .NET 4.x to enable it or import CSharp Parser add-ons to compile with Roslyn instead.");
            return(new CompileResult());
#endif
        }
Beispiel #18
0
        public override IList <ItemSelector.CustomItem> GetItems(Node source, MemberData data, System.Type type)
        {
            var items = new List <ItemSelector.CustomItem>();

            if (type.IsPrimitive && type != typeof(bool) && type != typeof(char))
            {
                string typeName = type.PrettyName();
                items.Add(new ItemSelector.CustomItem(string.Format("Add ({0}, {0})", typeName), () => {
                    NodeEditorUtility.AddNewNode(graph.editorData, null, null, mousePositionOnCanvas, (MultiArithmeticNode n) => {
                        n.targets[0]   = data;
                        n.targets[1]   = new MemberData(ReflectionUtils.CreateInstance(type));
                        n.operatorType = ArithmeticType.Add;
                        graph.Refresh();
                    });
                }, "Operator")
                {
                    icon = uNodeEditorUtility.GetTypeIcon(type)
                });
                items.Add(new ItemSelector.CustomItem(string.Format("Subtract ({0}, {0})", typeName), () => {
                    NodeEditorUtility.AddNewNode(graph.editorData, null, null, mousePositionOnCanvas, (MultiArithmeticNode n) => {
                        n.targets[0]   = data;
                        n.targets[1]   = new MemberData(ReflectionUtils.CreateInstance(type));
                        n.operatorType = ArithmeticType.Subtract;
                        graph.Refresh();
                    });
                }, "Operator")
                {
                    icon = uNodeEditorUtility.GetTypeIcon(type)
                });
                items.Add(new ItemSelector.CustomItem(string.Format("Divide ({0}, {0})", typeName), () => {
                    NodeEditorUtility.AddNewNode(graph.editorData, null, null, mousePositionOnCanvas, (MultiArithmeticNode n) => {
                        n.targets[0]   = data;
                        n.targets[1]   = new MemberData(ReflectionUtils.CreateInstance(type));
                        n.operatorType = ArithmeticType.Divide;
                        graph.Refresh();
                    });
                }, "Operator")
                {
                    icon = uNodeEditorUtility.GetTypeIcon(type)
                });
                items.Add(new ItemSelector.CustomItem(string.Format("Multiply ({0}, {0})", typeName), () => {
                    NodeEditorUtility.AddNewNode(graph.editorData, null, null, mousePositionOnCanvas, (MultiArithmeticNode n) => {
                        n.targets[0]   = data;
                        n.targets[1]   = new MemberData(ReflectionUtils.CreateInstance(type));
                        n.operatorType = ArithmeticType.Multiply;
                        graph.Refresh();
                    });
                }, "Operator")
                {
                    icon = uNodeEditorUtility.GetTypeIcon(type)
                });
                items.Add(new ItemSelector.CustomItem(string.Format("Modulo ({0}, {0})", typeName), () => {
                    NodeEditorUtility.AddNewNode(graph.editorData, null, null, mousePositionOnCanvas, (MultiArithmeticNode n) => {
                        n.targets[0]   = data;
                        n.targets[1]   = new MemberData(ReflectionUtils.CreateInstance(type));
                        n.operatorType = ArithmeticType.Modulo;
                        graph.Refresh();
                    });
                }, "Operator")
                {
                    icon = uNodeEditorUtility.GetTypeIcon(type)
                });
            }

            var preference         = uNodePreference.GetPreference();
            var assemblies         = EditorReflectionUtility.GetAssemblies();
            var includedAssemblies = uNodePreference.GetIncludedAssemblies();
            var ns = graph.editorData.GetNamespaces();

            foreach (var assembly in assemblies)
            {
                if (!includedAssemblies.Contains(assembly.GetName().Name))
                {
                    continue;
                }
                var operators = EditorReflectionUtility.GetOperators(assembly, (op) => {
                    return(ns.Contains(op.DeclaringType.Namespace));
                });
                if (operators.Count > 0)
                {
                    foreach (var op in operators)
                    {
                        switch (op.Name)
                        {
                        case "op_Addition": {
                            var parameters = op.GetParameters();
                            if (parameters[0].ParameterType != type && parameters[1].ParameterType != type)
                            {
                                break;
                            }
                            items.Add(GetItem(type, parameters[0].ParameterType, parameters[1].ParameterType, op.ReturnType, data, ArithmeticType.Add));
                            break;
                        }

                        case "op_Subtraction": {
                            var parameters = op.GetParameters();
                            if (parameters[0].ParameterType != type && parameters[1].ParameterType != type)
                            {
                                break;
                            }
                            items.Add(GetItem(type, parameters[0].ParameterType, parameters[1].ParameterType, op.ReturnType, data, ArithmeticType.Subtract));
                            break;
                        }

                        case "op_Division": {
                            var parameters = op.GetParameters();
                            if (parameters[0].ParameterType != type && parameters[1].ParameterType != type)
                            {
                                break;
                            }
                            items.Add(GetItem(type, parameters[0].ParameterType, parameters[1].ParameterType, op.ReturnType, data, ArithmeticType.Divide));
                            break;
                        }

                        case "op_Multiply": {
                            var parameters = op.GetParameters();
                            if (parameters[0].ParameterType != type && parameters[1].ParameterType != type)
                            {
                                break;
                            }
                            items.Add(GetItem(type, parameters[0].ParameterType, parameters[1].ParameterType, op.ReturnType, data, ArithmeticType.Multiply));
                            break;
                        }

                        case "op_Modulus": {
                            var parameters = op.GetParameters();
                            if (parameters[0].ParameterType != type && parameters[1].ParameterType != type)
                            {
                                break;
                            }
                            items.Add(GetItem(type, parameters[0].ParameterType, parameters[1].ParameterType, op.ReturnType, data, ArithmeticType.Modulo));
                            break;
                        }
                        }
                    }
                }
            }
            items.Sort((x, y) => string.Compare(x.name, y.name));
            return(items);
        }
Beispiel #19
0
        private void ResolveMethodTooltip(MethodBase methodBase, int numOfOverload, List <GUIContent> contents)
        {
            if (methodBase is MethodInfo)
            {
                contents.Add(new GUIContent(
                                 EditorReflectionUtility.GetOverloadingMethodNames(methodBase as MethodInfo),
                                 uNodeEditorUtility.GetIcon(methodBase)));
            }
            else if (methodBase is ConstructorInfo)
            {
                contents.Add(new GUIContent(
                                 EditorReflectionUtility.GetOverloadingConstructorNames(methodBase as ConstructorInfo),
                                 uNodeEditorUtility.GetIcon(methodBase)));
            }
            var mType = ReflectionUtils.GetMemberType(methodBase);

            #region Docs
            if (uNodePreference.GetPreference().showDocumentation&& XmlDoc.hasLoadDoc)
            {
                XmlElement documentation = XmlDoc.XMLFromMember(methodBase);
                if (documentation != null)
                {
                    contents.Add(new GUIContent("Documentation ▼ " + documentation["summary"].InnerText.Trim().AddLineInFirst()));
                }
                var parameters = methodBase.GetParameters();
                if (parameters.Length > 0)
                {
                    for (int x = 0; x < parameters.Length; x++)
                    {
                        Type PType = parameters[x].ParameterType;
                        if (PType != null)
                        {
                            contents.Add(new GUIContent(parameters[x].Name + " : " +
                                                        uNodeUtility.GetDisplayName(PType),
                                                        uNodeEditorUtility.GetTypeIcon(PType)));
                            if (documentation != null && documentation["param"] != null)
                            {
                                XmlNode paramDoc = null;
                                XmlNode doc      = documentation["param"];
                                while (doc.NextSibling != null)
                                {
                                    if (doc.Attributes["name"] != null && doc.Attributes["name"].Value.Equals(parameters[x].Name))
                                    {
                                        paramDoc = doc;
                                        break;
                                    }
                                    doc = doc.NextSibling;
                                }
                                if (paramDoc != null && !string.IsNullOrEmpty(paramDoc.InnerText))
                                {
                                    contents.Add(new GUIContent(paramDoc.InnerText.Trim()));
                                }
                            }
                        }
                    }
                }
            }
            #endregion
            //contents.Add(new GUIContent("Return	: " + mType.PrettyName(true), uNodeEditorUtility.GetTypeIcon(mType)));
            if (numOfOverload > 0)
            {
                contents.Add(new GUIContent("▲ " + (overrideIndex + 1).ToString() + " of " + numOfOverload + " ▼"));
            }
        }
Beispiel #20
0
        void InitializeView()
        {
            if (data.block == null)
            {
                return;
            }
            if (data.block is Events.HLAction || data.block is Events.HLCondition)
            {
                InitializeHLBlock(data.block);
                return;
            }
            var fields = EditorReflectionUtility.GetFields(data.block.GetType());

            if (fields != null && fields.Length > 0)
            {
                for (int idx = 0; idx < fields.Length; idx++)
                {
                    FieldInfo field = fields[idx];
                    if (uNodeGUIUtility.IsHide(field, data.block))
                    {
                        continue;
                    }
                    Type type = field.FieldType;
                    if (type == typeof(MemberData))
                    {
                        MemberData member         = field.GetValueOptimized(data.block) as MemberData;
                        object[]   fieldAttribute = field.GetCustomAttributes(true);
                        if (!ReflectionUtils.TryCorrectingAttribute(data.block, ref fieldAttribute))
                        {
                            continue;
                        }
                        var filter = ReflectionUtils.GetAttribute <FilterAttribute>(fieldAttribute);
                        if (member == null)
                        {
                            if (filter != null && !filter.SetMember && !filter.OnlyGetType && ReflectionUtils.CanCreateInstance(filter.GetActualType()))
                            {
                                member = new MemberData(ReflectionUtils.CreateInstance(filter.GetActualType()));
                            }
                            else if (filter != null && !filter.SetMember && !filter.OnlyGetType)
                            {
                                member = MemberData.none;
                            }
                            field.SetValueOptimized(data.block, member);
                            Repaint();
                        }
                        bool hasDependencies = EditorReflectionUtility.HasFieldDependencies(new string[] { field.Name }, fields);
                        var  port            = AddPort(new PortData()
                        {
                            getPortName    = () => ObjectNames.NicifyVariableName(field.Name),
                            getPortType    = () => filter?.GetActualType() ?? typeof(object),
                            getPortValue   = () => field.GetValueOptimized(data.block),
                            filter         = filter,
                            onValueChanged = (obj) => {
                                RegisterUndo();
                                member = obj as MemberData;
                                field.SetValueOptimized(data.block, member);
                                Repaint();
                                if (hasDependencies)
                                {
                                    owner.nodeView.MarkRepaint();
                                }
                            },
                        });
                        port.Add(new ControlView(port.portData.InstantiateControl(true), true));
                    }
                    else if (type == typeof(MultipurposeMember))
                    {
                        InitMultipurposeMember(field);
                    }
                    else
                    {
                        object   fieldVal       = field.GetValueOptimized(data.block);
                        object[] fieldAttribute = field.GetCustomAttributes(true);
                        if (!ReflectionUtils.TryCorrectingAttribute(data.block, ref fieldAttribute))
                        {
                            continue;
                        }
                        bool          hasDependencies = EditorReflectionUtility.HasFieldDependencies(new string[] { field.Name }, fields);
                        var           filter          = ReflectionUtils.GetAttribute <FilterAttribute>(fieldAttribute);
                        ControlConfig config          = new ControlConfig()
                        {
                            owner          = owner.nodeView,
                            value          = fieldVal,
                            type           = type,
                            filter         = filter,
                            onValueChanged = (obj) => {
                                RegisterUndo();
                                field.SetValueOptimized(data.block, obj);
                                Repaint();
                                if (hasDependencies)
                                {
                                    owner.nodeView.MarkRepaint();
                                }
                            },
                        };
                        var valueControl = UIElementUtility.CreateControl(type, config, true);
                        AddControl(field.Name, new ControlView(valueControl, true));
                        if (fieldVal is IList <MemberData> )
                        {
                            IList <MemberData> members = fieldVal as IList <MemberData>;
                            if (members != null)
                            {
                                for (int i = 0; i < members.Count; i++)
                                {
                                    int index  = i;
                                    var member = members[i];
                                    if (member == null)
                                    {
                                        if (filter != null && !filter.SetMember && !filter.OnlyGetType &&
                                            ReflectionUtils.CanCreateInstance(filter.GetActualType()))
                                        {
                                            member = new MemberData(ReflectionUtils.CreateInstance(filter.GetActualType()));
                                        }
                                        else
                                        {
                                            member = MemberData.none;
                                        }
                                        members[index] = member;
                                        field.SetValueOptimized(data.block, members);
                                        Repaint();
                                    }
                                    var port = AddPort(new PortData()
                                    {
                                        getPortName    = () => "Element " + index.ToString(),
                                        getPortType    = () => filter?.GetActualType() ?? typeof(object),
                                        getPortValue   = () => (field.GetValueOptimized(data.block) as IList <MemberData>)[index],
                                        filter         = filter,
                                        onValueChanged = (obj) => {
                                            RegisterUndo();
                                            member         = obj as MemberData;
                                            members[index] = member;
                                            field.SetValueOptimized(data.block, members);
                                            Repaint();
                                        },
                                    });
                                    port.Add(new ControlView(port.portData.InstantiateControl(true), true));
                                }
                            }
                        }
                        else if (fieldVal is IList)
                        {
                            IList list = fieldVal as IList;
                            if (list != null)
                            {
                                for (int i = 0; i < list.Count; i++)
                                {
                                    int           index   = i;
                                    var           element = list[i];
                                    ControlConfig cfg     = new ControlConfig()
                                    {
                                        owner          = owner.nodeView,
                                        value          = fieldVal,
                                        type           = type,
                                        filter         = filter,
                                        onValueChanged = (obj) => {
                                            RegisterUndo();
                                            field.SetValueOptimized(data.block, obj);
                                            Repaint();
                                        },
                                    };
                                    var elementControl = UIElementUtility.CreateControl(type, cfg, true);
                                    AddControl("Element " + index, new ControlView(elementControl, true));
                                }
                            }
                        }
                    }
                }
            }
        }
Beispiel #21
0
        public void Init()
        {
            //int typeCount = 0;
            Dictionary <string, List <Type> > typeMaps = new Dictionary <string, List <Type> >();
            var namespaces    = uNodePreference.GetBrowserNamespaceList();
            var excludedNS    = uNodePreference.GetExcludedNamespace();
            var excludedTypes = uNodePreference.GetExcludedTypes();

            foreach (var assembly in EditorReflectionUtility.GetAssemblies())
            {
                string assemblyName = assembly.GetName().Name;
                foreach (var type in EditorReflectionUtility.GetAssemblyTypes(assembly))
                {
                    if (type.IsNotPublic ||
                        !type.IsVisible ||
                        type.IsEnum ||
                        type.IsInterface ||
                        type.IsCOMObject ||
                        type.IsAutoClass ||
                        type.IsGenericType ||
                        type.Name.StartsWith("<") ||
                        type.IsCastableTo(typeof(Delegate)) ||
                        type.IsDefined(typeof(ObsoleteAttribute), true) ||
                        excludedTypes.Contains(type.FullName))
                    {
                        continue;
                    }
                    string ns = type.Namespace;
                    //if(ns.StartsWith("Unity.") || ns.Contains("Experimental") || ns.Contains("Internal")) {
                    //	continue;
                    //}
                    if (string.IsNullOrEmpty(ns))
                    {
                        ns = "global";
                    }
                    else if (!namespaces.Contains(ns))
                    {
                        continue;
                    }
                    if (excludedNS.Contains(ns))
                    {
                        continue;
                    }
                    List <Type> types;
                    if (!typeMaps.TryGetValue(ns, out types))
                    {
                        types        = new List <Type>();
                        typeMaps[ns] = types;
                    }
                    types.Add(type);
                    //typeCount++;
                }
            }
            //this.typeCount = typeCount;
            typeList = typeMaps.ToList();
            foreach (var list in typeList)
            {
                list.Value.Sort((x, y) => string.Compare(x.Name, y.Name));
            }
            typeList.Sort((x, y) => {
                if (x.Key == "global")
                {
                    if (y.Key == "global")
                    {
                        return(0);
                    }
                    return(-1);
                }
                else if (y.Key == "global")
                {
                    return(1);
                }
                if (x.Key.StartsWith("Unity"))
                {
                    if (y.Key.StartsWith("Unity"))
                    {
                        return(string.Compare(x.Key, y.Key));
                    }
                    return(-1);
                }
                else if (y.Key.StartsWith("Unity"))
                {
                    return(1);
                }
                return(string.Compare(x.Key, y.Key));
            });
        }
Beispiel #22
0
        public override IList <ItemSelector.CustomItem> GetItems(Node source, MemberData data, System.Type type)
        {
            var items = new List <ItemSelector.CustomItem>();

            if (type.IsPrimitive && type != typeof(bool) && type != typeof(char))             //Primitives
            {
                items.AddRange(GetCustomItemForPrimitives(type, data));
            }
            else
            {
                items.Add(GetItem(type, type, type, typeof(bool), data, ComparisonType.Equal));
                items.Add(GetItem(type, type, type, typeof(bool), data, ComparisonType.NotEqual));
            }
            var preference         = uNodePreference.GetPreference();
            var assemblies         = EditorReflectionUtility.GetAssemblies();
            var includedAssemblies = uNodePreference.GetIncludedAssemblies();
            var ns = graph.editorData.GetNamespaces();

            foreach (var assembly in assemblies)
            {
                if (!includedAssemblies.Contains(assembly.GetName().Name))
                {
                    continue;
                }
                var operators = EditorReflectionUtility.GetOperators(assembly, (op) => {
                    return(ns.Contains(op.DeclaringType.Namespace));
                });
                if (operators.Count > 0)
                {
                    foreach (var op in operators)
                    {
                        switch (op.Name)
                        {
                        //case "op_Equality": {
                        //	var parameters = op.GetParameters();
                        //	if(parameters[0].ParameterType != type && parameters[1].ParameterType != type)
                        //		break;
                        //	items.Add(GetItem(type, parameters[0].ParameterType, parameters[1].ParameterType, op.ReturnType, data, ComparisonType.Equal));
                        //	break;
                        //}
                        //case "op_Inequality": {
                        //	var parameters = op.GetParameters();
                        //	if(parameters[0].ParameterType != type && parameters[1].ParameterType != type)
                        //		break;
                        //	items.Add(GetItem(type, parameters[0].ParameterType, parameters[1].ParameterType, op.ReturnType, data, ComparisonType.NotEqual));
                        //	break;
                        //}
                        case "op_LessThan": {
                            var parameters = op.GetParameters();
                            if (parameters[0].ParameterType != type && parameters[1].ParameterType != type)
                            {
                                break;
                            }
                            items.Add(GetItem(type, parameters[0].ParameterType, parameters[1].ParameterType, op.ReturnType, data, ComparisonType.LessThan));
                            break;
                        }

                        case "op_GreaterThan": {
                            var parameters = op.GetParameters();
                            if (parameters[0].ParameterType != type && parameters[1].ParameterType != type)
                            {
                                break;
                            }
                            items.Add(GetItem(type, parameters[0].ParameterType, parameters[1].ParameterType, op.ReturnType, data, ComparisonType.GreaterThan));
                            break;
                        }

                        case "op_LessThanOrEqual": {
                            var parameters = op.GetParameters();
                            if (parameters[0].ParameterType != type && parameters[1].ParameterType != type)
                            {
                                break;
                            }
                            items.Add(GetItem(type, parameters[0].ParameterType, parameters[1].ParameterType, op.ReturnType, data, ComparisonType.LessThanOrEqual));
                            break;
                        }

                        case "op_GreaterThanOrEqual": {
                            var parameters = op.GetParameters();
                            if (parameters[0].ParameterType != type && parameters[1].ParameterType != type)
                            {
                                break;
                            }
                            items.Add(GetItem(type, parameters[0].ParameterType, parameters[1].ParameterType, op.ReturnType, data, ComparisonType.GreaterThanOrEqual));
                            break;
                        }
                        }
                    }
                }
            }
            items.Sort((x, y) => string.Compare(x.name, y.name));
            return(items);
        }
Beispiel #23
0
        protected override void InitializeView()
        {
            HLNode node = targetNode as HLNode;

            node.Refresh();
            var instance = node.instance;

            if (instance == null)
            {
                return;
            }
            if (instance is IStateNode || instance is IStateCoroutineNode)
            {
                AddOutputFlowPort(
                    new PortData()
                {
                    portID         = nameof(node.onSuccess),
                    onValueChanged = (o) => {
                        RegisterUndo();
                        node.onSuccess = o as MemberData;
                    },
                    getPortName    = () => "Success",
                    getPortType    = () => typeof(FlowInput),
                    getPortValue   = () => node.onSuccess,
                    getPortTooltip = () => "Flow to execute on success",
                }
                    );
                AddOutputFlowPort(
                    new PortData()
                {
                    portID         = nameof(node.onFailure),
                    onValueChanged = (o) => {
                        RegisterUndo();
                        node.onFailure = o as MemberData;
                    },
                    getPortName    = () => "Failure",
                    getPortType    = () => typeof(FlowInput),
                    getPortValue   = () => node.onFailure,
                    getPortTooltip = () => "Flow to execute on failure",
                }
                    );
            }
            if (node.IsFlowNode())              //Flow input
            {
                nodeFlowPort = AddInputFlowPort(
                    new PortData()
                {
                    portID        = UGraphView.SelfPortID,
                    getPortName   = () => "",
                    getConnection = () => {
                        return(new MemberData(node, MemberData.TargetType.FlowNode));
                    },
                }
                    );
                AddOutputFlowPort(
                    new PortData()
                {
                    portID         = "onFinished",
                    onValueChanged = (o) => {
                        RegisterUndo();
                        node.onFinished = o as MemberData;
                    },
                    getPortName  = () => instance is IStateNode || instance is IStateCoroutineNode ? "Finished" : "",
                    getPortType  = () => typeof(FlowInput),
                    getPortValue = () => node.onFinished,
                }
                    );
            }
            if (node.CanGetValue() || node.CanSetValue())              //Value output
            {
                nodeValuePort = AddOutputValuePort(
                    new PortData()
                {
                    portID        = UGraphView.SelfPortID,
                    getPortName   = () => "Out",
                    getPortType   = () => node.ReturnType(),
                    getPortValue  = () => node,
                    getConnection = () => {
                        return(new MemberData(node, MemberData.TargetType.ValueNode));
                    },
                }
                    );
            }
            Type type   = instance.GetType();
            var  fields = EditorReflectionUtility.GetFields(type);

            foreach (var field in fields)
            {
                if (field.IsDefined(typeof(NonSerializedAttribute)) || field.IsDefined(typeof(HideAttribute)))
                {
                    continue;
                }
                var option = field.GetCustomAttribute(typeof(NodePortAttribute), true) as NodePortAttribute;
                if (option != null && option.hideInNode)
                {
                    continue;
                }
                var val = node.initializers.FirstOrDefault(d => d.name == field.Name);
                if (val == null)
                {
                    val = new FieldValueData()
                    {
                        name  = field.Name,
                        value = MemberData.CreateFromValue(field.GetValue(instance), field.FieldType),
                    };
                    node.initializers.Add(val);
                }
                AddInputValuePort(
                    new PortData()
                {
                    portID         = field.Name,
                    onValueChanged = (o) => {
                        RegisterUndo();
                        val.value = o as MemberData;
                    },
                    getPortName    = () => option != null ? option.name : field.Name,
                    getPortType    = () => field.FieldType,
                    getPortValue   = () => val.value,
                    getPortTooltip = () => {
                        var tooltip = field.GetCustomAttribute(typeof(TooltipAttribute), true) as TooltipAttribute;
                        return(tooltip != null ? tooltip.tooltip : string.Empty);
                    },
                });
            }
        }
Beispiel #24
0
 private void BuildContextualMenu(ContextualMenuPopulateEvent evt)
 {
     if (config.type != null)
     {
         if (config.filter == null || !config.filter.SetMember && config.filter.IsValidTarget(MemberData.TargetType.Values))
         {
             evt.menu.AppendAction("To Default", (e) => {
                 if (config.type == typeof(Type))
                 {
                     member = new MemberData(typeof(object));
                 }
                 else if (config.type is RuntimeType)
                 {
                     member = MemberData.CreateFromValue(null, config.type);
                 }
                 else
                 {
                     member = new MemberData(ReflectionUtils.CanCreateInstance(config.type) ? ReflectionUtils.CreateInstance(config.type) : null)
                     {
                         startType      = config.type,
                         targetTypeName = config.type.FullName,
                     };
                 }
                 config.OnValueChanged(member);
                 config.owner.OnValueChanged();
                 config.owner.MarkRepaint();
                 UpdateControl();
                 uNodeEditor.GUIChanged();
             }, DropdownMenuAction.AlwaysEnabled);
             if (config.type == typeof(object))
             {
                 var types = EditorReflectionUtility.GetCommonType();
                 foreach (var t in types)
                 {
                     evt.menu.AppendAction("To Value/" + t.PrettyName(), (e) => {
                         member = new MemberData(ReflectionUtils.CanCreateInstance(t) ? ReflectionUtils.CreateInstance(t) : null)
                         {
                             startType      = t,
                             targetTypeName = t.FullName,
                         };
                         config.OnValueChanged(member);
                         config.owner.OnValueChanged();
                         config.owner.MarkRepaint();
                         UpdateControl();
                         uNodeEditor.GUIChanged();
                     }, DropdownMenuAction.AlwaysEnabled);
                 }
             }
             else if (config.type == typeof(Type))
             {
                 var mPos = NodeGraph.openedGraph.GetMousePosition();
                 evt.menu.AppendAction("Change Type", (e) => {
                     TypeSelectorWindow.ShowWindow(mPos, new FilterAttribute()
                     {
                         OnlyGetType = true
                     },
                                                   delegate(MemberData[] types) {
                         uNodeEditorUtility.RegisterUndo(config.owner.targetNode);
                         member.CopyFrom(types[0]);
                         config.OnValueChanged(member);
                         config.owner.OnValueChanged();
                         config.owner.MarkRepaint();
                         UpdateControl();
                         uNodeEditor.GUIChanged();
                     }, new TypeItem[1] {
                         member
                     }).targetObject = config.owner.targetNode;
                 }, DropdownMenuAction.AlwaysEnabled);
             }
             if (!config.type.IsValueType)
             {
                 evt.menu.AppendAction("To Null", (e) => {
                     uNodeEditorUtility.RegisterUndo(config.owner.targetNode);
                     member.CopyFrom(MemberData.Null);
                     config.OnValueChanged(member);
                     config.owner.OnValueChanged();
                     config.owner.MarkRepaint();
                     UpdateControl();
                     uNodeEditor.GUIChanged();
                 }, DropdownMenuAction.AlwaysEnabled);
             }
         }
     }
 }
Beispiel #25
0
        public virtual void AddChildNodes(NodeComponent nodeComponent, TreeViewItem parentTree, IList <TreeViewItem> rows)
        {
            var fields = EditorReflectionUtility.GetFields(nodeComponent.GetType());

            foreach (var field in fields)
            {
                var fieldType = field.FieldType;
                if (field.IsDefinedAttribute(typeof(FieldConnectionAttribute)))
                {
                    var  attributes = EditorReflectionUtility.GetAttributes(field);
                    var  FCA        = ReflectionUtils.GetAttribute <FieldConnectionAttribute>(attributes);
                    bool isFlow     = nodeComponent is Node && (nodeComponent as Node).IsFlowNode();
                    if (FCA.hideOnFlowNode && isFlow)
                    {
                        continue;
                    }
                    if (FCA.hideOnNotFlowNode && !isFlow)
                    {
                        continue;
                    }
                    if (fieldType == typeof(MemberData))
                    {
                        if (FCA.isFlowConnection)
                        {
                            MemberData member = field.GetValueOptimized(nodeComponent) as MemberData;
                            if (member != null)
                            {
                                if (!FCA.isFinishedFlow && field.Name != nameof(MultipurposeNode.onFinished))
                                {
                                    if (FCA.displayFlowInHierarchy)
                                    {
                                        var flowItem = CreateFlowTree(
                                            nodeComponent,
                                            field.Name,
                                            member,
                                            FCA.label != null ? FCA.label.text : field.Name
                                            );
                                        parentTree.AddChild(flowItem);
                                        rows.Add(flowItem);
                                        manager.AddNodeTree(member, flowItem, rows);
                                    }
                                    else
                                    {
                                        manager.AddNodeTree(member, parentTree, rows);
                                    }
                                }
                                else
                                {
                                    manager.AddNodeTree(member, parentTree, rows, false);
                                }
                            }
                        }
                    }
                    else if (fieldType == typeof(List <MemberData>) && FCA.isFlowConnection)
                    {
                        List <MemberData> members = field.GetValueOptimized(nodeComponent) as List <MemberData>;
                        if (members != null && members.Count > 0)
                        {
                            foreach (var member in members)
                            {
                                if (member != null && member.isAssigned && member.IsTargetingPinOrNode)
                                {
                                    Node n = member.GetTargetNode();
                                    if (n != null)
                                    {
                                        manager.AddNodes(n, parentTree, rows, isChildren: !FCA.isFinishedFlow && field.Name != nameof(MultipurposeNode.onFinished));
                                    }
                                }
                            }
                        }
                    }
                }
                else if (fieldType == typeof(EventData))
                {
                    var blocks = field.GetValueOptimized(nodeComponent) as EventData;
                    AddBlocks(blocks, field.Name, parentTree, rows);
                }
            }
        }
Beispiel #26
0
        public void PasteNode(Vector3 position)
        {
            if (nodeToCopy == null || nodeToCopy.Count == 0)
            {
                return;
            }
            if (uNodeEditorUtility.IsPrefab(editorData.graph.gameObject))
            {
                throw new Exception("Editing graph prefab dirrectly is not supported.");
            }
            uNodeEditorUtility.RegisterUndo(editorData.graph, "Paste Node");
            uNodeRoot UNR       = editorData.graph;
            float     progress  = 0;
            int       loopIndex = 0;

            if (nodeToCopy.Count > 5)
            {
                EditorUtility.DisplayProgressBar("Loading", "", progress);
            }
            Vector2 center       = Vector2.zero;
            int     centerLength = 0;
            Dictionary <uNodeComponent, uNodeComponent> CopyedObjectMap = new Dictionary <uNodeComponent, uNodeComponent>(EqualityComparer <uNodeComponent> .Default);

            foreach (uNodeComponent comp in nodeToCopy)
            {
                if (comp == null || comp is EventNode && editorData.selectedGroup != null)
                {
                    continue;
                }
                Node node = comp as Node;
                if (!CopyedObjectMap.ContainsKey(comp))
                {
                    uNodeComponent com = Object.Instantiate(comp);
                    com.gameObject.name = com.gameObject.name.Replace("(Clone)", "");
                    if (editorData.selectedGroup == null)
                    {
                        if (editorData.selectedRoot)
                        {
                            com.transform.parent = editorData.selectedRoot.transform;
                        }
                        else
                        {
                            com.transform.parent = NodeEditorUtility.GetNodeRoot(UNR).transform;
                        }
                    }
                    else
                    {
                        com.transform.parent = editorData.selectedGroup.transform;
                    }
                    int    index = 0;
                    string nm    = com.gameObject.name.TrimEnd(numberChar);
                    while (true)
                    {
                        bool   flag  = false;
                        string gName = com.gameObject.name;
                        foreach (Transform t in com.transform.parent)
                        {
                            if (t != com.transform)
                            {
                                if (t.gameObject.name.Equals(gName))
                                {
                                    flag = true;
                                    break;
                                }
                            }
                        }
                        if (flag)
                        {
                            com.gameObject.name = nm + index.ToString();
                            index++;
                            continue;
                        }
                        break;
                    }
                    CopyedObjectMap.Add(comp, com);
                    if (comp is IMacro || comp is ISuperNode)
                    {
                        var fields = EditorReflectionUtility.GetFields(comp.GetType());
                        foreach (var field in fields)
                        {
                            if (field.FieldType == typeof(List <Nodes.MacroPortNode>))
                            {
                                var value = field.GetValueOptimized(comp) as List <Nodes.MacroPortNode>;
                                if (value != null)
                                {
                                    var sourceValue = field.GetValueOptimized(com) as List <Nodes.MacroPortNode>;
                                    for (int i = 0; i < value.Count; i++)
                                    {
                                        if (value[i] == null)
                                        {
                                            continue;
                                        }
                                        CopyedObjectMap.Add(value[i], sourceValue[i]);
                                    }
                                }
                            }
                        }
                    }
                }
                if (node != null)
                {
                    center.x += node.editorRect.x;
                    center.y += node.editorRect.y;
                    centerLength++;
                }
                else
                {
                    BaseEventNode met = comp as BaseEventNode;
                    if (met != null)
                    {
                        center.x += met.editorRect.x;
                        center.y += met.editorRect.y;
                        centerLength++;
                    }
                }
                loopIndex++;
                progress = (float)loopIndex / (float)nodeToCopy.Count;
                if (nodeToCopy.Count > 5)
                {
                    EditorUtility.DisplayProgressBar("Loading", "", progress);
                }
            }
            progress = 0;
            center  /= centerLength;
            HashSet <uNodeComponent> needReflectedComponent = new HashSet <uNodeComponent>();
            uNodeRoot compEvent = null;

            foreach (uNodeComponent com in nodeToCopy)
            {
                uNodeComponent comp = null;
                if (CopyedObjectMap.ContainsKey(com))
                {
                    comp = CopyedObjectMap[com];
                    if (comp == null)
                    {
                        loopIndex++;
                        progress = (float)loopIndex / (float)nodeToCopy.Count;
                        if (nodeToCopy.Count > 5)
                        {
                            EditorUtility.DisplayProgressBar("Loading", "", progress);
                        }
                        continue;
                    }
                    if (comp as Node)
                    {
                        Node node = comp as Node;
                        Func <object, bool> validation = delegate(object o) {
                            if (o is MemberData)
                            {
                                MemberData member = o as MemberData;
                                if (member.IsTargetingPinOrNode)
                                {
                                    NodeComponent n = member.GetInstance() as NodeComponent;
                                    if (n && n is uNodeComponent)
                                    {
                                        if (CopyedObjectMap.ContainsKey(n))
                                        {
                                            member.instance = CopyedObjectMap[n] as NodeComponent;
                                            n.owner         = UNR;
                                            return(true);
                                        }
                                        else if (n.owner != UNR || n.transform.parent != node.transform.parent)
                                        {
                                            member.instance = null;
                                            n.owner         = UNR;
                                            return(true);
                                        }
                                        //return true;
                                    }
                                }
                            }
                            return(false);
                        };
                        if (node as StateNode)
                        {
                            StateNode         eventNode = node as StateNode;
                            TransitionEvent[] TE        = eventNode.GetTransitions();
                            foreach (TransitionEvent n in TE)
                            {
                                var tn = n.GetTargetNode();
                                if (tn == null)
                                {
                                    continue;
                                }
                                if (CopyedObjectMap.ContainsKey(tn))
                                {
                                    n.target = MemberData.CreateConnection(CopyedObjectMap[tn] as Node, true);
                                    n.owner  = UNR;
                                }
                                else if (n.owner != UNR || tn != null && tn.owner != UNR ||
                                         tn != null && tn.transform.parent != node.transform.parent)
                                {
                                    n.target = MemberData.none;
                                    n.owner  = UNR;
                                }
                            }
                        }
                        else if (node is IMacro || node is ISuperNode)
                        {
                            var fields = EditorReflectionUtility.GetFields(comp.GetType());
                            foreach (var field in fields)
                            {
                                if (field.FieldType == typeof(List <Nodes.MacroPortNode>))
                                {
                                    var value = field.GetValueOptimized(comp) as List <Nodes.MacroPortNode>;
                                    if (value != null)
                                    {
                                        foreach (var v in value)
                                        {
                                            AnalizerUtility.AnalizeObject(v, validation);
                                        }
                                    }
                                }
                            }
                        }
                        AnalizerUtility.AnalizeObject(node, validation);
                        node.editorRect = new Rect(node.editorRect.x - center.x + position.x, node.editorRect.y - center.y + position.y, node.editorRect.width, node.editorRect.height);
                        if (node.owner != UNR)
                        {
                            node.owner = UNR;
                        }
                    }
                    else if (comp is BaseEventNode)
                    {
                        BaseEventNode method = comp as BaseEventNode;
                        var           flows  = method.GetFlows();
                        for (int i = 0; i < flows.Count; i++)
                        {
                            var tn = flows[i].GetTargetNode();
                            if (tn != null && CopyedObjectMap.ContainsKey(tn))
                            {
                                flows[i] = new MemberData(CopyedObjectMap[flows[i].GetTargetNode()], MemberData.TargetType.FlowNode);
                            }
                            else if (method.owner != UNR)
                            {
                                flows[i] = MemberData.none;
                            }
                        }
                        method.owner      = UNR;
                        method.editorRect = new Rect(method.editorRect.x - center.x + position.x, method.editorRect.y - center.y + position.y, method.editorRect.width, method.editorRect.height);
                    }
                }
                loopIndex++;
                progress = (float)loopIndex / (float)nodeToCopy.Count;
                if (nodeToCopy.Count > 5)
                {
                    EditorUtility.DisplayProgressBar("Loading", "", progress);
                }
            }
            if (nodeToCopy.Count > 5)
            {
                EditorUtility.ClearProgressBar();
            }
            if (needReflectedComponent.Count > 0)
            {
                NodeEditorUtility.PerformReflectComponent(needReflectedComponent.ToList(), compEvent, UNR);
            }
            foreach (KeyValuePair <uNodeComponent, uNodeComponent> keys in CopyedObjectMap)
            {
                if (keys.Value != null)
                {
                    Undo.RegisterCreatedObjectUndo(keys.Value.gameObject, "Paste Node");
                }
            }
            //allCopyedEvent.Clear();
            Refresh();
        }
Beispiel #27
0
 void InitializeHLBlock(Block block)
 {
     if (block is Events.HLAction action)
     {
         Type type = action.type.startType;
         if (type != null)
         {
             var fields = EditorReflectionUtility.GetFields(type);
             foreach (var field in fields)
             {
                 if (field.IsDefined(typeof(NonSerializedAttribute)) || field.IsDefined(typeof(HideAttribute)))
                 {
                     continue;
                 }
                 var option = field.GetCustomAttribute(typeof(NodePortAttribute), true) as NodePortAttribute;
                 if (option != null && option.hideInNode)
                 {
                     continue;
                 }
                 var val = action.initializers.FirstOrDefault(d => d.name == field.Name);
                 if (val == null)
                 {
                     val = new FieldValueData()
                     {
                         name  = field.Name,
                         value = MemberData.CreateFromValue(field.GetValueOptimized(ReflectionUtils.CreateInstance(type)), field.FieldType),
                     };
                     action.initializers.Add(val);
                 }
                 var port = AddPort(new PortData()
                 {
                     portID         = field.Name,
                     getPortName    = () => option != null ? option.name : field.Name,
                     getPortType    = () => field.FieldType,
                     getPortValue   = () => val.value,
                     onValueChanged = (obj) => {
                         RegisterUndo();
                         val.value = obj as MemberData;
                         Repaint();
                     },
                     getPortTooltip = () => {
                         var tooltip = field.GetCustomAttribute(typeof(TooltipAttribute), true) as TooltipAttribute;
                         return(tooltip != null ? tooltip.tooltip : string.Empty);
                     },
                 });
                 port.Add(new ControlView(port.portData.InstantiateControl(true), true));
             }
         }
     }
     else if (block is Events.HLCondition condition)
     {
         Type type = condition.type.startType;
         if (type != null)
         {
             var fields = EditorReflectionUtility.GetFields(type);
             foreach (var field in fields)
             {
                 if (field.IsDefined(typeof(NonSerializedAttribute)) || field.IsDefined(typeof(HideAttribute)))
                 {
                     continue;
                 }
                 var option = field.GetCustomAttribute(typeof(NodePortAttribute), true) as NodePortAttribute;
                 if (option != null && option.hideInNode)
                 {
                     continue;
                 }
                 var val = condition.initializers.FirstOrDefault(d => d.name == field.Name);
                 if (val == null)
                 {
                     val = new FieldValueData()
                     {
                         name  = field.Name,
                         value = MemberData.CreateFromValue(field.GetValueOptimized(ReflectionUtils.CreateInstance(type)), field.FieldType),
                     };
                     condition.initializers.Add(val);
                 }
                 var port = AddPort(new PortData()
                 {
                     portID         = field.Name,
                     getPortName    = () => option != null ? option.name : field.Name,
                     getPortType    = () => field.FieldType,
                     getPortValue   = () => val.value,
                     onValueChanged = (obj) => {
                         RegisterUndo();
                         val.value = obj as MemberData;
                         Repaint();
                     },
                     getPortTooltip = () => {
                         var tooltip = field.GetCustomAttribute(typeof(TooltipAttribute), true) as TooltipAttribute;
                         return(tooltip != null ? tooltip.tooltip : string.Empty);
                     },
                 });
                 port.Add(new ControlView(port.portData.InstantiateControl(true), true));
             }
         }
     }
 }