Ejemplo n.º 1
0
    /// <summary>
    /// Draw and update the toolbar for the director control
    /// </summary>
    /// <param name="toolbarArea">The area for the toolbar</param>
    private void updateToolbar(Rect toolbarArea)
    {
        EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);

        // If there are no cutscenes, then only give option to create a new cutscene.
        if (GUILayout.Button(CREATE, EditorStyles.toolbarDropDown, GUILayout.Width(60)))
        {
            GenericMenu createMenu = new GenericMenu();
            createMenu.AddItem(new_cutscene, false, openCutsceneCreatorWindow);

            if (cutscene != null)
            {
                createMenu.AddSeparator(string.Empty);
                {
                    // foreach(var type in DirectorHelper.GetAllSubTypes(typeof(TrackGroup)))
                    var __enumerator2 = (DirectorHelper.GetAllSubTypes(typeof(TrackGroup))).GetEnumerator();
                    while (__enumerator2.MoveNext())
                    {
                        var type = (Type)__enumerator2.Current;
                        {
                            TrackGroupContextData userData = getContextDataFromType(type);
                            string text = string.Format(userData.Label);
                            createMenu.AddItem(new GUIContent(text), false, new GenericMenu.MenuFunction2(AddTrackGroup), userData);
                        }
                    }
                }
            }

            createMenu.DropDown(new Rect(5, TOOLBAR_HEIGHT, 0, 0));
        }

        // Cutscene selector
        cachedCutscenes = GameObject.FindObjectsOfType <Cutscene>();
        if (cachedCutscenes != null && cachedCutscenes.Length > 0)
        {
            // Get cutscene names
            GUIContent[] cutsceneNames = new GUIContent[cachedCutscenes.Length];
            for (int i = 0; i < cachedCutscenes.Length; i++)
            {
                cutsceneNames[i] = new GUIContent(cachedCutscenes[i].name);
            }

            // Sort alphabetically
            Array.Sort(cutsceneNames, delegate(GUIContent content1, GUIContent content2)
            {
                return(string.Compare(content1.text, content2.text));
            });

            Array.Sort(cachedCutscenes, delegate(Cutscene c1, Cutscene c2)
            {
                return(string.Compare(c1.name, c2.name));
            });

            // Find the currently selected cutscene.
            for (int i = 0; i < cachedCutscenes.Length; i++)
            {
                if (cutscene != null && cutscene.GetInstanceID() == cachedCutscenes[i].GetInstanceID())
                {
                    popupSelection = i;
                }
            }

            // Show the popup
            int tempPopup = EditorGUILayout.Popup(popupSelection, cutsceneNames, EditorStyles.toolbarPopup);
            if (tempPopup != popupSelection)
            {
                popupSelection = tempPopup;
                EditorPrefs.SetInt("DirectorControl.CutsceneID", cachedCutscenes[popupSelection].GetInstanceID());
            }
            popupSelection = Math.Min(popupSelection, cachedCutscenes.Length - 1);
            cutscene       = cachedCutscenes[popupSelection];
        }
        if (cutscene != null)
        {
            if (GUILayout.Button(pickerImage, EditorStyles.toolbarButton, GUILayout.Width(24)))
            {
                Selection.activeObject = cutscene;
            }
            if (GUILayout.Button(refreshImage, EditorStyles.toolbarButton, GUILayout.Width(24)))
            {
                cutscene.Refresh();
            }

            if (Event.current.control && Event.current.keyCode == KeyCode.Space)
            {
                cutscene.Refresh();
                Event.current.Use();
            }
        }
        GUILayout.FlexibleSpace();

        bool tempSnapping = GUILayout.Toggle(isSnappingEnabled, snapImage, EditorStyles.toolbarButton, GUILayout.Width(24));

        if (tempSnapping != isSnappingEnabled)
        {
            isSnappingEnabled = tempSnapping;
            directorControl.IsSnappingEnabled = isSnappingEnabled;
        }
        GUILayout.Button(rippleEditImage, EditorStyles.toolbarButton, GUILayout.Width(24));
        GUILayout.Button(rollingEditImage, EditorStyles.toolbarButton, GUILayout.Width(24));
        GUILayout.Space(10f);

        if (GUILayout.Button(rescaleImage, EditorStyles.toolbarButton, GUILayout.Width(24)))
        {
            directorControl.Rescale();
        }
        if (GUILayout.Button(new GUIContent(zoomInImage, "Zoom In"), EditorStyles.toolbarButton, GUILayout.Width(24)))
        {
            directorControl.ZoomIn();
        }
        if (GUILayout.Button(zoomOutImage, EditorStyles.toolbarButton, GUILayout.Width(24)))
        {
            directorControl.ZoomOut();
        }
        GUILayout.Space(10f);

        Color temp = GUI.color;

        GUI.color = directorControl.InPreviewMode ? Color.red : temp;
        directorControl.InPreviewMode = GUILayout.Toggle(directorControl.InPreviewMode, PREVIEW_MODE, EditorStyles.toolbarButton, GUILayout.Width(150));
        GUI.color = temp;
        GUILayout.Space(10);

        if (GUILayout.Button("?", EditorStyles.toolbarButton))
        {
            EditorWindow.GetWindow <DirectorHelpWindow>();
        }
        EditorGUILayout.EndHorizontal();
    }
Ejemplo n.º 2
0
        /// <summary>
        /// Draw a header similar to the one used for the post-process stack
        /// </summary>
        static public Rect DrawHeader(ref bool expanded, ref bool activeField, string title, Color feedbackColor, System.Action <GenericMenu> fillGenericMenu,
                                      float startedAt, float duration, float totalDuration, MMFeedbackTiming timing, bool pause, MMFeedbacks host)
        {
            float thisTime      = timing.TimescaleMode == TimescaleModes.Scaled ? Time.time : Time.unscaledTime;
            float thisDeltaTime = timing.TimescaleMode == TimescaleModes.Scaled ? Time.deltaTime : Time.unscaledDeltaTime;

            var e = Event.current;

            // Initialize Rects
            var backgroundRect = GUILayoutUtility.GetRect(1f, 17f);

            var progressRect = GUILayoutUtility.GetRect(1f, 2f);

            var offset = 4f;

            var reorderRect = backgroundRect;

            reorderRect.xMin  -= 8f;
            reorderRect.y     += 5f;
            reorderRect.width  = 9f;
            reorderRect.height = 9f;

            var labelRect = backgroundRect;

            labelRect.xMin += 32f + offset;
            labelRect.xMax -= 20f;

            var foldoutRect = backgroundRect;

            foldoutRect.y     += 1f;
            foldoutRect.xMin  += offset;
            foldoutRect.width  = 13f;
            foldoutRect.height = 13f;

            var toggleRect = backgroundRect;

            toggleRect.x     += 16f;
            toggleRect.xMin  += offset;
            toggleRect.y     += 2f;
            toggleRect.width  = 13f;
            toggleRect.height = 13f;

            var menuIcon = PaneOptionsIcon;
            var menuRect = new Rect(labelRect.xMax + 4f, labelRect.y + 4f, menuIcon.width, menuIcon.height);

            _timingStyle.normal.textColor = EditorGUIUtility.isProSkin ? _timingDark : _timingLight;
            _timingStyle.alignment        = TextAnchor.MiddleRight;

            var colorRect = new Rect(labelRect.xMin, labelRect.yMin, 5f, 17f);

            colorRect.xMin = 0f;
            colorRect.xMax = 5f;
            EditorGUI.DrawRect(colorRect, feedbackColor);

            // Background rect should be full-width
            backgroundRect.xMin   = 0f;
            backgroundRect.width += 4f;

            progressRect.xMin   = 0f;
            progressRect.width += 4f;

            Color headerBackgroundColor = Color.white;

            // Background - if color is white we draw the default color
            if (!pause)
            {
                headerBackgroundColor = HeaderBackground;
            }
            else
            {
                headerBackgroundColor = feedbackColor;
            }
            EditorGUI.DrawRect(backgroundRect, headerBackgroundColor);

            // Foldout
            expanded = GUI.Toggle(foldoutRect, expanded, GUIContent.none, EditorStyles.foldout);

            // Title ----------------------------------------------------------------------------------------------------

            using (new EditorGUI.DisabledScope(!activeField))
            {
                EditorGUI.LabelField(labelRect, title, EditorStyles.boldLabel);
            }

            // Direction ----------------------------------------------------------------------------------------------

            float directionRectWidth = 70f;
            var   directionRect      = new Rect(labelRect.xMax - directionRectWidth, labelRect.yMin, directionRectWidth, 17f);

            directionRect.xMin = labelRect.xMax - directionRectWidth;
            directionRect.xMax = labelRect.xMax;

            if (timing.MMFeedbacksDirectionCondition == MMFeedbackTiming.MMFeedbacksDirectionConditions.OnlyWhenBackwards)
            {
                GUIContent directionIcon = EditorGUIUtility.IconContent("vcs_change", "Only play when backwards");
                EditorGUI.LabelField(directionRect, directionIcon);
            }

            if (timing.MMFeedbacksDirectionCondition == MMFeedbackTiming.MMFeedbacksDirectionConditions.OnlyWhenForwards)
            {
                float rotationAngle = 180f;
                var   pivotPoint    = new Vector2(directionRect.xMin + 9, directionRect.yMin + 8);
                var   matrixBackup  = GUI.matrix;
                GUIUtility.RotateAroundPivot(rotationAngle, pivotPoint);
                GUIContent directionIcon = EditorGUIUtility.IconContent("vcs_incoming", "Only play when forwards");
                EditorGUI.LabelField(directionRect, directionIcon);
                GUI.matrix = matrixBackup;
            }

            // Time -----------------------------------------------------------------------------------------------------

            string timingInfo   = "";
            bool   displayTotal = false;

            if (host.DisplayFullDurationDetails)
            {
                if (timing.InitialDelay != 0)
                {
                    timingInfo  += host.ApplyTimeMultiplier(timing.InitialDelay).ToString() + "s + ";
                    displayTotal = true;
                }

                timingInfo += duration.ToString("F2") + "s";

                if (timing.NumberOfRepeats != 0)
                {
                    float delayBetweenRepeats = host.ApplyTimeMultiplier(timing.DelayBetweenRepeats);

                    timingInfo += " + " + timing.NumberOfRepeats.ToString() + " x ";
                    if (timing.DelayBetweenRepeats > 0)
                    {
                        timingInfo += "(";
                    }
                    timingInfo += duration + "s";
                    if (timing.DelayBetweenRepeats > 0)
                    {
                        timingInfo += " + " + host.ApplyTimeMultiplier(timing.DelayBetweenRepeats) + "s )";
                    }
                    displayTotal = true;
                }

                if (displayTotal)
                {
                    timingInfo += " = " + totalDuration.ToString("F2") + "s";
                }
            }
            else
            {
                timingInfo = totalDuration.ToString("F2") + "s";
            }

            //"[ 2s + 3 x (4s + 1s) ]"

            float timingRectWidth = 150f;
            var   timingRect      = new Rect(labelRect.xMax - timingRectWidth, labelRect.yMin, timingRectWidth, 17f);

            timingRect.xMin = labelRect.xMax - timingRectWidth;
            timingRect.xMax = labelRect.xMax;
            EditorGUI.LabelField(timingRect, timingInfo, _timingStyle);

            // Progress bar
            if (totalDuration == 0f)
            {
                totalDuration = 0.1f;
            }
            if ((startedAt > 0f) && (thisTime - startedAt < totalDuration + 0.05f))
            {
                float fullWidth = progressRect.width;
                if (totalDuration == 0f)
                {
                    totalDuration = 0.1f;
                }
                float percent = ((thisTime - startedAt) / totalDuration) * 100f;
                progressRect.width = percent * fullWidth / 100f;
                Color barColor = Color.white;
                if (thisTime - startedAt > totalDuration)
                {
                    barColor = Color.yellow;
                }
                EditorGUI.DrawRect(progressRect, barColor);
            }
            else
            {
                EditorGUI.DrawRect(progressRect, headerBackgroundColor);
            }

            // Active checkbox
            activeField = GUI.Toggle(toggleRect, activeField, GUIContent.none, SmallTickbox);

            // Dropdown menu icon
            GUI.DrawTexture(menuRect, menuIcon);

            for (int i = 0; i < 3; i++)
            {
                Rect r = reorderRect;
                r.height = 1;
                r.y      = reorderRect.y + reorderRect.height * (i / 3.0f);
                EditorGUI.DrawRect(r, Reorder);
            }


            // Handle events

            if (e.type == EventType.MouseDown)
            {
                if (menuRect.Contains(e.mousePosition))
                {
                    var menu = new GenericMenu();
                    fillGenericMenu(menu);
                    menu.DropDown(new Rect(new Vector2(menuRect.x, menuRect.yMax), Vector2.zero));
                    e.Use();
                }
            }

            if (e.type == EventType.MouseDown && labelRect.Contains(e.mousePosition) && e.button == 0)
            {
                expanded = !expanded;
                e.Use();
            }

            return(backgroundRect);
        }
Ejemplo n.º 3
0
        void OnGUI()
        {
            using (new EditorGUI.DisabledScope(_state != GenerationState.Waiting))
            {
                EditorGUILayout.Space();

                using (new GUILayout.HorizontalScope())
                {
                    GUILayout.FlexibleSpace();

                    var popupRect = GUILayoutUtility.GetRect(0.0f, 20.0f);

                    if (GUILayout.Button(_newButton.Content, GUILayout.MinWidth(20), GUILayout.MaxWidth(80.0f)))
                    {
                        _templateMenu.DropDown(popupRect);
                    }

                    if (GUILayout.Button(_openButton.Content, GUILayout.MinWidth(20), GUILayout.MaxWidth(80.0f)))
                    {
                        OpenSettings();
                    }
                }

                EditorGUILayout.Space();
                EditorGUILayout.Space();

                if (_generator != null)
                {
                    using (new EditorGUILayout.HorizontalScope())
                    {
                        EditorGUILayout.SelectableLabel(_settingsFile);

                        if (GUILayout.Button(_generateButton.Content, GUILayout.MaxWidth(80.0f)))
                        {
                            StartGeneration();
                        }

                        if (GUILayout.Button(_saveButton.Content, GUILayout.MaxWidth(80.0f)))
                        {
                            SaveGenerator(_generator, _settingsFile);
                        }
                    }

                    EditorGUILayout.Space();

                    using (var scrolling = new EditorGUILayout.ScrollViewScope(_scrollPosition))
                    {
                        var editor = Editor.CreateEditor(_generator);
                        editor.DrawDefaultInspector();
                        _scrollPosition = scrolling.scrollPosition;
                    }
                }
            }

            if (_state == GenerationState.Done || _state == GenerationState.Error)
            {
                FinishGeneration();
                EditorUtility.ClearProgressBar();
            }
            else if (_state != GenerationState.Waiting)
            {
                EditorUtility.DisplayProgressBar("Generating Documentation", _message, _progress);
            }
        }
Ejemplo n.º 4
0
 public void DropDown(Rect position)
 {
     _innerMenu.DropDown(position);
 }
            private void DrawValue(PropertyRecord record, out bool delete)
            {
                delete = false;

                GUIContent removeLabel = new GUIContent("Remove");

                Rect position = EditorGUILayout.GetControlRect();

                Rect nameLabelRect = position;

                nameLabelRect.width = EditorGUIUtility.labelWidth;

                Rect removeButtonRect = position;

                removeButtonRect.width = EditorStyles.miniButton.CalcSize(removeLabel).x;
                removeButtonRect.x     = position.xMax - removeButtonRect.width;

                Rect sliderRect = position;

                sliderRect.xMin = nameLabelRect.xMax;
                sliderRect.xMax = removeButtonRect.xMin - EditorStyles.miniButton.margin.left;

                GUIContent nameLabel = new GUIContent(record.name);

                float value       = 0;
                bool  mixedValues = false;

                // We use EditorGUI.BeginProperty when there is a single object selected, so
                // the user can revert the value to prefab by context-clicking the name.
                // We handle multi-selections ourselves, so that we can deal with
                // mismatched arrays nicely.
                if (record.valueProperties.Count == 1)
                {
                    value = record.valueProperties[0].floatValue;
                    EditorGUI.BeginProperty(position, nameLabel, record.valueProperties[0]);
                }
                else
                {
                    bool first = true;

                    foreach (SerializedProperty property in record.valueProperties)
                    {
                        if (first)
                        {
                            value = property.floatValue;
                            first = false;
                        }
                        else if (property.floatValue != value)
                        {
                            mixedValues = true;
                            break;
                        }
                    }
                }

                EditorGUI.LabelField(nameLabelRect, nameLabel);

                EditorGUI.BeginChangeCheck();

                EditorGUI.showMixedValue = mixedValues;

                float newValue = EditorGUI.Slider(sliderRect, value, record.paramRef.Min, record.paramRef.Max);

                EditorGUI.showMixedValue = false;

                if (EditorGUI.EndChangeCheck())
                {
                    foreach (SerializedProperty property in record.valueProperties)
                    {
                        property.floatValue = newValue;
                    }
                }

                delete = GUI.Button(removeButtonRect, removeLabel, EditorStyles.miniButton);

                if (record.valueProperties.Count == 1)
                {
                    EditorGUI.EndProperty();
                }
                else
                {
                    // Context menu to set all values from one object in the multi-selection.
                    if (mixedValues && Event.current.type == EventType.ContextClick &&
                        nameLabelRect.Contains(Event.current.mousePosition))
                    {
                        GenericMenu menu = new GenericMenu();

                        foreach (SerializedProperty sourceProperty in record.valueProperties)
                        {
                            UnityEngine.Object targetObject = sourceProperty.serializedObject.targetObject;

                            menu.AddItem(new GUIContent(string.Format("Set to Value of '{0}'", targetObject.name)), false,
                                         (userData) => CopyValueToAll(userData as SerializedProperty, record.valueProperties),
                                         sourceProperty);
                        }

                        menu.DropDown(position);
                    }
                }
            }
Ejemplo n.º 6
0
        /// <summary>
        /// ここに独自のエディターの GUI を実装します
        /// </summary>
        void OnGUI()
        {
            if (toolbarSearchField == null)
            {
                toolbarSearchField = new GUIStyle("ToolbarSeachTextField");
            }
            if (toolbarSearchFieldCancelButton == null)
            {
                toolbarSearchFieldCancelButton = new GUIStyle("ToolbarSeachCancelButton");
            }
            if (toolbarSearchFieldCancelButtonEmpty == null)
            {
                toolbarSearchFieldCancelButtonEmpty = new GUIStyle("ToolbarSeachCancelButtonEmpty");
            }

            //toolbarSearchField.fixedHeight = 18;
            //toolbarSearchFieldCancelButton.fixedHeight = 18;
            //toolbarSearchFieldCancelButtonEmpty.fixedHeight = 18;
            if (m_styles == null)
            {
                m_styles = new Styles();
            }
            m_styles.ToolbarPopup           = new GUIStyle(EditorStyles.toolbarPopup);
            m_styles.ToolbarPopup.alignment = TextAnchor.MiddleCenter;

            if (m_localSettings == null)
            {
                m_localSettings = LocalSettings.i;
            }

            using (new GUILayout.HorizontalScope(EditorStyles.toolbar)) {
                GUILayout.Label(Icon.Get("Animation.PrevKey"), EditorStyles.toolbarButton);
                if (EditorHelper.HasMouseClick(GUILayoutUtility.GetLastRect()))
                {
                    //EditorApplication.ExecuteMenuItem( "Assets/Navigate Backward History %-" );
                    UnityEditorProjectBrowser.lockOnce();
                    //SelectionHistory.Backward();
                }
                GUILayout.Label(Icon.Get("Animation.NextKey"), EditorStyles.toolbarButton);
                if (EditorHelper.HasMouseClick(GUILayoutUtility.GetLastRect()))
                {
                    //EditorApplication.ExecuteMenuItem( "Assets/Navigate Forward History %#-" );
                    UnityEditorProjectBrowser.lockOnce();
                    //SelectionHistory.Forward();
                }

                GUILayout.Space(6);


                GUILayout.Label(Icon.Get("SceneAsset Icon"), EditorStyles.toolbarButton, GUILayout.Width(26));
                if (EditorHelper.HasMouseClick(GUILayoutUtility.GetLastRect()))
                {
                    var optionsMenu = new GenericMenu();
                    foreach (var e in m_localSettings.sceneList)
                    {
                        var path = AssetDatabase.GUIDToAssetPath(e);
                        if (File.Exists(path))
                        {
                            optionsMenu.AddItem(new GUIContent(path.fileNameWithoutExtension()), false, onLoadScene, path);
                        }
                        else
                        {
                            optionsMenu.AddDisabledItem(new GUIContent(path.fileNameWithoutExtension( ) + ": File not found"));
                        }
                    }
                    optionsMenu.DropDown(EditorHelper.PopupRect(GUILayoutUtility.GetLastRect()));
                }
                GUILayout.Label(Icon.Get("SceneAsset Icon"), EditorStyles.toolbarButton, GUILayout.Width(26));
                if (EditorHelper.HasMouseClick(GUILayoutUtility.GetLastRect()))
                {
                    var optionsMenu = new GenericMenu();
                    foreach (var e in m_localSettings.sceneList2)
                    {
                        var path = AssetDatabase.GUIDToAssetPath(e);
                        if (File.Exists(path))
                        {
                            optionsMenu.AddItem(new GUIContent(path.fileNameWithoutExtension(  )), false, onLoadScene, path);
                        }
                        else
                        {
                            optionsMenu.AddDisabledItem(new GUIContent(path.fileNameWithoutExtension(  ) + ": File not found"));
                        }
                    }
                    optionsMenu.DropDown(EditorHelper.PopupRect(GUILayoutUtility.GetLastRect()));
                }


                GUILayout.Label(Icon.Get("GameManager Icon"), EditorStyles.toolbarButton, GUILayout.Width(26));
                if (EditorHelper.HasMouseClick(GUILayoutUtility.GetLastRect()))
                {
                    var optionsMenu = new GenericMenu();
                    //optionsMenu.AddItem( new GUIContent( "ScriptingDefineSymbols" ), false, onSelectObject, "Assets/Game/ScriptingDefineSymbols.asset" );
                    foreach (var e in m_localSettings.scriptableObjectList)
                    {
                        var path = AssetDatabase.GUIDToAssetPath(e);
                        if (File.Exists(path))
                        {
                            optionsMenu.AddItem(new GUIContent(path.fileNameWithoutExtension(  )), false, onSelectObject, path);
                        }
                        else
                        {
                            optionsMenu.AddDisabledItem(new GUIContent(path.fileNameWithoutExtension(  ) + ": File not found"));
                        }
                    }
                    optionsMenu.DropDown(EditorHelper.PopupRect(GUILayoutUtility.GetLastRect()));
                }

                GUILayout.Label(Icon.Get("Folder Icon"), EditorStyles.toolbarButton, GUILayout.Width(26));
                if (EditorHelper.HasMouseClick(GUILayoutUtility.GetLastRect()))
                {
                    var optionsMenu = new GenericMenu();
                    optionsMenu.AddItem(new GUIContent("Local"), false, onShowFolderConternts, "Assets/Local");
                    optionsMenu.AddItem(new GUIContent("CutScene"), false, onShowFolderConternts, "Assets/Grp/CutScene");
                    optionsMenu.DropDown(EditorHelper.PopupRect(GUILayoutUtility.GetLastRect()));
                }



                GUILayout.Space(12);
#if false
                GUILayout.Label(Icon.Get("BuildSettings.Metro.Small"), EditorStyles.toolbarButton, GUILayout.Width(26));
                if (ut.hasMouseClick(GUILayoutUtility.GetLastRect()))
                {
                    EditorApplication.ExecuteMenuItem("Window/" + Hananokia.className + "/" + BuildWindow.className);
                }
#endif
                GUILayout.Label(Icon.Get("GameManager Icon"), EditorStyles.toolbarButton, GUILayout.Width(26));
                if (EditorHelper.HasMouseClick(GUILayoutUtility.GetLastRect()))
                {
                    EditorApplication.ExecuteMenuItem("Window/ProjectSettingWindow");
                }

#if UNITY_2017
                GUILayout.Label(Icon.Get("Animation Icon"), EditorStyles.toolbarButton, GUILayout.Width(26));
#endif
#if UNITY_2018
                GUILayout.Label(Icon.Get("UnityEditor.AnimationWindow"), EditorStyles.toolbarButton, GUILayout.Width(26));
#endif
                if (EditorHelper.HasMouseClick(GUILayoutUtility.GetLastRect()))
                {
                    EditorUtils.AnimationWindow();
                }

#if UNITY_2017
                GUILayout.Label(Icon.Get("Animator Icon"), EditorStyles.toolbarButton, GUILayout.Width(26));
#endif
#if UNITY_2018
                GUILayout.Label(Icon.Get("UnityEditor.Graphs.AnimatorControllerTool"), EditorStyles.toolbarButton, GUILayout.Width(26));
#endif
                if (EditorHelper.HasMouseClick(GUILayoutUtility.GetLastRect()))
                {
                    EditorUtils.AnimatorWindow();
                }
                GUILayout.Label(Icon.Get("ViewToolZoom"), EditorStyles.toolbarButton, GUILayout.Width(26));
                if (EditorHelper.HasMouseClick(GUILayoutUtility.GetLastRect()))
                {
                    //builtinWindow.AnimatorWindow();
                    EditorApplication.ExecuteMenuItem("Window/Frame Debugger");
                }
#if UNITY_2017
                GUILayout.Label(Icon.Get("TimelineAsset Icon"), EditorStyles.toolbarButton, GUILayout.Width(26));
                if (ut.hasMouseClick(GUILayoutUtility.GetLastRect()))
                {
                    //builtinWindow.AnimatorWindow();
                    EditorApplication.ExecuteMenuItem("Window/Timeline");
                }
#endif
#if UNITY_2018
                GUILayout.Label(Icon.Get("TimelineSelector"), EditorStyles.toolbarButton, GUILayout.Width(26));
                if (EditorHelper.HasMouseClick(GUILayoutUtility.GetLastRect()))
                {
                    EditorApplication.ExecuteMenuItem("Window/Sequencing/Timeline");
                }
#endif

#if UNITY_2017
                GUILayout.Label(icon.get("Lighting"), EditorStyles.toolbarButton, GUILayout.Width(26));
                if (ut.hasMouseClick(GUILayoutUtility.GetLastRect()))
                {
                    EditorApplication.ExecuteMenuItem("Window/Lighting/Light Explorer");
                }
#endif
#if UNITY_2018
                GUILayout.Label(Icon.Get("Lighting"), EditorStyles.toolbarButton, GUILayout.Width(26));
                if (EditorHelper.HasMouseClick(GUILayoutUtility.GetLastRect()))
                {
                    EditorApplication.ExecuteMenuItem("Window/Rendering/Light Explorer");
                }
#endif
                GUILayout.Label(Icon.Get("UnityEditor.ConsoleWindow"), EditorStyles.toolbarButton, GUILayout.Width(26));
                if (EditorHelper.HasMouseClick(GUILayoutUtility.GetLastRect()))
                {
                    //builtinWindow.ConsoleWindow();
                    EditorApplication.ExecuteMenuItem("Window/Console Pro 3");
                }

                GUILayout.Label(Icon.Get("WelcomeScreen.AssetStoreLogo"), EditorStyles.toolbarButton, GUILayout.Width(26));
                if (EditorHelper.HasMouseClick(GUILayoutUtility.GetLastRect()))
                {
                    EditorUtils.AssetStoreWindow();
                }


                GUILayout.Space(6);
                GUILayout.Label(m_searchFilterModeName[m_searchFilterMode], m_styles.ToolbarPopup, GUILayout.Width(140));
                if (EditorHelper.HasMouseClick(GUILayoutUtility.GetLastRect(), EventMouseButton.R))
                {
                    m_searchFilterMode = 1 - m_searchFilterMode;
                    this.Repaint();
                }
                else if (EditorHelper.HasMouseClick(GUILayoutUtility.GetLastRect(), EventMouseButton.L))
                {
                    var m = new GenericMenu();

                    if (m_searchFilterMode == 0)
                    {
                        for (int i = 0; i < m_searchFilterHierarchy.Length; i++)
                        {
                            m.AddItem(m_searchFilterHierarchy[i], false, onHierarchy_SetSearchFilter, m_searchFilterHierarchy[i].text);
                        }
                    }
                    else if (m_searchFilterMode == 1)
                    {
                        for (int i = 0; i < m_searchFilterProject.Length; i++)
                        {
                            m.AddItem(m_searchFilterProject[i], false, onProjectBrowser_SetSearch, m_searchFilterProject[i].text);
                        }
                    }

                    m.DropDown(EditorHelper.PopupRect(GUILayoutUtility.GetLastRect()));
                }

                //if( m_guidEdit == false ) {
                GUILayout.Label(m_guid, EditorStyles.toolbarButton, GUILayout.Width(220));
                if (EditorHelper.HasMouseClick(GUILayoutUtility.GetLastRect(), EventMouseButton.R))
                {
                    m_guidEdit = !m_guidEdit;
                    Repaint();
                }
                if (EditorHelper.HasMouseClick(GUILayoutUtility.GetLastRect()))
                {
                    //var path = AssetDatabase.GUIDToAssetPath( m_guid );
                    //if( !string.IsNullOrEmpty( path ) ){
                    //	var obj = AssetDatabase.LoadAssetAtPath<UnityObject>( path );
                    //	Selection.activeObject = obj;
                    //}
                    var m = new GenericMenu();
                    m.AddItem(new GUIContent("クリップボードにコピー"), false, () => { GUIUtility.systemCopyBuffer = m_guid; });
                    m.DropDown(EditorHelper.PopupRect(GUILayoutUtility.GetLastRect()));
                }

                if (m_focusLost)
                {
                    GUIUtility.keyboardControl = 0;
                    m_focusLost = false;
                }

                int textFieldID = GUIUtility.GetControlID("TextField".GetHashCode(), FocusType.Keyboard) + 1;
                if (textFieldID == 0)
                {
                }
                else
                {
                    // Handle custom copy-paste
                    string guid = HandleCopyPaste(textFieldID) ?? "";
                    bool   bb   = false;
                    if (!string.IsNullOrEmpty(guid))
                    {
                        m_guidTextEdit = guid;
                        bb             = true;
                    }
                    GUI.changed = false;

                    //Rect rect = GUILayoutUtility.GetRect( 220f, GUILayoutUtility.GetLastRect().y );
                    //rect.x += 4f;
                    //rect.y += 2f;

                    // 検索ボックスを表示
                    //int controlID = GUIUtility.GetControlID( searchFieldHash, FocusType.Passive, rect );
                    //m_guidTextEdit = ToolbarSearchField( controlID, rect, m_guidTextEdit, false );
                    m_guidTextEdit = GUILayout.TextField(m_guidTextEdit, toolbarSearchField, GUILayout.Width(220));
                    if (GUI.changed || bb)
                    {
                        var path = AssetDatabase.GUIDToAssetPath(m_guidTextEdit);
                        if (!string.IsNullOrEmpty(path))
                        {
                            var obj = AssetDatabase.LoadAssetAtPath <UnityObject>(path);
                            EditorGUIUtility.PingObject(obj);
                        }
                    }
                    GUILayout.Button(GUIContent.none, toolbarSearchFieldCancelButtonEmpty);
                }

                //}
                //else {
                //	int textFieldID = GUIUtility.GetControlID( "TextField".GetHashCode(), FocusType.Keyboard ) + 1;
                //	if( textFieldID == 0 ) { }
                //	else {
                //		// Handle custom copy-paste
                //		string guid = HandleCopyPaste( textFieldID ) ?? m_guid;

                //		guid = GUILayout.TextField( guid, EditorStyles.toolbarTextField, GUILayout.Width( 220 ) );
                //		if( m_guid != guid ) {
                //			//Event.current.Use();
                //			var path = AssetDatabase.GUIDToAssetPath( guid );
                //			if( !string.IsNullOrEmpty( path ) ) {
                //				var obj = AssetDatabase.LoadAssetAtPath<UnityObject>( path );
                //				EditorGUIUtility.PingObject( obj );
                //			}
                //		}
                //		m_guid = guid;
                //	}
                //	//if( ut.hasMouseClick( GUILayoutUtility.GetLastRect(), EventMouseButton.R ) ) {
                //	//	m_guidEdit = !m_guidEdit;
                //	//	Repaint();
                //	//}
                //}

                GUILayout.FlexibleSpace();
            }
        }
        private void SinglePassStereoGUI(BuildTargetGroup targetGroup, SerializedProperty stereoRenderingPath)
        {
            if (!PlayerSettings.virtualRealitySupported)
            {
                return;
            }

            bool supportsMultiPass           = IsStereoRenderingModeSupported(targetGroup, StereoRenderingPath.MultiPass);
            bool supportsSinglePass          = IsStereoRenderingModeSupported(targetGroup, StereoRenderingPath.SinglePass);
            bool supportsSinglePassInstanced = IsStereoRenderingModeSupported(targetGroup, StereoRenderingPath.Instancing);

            // populate the dropdown with the valid options based on target platform.
            int multiPassAndSinglePass           = 2;
            int validStereoRenderingOptionsCount = multiPassAndSinglePass + (supportsSinglePassInstanced ? 1 : 0);
            var validStereoRenderingPaths        = new GUIContent[validStereoRenderingOptionsCount];
            var validStereoRenderingValues       = new int[validStereoRenderingOptionsCount];

            GUIContent[] stereoRenderingPaths = GetStereoRenderingPaths(targetGroup);

            int addedStereoRenderingOptionsCount = 0;

            validStereoRenderingPaths[addedStereoRenderingOptionsCount]    = stereoRenderingPaths[(int)StereoRenderingPath.MultiPass];
            validStereoRenderingValues[addedStereoRenderingOptionsCount++] = (int)StereoRenderingPath.MultiPass;

            validStereoRenderingPaths[addedStereoRenderingOptionsCount]    = stereoRenderingPaths[(int)StereoRenderingPath.SinglePass];
            validStereoRenderingValues[addedStereoRenderingOptionsCount++] = (int)StereoRenderingPath.SinglePass;

            if (supportsSinglePassInstanced)
            {
                validStereoRenderingPaths[addedStereoRenderingOptionsCount]    = stereoRenderingPaths[(int)StereoRenderingPath.Instancing];
                validStereoRenderingValues[addedStereoRenderingOptionsCount++] = (int)StereoRenderingPath.Instancing;
            }

            // setup fallbacks
            if (!supportsMultiPass && (stereoRenderingPath.intValue == (int)StereoRenderingPath.MultiPass))
            {
                stereoRenderingPath.intValue = (int)StereoRenderingPath.SinglePass;
                m_ShowMultiPassSRPInfoBox    = true;
            }

            if (!supportsSinglePassInstanced && (stereoRenderingPath.intValue == (int)StereoRenderingPath.Instancing))
            {
                stereoRenderingPath.intValue = (int)StereoRenderingPath.SinglePass;
            }

            if (!supportsSinglePass && (stereoRenderingPath.intValue == (int)StereoRenderingPath.SinglePass))
            {
                stereoRenderingPath.intValue = (int)StereoRenderingPath.MultiPass;
            }

            if (m_ShowMultiPassSRPInfoBox)
            {
                EditorGUILayout.HelpBox(Styles.multiPassNotSupportedWithSRP.text, MessageType.Info);
            }

            var rect = EditorGUILayout.GetControlRect();

            EditorGUI.BeginProperty(rect, EditorGUIUtility.TrTextContent("Stereo Rendering Mode*"), stereoRenderingPath);
            rect = EditorGUI.PrefixLabel(rect, EditorGUIUtility.TrTextContent("Stereo Rendering Mode*"));

            int index = Math.Max(0, Array.IndexOf(validStereoRenderingValues, stereoRenderingPath.intValue));

            if (EditorGUI.DropdownButton(rect, validStereoRenderingPaths[index], FocusType.Passive))
            {
                var menu = new GenericMenu();
                for (int i = 0; i < validStereoRenderingValues.Length; i++)
                {
                    int  value    = validStereoRenderingValues[i];
                    bool selected = (value == stereoRenderingPath.intValue);

                    if (!IsStereoRenderingModeSupported(targetGroup, (StereoRenderingPath)value))
                    {
                        menu.AddDisabledItem(validStereoRenderingPaths[i], selected);
                    }
                    else
                    {
                        menu.AddItem(validStereoRenderingPaths[i], selected, (object userData) => { OnStereoModeSelected(stereoRenderingPath, userData); }, value);
                    }
                }
                menu.DropDown(rect);
            }
            EditorGUI.EndProperty();

            if ((stereoRenderingPath.intValue == (int)StereoRenderingPath.SinglePass) && (targetGroup == BuildTargetGroup.Android))
            {
                var apisAndroid = PlayerSettings.GetGraphicsAPIs(BuildTarget.Android);
                if ((apisAndroid.Length > 0) && (apisAndroid[0] == GraphicsDeviceType.OpenGLES3))
                {
                    if (supportsMultiPass)
                    {
                        EditorGUILayout.HelpBox(Styles.singlepassAndroidWarning2.text, MessageType.Info);
                    }
                    else
                    {
                        EditorGUILayout.HelpBox(Styles.singlepassAndroidWarning3.text, MessageType.Info);
                    }
                }
                else
                {
                    EditorGUILayout.HelpBox(Styles.singlepassAndroidWarning.text, MessageType.Warning);
                }
            }
            else if ((stereoRenderingPath.intValue == (int)StereoRenderingPath.Instancing) && (targetGroup == BuildTargetGroup.Standalone))
            {
                EditorGUILayout.HelpBox(Styles.singlePassInstancedWarning.text, MessageType.Warning);
            }

            m_Settings.serializedObject.ApplyModifiedProperties();
        }
        void DrawOptions()
        {
            if (currentMode.headerState.options == TimelineModeGUIState.Hidden || state.editSequence.asset == null)
            {
                return;
            }

            using (new EditorGUI.DisabledScope(currentMode.headerState.options == TimelineModeGUIState.Disabled))
            {
                var rect = new Rect(position.width - WindowConstants.cogButtonWidth, 0, WindowConstants.cogButtonWidth, WindowConstants.timeAreaYPosition);
                if (EditorGUI.DropdownButton(rect, DirectorStyles.optionsCogIcon, FocusType.Keyboard, EditorStyles.toolbarButton))
                {
                    GenericMenu menu = new GenericMenu();

                    menu.AddItem(L10n.TextContent("Preferences Page..."), false, () => SettingsWindow.Show(SettingsScope.User, "Preferences/Timeline"));
                    menu.AddSeparator("");

                    menu.AddItem(MenuItemFrames, state.timeFormat == TimeFormat.Frames, () => state.timeFormat     = TimeFormat.Frames);
                    menu.AddItem(MenuItemTimecode, state.timeFormat == TimeFormat.Timecode, () => state.timeFormat = TimeFormat.Timecode);
                    menu.AddItem(MenuItemSeconds, state.timeFormat == TimeFormat.Seconds, () => state.timeFormat   = TimeFormat.Seconds);

                    menu.AddSeparator("");

                    TimeAreaContextMenu.AddTimeAreaMenuItems(menu, state);

                    menu.AddSeparator("");

                    bool standardFrameRate = false;
                    for (int i = 0; i < TimelineProjectSettings.framerateValues.Length; i++)
                    {
                        standardFrameRate |= AddStandardFrameRateMenu(menu, "Frame Rate/" + TimelineProjectSettings.framerateLabels[i], TimelineProjectSettings.framerateValues[i]);
                    }

                    if (standardFrameRate)
                    {
                        menu.AddDisabledItem(L10n.TextContent("Frame Rate/Custom"));
                    }
                    else
                    {
                        menu.AddItem(L10n.TextContent("Frame Rate/Custom (" + state.editSequence.frameRate + ")"), true, () => {});
                    }

                    menu.AddSeparator("");
                    if (state.playRangeEnabled)
                    {
                        menu.AddItem(L10n.TextContent("Play Range Mode/Loop"), state.playRangeLoopMode, () => state.playRangeLoopMode  = true);
                        menu.AddItem(L10n.TextContent("Play Range Mode/Once"), !state.playRangeLoopMode, () => state.playRangeLoopMode = false);
                    }
                    else
                    {
                        menu.AddDisabledItem(L10n.TextContent("Play Range Mode"));
                    }

                    if (Unsupported.IsDeveloperMode())
                    {
                        menu.AddSeparator("");
                        menu.AddItem(L10n.TextContent("Show Snapping Debug"), SnapEngine.displayDebugLayout,
                                     () => SnapEngine.displayDebugLayout = !SnapEngine.displayDebugLayout);

                        menu.AddItem(L10n.TextContent("Debug TimeArea"), false,
                                     () =>
                                     Debug.LogFormat("translation: {0}   scale: {1}   rect: {2}   shownRange: {3}", m_TimeArea.translation, m_TimeArea.scale, m_TimeArea.rect, m_TimeArea.shownArea));

                        menu.AddItem(L10n.TextContent("Edit Skin"), false, () => Selection.activeObject = DirectorStyles.Instance.customSkin);

                        menu.AddItem(L10n.TextContent("Show QuadTree Debugger"), state.showQuadTree,
                                     () => state.showQuadTree = !state.showQuadTree);
                    }

                    menu.DropDown(rect);
                }
            }
        }
Ejemplo n.º 9
0
        void TopToolbar(Rect toolbarPos)
        {
            if (m_SearchStyles == null)
            {
                m_SearchStyles = new List <GUIStyle>();
                m_SearchStyles.Add(GetStyle("ToolbarSeachTextFieldPopup")); //GetStyle("ToolbarSeachTextField");
                m_SearchStyles.Add(GetStyle("ToolbarSeachCancelButton"));
                m_SearchStyles.Add(GetStyle("ToolbarSeachCancelButtonEmpty"));
            }
            if (m_ButtonStyle == null)
            {
                m_ButtonStyle = GetStyle("ToolbarButton");
            }
            if (m_CogIcon == null)
            {
                m_CogIcon = EditorGUIUtility.FindTexture("_Popup");
            }


            GUILayout.BeginArea(new Rect(0, 0, toolbarPos.width, k_SearchHeight));

            GUILayout.BeginHorizontal(EditorStyles.toolbar);
            {
                float spaceBetween = 4f;


                {
                    var  guiMode = new GUIContent("Create");
                    Rect rMode   = GUILayoutUtility.GetRect(guiMode, EditorStyles.toolbarDropDown);
                    if (EditorGUI.DropdownButton(rMode, guiMode, FocusType.Passive, EditorStyles.toolbarDropDown))
                    {
                        var menu = new GenericMenu();
                        foreach (var templateObject in settings.GroupTemplateObjects)
                        {
                            if (templateObject != null)
                            {
                                menu.AddItem(new GUIContent("Group/" + templateObject.name), false, m_EntryTree.CreateNewGroup, templateObject);
                            }
                        }
                        menu.AddSeparator(string.Empty);
                        menu.AddItem(new GUIContent("Group/Blank (no schema)"), false, m_EntryTree.CreateNewGroup, null);
                        menu.DropDown(rMode);
                    }
                }

                CreateProfileDropdown();

                {
                    var  guiMode = new GUIContent("Tools");
                    Rect rMode   = GUILayoutUtility.GetRect(guiMode, EditorStyles.toolbarDropDown);
                    if (EditorGUI.DropdownButton(rMode, guiMode, FocusType.Passive, EditorStyles.toolbarDropDown))
                    {
                        var menu = new GenericMenu();
                        menu.AddItem(new GUIContent("Inspect System Settings"), false, () =>
                        {
                            EditorApplication.ExecuteMenuItem("Window/General/Inspector");
                            EditorGUIUtility.PingObject(AddressableAssetSettingsDefaultObject.Settings);
                            Selection.activeObject = AddressableAssetSettingsDefaultObject.Settings;
                        });
                        menu.AddItem(new GUIContent("Profiles"), false, () => EditorWindow.GetWindow <ProfileWindow>().Show(true));
                        menu.AddItem(new GUIContent("Labels"), false, () => EditorWindow.GetWindow <LabelWindow>(true).Intialize(settings));
                        menu.AddItem(new GUIContent("Analyze"), false, AnalyzeWindow.ShowWindow);
                        menu.AddItem(new GUIContent("Hosting Services"), false, () => EditorWindow.GetWindow <HostingServicesWindow>().Show(settings));
                        menu.AddItem(new GUIContent("Event Viewer"), false, ResourceProfilerWindow.ShowWindow);
                        menu.AddItem(new GUIContent("Check for Content Update Restrictions"), false, OnPrepareUpdate);
                        menu.AddItem(new GUIContent("Show Sprite and Subobject Addresses"), ProjectConfigData.showSubObjectsInGroupView, () => { ProjectConfigData.showSubObjectsInGroupView = !ProjectConfigData.showSubObjectsInGroupView; m_EntryTree.Reload(); });

                        var bundleList = AssetDatabase.GetAllAssetBundleNames();
                        if (bundleList != null && bundleList.Length > 0)
                        {
                            menu.AddItem(new GUIContent("Convert Legacy AssetBundles"), false, () => window.OfferToConvert(AddressableAssetSettingsDefaultObject.Settings));
                        }

                        menu.DropDown(rMode);
                    }
                }

                GUILayout.FlexibleSpace();
                GUILayout.Space(spaceBetween * 2f);

                {
                    GUILayout.Space(8);
                    var  guiMode = new GUIContent("Play Mode Script");
                    Rect rMode   = GUILayoutUtility.GetRect(guiMode, EditorStyles.toolbarDropDown);
                    if (EditorGUI.DropdownButton(rMode, guiMode, FocusType.Passive, EditorStyles.toolbarDropDown))
                    {
                        var menu = new GenericMenu();
                        for (int i = 0; i < settings.DataBuilders.Count; i++)
                        {
                            var m = settings.GetDataBuilder(i);
                            if (m.CanBuildData <AddressablesPlayModeBuildResult>())
                            {
                                menu.AddItem(new GUIContent(m.Name), i == settings.ActivePlayModeDataBuilderIndex, OnSetActivePlayModeScript, i);
                            }
                        }
                        menu.DropDown(rMode);
                    }
                }

                var  guiBuild = new GUIContent("Build");
                Rect rBuild   = GUILayoutUtility.GetRect(guiBuild, EditorStyles.toolbarDropDown);
                if (EditorGUI.DropdownButton(rBuild, guiBuild, FocusType.Passive, EditorStyles.toolbarDropDown))
                {
                    //GUIUtility.hotControl = 0;
                    var menu = new GenericMenu();
                    var AddressablesPlayerBuildResultBuilderExists = false;
                    for (int i = 0; i < settings.DataBuilders.Count; i++)
                    {
                        var m = settings.GetDataBuilder(i);
                        if (m.CanBuildData <AddressablesPlayerBuildResult>())
                        {
                            AddressablesPlayerBuildResultBuilderExists = true;
                            menu.AddItem(new GUIContent("New Build/" + m.Name), false, OnBuildScript, i);
                        }
                    }

                    if (!AddressablesPlayerBuildResultBuilderExists)
                    {
                        menu.AddDisabledItem(new GUIContent("New Build/No Build Script Available"));
                    }

                    menu.AddItem(new GUIContent("Update a Previous Build"), false, OnUpdateBuild);
                    menu.AddItem(new GUIContent("Clean Build/All"), false, OnCleanAll);
                    menu.AddItem(new GUIContent("Clean Build/Content Builders/All"), false, OnCleanAddressables, null);
                    for (int i = 0; i < settings.DataBuilders.Count; i++)
                    {
                        var m = settings.GetDataBuilder(i);
                        menu.AddItem(new GUIContent("Clean Build/Content Builders/" + m.Name), false, OnCleanAddressables, m);
                    }
                    menu.AddItem(new GUIContent("Clean Build/Build Pipeline Cache"), false, OnCleanSBP);
                    menu.DropDown(rBuild);
                }

                GUILayout.Space(4);
                Rect searchRect    = GUILayoutUtility.GetRect(0, toolbarPos.width * 0.6f, 16f, 16f, m_SearchStyles[0], GUILayout.MinWidth(65), GUILayout.MaxWidth(300));
                Rect popupPosition = searchRect;
                popupPosition.width = 20;

                if (Event.current.type == EventType.MouseDown && popupPosition.Contains(Event.current.mousePosition))
                {
                    var menu = new GenericMenu();
                    menu.AddItem(new GUIContent("Hierarchical Search"), ProjectConfigData.hierarchicalSearch, OnHierSearchClick);
                    menu.DropDown(popupPosition);
                }
                else
                {
                    var baseSearch   = ProjectConfigData.hierarchicalSearch ? m_EntryTree.customSearchString : m_EntryTree.searchString;
                    var searchString = m_SearchField.OnGUI(searchRect, baseSearch, m_SearchStyles[0], m_SearchStyles[1], m_SearchStyles[2]);
                    if (baseSearch != searchString)
                    {
                        if (ProjectConfigData.hierarchicalSearch)
                        {
                            m_EntryTree.customSearchString = searchString;
                            Reload();
                        }
                        else
                        {
                            m_EntryTree.searchString = searchString;
                        }
                    }
                }
            }
            GUILayout.EndHorizontal();
            GUILayout.EndArea();
        }
Ejemplo n.º 10
0
        public static void DisplayDropdownMenu(Rect position, IList <MenuOption> options)
        {
            if (Mode == DisplayMode.Playback)
            {
                if (prepickedSelections.Count == 0)
                {
                    return;
                }

                int index;
                if (int.TryParse(prepickedSelections.Dequeue(), out index) == false)
                {
                    return;
                }

                if (index == -1)
                {
                    return;
                }

                MenuItem item = options[index] as MenuItem;
                if (item == null)
                {
                    return;
                }

                if (item.Func != null)
                {
                    item.Func();
                }
                else if (item.Func2 != null)
                {
                    item.Func2(item.UserData);
                }

                return;
            }

            GenericMenu menu = new GenericMenu();

            for (int i = 0; i < options.Count; i++)
            {
                MenuOption closuredOption = options[i];

                if (closuredOption is MenuSeparator)
                {
                    menu.AddSeparator(closuredOption.Label.text);
                }
                else if (closuredOption is DisabledMenuItem)
                {
                    menu.AddDisabledItem(closuredOption.Label);
                }
                else
                {
                    MenuItem item = closuredOption as MenuItem;

                    Action itemCallback;

                    if (item.Func2 != null)
                    {
                        itemCallback = () => item.Func2(item.UserData);
                    }
                    else
                    {
                        itemCallback = () => item.Func();
                    }

                    GenericMenu.MenuFunction finalCallback = new GenericMenu.MenuFunction(itemCallback);

                    if (Mode == DisplayMode.Recording)
                    {
                        int closuredIndex = i;
                        finalCallback = () =>
                        {
                            recordedSelections.Enqueue(closuredIndex.ToString());
                            itemCallback();
                        };
                    }

                    menu.AddItem(closuredOption.Label, item.On, finalCallback);
                }
            }

            menu.DropDown(position);
        }
Ejemplo n.º 11
0
        public static void OnPrimitiveMenuGUI(int windowID)
        {
            GUIStyle createBrushStyle = new GUIStyle(EditorStyles.toolbarButton);

            createBrushStyle.fixedHeight = 20;

            GUILayout.BeginHorizontal();
            GUILayout.Label("Create primitive", EditorStyles.boldLabel);
            GUILayout.FlexibleSpace();

            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();

            if (GUILayout.Button(SabreCSGResources.ButtonSphereTexture, createBrushStyle))
            {
                CreatePrimitiveBrush(PrimitiveBrushType.Sphere);
                primitiveMenuShowing = false;
            }

            if (GUILayout.Button(SabreCSGResources.ButtonIcoSphereTexture, createBrushStyle))
            {
                CreatePrimitiveBrush(PrimitiveBrushType.IcoSphere);
                primitiveMenuShowing = false;
            }

            if (GUILayout.Button(SabreCSGResources.ButtonStairsTexture, createBrushStyle))
            {
                CreateCompoundBrush <StairBrush>();
                primitiveMenuShowing = false;
            }

            if (GUILayout.Button(SabreCSGResources.ButtonCurvedStairsTexture, createBrushStyle))
            {
                CreateCompoundBrush <CurvedStairBrush>();
                primitiveMenuShowing = false;
            }

            GUILayout.EndHorizontal();
            GUILayout.BeginHorizontal(GUILayout.ExpandHeight(true));

            if (GUILayout.Button(SabreCSGResources.ButtonCylinderTexture, createBrushStyle))
            {
                CreatePrimitiveBrush(PrimitiveBrushType.Cylinder);
                primitiveMenuShowing = false;
            }

            if (GUILayout.Button(SabreCSGResources.ButtonConeTexture, createBrushStyle))
            {
                CreatePrimitiveBrush(PrimitiveBrushType.Cone);
                primitiveMenuShowing = false;
            }

            if (GUILayout.Button(SabreCSGResources.ButtonShapeEditorTexture, createBrushStyle))
            {
                CreateCompoundBrush <ShapeEditor.ShapeEditorBrush>();
                primitiveMenuShowing = false;
            }

            if (GUILayout.Button(SabreCSGResources.ButtonMoreTexture, createBrushStyle))
            {
                GenericMenu menu = new GenericMenu();

                List <Type> compoundBrushTypes = CompoundBrush.FindAllInAssembly();
                for (int i = 0; i < compoundBrushTypes.Count; i++)
                {
                    int j = i; // Closure causes "i" to be "2" in the lambda expression unless we assign it to a scoped variable.
                    menu.AddItem(
                        new GUIContent(compoundBrushTypes[i].Name),
                        false,
                        () => {
                        CreateCompoundBrush(compoundBrushTypes[j]);
                        primitiveMenuShowing = false;
                    }
                        );
                }

                menu.AddSeparator("");

                menu.AddItem(
                    new GUIContent("Add More?"),
                    false,
                    () => {
                    EditorUtility.DisplayDialog("SabreCSG - About Compound Brushes", "Any custom compound brushes in your project are automatically detected and added to this list. Simply inherit from 'Sabresaurus.SabreCSG.CompoundBrush'.", "Okay");
                    primitiveMenuShowing = false;
                }
                    );

                menu.DropDown(new Rect(60, createBrushStyle.fixedHeight, 100, createBrushStyle.fixedHeight));
            }

            GUILayout.EndHorizontal();
        }
Ejemplo n.º 12
0
        public override void OnFlowWindowGUI(FD.FlowWindow window)
        {
            var data = FlowSystem.GetData();

            if (data == null)
            {
                return;
            }

            var flag = (window.IsFunction() == true &&
                        window.IsSmall() == true &&
                        window.IsContainer() == false);

            if (flag == true)
            {
                var alreadyConnectedFunctionIds = new List <int>();

                // Find caller window
                var windowFrom = data.windowAssets.FirstOrDefault((item) => item.HasAttach(window.id));
                if (windowFrom != null)
                {
                    var attaches = windowFrom.GetAttachedWindows();
                    foreach (var attachWindow in attaches)
                    {
                        if (attachWindow.IsFunction() == true)
                        {
                            alreadyConnectedFunctionIds.Add(attachWindow.GetFunctionId());
                        }
                    }
                }

                foreach (var win in data.windowAssets)
                {
                    if (win.IsFunction() == true &&
                        win.IsContainer() == true)
                    {
                        var count = alreadyConnectedFunctionIds.Count((e) => e == win.id);
                        if ((window.GetFunctionId() == win.id && count == 1) || count == 0)
                        {
                        }
                        else
                        {
                            if (win.id == window.functionId)
                            {
                                window.functionId = 0;
                            }
                            alreadyConnectedFunctionIds.Remove(win.id);
                        }
                    }
                }

                var functionId        = window.GetFunctionId();
                var functionContainer = functionId == 0 ? null : data.GetWindow(functionId);
                var isActiveSelected  = true;

                var oldColor = GUI.color;
                GUI.color = isActiveSelected ? Color.white : Color.grey;
                var result = GUILayout.Button(functionContainer != null ? functionContainer.title : "None", FlowSystemEditorWindow.defaultSkin.button, GUILayout.ExpandHeight(true));
                GUI.color = oldColor;
                var rect = GUILayoutUtility.GetLastRect();
                rect.y += rect.height;

                if (result == true)
                {
                    var menu = new GenericMenu();
                    menu.AddItem(new GUIContent("None"), window.functionId == 0, () => {
                        window.functionId = 0;
                    });

                    if (windowFrom != null)
                    {
                        alreadyConnectedFunctionIds.Clear();
                        var attaches = windowFrom.GetAttachedWindows();
                        foreach (var attachWindow in attaches)
                        {
                            if (attachWindow.IsFunction() == true)
                            {
                                alreadyConnectedFunctionIds.Add(attachWindow.GetFunctionId());
                            }
                        }
                    }
                    foreach (var win in data.windowAssets)
                    {
                        if (win.IsFunction() == true &&
                            win.IsContainer() == true)
                        {
                            var count = alreadyConnectedFunctionIds.Count((e) => e == win.id);
                            if ((window.GetFunctionId() == win.id && count == 1) || count == 0)
                            {
                                var id = win.id;
                                menu.AddItem(new GUIContent(win.title), win.id == window.functionId, () => {
                                    window.functionId = id;
                                });
                            }
                            else
                            {
                                if (win.id == window.functionId)
                                {
                                    window.functionId = 0;
                                }

                                alreadyConnectedFunctionIds.Remove(win.id);
                                menu.AddDisabledItem(new GUIContent(win.title));
                            }
                        }
                    }

                    menu.DropDown(rect);
                }
            }
        }
Ejemplo n.º 13
0
 public static void Show(this GenericMenu menu, Vector2 pos, float minWidth = 40)
 {
     menu.DropDown(new Rect(pos, Vector2.zero));
 }
Ejemplo n.º 14
0
        static Object DoObjectField(Rect position, Rect dropRect, int id, Object obj, Object objBeingEdited, System.Type objType, SerializedProperty property, EditorGUI.ObjectFieldValidator validator, GUIStyle style, SearchContext context, SearchViewFlags searchViewFlags = SearchViewFlags.None)
        {
            if (validator == null)
            {
                validator = EditorGUI.ValidateObjectFieldAssignment;
            }
            if (property != null)
            {
                obj = property.objectReferenceValue;
            }
            Event     evt       = Event.current;
            EventType eventType = evt.type;

            // special case test, so we continue to ping/select objects with the object field disabled
            if (!GUI.enabled && Utils.IsGUIClipEnabled() && (Event.current.rawType == EventType.MouseDown))
            {
                eventType = Event.current.rawType;
            }

            bool hasThumbnail = EditorGUIUtility.HasObjectThumbnail(objType);

            // Determine visual type
            ObjectFieldVisualType visualType = ObjectFieldVisualType.IconAndText;

            if (hasThumbnail && position.height <= EditorGUI.kObjectFieldMiniThumbnailHeight && position.width <= EditorGUI.kObjectFieldMiniThumbnailWidth)
            {
                visualType = ObjectFieldVisualType.MiniPreview;
            }
            else if (hasThumbnail && position.height > EditorGUI.kSingleLineHeight)
            {
                visualType = ObjectFieldVisualType.LargePreview;
            }

            Vector2 oldIconSize = EditorGUIUtility.GetIconSize();

            if (visualType == ObjectFieldVisualType.IconAndText)
            {
                EditorGUIUtility.SetIconSize(new Vector2(12, 12));  // Have to be this small to fit inside a single line height ObjectField
            }
            else if (visualType == ObjectFieldVisualType.LargePreview)
            {
                EditorGUIUtility.SetIconSize(new Vector2(64, 64));
            }

            if ((eventType == EventType.MouseDown && Event.current.button == 1 || eventType == EventType.ContextClick) &&
                position.Contains(Event.current.mousePosition))
            {
                var actualObject = property != null ? property.objectReferenceValue : obj;
                var contextMenu  = new GenericMenu();

                if (EditorGUI.FillPropertyContextMenu(property, null, contextMenu) != null)
                {
                    contextMenu.AddSeparator("");
                }
                contextMenu.AddItem(Utils.GUIContentTemp("Properties..."), false, () => Utils.OpenPropertyEditor(actualObject));
                contextMenu.DropDown(position);
                Event.current.Use();
            }

            switch (eventType)
            {
            case EventType.DragExited:
                if (GUI.enabled)
                {
                    HandleUtility.Repaint();
                }

                break;

            case EventType.DragUpdated:
            case EventType.DragPerform:

                if (eventType == EventType.DragPerform)
                {
                    string errorString;
                    if (!ValidDroppedObject(DragAndDrop.objectReferences, objType, out errorString))
                    {
                        Object reference = DragAndDrop.objectReferences[0];
                        EditorUtility.DisplayDialog("Can't assign script", errorString, "OK");
                        break;
                    }
                }

                if (dropRect.Contains(Event.current.mousePosition) && GUI.enabled)
                {
                    Object[] references      = DragAndDrop.objectReferences;
                    Object   validatedObject = validator(references, objType, property, EditorGUI.ObjectFieldValidatorOptions.None);

                    if (validatedObject != null)
                    {
                        DragAndDrop.visualMode = DragAndDropVisualMode.Generic;
                        if (eventType == EventType.DragPerform)
                        {
                            if (property != null)
                            {
                                property.objectReferenceValue = validatedObject;
                            }
                            else
                            {
                                obj = validatedObject;
                            }

                            GUI.changed = true;
                            DragAndDrop.AcceptDrag();
                            DragAndDrop.activeControlID = 0;
                        }
                        else
                        {
                            DragAndDrop.activeControlID = id;
                        }
                        Event.current.Use();
                    }
                }
                break;

            case EventType.MouseDown:
                if (position.Contains(Event.current.mousePosition) && Event.current.button == 0)
                {
                    // Get button rect for Object Selector
                    Rect buttonRect = GetButtonRect(visualType, position);

                    EditorGUIUtility.editingTextField = false;

                    if (buttonRect.Contains(Event.current.mousePosition))
                    {
                        if (GUI.enabled)
                        {
                            GUIUtility.keyboardControl = id;
                            ShowSearchPicker(context, searchViewFlags, property, property == null ? obj : null, id, evt, objType);
                        }
                    }
                    else
                    {
                        Object    actualTargetObject = property != null ? property.objectReferenceValue : obj;
                        Component com = actualTargetObject as Component;
                        if (com)
                        {
                            actualTargetObject = com.gameObject;
                        }
                        if (EditorGUI.showMixedValue)
                        {
                            actualTargetObject = null;
                        }

                        // One click shows where the referenced object is, or pops up a preview
                        if (Event.current.clickCount == 1)
                        {
                            GUIUtility.keyboardControl = id;

                            PingObjectOrShowPreviewOnClick(actualTargetObject, position);
                            evt.Use();
                        }
                        // Double click opens the asset in external app or changes selection to referenced object
                        else if (Event.current.clickCount == 2)
                        {
                            if (actualTargetObject)
                            {
                                AssetDatabase.OpenAsset(actualTargetObject);
                                evt.Use();
                                GUIUtility.ExitGUI();
                            }
                        }
                    }
                }
                break;

            case EventType.ExecuteCommand:
                string commandName = evt.commandName;
                if (commandName == k_PickerUpdatedCommand && s_LastPickerId == id && GUIUtility.keyboardControl == id && (property == null || !Utils.SerializedPropertyIsScript(property)))
                {
                    return(AssignSelectedObject(property, validator, objType, evt));
                }
                else if (commandName == k_PickerClosedCommand && s_LastPickerId == id && GUIUtility.keyboardControl == id)
                {
                    if (s_LastSelectionWasCanceled)
                    {
                        // User canceled object selection; don't apply
                        evt.Use();

                        // When we operate directly on objects, the undo system doesn't work.
                        // We added a hack that sets the s_LastSelectedItem to the original item
                        // when canceling with an object.
                        if (property == null)
                        {
                            return(s_LastSelectedItem);
                        }

                        break;
                    }

                    // When property is script, it is not assigned on update, so assign it on close
                    if (property != null && Utils.SerializedPropertyIsScript(property))
                    {
                        return(AssignSelectedObject(property, validator, objType, evt));
                    }

                    return(property != null ? property.objectReferenceValue : obj);
                }
                else if (Utils.IsCommandDelete(evt.commandName) && GUIUtility.keyboardControl == id)
                {
                    if (property != null)
                    {
                        property.objectReferenceValue = null;
                    }
                    else
                    {
                        obj = null;
                    }

                    GUI.changed = true;
                    evt.Use();
                }
                break;

            case EventType.ValidateCommand:
                if (Utils.IsCommandDelete(evt.commandName) && GUIUtility.keyboardControl == id)
                {
                    evt.Use();
                }
                break;

            case EventType.KeyDown:
                if (GUIUtility.keyboardControl == id)
                {
                    if (evt.keyCode == KeyCode.Backspace || (evt.keyCode == KeyCode.Delete && (evt.modifiers & EventModifiers.Shift) == 0))
                    {
                        if (property != null)
                        {
                            property.objectReferenceValue = null;
                        }
                        else
                        {
                            obj = null;
                        }

                        GUI.changed = true;
                        evt.Use();
                    }

                    // Apparently we have to check for the character being space instead of the keyCode,
                    // otherwise the Inspector will maximize upon pressing space.
                    if (Utils.MainActionKeyForControl(evt, id))
                    {
                        ShowSearchPicker(context, searchViewFlags, property, property == null ? obj : null, id, evt, objType);
                    }
                }
                break;

            case EventType.Repaint:
                GUIContent temp;
                if (EditorGUI.showMixedValue)
                {
                    temp = EditorGUI.mixedValueContent;
                }
                else
                {
                    // If obj or objType are both null, we have to rely on
                    // property.objectReferenceStringValue to display None/Missing and the
                    // correct type. But if not, EditorGUIUtility.ObjectContent is more reliable.
                    // It can take a more specific object type specified as argument into account,
                    // and it gets the icon at the same time.
                    if (obj == null && objType == null && property != null)
                    {
                        temp = Utils.GUIContentTemp(Utils.SerializedPropertyObjectReferenceStringValue(property));
                    }
                    else
                    {
                        // In order for ObjectContext to be able to distinguish between None/Missing,
                        // we need to supply an instanceID. For some reason, getting the instanceID
                        // from property.objectReferenceValue is not reliable, so we have to
                        // explicitly check property.objectReferenceInstanceIDValue if a property exists.
                        if (property != null)
                        {
                            temp = Utils.ObjectContent(obj, objType, property.objectReferenceInstanceIDValue);
                        }
                        else
                        {
                            temp = EditorGUIUtility.ObjectContent(obj, objType);
                        }
                    }

                    if (property != null)
                    {
                        if (obj != null)
                        {
                            Object[] references = { obj };
                            if (EditorSceneManager.preventCrossSceneReferences && EditorGUI.CheckForCrossSceneReferencing(obj, property.serializedObject.targetObject))
                            {
                                if (!EditorApplication.isPlaying)
                                {
                                    temp = s_SceneMismatch;
                                }
                                else
                                {
                                    temp.text = temp.text + string.Format(" ({0})", EditorGUI.GetGameObjectFromObject(obj).scene.name);
                                }
                            }
                            else if (validator(references, objType, property, EditorGUI.ObjectFieldValidatorOptions.ExactObjectTypeValidation) == null)
                            {
                                temp = s_TypeMismatch;
                            }
                        }
                    }
                }

                switch (visualType)
                {
                case ObjectFieldVisualType.IconAndText:
                    EditorGUI.BeginHandleMixedValueContentColor();
                    style.Draw(position, temp, id, DragAndDrop.activeControlID == id, position.Contains(Event.current.mousePosition));

                    Rect buttonRect = Utils.objectFieldButton.margin.Remove(GetButtonRect(visualType, position));
                    Utils.objectFieldButton.Draw(buttonRect, GUIContent.none, id, DragAndDrop.activeControlID == id, buttonRect.Contains(Event.current.mousePosition));
                    EditorGUI.EndHandleMixedValueContentColor();
                    break;

                case ObjectFieldVisualType.LargePreview:
                    DrawObjectFieldLargeThumb(position, id, obj, temp);
                    break;

                case ObjectFieldVisualType.MiniPreview:
                    DrawObjectFieldMiniThumb(position, id, obj, temp);
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
                break;
            }

            EditorGUIUtility.SetIconSize(oldIconSize);

            return(obj);
        }
Ejemplo n.º 15
0
		public override void OnFlowWindowGUI(FlowWindow window) {

			var data = FlowSystem.GetData();
			if (data == null) return;

			var flag = window.IsFunction() == true && 
					window.IsSmall() == true &&
					window.IsContainer() == false;

			if (flag == true) {

				var functionId = window.GetFunctionId();
				var functionContainer = data.GetWindow(functionId);
				var isActiveSelected = true;

				var oldColor = GUI.color;
				GUI.color = isActiveSelected ? Color.white : Color.grey;
				var result = GUILayoutExt.LargeButton(functionContainer != null ? functionContainer.title : "None", 60f, 150f);
				GUI.color = oldColor;
				var rect = GUILayoutUtility.GetLastRect();
				rect.y += rect.height;

				if (result == true) {

					var menu = new GenericMenu();
					menu.AddItem(new GUIContent("None"), window.functionId == 0, () => {

						window.functionId = 0;

					});

					foreach (var win in data.windows) {
						
						if (win.IsFunction() == true &&
						    win.IsContainer() == true) {

							var id = win.id;
							menu.AddItem(new GUIContent(win.title), win.id == window.functionId, () => {

								window.functionId = id;

							});

						}
						
					}

					menu.DropDown(rect);

				}

			}

		}
Ejemplo n.º 16
0
 public void DropDown(Rect position, VisualElement targetElement = null, bool anchored = false)
 {
     m_GenericMenu.DropDown(position);
 }
Ejemplo n.º 17
0
 internal static void Show(string folder, string currentSubFolder, Rect activatorRect, ProjectBrowser caller)
 {
     m_Caller = caller;
     string[] subFolders = AssetDatabase.GetSubFolders(folder);
     GenericMenu menu = new GenericMenu();
     if (subFolders.Length >= 0)
     {
         currentSubFolder = Path.GetFileName(currentSubFolder);
         foreach (string str in subFolders)
         {
             string fileName = Path.GetFileName(str);
             menu.AddItem(new GUIContent(fileName), fileName == currentSubFolder, new GenericMenu.MenuFunction(new ProjectBrowser.BreadCrumbListMenu(str).SelectSubFolder));
             menu.ShowAsContext();
         }
     }
     else
     {
         menu.AddDisabledItem(new GUIContent("No sub folders..."));
     }
     menu.DropDown(activatorRect);
 }
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        float BTN_WIDTH   = EditorGUIUtility.singleLineHeight + 3f;
        float BTN_GAP     = 1f;
        float LABEL_WIDTH = EditorGUIUtility.labelWidth;
        float LABEL_GAP   = EditorGUIUtility.standardVerticalSpacing;

        //Clear the editor every frame - More expensive, but caching it acts weird in lists.
        Editor editor = null;

        //Sets up the total property, to determine sizing
        EditorGUI.BeginProperty(position, label, property);

        //Generate the list of all effect types
        List <Type>   types = GetAllEffectTypes();
        List <String> names = types.Select(x => x.Name).ToList();

        //Create the bounding boxes for our new pieces. Not super important, the start positions are the main part that we need. xRect is unused if 'heldEffect' is null.
        var labelRect  = new Rect(position.x, position.y, LABEL_WIDTH, EditorGUIUtility.singleLineHeight);
        var buttonRect = new Rect(position.x + LABEL_WIDTH + LABEL_GAP, position.y, position.width - LABEL_WIDTH - LABEL_GAP, EditorGUIUtility.singleLineHeight);
        var xRect      = new Rect(position.x + position.width - (BTN_WIDTH), position.y, BTN_WIDTH, EditorGUIUtility.singleLineHeight);


        //Get our serialized properties
        SerializedProperty effect = property.FindPropertyRelative("heldEffect");

        int typeVal = -1;

        //Handle the deletion of a property / New property creation!
        if (effect.objectReferenceValue == null)
        {
            typeVal = -1;
        }
        else
        {
            //Confirm that we have the right type
            typeVal = types.IndexOf(effect.objectReferenceValue.GetType());

            if (typeVal == -1)
            {
                Debug.LogError("Didn't find it!");
            }

            buttonRect.width -= 1 * (BTN_WIDTH + BTN_GAP);

            //If we have a type, offer a deletion button!
            if (GUI.Button(xRect, "X"))
            {
                string path = AssetDatabase.GetAssetPath(effect.objectReferenceValue);
                effect.objectReferenceValue = null;
                AssetDatabase.DeleteAsset(path);
            }
        }

        //Set up the dropdown
        int selection = typeVal;


        //Temporary Testing Code

        if (effect.objectReferenceValue != null)
        {
            property.isExpanded = EditorGUI.Foldout(labelRect, property.isExpanded, GUIContent.none);
        }
        EditorGUI.LabelField(labelRect, label);

        if (EditorGUI.DropdownButton(buttonRect, new GUIContent(selection == -1 ? "" : names[selection]), FocusType.Passive))
        {
            GenericMenu menu = new GenericMenu();

            for (int i = 0; i < names.Count; i++)
            {
                string groupName           = "Default";
                Type   itemType            = types[i];
                EffectGroupAttribute group = (EffectGroupAttribute)Attribute.GetCustomAttribute(itemType, typeof(EffectGroupAttribute));
                if (group != null)
                {
                    groupName = group.groupName;
                }
                menu.AddItem(new GUIContent(groupName + "/" + names[i]), i == selection, UpdateValue, (property, i));
            }

            menu.DropDown(buttonRect);
            return;
        }

        //End Testing Code

        // Draw the SO properties, if we have an effect to draw. This code stolen from the internet. Thanks StackOverflow!
        if (effect.objectReferenceValue != null && property.isExpanded)
        {
            // Make child fields be indented
            EditorGUI.indentLevel++;

            // Draw object properties
            Editor.CreateCachedEditor(effect.objectReferenceValue, null, ref editor);

            if (editor == null)
            {
                return; //This is the something went really wrong case.
            }
            //March out rectangles for the sub-editor positions
            SerializedProperty field = editor.serializedObject.GetIterator();
            field.NextVisible(true);
            List <Rect> propertyRects = new List <Rect>();

            var marchingRect = new Rect(position.x, position.y + 20f, position.width, EditorGUIUtility.singleLineHeight);

            if (SHOW_SCRIPT_FIELD)
            {
                propertyRects.Add(marchingRect);
                marchingRect.y += EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing;
            }

            while (field.NextVisible(false))
            {
                marchingRect.height = EditorGUI.GetPropertyHeight(field, true);
                propertyRects.Add(marchingRect);
                marchingRect.y += marchingRect.height + EditorGUIUtility.standardVerticalSpacing;
            }

            //Draw the actual editor fields!
            int index = 0;
            field = editor.serializedObject.GetIterator();
            field.NextVisible(true);

            if (SHOW_SCRIPT_FIELD)
            {
                EditorGUI.BeginDisabledGroup(true);
                EditorGUI.PropertyField(propertyRects[index], field, true);
                EditorGUI.EndDisabledGroup();
                index++;
            }

            //The magicc
            while (field.NextVisible(false))
            {
                try
                {
                    EditorGUI.PropertyField(propertyRects[index], field, true);
                }
                catch (StackOverflowException)
                {
                    field.objectReferenceValue = null;
                    Debug.LogError("Self-nesting detected. The offending object has been set to null, please don't do that anymore.");
                }

                index++;
            }

            EditorGUI.indentLevel--;

            //VERY IMPORTANT - THE WHOLE THING BREAKS WITHOUT THIS
            editor.serializedObject.ApplyModifiedProperties();
        }

        EditorGUI.EndProperty();
    }
Ejemplo n.º 19
0
        public void DrawUI(SerializedProperty property)
        {
            objectId = property.serializedObject.targetObject.GetInstanceID().ToString();
            var         serializedMapObject = property.serializedObject;
            AbstractMap mapObject           = (AbstractMap)serializedMapObject.targetObject;

            tileJSONData = mapObject.VectorData.GetTileJsonData();

            var sourceTypeProperty = property.FindPropertyRelative("_sourceType");
            var sourceTypeValue    = (VectorSourceType)sourceTypeProperty.enumValueIndex;

            var displayNames = sourceTypeProperty.enumDisplayNames;
            int count        = sourceTypeProperty.enumDisplayNames.Length;

            if (!_isGUIContentSet)
            {
                _sourceTypeContent = new GUIContent[count];
                for (int extIdx = 0; extIdx < count; extIdx++)
                {
                    _sourceTypeContent[extIdx] = new GUIContent
                    {
                        text    = displayNames[extIdx],
                        tooltip = ((VectorSourceType)extIdx).Description(),
                    };
                }
                _isGUIContentSet = true;
            }

            sourceTypeValue = (VectorSourceType)sourceTypeProperty.enumValueIndex;

            var sourceOptionsProperty = property.FindPropertyRelative("sourceOptions");
            var layerSourceProperty   = sourceOptionsProperty.FindPropertyRelative("layerSource");
            var layerSourceId         = layerSourceProperty.FindPropertyRelative("Id");
            var isActiveProperty      = sourceOptionsProperty.FindPropertyRelative("isActive");

            switch (sourceTypeValue)
            {
            case VectorSourceType.MapboxStreets:
            case VectorSourceType.MapboxStreetsWithBuildingIds:
                var sourcePropertyValue = MapboxDefaultVector.GetParameters(sourceTypeValue);
                layerSourceId.stringValue = sourcePropertyValue.Id;
                GUI.enabled = false;
                if (_isInitialized)
                {
                    LoadEditorTileJSON(property, sourceTypeValue, layerSourceId.stringValue);
                }
                else
                {
                    _isInitialized = true;
                }
                if (tileJSONData.PropertyDisplayNames.Count == 0 && tileJSONData.tileJSONLoaded)
                {
                    EditorGUILayout.HelpBox("Invalid Map Id / There might be a problem with the internet connection.", MessageType.Error);
                }
                GUI.enabled = true;
                isActiveProperty.boolValue = true;
                break;

            case VectorSourceType.Custom:
                if (_isInitialized)
                {
                    string test = layerSourceId.stringValue;
                    LoadEditorTileJSON(property, sourceTypeValue, layerSourceId.stringValue);
                }
                else
                {
                    _isInitialized = true;
                }
                if (tileJSONData.PropertyDisplayNames.Count == 0 && tileJSONData.tileJSONLoaded)
                {
                    EditorGUILayout.HelpBox("Invalid Map Id / There might be a problem with the internet connection.", MessageType.Error);
                }
                isActiveProperty.boolValue = true;
                break;

            case VectorSourceType.None:
                isActiveProperty.boolValue = false;
                break;

            default:
                isActiveProperty.boolValue = false;
                break;
            }

            if (sourceTypeValue != VectorSourceType.None)
            {
                EditorGUILayout.LabelField(new GUIContent
                {
                    text    = "Map Features",
                    tooltip = "Visualizers for vector features contained in a layer. "
                });

                var subLayerArray = property.FindPropertyRelative("vectorSubLayers");

                var layersRect = EditorGUILayout.GetControlRect(GUILayout.MinHeight(Mathf.Max(subLayerArray.arraySize + 1, 1) * _lineHeight + MultiColumnHeader.DefaultGUI.defaultHeight),
                                                                GUILayout.MaxHeight((subLayerArray.arraySize + 1) * _lineHeight + MultiColumnHeader.DefaultGUI.defaultHeight));

                if (!m_Initialized)
                {
                    bool firstInit   = m_MultiColumnHeaderState == null;
                    var  headerState = FeatureSubLayerTreeView.CreateDefaultMultiColumnHeaderState();
                    if (MultiColumnHeaderState.CanOverwriteSerializedFields(m_MultiColumnHeaderState, headerState))
                    {
                        MultiColumnHeaderState.OverwriteSerializedFields(m_MultiColumnHeaderState, headerState);
                    }
                    m_MultiColumnHeaderState = headerState;

                    var multiColumnHeader = new FeatureSectionMultiColumnHeader(headerState);

                    if (firstInit)
                    {
                        multiColumnHeader.ResizeToFit();
                    }

                    treeModel = new TreeModel <FeatureTreeElement>(GetData(subLayerArray));
                    if (m_TreeViewState == null)
                    {
                        m_TreeViewState = new TreeViewState();
                    }

                    if (layerTreeView == null)
                    {
                        layerTreeView = new FeatureSubLayerTreeView(m_TreeViewState, multiColumnHeader, treeModel);
                    }
                    layerTreeView.multiColumnHeader = multiColumnHeader;
                    m_Initialized = true;
                }
                layerTreeView.Layers = subLayerArray;
                layerTreeView.Reload();
                layerTreeView.OnGUI(layersRect);

                if (layerTreeView.hasChanged)
                {
                    EditorHelper.CheckForModifiedProperty(property);
                    layerTreeView.hasChanged = false;
                }

                selectedLayers = layerTreeView.GetSelection();

                //if there are selected elements, set the selection index at the first element.
                //if not, use the Selection index to persist the selection at the right index.
                if (selectedLayers.Count > 0)
                {
                    //ensure that selectedLayers[0] isn't out of bounds
                    if (selectedLayers[0] - FeatureSubLayerTreeView.uniqueIdFeature > subLayerArray.arraySize - 1)
                    {
                        selectedLayers[0] = subLayerArray.arraySize - 1 + FeatureSubLayerTreeView.uniqueIdFeature;
                    }

                    SelectionIndex = selectedLayers[0];
                }
                else
                {
                    if (SelectionIndex > 0 && (SelectionIndex - FeatureSubLayerTreeView.uniqueIdFeature <= subLayerArray.arraySize - 1))
                    {
                        selectedLayers = new int[1] {
                            SelectionIndex
                        };
                        layerTreeView.SetSelection(selectedLayers);
                    }
                }

                GUILayout.Space(EditorGUIUtility.singleLineHeight);

                EditorGUILayout.BeginHorizontal();
                //var presetTypes = property.FindPropertyRelative("presetFeatureTypes");
                GenericMenu menu = new GenericMenu();
                foreach (var name in Enum.GetNames(typeof(PresetFeatureType)))
                {
                    menu.AddItem(new GUIContent()
                    {
                        text = name
                    }, false, FetchPresetProperties, name);
                }
                GUILayout.Space(0);                 // do not remove this line; it is needed for the next line to work
                Rect rect = GUILayoutUtility.GetLastRect();
                rect.y += 2 * _lineHeight / 3;

                if (EditorGUILayout.DropdownButton(new GUIContent {
                    text = "Add Feature"
                }, FocusType.Passive, (GUIStyle)"minibuttonleft"))
                {
                    menu.DropDown(rect);
                }

                //Assign subLayerProperties after fetching it from the presets class. This happens everytime an element is added
                if (subLayerProperties != null)
                {
                    subLayerArray.arraySize++;
                    var subLayer = subLayerArray.GetArrayElementAtIndex(subLayerArray.arraySize - 1);
                    SetSubLayerProps(subLayer);

                    //Refreshing the tree
                    layerTreeView.Layers = subLayerArray;
                    layerTreeView.AddElementToTree(subLayer);
                    layerTreeView.Reload();

                    selectedLayers = new int[1] {
                        subLayerArray.arraySize - 1 + FeatureSubLayerTreeView.uniqueIdFeature
                    };
                    layerTreeView.SetSelection(selectedLayers);
                    subLayerProperties = null;                     // setting this to null so that the if block is not called again

                    if (EditorHelper.DidModifyProperty(property))
                    {
                        ((VectorLayerProperties)EditorHelper.GetTargetObjectOfProperty(property)).OnSubLayerPropertyAdded(new VectorLayerUpdateArgs {
                            property = EditorHelper.GetTargetObjectOfProperty(subLayer) as MapboxDataProperty
                        });
                    }
                }

                if (GUILayout.Button(new GUIContent("Remove Selected"), (GUIStyle)"minibuttonright"))
                {
                    foreach (var index in selectedLayers.OrderByDescending(i => i))
                    {
                        if (layerTreeView != null)
                        {
                            var subLayer = subLayerArray.GetArrayElementAtIndex(index - FeatureSubLayerTreeView.uniqueIdFeature);

                            VectorLayerProperties    vectorLayerProperties    = (VectorLayerProperties)EditorHelper.GetTargetObjectOfProperty(property);
                            VectorSubLayerProperties vectorSubLayerProperties = (VectorSubLayerProperties)EditorHelper.GetTargetObjectOfProperty(subLayer);

                            vectorLayerProperties.OnSubLayerPropertyRemoved(new VectorLayerUpdateArgs {
                                property = vectorSubLayerProperties
                            });

                            layerTreeView.RemoveItemFromTree(index);
                            subLayerArray.DeleteArrayElementAtIndex(index - FeatureSubLayerTreeView.uniqueIdFeature);
                            layerTreeView.treeModel.SetData(GetData(subLayerArray));
                        }
                    }

                    selectedLayers = new int[0];
                    layerTreeView.SetSelection(selectedLayers);
                }

                EditorGUILayout.EndHorizontal();

                GUILayout.Space(EditorGUIUtility.singleLineHeight);

                if (selectedLayers.Count == 1 && subLayerArray.arraySize != 0 && selectedLayers[0] - FeatureSubLayerTreeView.uniqueIdFeature >= 0)
                {
                    //ensure that selectedLayers[0] isn't out of bounds
                    if (selectedLayers[0] - FeatureSubLayerTreeView.uniqueIdFeature > subLayerArray.arraySize - 1)
                    {
                        selectedLayers[0] = subLayerArray.arraySize - 1 + FeatureSubLayerTreeView.uniqueIdFeature;
                    }

                    SelectionIndex = selectedLayers[0];

                    var layerProperty = subLayerArray.GetArrayElementAtIndex(SelectionIndex - FeatureSubLayerTreeView.uniqueIdFeature);

                    layerProperty.isExpanded = true;
                    var  subLayerCoreOptions = layerProperty.FindPropertyRelative("coreOptions");
                    bool isLayerActive       = subLayerCoreOptions.FindPropertyRelative("isActive").boolValue;
                    if (!isLayerActive)
                    {
                        GUI.enabled = false;
                    }

                    DrawLayerVisualizerProperties(sourceTypeValue, layerProperty, property);

                    if (!isLayerActive)
                    {
                        GUI.enabled = true;
                    }
                }
                else
                {
                    GUILayout.Label("Select a visualizer to see properties");
                }
            }
        }
Ejemplo n.º 20
0
        void OnContextClick(Vector2 position, VolumeComponentEditor targetEditor, int id)
        {
            var targetComponent = targetEditor.target;
            var menu            = new GenericMenu();

            if (id == 0)
            {
                menu.AddDisabledItem(EditorGUIUtility.TrTextContent("Move Up"));
                menu.AddDisabledItem(EditorGUIUtility.TrTextContent("Move to Top"));
            }
            else
            {
                menu.AddItem(EditorGUIUtility.TrTextContent("Move to Top"), false, () => MoveComponent(id, -id));
                menu.AddItem(EditorGUIUtility.TrTextContent("Move Up"), false, () => MoveComponent(id, -1));
            }

            if (id == m_Editors.Count - 1)
            {
                menu.AddDisabledItem(EditorGUIUtility.TrTextContent("Move to Bottom"));
                menu.AddDisabledItem(EditorGUIUtility.TrTextContent("Move Down"));
            }
            else
            {
                menu.AddItem(EditorGUIUtility.TrTextContent("Move to Bottom"), false, () => MoveComponent(id, (m_Editors.Count - 1) - id));
                menu.AddItem(EditorGUIUtility.TrTextContent("Move Down"), false, () => MoveComponent(id, 1));
            }

            menu.AddSeparator(string.Empty);
            menu.AddItem(EditorGUIUtility.TrTextContent("Collapse All"), false, () => CollapseComponents());
            menu.AddItem(EditorGUIUtility.TrTextContent("Expand All"), false, () => ExpandComponents());
            menu.AddSeparator(string.Empty);
            menu.AddItem(EditorGUIUtility.TrTextContent("Reset"), false, () => ResetComponent(targetComponent.GetType(), id));
            menu.AddItem(EditorGUIUtility.TrTextContent("Remove"), false, () => RemoveComponent(id));
            menu.AddSeparator(string.Empty);
            if (targetEditor.hasAdditionalProperties)
            {
                menu.AddItem(EditorGUIUtility.TrTextContent("Show Additional Properties"), targetEditor.showAdditionalProperties, () => targetEditor.showAdditionalProperties ^= true);
                menu.AddItem(EditorGUIUtility.TrTextContent("Show All Additional Properties..."), false, () => CoreRenderPipelinePreferences.Open());
            }
            else
            {
                menu.AddDisabledItem(EditorGUIUtility.TrTextContent("Show Additional Properties"));
                menu.AddDisabledItem(EditorGUIUtility.TrTextContent("Show All Additional Properties..."));
            }

            menu.AddSeparator(string.Empty);
            menu.AddItem(EditorGUIUtility.TrTextContent("Copy Settings"), false, () => CopySettings(targetComponent));

            if (CanPaste(targetComponent))
            {
                menu.AddItem(EditorGUIUtility.TrTextContent("Paste Settings"), false, () => PasteSettings(targetComponent));
            }
            else
            {
                menu.AddDisabledItem(EditorGUIUtility.TrTextContent("Paste Settings"));
            }

            menu.AddSeparator(string.Empty);
            menu.AddItem(EditorGUIUtility.TrTextContent("Toggle All"), false, () => m_Editors[id].SetAllOverridesTo(true));
            menu.AddItem(EditorGUIUtility.TrTextContent("Toggle None"), false, () => m_Editors[id].SetAllOverridesTo(false));

            menu.DropDown(new Rect(position, Vector2.zero));
        }
Ejemplo n.º 21
0
        private static void OnBottomToolbarGUI(int windowID)
        {
            GUILayout.BeginHorizontal();

            GUIStyle createBrushStyle = new GUIStyle(EditorStyles.toolbarButton);

            createBrushStyle.fixedHeight = 20;
            if (GUI.Button(new Rect(0, 0, 30, createBrushStyle.fixedHeight), SabreCSGResources.ButtonCubeTexture, createBrushStyle))
            {
                CreatePrimitiveBrush(PrimitiveBrushType.Cube);
            }

            if (GUI.Button(new Rect(30, 0, 30, createBrushStyle.fixedHeight), SabreCSGResources.ButtonPrismTexture, createBrushStyle))
            {
                CreatePrimitiveBrush(PrimitiveBrushType.Prism);
            }

            //if(GUI.Button(new Rect(60,0, 30, createBrushStyle.fixedHeight), "", createBrushStyle))
            //{
            //}

            if (GUI.Button(new Rect(60, 0, 30, createBrushStyle.fixedHeight), SabreCSGResources.ButtonStairsTexture, createBrushStyle))
            {
                CreateCompoundBrush <StairBrush>();
            }

            GUILayout.Space(92);
#if DEBUG_SABRECSG_PERF
            // For debugging frame rate
            GUILayout.Label(((int)(1 / csgModel.CurrentFrameDelta)).ToString(), SabreGUILayout.GetLabelStyle());
#endif

            if (SabreGUILayout.Button("Rebuild"))
            {
                csgModel.Build(false, false);
            }

            if (SabreGUILayout.Button("Force Rebuild"))
            {
                csgModel.Build(true, false);
            }

            GUI.color = Color.white;

            if (csgModel.AutoRebuild)
            {
                GUI.color = Color.green;
            }
            csgModel.AutoRebuild = SabreGUILayout.Toggle(csgModel.AutoRebuild, "Auto Rebuild");
            GUI.color            = Color.white;

            GUILayout.Label(csgModel.BuildMetrics.BuildMetaData.ToString(), SabreGUILayout.GetForeStyle(), GUILayout.Width(140));

            bool lastBrushesHidden = CurrentSettings.BrushesHidden;
            if (lastBrushesHidden)
            {
                GUI.color = Color.red;
            }
            CurrentSettings.BrushesHidden = SabreGUILayout.Toggle(CurrentSettings.BrushesHidden, "Brushes Hidden");
            if (CurrentSettings.BrushesHidden != lastBrushesHidden)
            {
                // Has changed
                CSGModel.UpdateAllBrushesVisibility();
                SceneView.RepaintAll();
            }
            GUI.color = Color.white;


            bool lastMeshHidden = CurrentSettings.MeshHidden;
            if (lastMeshHidden)
            {
                GUI.color = Color.red;
            }
            CurrentSettings.MeshHidden = SabreGUILayout.Toggle(CurrentSettings.MeshHidden, "Mesh Hidden");
            if (CurrentSettings.MeshHidden != lastMeshHidden)
            {
                // Has changed
                CSGModel.UpdateAllBrushesVisibility();
                SceneView.RepaintAll();
            }

            GUI.color = Color.white;


            if (GUILayout.Button("Grid " + CurrentSettings.GridMode.ToString(), EditorStyles.toolbarDropDown, GUILayout.Width(90)))
            {
                GenericMenu menu = new GenericMenu();

                string[] names = Enum.GetNames(typeof(GridMode));

                for (int i = 0; i < names.Length; i++)
                {
                    GridMode value    = (GridMode)Enum.Parse(typeof(GridMode), names[i]);
                    bool     selected = false;
                    if (CurrentSettings.GridMode == value)
                    {
                        selected = true;
                    }
                    menu.AddItem(new GUIContent(names[i]), selected, OnSelectedGridOption, value);
                }

                menu.DropDown(gridRect);
            }

            if (Event.current.type == EventType.Repaint)
            {
                gridRect       = GUILayoutUtility.GetLastRect();
                gridRect.width = 100;
            }

            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();

            // Line Two
            GUILayout.BeginHorizontal();

            if (GUI.Button(new Rect(0, createBrushStyle.fixedHeight, 30, createBrushStyle.fixedHeight), SabreCSGResources.ButtonCylinderTexture, createBrushStyle))
            {
                CreatePrimitiveBrush(PrimitiveBrushType.Cylinder);
            }

            if (GUI.Button(new Rect(30, createBrushStyle.fixedHeight, 30, createBrushStyle.fixedHeight), SabreCSGResources.ButtonSphereTexture, createBrushStyle))
            {
                CreatePrimitiveBrush(PrimitiveBrushType.Sphere);
            }

            //if (GUI.Button(new Rect(60, createBrushStyle.fixedHeight, 30, createBrushStyle.fixedHeight), "", createBrushStyle))
            //{
            //}

            if (GUI.Button(new Rect(60, createBrushStyle.fixedHeight, 30, createBrushStyle.fixedHeight), "...", createBrushStyle))
            {
                GenericMenu menu = new GenericMenu();

                List <Type> compoundBrushTypes = CompoundBrush.FindAllInAssembly();
                for (int i = 0; i < compoundBrushTypes.Count; i++)
                {
                    menu.AddItem(new GUIContent(compoundBrushTypes[i].Name), false, CreateCompoundBrush, compoundBrushTypes[i]);
                }

                menu.DropDown(new Rect(60, createBrushStyle.fixedHeight, 100, createBrushStyle.fixedHeight));
            }

            GUILayout.Space(92);

            // Display brush count
            GUILayout.Label(csgModel.BrushCount.ToStringWithSuffix(" brush", " brushes"), SabreGUILayout.GetLabelStyle());
//			CurrentSettings.GridMode = (GridMode)EditorGUILayout.EnumPopup(CurrentSettings.GridMode, EditorStyles.toolbarPopup, GUILayout.Width(80));

            if (Selection.activeGameObject != null)
            {
                BrushBase        primaryBrush = Selection.activeGameObject.GetComponent <BrushBase>();
                List <BrushBase> brushes      = new List <BrushBase>();
                for (int i = 0; i < Selection.gameObjects.Length; i++)
                {
                    BrushBase brush = Selection.gameObjects[i].GetComponent <BrushBase>();
                    if (brush != null)
                    {
                        brushes.Add(brush);
                    }
                }
                if (primaryBrush != null)
                {
                    CSGMode brushMode = (CSGMode)EditorGUILayout.EnumPopup(primaryBrush.Mode, EditorStyles.toolbarPopup, GUILayout.Width(80));
                    if (brushMode != primaryBrush.Mode)
                    {
                        bool anyChanged = false;

                        foreach (BrushBase brush in brushes)
                        {
                            Undo.RecordObject(brush, "Change Brush To " + brushMode);
                            brush.Mode = brushMode;
                            anyChanged = true;
                        }
                        if (anyChanged)
                        {
                            // Need to update the icon for the csg mode in the hierarchy
                            EditorApplication.RepaintHierarchyWindow();
                        }
                    }


                    bool[] noCSGStates = brushes.Select(brush => brush.IsNoCSG).Distinct().ToArray();
                    bool   isNoCSG     = (noCSGStates.Length == 1) ? noCSGStates[0] : false;

                    bool newIsNoCSG = SabreGUILayout.ToggleMixed(noCSGStates, "NoCSG", GUILayout.Width(53));


                    bool[] collisionStates = brushes.Select(item => item.HasCollision).Distinct().ToArray();
                    bool   hasCollision    = (collisionStates.Length == 1) ? collisionStates[0] : false;

                    bool newHasCollision = SabreGUILayout.ToggleMixed(collisionStates, "Collision", GUILayout.Width(53));


                    bool[] visibleStates = brushes.Select(item => item.IsVisible).Distinct().ToArray();
                    bool   isVisible     = (visibleStates.Length == 1) ? visibleStates[0] : false;

                    bool newIsVisible = SabreGUILayout.ToggleMixed(visibleStates, "Visible", GUILayout.Width(53));

                    if (newIsNoCSG != isNoCSG)
                    {
                        foreach (BrushBase brush in brushes)
                        {
                            Undo.RecordObject(brush, "Change Brush NoCSG Mode");
                            brush.IsNoCSG = newIsNoCSG;
                        }
                        // Tell the brushes that they have changed and need to recalc intersections
                        foreach (BrushBase brush in brushes)
                        {
                            brush.Invalidate(true);
                        }

                        EditorApplication.RepaintHierarchyWindow();
                    }
                    if (newHasCollision != hasCollision)
                    {
                        foreach (BrushBase brush in brushes)
                        {
                            Undo.RecordObject(brush, "Change Brush Collision Mode");
                            brush.HasCollision = newHasCollision;
                        }
                        // Tell the brushes that they have changed and need to recalc intersections
                        foreach (BrushBase brush in brushes)
                        {
                            brush.Invalidate(true);
                        }
                    }
                    if (newIsVisible != isVisible)
                    {
                        foreach (BrushBase brush in brushes)
                        {
                            Undo.RecordObject(brush, "Change Brush Visible Mode");
                            brush.IsVisible = newIsVisible;
                        }
                        // Tell the brushes that they have changed and need to recalc intersections
                        foreach (BrushBase brush in brushes)
                        {
                            brush.Invalidate(true);
                        }
                        if (newIsVisible == false)
                        {
                            csgModel.NotifyPolygonsRemoved();
                        }
                    }
                }
            }

            GUILayout.Space(10);

            // Position snapping UI
            CurrentSettings.PositionSnappingEnabled = SabreGUILayout.Toggle(CurrentSettings.PositionSnappingEnabled, "Pos Snapping");
            CurrentSettings.PositionSnapDistance    = EditorGUILayout.FloatField(CurrentSettings.PositionSnapDistance, GUILayout.Width(50));

            if (SabreGUILayout.Button("-", EditorStyles.miniButtonLeft))
            {
                CurrentSettings.ChangePosSnapDistance(.5f);
            }
            if (SabreGUILayout.Button("+", EditorStyles.miniButtonRight))
            {
                CurrentSettings.ChangePosSnapDistance(2f);
            }

            // Rotation snapping UI
            CurrentSettings.AngleSnappingEnabled = SabreGUILayout.Toggle(CurrentSettings.AngleSnappingEnabled, "Ang Snapping");
            CurrentSettings.AngleSnapDistance    = EditorGUILayout.FloatField(CurrentSettings.AngleSnapDistance, GUILayout.Width(50));

            if (SabreGUILayout.Button("-", EditorStyles.miniButtonLeft))
            {
                if (CurrentSettings.AngleSnapDistance > 15)
                {
                    CurrentSettings.AngleSnapDistance -= 15;
                }
                else
                {
                    CurrentSettings.AngleSnapDistance -= 5;
                }
            }
            if (SabreGUILayout.Button("+", EditorStyles.miniButtonRight))
            {
                if (CurrentSettings.AngleSnapDistance >= 15)
                {
                    CurrentSettings.AngleSnapDistance += 15;
                }
                else
                {
                    CurrentSettings.AngleSnapDistance += 5;
                }
            }

            GUILayout.FlexibleSpace();

            if (SabreGUILayout.Button("Prefs"))
            {
                SabreCSGPreferences.CreateAndShow();
            }

            if (SabreGUILayout.Button("Disable"))
            {
                Selection.activeGameObject = null;
                csgModel.EditMode          = false;
            }

            GUILayout.EndHorizontal();
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Draws a variable field on the GUI.
        /// <param name= "guiContent">The GUI content to draw the property.</param>
        /// <param name= "property">The variable property.</param>
        /// <param name= "node">The node that owns the variable to be drawn.</param>
        /// </summary>
        public static void VariableField(GUIContent guiContent, SerializedNodeProperty property, ActionNode node)
        {
            var variable   = property.value as Variable;
            var isNone     = variable == null || variable.isNone;
            var isConstant = !isNone && variable.isConstant;
            VariableInfoAttribute variableInfo = property.variableInfo;
            string  popupName    = string.Empty;
            Texture popupTexture = null;


            #if UNITY_4_0_0 || UNITY_4_1 || UNITY_4_2
            var rect = GUILayoutUtility.GetRect(guiContent, EditorStyles.popup);
            #else
            var rect = EditorGUILayout.GetControlRect();
            #endif

            var id = GUIUtility.GetControlID(FocusType.Keyboard);

            // Set label color
            if (isNone && variableInfo.requiredField)
            {
                EditorStyles.label.normal.textColor = Color.red;
            }
            // Draw label
            rect = EditorGUI.PrefixLabel(rect, id, guiContent);
            // Restore label color
            EditorStyles.label.normal.textColor = s_Styles.labelTextColor;

            if (isNone)
            {
                popupName    = variableInfo.nullLabel;
                popupTexture = s_Styles.noneTexture;
            }
            else if (isConstant)
            {
                if (property.isConcreteVariable)
                {
                    popupName    = "Constant";
                    popupTexture = s_Styles.constantTexture;
                }
                else
                {
                    popupName    = variable.GetType().Name;
                    popupTexture = IconUtility.GetIcon(variable.GetType());
                }
            }
            else
            {
                popupName = variable.name;
                // Its a global var?
                popupTexture = variable.isGlobal ? s_Styles.globalBlackboardTexture : popupTexture = s_Styles.blackboardTexture;;
            }

            // Popup button
            if (GUIHelper.EditorButton(rect, id, new GUIContent(popupName, popupTexture), s_Styles.popup))
            {
                // Set keyboard focus to the label
                GUIUtility.keyboardControl = id;
                // Create the menu and the list of unique names
                var menu  = new GenericMenu();
                var names = new List <string>()
                {
                };

                // None
                names.Add(variableInfo.nullLabel);
                menu.AddItem(new GUIContent(variableInfo.nullLabel), isNone, delegate {
                    if (isConstant && property.isConcreteVariable)
                    {
                        variable.SetAsNone();
                        property.ValueChanged();
                    }
                    else if (!isNone)
                    {
                        object noneVariable;
                        if (property.type == typeof(GameObjectVar))
                        {
                            noneVariable = Activator.CreateInstance(TypeUtility.GetConcreteType(property.type), new object[] { node.self });
                        }
                        else if (property.type.IsAbstract)
                        {
                            noneVariable = Activator.CreateInstance(TypeUtility.GetConcreteType(property.type));
                        }
                        else
                        {
                            noneVariable = Activator.CreateInstance(property.type);
                        }
                        property.value = noneVariable;
                    }
                });

                // Create the anonymous function to set constants
                GenericMenu.MenuFunction2 createConstant = delegate(object userData) {
                    // Get the desired variable type
                    var type = userData as System.Type;

                    // its not a constant or its an "ex global" var (an ex global var does not have a GlobalBlackboard)?
                    if (variable == null || variable.isInvalid || property.type == typeof(BehaviourMachine.Variable))
                    {
                        // Create a constant
                        Variable newVariable;
                        if (property.type == typeof(GameObjectVar))
                        {
                            newVariable = Activator.CreateInstance(TypeUtility.GetConcreteType(type), new object[] { node.self }) as Variable;
                        }
                        else if (type.IsAbstract)
                        {
                            newVariable = Activator.CreateInstance(TypeUtility.GetConcreteType(type)) as Variable;
                        }
                        else
                        {
                            newVariable = Activator.CreateInstance(type) as Variable;
                        }

                        newVariable.SetAsConstant();
                        property.value = newVariable;
                        property.ValueChanged();
                    }
                    else if (isNone)
                    {
                        variable.SetAsConstant();
                        property.ValueChanged();
                    }
                    else if ((isConstant && !property.isConcreteVariable) || !isConstant)
                    {
                        // Create a concrete variable type and update the field value!
                        Variable newVariable;

                        if (type == typeof(GameObjectVar))
                        {
                            newVariable = Activator.CreateInstance(TypeUtility.GetConcreteType(type), new object[] { node.self }) as Variable;
                        }
                        else if (type.IsAbstract)
                        {
                            newVariable = Activator.CreateInstance(TypeUtility.GetConcreteType(type)) as Variable;
                        }
                        else
                        {
                            newVariable = Activator.CreateInstance(type) as Variable;
                        }

                        newVariable.SetAsConstant();
                        property.value = newVariable;
                    }
                };

                // Add the Constant name to the list
                names.Add("Constant");

                // Can be constant?
                if (variableInfo.canBeConstant && property.type != typeof(BehaviourMachine.FsmEvent) && property.type != typeof(BehaviourMachine.DynamicList))
                {
                    if (property.type != typeof(BehaviourMachine.Variable))
                    {
                        menu.AddItem(new GUIContent("Constant"), isConstant && property.isConcreteVariable, createConstant, property.type);
                    }
                    else
                    {
                        bool variableNotNull = variable != null;
                        // If its a Variable type then add options for all concrete variables
                        if (!variableInfo.fixedType)
                        {
                            menu.AddItem(new GUIContent("Constant/Variable"), isConstant && variableNotNull && variable.GetType() == typeof(BehaviourMachine.Variable), createConstant, typeof(BehaviourMachine.Variable));
                            menu.AddItem(new GUIContent("Constant/FloatVar"), isConstant && variableNotNull && variable.GetType() == typeof(BehaviourMachine.ConcreteFloatVar), createConstant, typeof(BehaviourMachine.ConcreteFloatVar));
                            menu.AddItem(new GUIContent("Constant/IntVar"), isConstant && variableNotNull && variable.GetType() == typeof(BehaviourMachine.ConcreteIntVar), createConstant, typeof(BehaviourMachine.ConcreteIntVar));
                            menu.AddItem(new GUIContent("Constant/BoolVar"), isConstant && variableNotNull && variable.GetType() == typeof(BehaviourMachine.ConcreteBoolVar), createConstant, typeof(BehaviourMachine.ConcreteBoolVar));
                            menu.AddItem(new GUIContent("Constant/StringVar"), isConstant && variableNotNull && variable.GetType() == typeof(BehaviourMachine.ConcreteStringVar), createConstant, typeof(BehaviourMachine.ConcreteStringVar));
                            menu.AddItem(new GUIContent("Constant/Vector3Var"), isConstant && variableNotNull && variable.GetType() == typeof(BehaviourMachine.ConcreteVector3Var), createConstant, typeof(BehaviourMachine.ConcreteVector3Var));
                            menu.AddItem(new GUIContent("Constant/RectVar"), isConstant && variableNotNull && variable.GetType() == typeof(BehaviourMachine.ConcreteRectVar), createConstant, typeof(BehaviourMachine.ConcreteRectVar));
                            menu.AddItem(new GUIContent("Constant/ColorVar"), isConstant && variableNotNull && variable.GetType() == typeof(BehaviourMachine.ConcreteColorVar), createConstant, typeof(BehaviourMachine.ConcreteColorVar));
                            menu.AddItem(new GUIContent("Constant/QuaternionVar"), isConstant && variableNotNull && variable.GetType() == typeof(BehaviourMachine.ConcreteQuaternionVar), createConstant, typeof(BehaviourMachine.ConcreteQuaternionVar));
                            menu.AddItem(new GUIContent("Constant/GameObjectVar"), isConstant && variableNotNull && variable.GetType() == typeof(BehaviourMachine.ConcreteGameObjectVar), createConstant, typeof(BehaviourMachine.ConcreteGameObjectVar));
                            menu.AddItem(new GUIContent("Constant/MaterialVar"), isConstant && variableNotNull && variable.GetType() == typeof(BehaviourMachine.ConcreteMaterialVar), createConstant, typeof(BehaviourMachine.ConcreteMaterialVar));
                            menu.AddItem(new GUIContent("Constant/TextureVar"), isConstant && variableNotNull && variable.GetType() == typeof(BehaviourMachine.ConcreteTextureVar), createConstant, typeof(BehaviourMachine.ConcreteTextureVar));
                            menu.AddItem(new GUIContent("Constant/ObjectVar"), isConstant && variableNotNull && variable.GetType() == typeof(BehaviourMachine.ConcreteObjectVar), createConstant, typeof(BehaviourMachine.ConcreteObjectVar));
                        }
                        else if (variable != null)
                        {
                            // Get the base type
                            System.Type baseType = BehaviourMachine.TypeUtility.GetBaseType(variable.GetType());
                            if (baseType == typeof(Variable))
                            {
                                menu.AddItem(new GUIContent("Constant"), isConstant && variableNotNull && variable.GetType() == typeof(BehaviourMachine.Variable), createConstant, typeof(BehaviourMachine.Variable));
                            }
                            else if (baseType == typeof(FloatVar))
                            {
                                menu.AddItem(new GUIContent("Constant"), isConstant && variableNotNull && variable.GetType() == typeof(BehaviourMachine.ConcreteFloatVar), createConstant, typeof(BehaviourMachine.ConcreteFloatVar));
                            }
                            else if (baseType == typeof(IntVar))
                            {
                                menu.AddItem(new GUIContent("Constant"), isConstant && variableNotNull && variable.GetType() == typeof(BehaviourMachine.ConcreteIntVar), createConstant, typeof(BehaviourMachine.ConcreteIntVar));
                            }
                            else if (baseType == typeof(BoolVar))
                            {
                                menu.AddItem(new GUIContent("Constant"), isConstant && variableNotNull && variable.GetType() == typeof(BehaviourMachine.ConcreteBoolVar), createConstant, typeof(BehaviourMachine.ConcreteBoolVar));
                            }
                            else if (baseType == typeof(StringVar))
                            {
                                menu.AddItem(new GUIContent("Constant"), isConstant && variableNotNull && variable.GetType() == typeof(BehaviourMachine.ConcreteStringVar), createConstant, typeof(BehaviourMachine.ConcreteStringVar));
                            }
                            else if (baseType == typeof(Vector3Var))
                            {
                                menu.AddItem(new GUIContent("Constant"), isConstant && variableNotNull && variable.GetType() == typeof(BehaviourMachine.ConcreteVector3Var), createConstant, typeof(BehaviourMachine.ConcreteVector3Var));
                            }
                            else if (baseType == typeof(RectVar))
                            {
                                menu.AddItem(new GUIContent("Constant"), isConstant && variableNotNull && variable.GetType() == typeof(BehaviourMachine.ConcreteRectVar), createConstant, typeof(BehaviourMachine.ConcreteRectVar));
                            }
                            else if (baseType == typeof(ColorVar))
                            {
                                menu.AddItem(new GUIContent("Constant"), isConstant && variableNotNull && variable.GetType() == typeof(BehaviourMachine.ConcreteColorVar), createConstant, typeof(BehaviourMachine.ConcreteColorVar));
                            }
                            else if (baseType == typeof(QuaternionVar))
                            {
                                menu.AddItem(new GUIContent("Constant"), isConstant && variableNotNull && variable.GetType() == typeof(BehaviourMachine.ConcreteQuaternionVar), createConstant, typeof(BehaviourMachine.ConcreteQuaternionVar));
                            }
                            else if (baseType == typeof(GameObjectVar))
                            {
                                menu.AddItem(new GUIContent("Constant"), isConstant && variableNotNull && variable.GetType() == typeof(BehaviourMachine.ConcreteGameObjectVar), createConstant, typeof(BehaviourMachine.ConcreteGameObjectVar));
                            }
                            else if (baseType == typeof(MaterialVar))
                            {
                                menu.AddItem(new GUIContent("Constant"), isConstant && variableNotNull && variable.GetType() == typeof(BehaviourMachine.ConcreteMaterialVar), createConstant, typeof(BehaviourMachine.ConcreteMaterialVar));
                            }
                            else if (baseType == typeof(TextureVar))
                            {
                                menu.AddItem(new GUIContent("Constant"), isConstant && variableNotNull && variable.GetType() == typeof(BehaviourMachine.ConcreteTextureVar), createConstant, typeof(BehaviourMachine.ConcreteTextureVar));
                            }
                            else if (baseType == typeof(ObjectVar))
                            {
                                menu.AddItem(new GUIContent("Constant"), isConstant && variableNotNull && variable.GetType() == typeof(BehaviourMachine.ConcreteObjectVar), createConstant, typeof(BehaviourMachine.ConcreteObjectVar));
                            }
                        }
                    }
                }
                else
                {
                    menu.AddDisabledItem(new GUIContent("Constant"));
                }

                // Custom variables
                if (property.type != null)
                {
                    System.Type[] customVars = CustomVariableUtility.GetCustomVariables(variableInfo.fixedType && variable != null ? BehaviourMachine.TypeUtility.GetBaseType(variable.GetType()) : property.type);

                    // if (customVars.Length > 0) {
                    //     menu.AddSeparator(string.Empty);
                    // }

                    for (int i = 0; i < customVars.Length; i++)
                    {
                        // Get the type of the custom variable
                        System.Type customVarType = customVars[i];
                        // Get a unique name
                        string uniqueName = StringHelper.GetUniqueNameInList(names, "Custom/" + customVarType.Name);
                        names.Add(uniqueName);
                        // Add to the menu
                        menu.AddItem(new GUIContent(uniqueName), isConstant && variable != null && variable.GetType() == customVarType, delegate {
                            try {
                                var newVariable = Activator.CreateInstance(customVarType, new object[] { node.self }) as Variable;
                                if (newVariable != null)
                                {
                                    newVariable.SetAsConstant();
                                    property.value = newVariable;
                                }
                            }
                            catch (Exception e) {
                                Print.LogError(e.ToString());
                            }
                        });
                    }
                }

                // Boolean used to know if the variables separator was already added to the menu.
                bool separatorAdded = false;

                // Blackboard variables
                var variables = node.self.GetComponent <InternalBlackboard>().GetVariables(variable != null && variableInfo.fixedType ? BehaviourMachine.TypeUtility.GetBaseType(variable.GetType()) : property.type);

                // Add separator?
                if (variables.Count > 0)
                {
                    menu.AddSeparator(string.Empty);
                    separatorAdded = true;
                }

                // Blackboard variables
                for (int i = 0; i < variables.Count; i++)
                {
                    var v    = variables[i];
                    var name = StringHelper.GetUniqueNameInList(names, v.name);
                    names.Add(name);
                    menu.AddItem(new GUIContent(name), variable == v, delegate { property.value = v; });
                }

                // Global variables
                if (InternalGlobalBlackboard.Instance != null)
                {
                    var globalVariables = InternalGlobalBlackboard.Instance.GetVariables(property.type);

                    // Add separator?
                    if (!separatorAdded && globalVariables.Count > 0)
                    {
                        menu.AddSeparator(string.Empty);
                        separatorAdded = true;
                    }

                    for (int i = 0; i < globalVariables.Count; i++)
                    {
                        var v    = globalVariables[i];
                        var name = StringHelper.GetUniqueNameInList(names, "Global/" + v.name);
                        names.Add(name);
                        menu.AddItem(new GUIContent(name), variable == v, delegate { property.value = v; });
                    }
                }

                // Show menu
                menu.DropDown(rect);
                // Set GUI as not changed
                GUI.changed = false;
            }

            // Draw constant properties
            if (isConstant)
            {
                // Get children
                var children = property.children;

                // The variable is an ObjectVar?
                var         objectVar = variable as ObjectVar;
                System.Type objType   = objectVar != null ? objectVar.ObjectType : null;

                // Draw properties
                if (children.Length > 0)
                {
                    EditorGUI.indentLevel++;

                    if (property.isConcreteVariable)
                    {
                        for (int i = 0; i < children.Length; i++)
                        {
                            SerializedNodeProperty childProperty = children[i];
                            if (!childProperty.hideInInspector)
                            {
                                if (childProperty.propertyType == NodePropertyType.Vector3 || childProperty.propertyType == NodePropertyType.Quaternion || childProperty.propertyType == NodePropertyType.Vector2)
                                {
                                    #if UNITY_4_0_0 || UNITY_4_1 || UNITY_4_2
                                    GUILayout.Space(-20f);
                                    EditorGUI.indentLevel--;
                                    #endif

                                    DrawNodeProperty(GUIContent.none, childProperty, node, objType);

                                    #if UNITY_4_0_0 || UNITY_4_1 || UNITY_4_2
                                    EditorGUI.indentLevel++;
                                    #endif
                                }
                                else if (childProperty.propertyType == NodePropertyType.Rect)
                                {
                                    #if UNITY_4_0_0 || UNITY_4_1 || UNITY_4_2
                                    GUILayout.Space(-20f);
                                    EditorGUI.indentLevel--;
                                    #endif

                                    DrawNodeProperty(GUIContent.none, childProperty, node, objType);

                                    #if UNITY_4_0_0 || UNITY_4_1 || UNITY_4_2
                                    GUILayout.Space(20f);
                                    EditorGUI.indentLevel++;
                                    #endif
                                }
                                else
                                {
                                    DrawNodeProperty(new GUIContent(childProperty.label, childProperty.tooltip), childProperty, node, objType);
                                }
                            }
                        }
                    }
                    else
                    {
                        for (int i = 0; i < children.Length; i++)
                        {
                            SerializedNodeProperty childProperty = children[i];
                            if (!childProperty.hideInInspector)
                            {
                                DrawNodeProperty(new GUIContent(childProperty.label, childProperty.tooltip), childProperty, node, objType);
                            }
                        }
                    }

                    EditorGUI.indentLevel--;
                }
            }
        }
Ejemplo n.º 23
0
        public void Controls()
        {
            wantsMouseMove = true;
            Event e = Event.current;

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

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

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

            case EventType.MouseDrag:
                if (e.button == 0)
                {
                    if (IsDraggingPort)
                    {
                        if (IsHoveringPort && hoveredPort.IsInput && draggedOutput.CanConnectTo(hoveredPort))
                        {
                            if (!draggedOutput.IsConnectedTo(hoveredPort))
                            {
                                draggedOutputTarget = hoveredPort;
                            }
                        }
                        else
                        {
                            draggedOutputTarget = null;
                        }
                        Repaint();
                    }
                    else if (currentActivity == NodeActivity.HoldNode)
                    {
                        RecalculateDragOffsets(e);
                        currentActivity = NodeActivity.DragNode;
                        Repaint();
                    }
                    if (currentActivity == NodeActivity.DragNode)
                    {
                        // Holding ctrl inverts grid snap
                        bool gridSnap = NodeEditorPreferences.GetSettings().gridSnap;
                        if (e.control)
                        {
                            gridSnap = !gridSnap;
                        }

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

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

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

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

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

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

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

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

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

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

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

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

                    Repaint();
                    currentActivity = NodeActivity.Idle;
                }
                else if (e.button == 1 || e.button == 2)
                {
                    if (!isPanning)
                    {
                        if (IsDraggingPort)
                        {
                            draggedOutputReroutes.Add(WindowToGridPosition(e.mousePosition));
                        }
                        else if (currentActivity == NodeActivity.DragNode && Selection.activeObject == null && selectedReroutes.Count == 1)
                        {
                            selectedReroutes[0].InsertPoint(selectedReroutes[0].GetPoint());
                            selectedReroutes[0] = new RerouteReference(selectedReroutes[0].port, selectedReroutes[0].connectionIndex, selectedReroutes[0].pointIndex + 1);
                        }
                        else if (IsHoveringReroute)
                        {
                            ShowRerouteContextMenu(hoveredReroute);
                        }
                        else if (IsHoveringPort)
                        {
                            ShowPortContextMenu(hoveredPort);
                        }
                        else if (IsHoveringNode && IsHoveringTitle(hoveredNode))
                        {
                            if (!Selection.Contains(hoveredNode))
                            {
                                SelectNode(hoveredNode, false);
                            }
                            autoConnectOutput = null;
                            GenericMenu menu = new GenericMenu();
                            NodeEditor.GetEditor(hoveredNode, this).AddContextMenuItems(menu);
                            menu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero));
                            e.Use();     // Fixes copy/paste context menu appearing in Unity 5.6.6f2 - doesn't occur in 2018.3.2f1 Probably needs to be used in other places.
                        }
                        else if (!IsHoveringNode)
                        {
                            autoConnectOutput = null;
                            GenericMenu menu = new GenericMenu();
                            graphEditor.AddContextMenuItems(menu);
                            menu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero));
                        }
                    }
                    isPanning = false;
                }
                // Reset DoubleClick
                isDoubleClick = false;
                break;

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

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

            case EventType.Ignore:
                // If release mouse outside window
                if (e.rawType == EventType.MouseUp && currentActivity == NodeActivity.DragGrid)
                {
                    Repaint();
                    currentActivity = NodeActivity.Idle;
                }
                break;
            }
        }
Ejemplo n.º 24
0
        void DrawBackgroundTexture(Rect rect, int pass)
        {
            if (s_MaterialGrid == null)
            {
                s_MaterialGrid = new Material(Shader.Find("Hidden/PostProcessing/Editor/CurveGrid"))
                {
                    hideFlags = HideFlags.HideAndDontSave
                }
            }
            ;

            float scale = EditorGUIUtility.pixelsPerPoint;

        #if UNITY_2018_1_OR_NEWER
            const RenderTextureReadWrite kReadWrite = RenderTextureReadWrite.sRGB;
        #else
            const RenderTextureReadWrite kReadWrite = RenderTextureReadWrite.Linear;
        #endif

            var oldRt = RenderTexture.active;
            var rt    = RenderTexture.GetTemporary(Mathf.CeilToInt(rect.width * scale), Mathf.CeilToInt(rect.height * scale), 0, RenderTextureFormat.ARGB32, kReadWrite);
            s_MaterialGrid.SetFloat("_DisabledState", GUI.enabled ? 1f : 0.5f);
            s_MaterialGrid.SetFloat("_PixelScaling", EditorGUIUtility.pixelsPerPoint);

            Graphics.Blit(null, rt, s_MaterialGrid, pass);
            RenderTexture.active = oldRt;

            GUI.DrawTexture(rect, rt);
            RenderTexture.ReleaseTemporary(rt);
        }

        int DoCurveSelectionPopup(int id, bool hdr)
        {
            GUILayout.Label(s_Curves[id], EditorStyles.toolbarPopup, GUILayout.MaxWidth(150f));

            var lastRect = GUILayoutUtility.GetLastRect();
            var e        = Event.current;

            if (e.type == EventType.MouseDown && e.button == 0 && lastRect.Contains(e.mousePosition))
            {
                var menu = new GenericMenu();

                for (int i = 0; i < s_Curves.Length; i++)
                {
                    if (i == 4)
                    {
                        menu.AddSeparator("");
                    }

                    if (hdr && i < 4)
                    {
                        menu.AddDisabledItem(s_Curves[i]);
                    }
                    else
                    {
                        int current = i; // Capture local for closure
                        menu.AddItem(s_Curves[i], current == id, () => GlobalSettings.currentCurve = current);
                    }
                }

                menu.DropDown(new Rect(lastRect.xMin, lastRect.yMax, 1f, 1f));
            }

            return(id);
        }
    }
Ejemplo n.º 25
0
        public void Controls()
        {
            wantsMouseMove = true;
            Event e = Event.current;

            switch (e.type)
            {
            case EventType.MouseMove:
                break;

            case EventType.ScrollWheel:
                if (e.delta.y > 0)
                {
                    zoom += 0.1f * zoom;
                }
                else
                {
                    zoom -= 0.1f * zoom;
                }
                break;

            case EventType.MouseDrag:
                if (e.button == 0)
                {
                    if (IsDraggingPort)
                    {
                        if (IsHoveringPort && hoveredPort.IsInput)
                        {
                            if (!draggedOutput.IsConnectedTo(hoveredPort))
                            {
                                draggedOutputTarget = hoveredPort;
                            }
                        }
                        else
                        {
                            draggedOutputTarget = null;
                        }
                        Repaint();
                    }
                    else if (currentActivity == NodeActivity.HoldNode)
                    {
                        RecalculateDragOffsets(e);
                        currentActivity = NodeActivity.DragNode;
                        Repaint();
                    }
                    if (currentActivity == NodeActivity.DragNode)
                    {
                        // Holding ctrl inverts grid snap
                        bool gridSnap = NodeEditorPreferences.GetSettings().gridSnap;
                        if (e.control)
                        {
                            gridSnap = !gridSnap;
                        }

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

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

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

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

                    if (IsHoveringPort)
                    {
                        if (hoveredPort.IsOutput)
                        {
                            draggedOutput = hoveredPort;
                        }
                        else
                        {
                            hoveredPort.VerifyConnections();
                            if (hoveredPort.IsConnected)
                            {
                                XNode.Node     node   = hoveredPort.node;
                                XNode.NodePort output = hoveredPort.Connection;
                                int            outputConnectionIndex = output.GetConnectionIndex(hoveredPort);
                                draggedOutputReroutes = output.GetReroutePoints(outputConnectionIndex);
                                hoveredPort.Disconnect(output);
                                draggedOutput       = output;
                                draggedOutputTarget = hoveredPort;
                                if (NodeEditor.onUpdateNode != null)
                                {
                                    NodeEditor.onUpdateNode(node);
                                }
                            }
                        }
                    }
                    else if (IsHoveringNode && IsHoveringTitle(hoveredNode))
                    {
                        // If mousedown on node header, select or deselect
                        if (!Selection.Contains(hoveredNode))
                        {
                            SelectNode(hoveredNode, e.control || e.shift);
                            if (!e.control && !e.shift)
                            {
                                selectedReroutes.Clear();
                            }
                        }
                        else if (e.control || e.shift)
                        {
                            DeselectNode(hoveredNode);
                        }
                        e.Use();
                        currentActivity = NodeActivity.HoldNode;
                    }
                    else if (IsHoveringReroute)
                    {
                        // If reroute isn't selected
                        if (!selectedReroutes.Contains(hoveredReroute))
                        {
                            // Add it
                            if (e.control || e.shift)
                            {
                                selectedReroutes.Add(hoveredReroute);
                            }
                            // Select it
                            else
                            {
                                selectedReroutes = new List <RerouteReference>()
                                {
                                    hoveredReroute
                                };
                                Selection.activeObject = null;
                            }
                        }
                        // Deselect
                        else if (e.control || e.shift)
                        {
                            selectedReroutes.Remove(hoveredReroute);
                        }
                        e.Use();
                        currentActivity = NodeActivity.HoldNode;
                    }
                    // If mousedown on grid background, deselect all
                    else if (!IsHoveringNode)
                    {
                        currentActivity = NodeActivity.HoldGrid;
                        if (!e.control && !e.shift)
                        {
                            selectedReroutes.Clear();
                            Selection.activeObject = null;
                        }
                    }
                }
                break;

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

                            // ConnectionIndex can be -1 if the connection is removed instantly after creation
                            int connectionIndex = draggedOutput.GetConnectionIndex(draggedOutputTarget);
                            if (connectionIndex != -1)
                            {
                                draggedOutput.GetReroutePoints(connectionIndex).AddRange(draggedOutputReroutes);
                                if (NodeEditor.onUpdateNode != null)
                                {
                                    NodeEditor.onUpdateNode(node);
                                }
                                EditorUtility.SetDirty(graph);
                            }
                        }
                        //Release dragged connection
                        draggedOutput       = null;
                        draggedOutputTarget = null;
                        EditorUtility.SetDirty(graph);
                        if (NodeEditorPreferences.GetSettings().autoSave)
                        {
                            AssetDatabase.SaveAssets();
                        }
                    }
                    else if (currentActivity == NodeActivity.DragNode)
                    {
                        IEnumerable <XNode.Node> nodes = Selection.objects.Where(x => x is XNode.Node).Select(x => x as XNode.Node);
                        foreach (XNode.Node node in nodes)
                        {
                            EditorUtility.SetDirty(node);
                        }
                        if (NodeEditorPreferences.GetSettings().autoSave)
                        {
                            AssetDatabase.SaveAssets();
                        }
                    }
                    else if (!IsHoveringNode)
                    {
                        // If click outside node, release field focus
                        if (!isPanning)
                        {
                            EditorGUI.FocusTextInControl(null);
                        }
                        if (NodeEditorPreferences.GetSettings().autoSave)
                        {
                            AssetDatabase.SaveAssets();
                        }
                    }

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

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

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

            case EventType.KeyDown:
                if (EditorGUIUtility.editingTextField)
                {
                    break;
                }
                else if (e.keyCode == KeyCode.F)
                {
                    Home();
                }
                if (SystemInfo.operatingSystemFamily == OperatingSystemFamily.MacOSX)
                {
                    if (e.keyCode == KeyCode.Return)
                    {
                        RenameSelectedNode();
                    }
                }
                else
                {
                    if (e.keyCode == KeyCode.F2)
                    {
                        RenameSelectedNode();
                    }
                }
                break;

            case EventType.ValidateCommand:
            case EventType.ExecuteCommand:
                if (e.commandName == "SoftDelete")
                {
                    if (e.type == EventType.ExecuteCommand)
                    {
                        RemoveSelectedNodes();
                    }
                    e.Use();
                }
                else if (SystemInfo.operatingSystemFamily == OperatingSystemFamily.MacOSX && e.commandName == "Delete")
                {
                    if (e.type == EventType.ExecuteCommand)
                    {
                        RemoveSelectedNodes();
                    }
                    e.Use();
                }
                else if (e.commandName == "Duplicate")
                {
                    if (e.type == EventType.ExecuteCommand)
                    {
                        DuplicateSelectedNodes();
                    }
                    e.Use();
                }
                Repaint();
                break;

            case EventType.Ignore:
                // If release mouse outside window
                if (e.rawType == EventType.MouseUp && currentActivity == NodeActivity.DragGrid)
                {
                    Repaint();
                    currentActivity = NodeActivity.Idle;
                }
                break;
            }
        }
Ejemplo n.º 26
0
 public void ShowMenu()
 {
     m_tabMenu.DropDown(m_tabArea);
 }
Ejemplo n.º 27
0
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            var sObj   = property.serializedObject;
            var sPro   = property.FindPropertyRelative("mask");
            var right  = position; right.xMin += EditorGUIUtility.labelWidth;
            var handle = default(string);

            EditorGUI.LabelField(position, label);

            if (sPro.intValue == 0)
            {
                handle = "Nothing";
            }
            else if (sPro.intValue == -1)
            {
                handle = "Everything";
            }
            else
            {
                //handle = "Mixed ...";
                var total = 0;

                for (var i = 0; i < 32; i++)
                {
                    var on = P3dHelper.IndexInMask(i, sPro.intValue);

                    if (on == true)
                    {
                        if (total == 0)
                        {
                            handle = "Group " + i;
                        }
                        else
                        {
                            handle += ", Group " + i;
                        }

                        total += 1;
                    }
                }
            }

            if (GUI.Button(right, handle, EditorStyles.popup) == true)
            {
                var menu = new GenericMenu();

                menu.AddItem(new GUIContent("Nothing"), sPro.intValue == 0, () => { sPro.intValue = 0; sObj.ApplyModifiedProperties(); });

                menu.AddItem(new GUIContent("Everything"), sPro.intValue == -1, () => { sPro.intValue = -1; sObj.ApplyModifiedProperties(); });

                for (var i = 0; i < 32; i++)
                {
                    var index   = i;
                    var content = new GUIContent("Group " + index);
                    var on      = P3dHelper.IndexInMask(index, sPro.intValue);

                    menu.AddItem(content, on, () => { sPro.intValue ^= 1 << index; sObj.ApplyModifiedProperties(); });
                }

                menu.DropDown(right);
            }
        }
Ejemplo n.º 28
0
        void DrawToolbar()
        {
            using (new GUILayout.HorizontalScope(EditorStyles.toolbar, GUILayout.ExpandWidth(true)))
            {
                EditorGUI.BeginDisabledGroup(!m_GotoHistory.HasBack());
                if (GUILayout.Button(new GUIContent(HeEditorStyles.backwardImage, "Navigate Backward"), EditorStyles.toolbarButton, GUILayout.Width(24)))
                {
                    var cmd = m_GotoHistory.Back();
                    if (cmd != null)
                    {
                        GotoInternal(cmd, true);
                    }
                }
                EditorGUI.EndDisabledGroup();

                EditorGUI.BeginDisabledGroup(!m_GotoHistory.HasForward());
                if (GUILayout.Button(new GUIContent(HeEditorStyles.forwardImage, "Navigate Forward"), EditorStyles.toolbarButton, GUILayout.Width(24)))
                {
                    var cmd = m_GotoHistory.Forward();
                    if (cmd != null)
                    {
                        GotoInternal(cmd, false);
                    }
                }
                EditorGUI.EndDisabledGroup();


                if (GUILayout.Button("File", EditorStyles.toolbarDropDown, GUILayout.Width(60)))
                {
                    var menu = new GenericMenu();
                    menu.AddItem(new GUIContent("Open..."), false, LoadFromFile);

                    for (int n = 0; n < HeMruFiles.count; ++n)
                    {
                        var path = HeMruFiles.GetPath(n);

                        if (string.IsNullOrEmpty(path))
                        {
                            continue;
                        }

                        if (!System.IO.File.Exists(path))
                        {
                            continue;
                        }

                        menu.AddItem(new GUIContent(string.Format("Recent/{0}     {1}", (n + 1), path.Replace('/', '\\'))), false, delegate(System.Object obj)
                        {
                            var p = obj as string;
                            LoadFromFile(p);
                        }, path);
                    }
                    menu.AddSeparator("Recent/");
                    menu.AddItem(new GUIContent("Recent/Clear list"), false, delegate()
                    {
                        if (EditorUtility.DisplayDialog("Clear list...", "Do you want to clear the most recently used files list?", "Clear", "Cancel"))
                        {
                            HeMruFiles.RemoveAll();
                        }
                    });

                    menu.AddSeparator("");
                    menu.AddItem(new GUIContent("Close Snapshot"), false, CloseFile);
                    menu.AddSeparator("");
                    if (m_Heap == null)
                    {
                        menu.AddDisabledItem(new GUIContent("Save as..."));
                    }
                    else
                    {
                        menu.AddItem(new GUIContent("Save as..."), false, SaveToFile);
                    }
                    menu.AddSeparator("");
                    menu.AddItem(new GUIContent("New Window"), false, delegate()
                    {
                        var wnd = EditorWindow.CreateInstance <HeapExplorerWindow>();
                        wnd.Show();
                    });

                    menu.AddSeparator("");
                    menu.AddItem(new GUIContent("Settings/Use Multi-Threading"), useThreads, delegate()
                    {
                        useThreads = !useThreads;
                    });
                    menu.AddItem(new GUIContent("Settings/Debug View Menu"), debugViewMenu, delegate()
                    {
                        debugViewMenu = !debugViewMenu;
                    });
                    menu.AddItem(new GUIContent("Settings/Show unaligned memory sections (removes MonoMemPool sections)"), showInternalMemorySections, delegate()
                    {
                        showInternalMemorySections = !showInternalMemorySections;
                    });
                    menu.DropDown(m_FileToolbarButtonRect);
                }
                if (Event.current.type == EventType.Repaint)
                {
                    m_FileToolbarButtonRect = GUILayoutUtility.GetLastRect();
                }


                EditorGUI.BeginDisabledGroup(m_Heap == null || m_Heap.isBusy);
                if (GUILayout.Button("View", EditorStyles.toolbarDropDown, GUILayout.Width(60)))
                {
                    m_Views.Sort(delegate(HeapExplorerView x, HeapExplorerView y)
                    {
                        var value = x.viewMenuOrder.CompareTo(y.viewMenuOrder);
                        if (value == 0)
                        {
                            value = string.Compare(x.titleContent.text, y.titleContent.text);
                        }
                        return(value);
                    });

                    var prevOrder = -1;
                    var menu      = new GenericMenu();
                    foreach (var view in m_Views)
                    {
                        if (view.viewMenuOrder < 0)
                        {
                            continue;
                        }
                        if (prevOrder == -1)
                        {
                            prevOrder = view.viewMenuOrder;
                        }

                        var p0 = prevOrder / 100;
                        var p1 = view.viewMenuOrder / 100;
                        if (p1 - p0 >= 1)
                        {
                            var i = view.titleContent.text.LastIndexOf("/");
                            if (i == -1)
                            {
                                menu.AddSeparator("");
                            }
                            else
                            {
                                menu.AddSeparator(view.titleContent.text.Substring(0, i));
                            }
                        }
                        prevOrder = view.viewMenuOrder;

                        var c = new GUIContent(view.titleContent);
                        if (debugViewMenu)
                        {
                            c.text = string.Format("{2}   [viewMenuOrder={0}, type={1}]", view.viewMenuOrder, view.GetType().Name, c.text);
                        }

                        menu.AddItem(c, m_ActiveView == view, (GenericMenu.MenuFunction2) delegate(System.Object o)
                        {
                            if (o == m_ActiveView)
                            {
                                return;
                            }

                            var v  = o as HeapExplorerView;
                            var c0 = m_ActiveView.GetRestoreCommand(); c0.fromView = m_ActiveView;
                            var c1 = v.GetRestoreCommand(); c1.toView = v;
                            m_GotoHistory.Add(c0, c1);
                            ActivateView(v);
                        }, view);
                    }

                    menu.DropDown(m_ViewToolbarButtonRect);
                }
                if (Event.current.type == EventType.Repaint)
                {
                    m_ViewToolbarButtonRect = GUILayoutUtility.GetLastRect();
                }
                EditorGUI.EndDisabledGroup();


                var connectedProfiler = UnityEditorInternal.ProfilerDriver.GetConnectionIdentifier(UnityEditorInternal.ProfilerDriver.connectedProfiler);
                if (GUILayout.Button(new GUIContent("Capture", HeEditorStyles.magnifyingGlassImage), EditorStyles.toolbarDropDown, GUILayout.Width(80)))
                {
                    var menu = new GenericMenu();
                    menu.AddItem(new GUIContent(string.Format("Capture and Save '{0}'...", connectedProfiler)), false, CaptureAndSaveHeap);
                    menu.AddItem(new GUIContent(string.Format("Capture and Analyze '{0}'", connectedProfiler)), false, CaptureAndAnalyzeHeap);
                    menu.AddSeparator("");
                    menu.AddItem(new GUIContent(string.Format("Open Profiler")), false, delegate() { HeEditorUtility.OpenProfiler(); });
                    menu.DropDown(m_CaptureToolbarButtonRect);
                }
                if (Event.current.type == EventType.Repaint)
                {
                    m_CaptureToolbarButtonRect = GUILayoutUtility.GetLastRect();
                }

                if (m_ActiveView != null)
                {
                    m_ActiveView.OnToolbarGUI();
                }
            }
        }
        //----------------------------------------------------------------------

        private void ShowContextMenu(
            Rect position,
            int controlID,
            SerializedProperty property,
            Type[] types)
        {
            var menu = new GenericMenu();

            menu.AddItem(
                gui.selectContent,
                on: false,
                func: () => ShowObjectSelector(controlID, property));

            menu.AddSeparator("");

            var target = property.objectReferenceValue;

            if (target != null && TargetIsSubassetOf(property))
            {
                menu.AddItem(
                    gui.deleteSubassetContent,
                    on: false,
                    func: () => DestroyTarget(property));
            }
            else
            {
                menu.AddDisabledItem(gui.deleteSubassetContent);
            }

            if (types.Length > 0)
            {
                menu.AddSeparator("");

                menu.AddDisabledItem(gui.createSubassetContent);

                var typeIndex       = 0;
                var useTypeFullName = types.Length > 16;
                foreach (var type in types)
                {
                    var createAssetMenuAttribute =
                        (CreateAssetMenuAttribute)
                        type.GetCustomAttribute(
                            typeof(CreateAssetMenuAttribute));
                    var menuPath =
                        createAssetMenuAttribute != null
                        ? createAssetMenuAttribute.menuName
                        : useTypeFullName
                        ? type.FullName.Replace('.', '/')
                        : type.Name;

                    var menuTypeIndex = typeIndex++;
                    menu.AddItem(
                        new GUIContent(menuPath),
                        on: false,
                        func: () =>
                        AddSubasset(property, types, menuTypeIndex));
                }
            }

            menu.DropDown(position);
        }
Ejemplo n.º 30
0
    void OnGUI()
    {
        if (m_DragHandler == null)
        {
            // Setup GUI handler
            m_DragHandler = new GUIDragHandler();
            m_DragHandler.dragIdentifier = "BundleTreeView";
            m_DragHandler.AddRecieveIdentifier(m_DragHandler.dragIdentifier);
            m_DragHandler.canRecieveCallBack = OnCanRecieve;
            m_DragHandler.reciveDragCallBack = OnRecieve;
        }

        if (Event.current.type == EventType.MouseDown || Event.current.type == EventType.DragUpdated || !HasFocuse())
        {
            // Any mouse down msg or lose focuse will cancle the edit waiting process
            m_EditWaitStartTime = -1;
            m_EditWaitBundle    = "";
        }

        Rect curWindowRect = EditorGUILayout.BeginVertical(BMGUIStyles.GetStyle("OL Box"));

        {
            // Update rect info
            if (Event.current.type != EventType.Layout)
            {
                m_rect = curWindowRect;
            }

            // Toobar
            EditorGUILayout.BeginHorizontal(EditorStyles.toolbar, GUILayout.ExpandWidth(true));
            {
                // Create drop down
                Rect createBtnRect = GUILayoutUtility.GetRect(new GUIContent("Create"), EditorStyles.toolbarDropDown, GUILayout.ExpandWidth(false));
                if (GUI.Button(createBtnRect, "Create", EditorStyles.toolbarDropDown))
                {
                    GenericMenu menu = new GenericMenu();
                    if (m_Selections.Count <= 1)
                    {
                        menu.AddItem(new GUIContent("Scene Bundle"), false, CreateSceneBundle);
                        menu.AddItem(new GUIContent("Asset Bundle"), false, CreateAssetBundle);
                    }
                    else
                    {
                        menu.AddItem(new GUIContent("Scene Bundle"), false, null);
                        menu.AddItem(new GUIContent("Asset Bundle"), false, null);
                    }
                    menu.DropDown(createBtnRect);
                }

                // Build button
                Rect buildBtnRect = GUILayoutUtility.GetRect(new GUIContent("Build"), EditorStyles.toolbarDropDown, GUILayout.ExpandWidth(false));
                if (GUI.Button(buildBtnRect, "Build", EditorStyles.toolbarDropDown))
                {
                    GenericMenu menu = new GenericMenu();
                    menu.AddItem(new GUIContent("Build Selection"), false, BuildSelection);
                    menu.AddItem(new GUIContent("Rebuild Selection"), false, RebuildSelection);
                    menu.AddItem(new GUIContent("Build All"), false, BuildAll);
                    menu.AddItem(new GUIContent("Rebuild All"), false, RebuildAll);
                    menu.AddItem(new GUIContent("Clear"), false, ClearOutputs);
                    menu.DropDown(buildBtnRect);
                }

                GUILayout.FlexibleSpace();

                if (GUILayout.Button("Settings", EditorStyles.toolbarButton))
                {
                    BMSettingsEditor.Show();
                }
            }
            EditorGUILayout.EndHorizontal();

            // Tree view
            m_ScrollPos = EditorGUILayout.BeginScrollView(m_ScrollPos);
            {
                m_CurrentShowingBundles.Clear();

                foreach (BundleData rootBundle in BundleManager.Roots)
                {
                    if (!GUI_TreeItem(0, rootBundle.name))
                    {
                        Repaint();
                        break;
                    }
                }

                m_LastTimeShowingBundles.Clear();
                m_LastTimeShowingBundles.AddRange(m_CurrentShowingBundles);

                if (m_CurrentEditing == "")
                {
                    ArrowKeyProcess();
                    HotkeyProcess();
                }

                // Empty space for root selection
                Rect spaceRect = EditorGUILayout.BeginVertical(BMGUIStyles.GetStyle("Space"));
                GUILayout.Space(m_ItemHeight);
                EditorGUILayout.EndVertical();
                RootSpaceProcess(spaceRect);
            } EditorGUILayout.EndScrollView();

            Rect scrollViewRect = GUILayoutUtility.GetLastRect();
            if (scrollViewRect.height != 1)
            {
                UpdateScrollBarBySelection(scrollViewRect.height);
            }
        } EditorGUILayout.EndVertical();
    }
Ejemplo n.º 31
0
		/*public override string OnCompilerTransitionGeneration(FD.FlowWindow window) {
			
			return Tpl.GenerateTransitionMethods(window);

		}
		
		public override string OnCompilerTransitionAttachedGeneration(FD.FlowWindow windowFrom, FD.FlowWindow windowTo, bool everyPlatformHasUniqueName) {
			
			if (windowTo.IsFunction() == true && 
			    windowTo.IsSmall() == true &&
			    windowTo.IsContainer() == false &&
			    windowTo.GetFunctionId() > 0) {
				
				return FlowFunctionsTemplateGenerator.GenerateTransitionMethod(this.flowEditor, windowFrom, windowTo);

			}
			
			return base.OnCompilerTransitionAttachedGeneration(windowFrom, windowTo, everyPlatformHasUniqueName);
			
		}*/

		/*public override string OnCompilerTransitionAttachedGeneration(FD.FlowWindow windowFrom, FD.FlowWindow windowTo, bool everyPlatformHasUniqueName) {
			
			if (windowTo.IsLinker() == true &&
				windowTo.GetLinkerId() > 0) {

				var result = string.Empty;

				var linkerWindow = FlowSystem.GetWindow(windowTo.GetLinkerId());

				var className = linkerWindow.directory;
				var classNameWithNamespace = Tpl.GetNamespace(linkerWindow) + "." + Tpl.GetDerivedClassName(linkerWindow);

				result += TemplateGenerator.GenerateWindowLayoutTransitionMethod(windowFrom, linkerWindow, className, classNameWithNamespace);

				WindowSystem.CollectCallVariations(linkerWindow.GetScreen(), (listTypes, listNames) => {

					result += TemplateGenerator.GenerateWindowLayoutTransitionTypedMethod(windowFrom, linkerWindow, className, classNameWithNamespace, listTypes, listNames);

				});

				return result;

			}

			return base.OnCompilerTransitionAttachedGeneration(windowFrom, windowTo, everyPlatformHasUniqueName);

		}*/

		/*public override string OnCompilerTransitionTypedAttachedGeneration(FD.FlowWindow windowFrom, FD.FlowWindow windowTo, bool everyPlatformHasUniqueName, System.Type[] types, string[] names) {
			
			if (windowTo.IsLinker() == true &&
				windowTo.GetLinkerId() > 0) {

				var result = string.Empty;

				var window = FlowSystem.GetWindow(windowTo.GetLinkerId());

				var className = window.directory;
				var classNameWithNamespace = Tpl.GetNamespace(window) + "." + Tpl.GetDerivedClassName(window);

				result += TemplateGenerator.GenerateWindowLayoutTransitionMethod(windowFrom, window, className, classNameWithNamespace);

				WindowSystem.CollectCallVariations(windowTo.GetScreen(), (listTypes, listNames) => {

					result += TemplateGenerator.GenerateWindowLayoutTransitionTypedMethod(windowFrom, window, className, classNameWithNamespace, listTypes, listNames);

				});

				Debug.Log(className + " :: " + classNameWithNamespace + " == " + result);

				return result;

			}
			
			return base.OnCompilerTransitionTypedAttachedGeneration(windowFrom, windowTo, everyPlatformHasUniqueName, types, names);
			
		}*/

		public override void OnFlowWindowGUI(FD.FlowWindow window) {

			var data = FlowSystem.GetData();
			if (data == null) return;

			var flag =
				(window.IsLinker() == true && 
				 window.IsSmall() == true &&
				 window.IsContainer() == false);

			if (flag == true) {
				
				var alreadyConnectedFunctionIds = new List<int>();

				// Find caller window
				var windowFrom = data.windowAssets.FirstOrDefault((item) => item.HasAttach(window.id));
				if (windowFrom != null) {
					
					var attaches = windowFrom.GetAttachedWindows();
					foreach (var attachWindow in attaches) {
						
						if (attachWindow.IsLinker() == true) {
							
							alreadyConnectedFunctionIds.Add(attachWindow.GetLinkerId());
							
						}
						
					}
					
				}
				
				foreach (var win in data.windowAssets) {

					if (win.CanDirectCall() == true) {

						var count = alreadyConnectedFunctionIds.Count((e) => e == win.id);
						if ((window.GetLinkerId() == win.id && count == 1) || count == 0) {
							
						} else {
							
							if (win.id == window.GetLinkerId()) window.linkerId = 0;
							alreadyConnectedFunctionIds.Remove(win.id);
							
						}

					}

				}

				var linkerId = window.GetLinkerId();
				var linker = linkerId == 0 ? null : data.GetWindow(linkerId);
				var isActiveSelected = true;

				var oldColor = GUI.color;
				GUI.color = isActiveSelected ? Color.white : Color.grey;
				var result = GUILayout.Button(linker != null ? string.Format("{0} ({1})", linker.title, linker.directory) : "None", FlowSystemEditorWindow.defaultSkin.button, GUILayout.ExpandHeight(true));
				GUI.color = oldColor;
				var rect = GUILayoutUtility.GetLastRect();
				rect.y += rect.height;

				if (result == true) {

					System.Action<int> onApply = (int id) => {

						var linkerSources = new List<FD.FlowWindow>();
						foreach (var w in data.windowAssets) {

							if (w.AlreadyAttached(window.id) == true) {

								linkerSources.Add(w);

							}

						}

						if (window.linkerId != 0) {

							foreach (var w in linkerSources) {

								data.Detach(w.id, window.linkerId, oneWay: true);

							}

						}

						window.linkerId = id;

						if (window.linkerId != 0) {

							foreach (var w in linkerSources) {

								data.Attach(w.id, window.linkerId, oneWay: true);

							}

						}

					};

					var menu = new GenericMenu();
					menu.AddItem(new GUIContent("None"), window.linkerId == 0, () => {

						onApply(0);

					});

					if (windowFrom != null) {

						alreadyConnectedFunctionIds.Clear();
						var attaches = windowFrom.GetAttachedWindows();
						foreach (var attachWindow in attaches) {
							
							if (attachWindow.IsLinker() == true) {
								
								alreadyConnectedFunctionIds.Add(attachWindow.GetLinkerId());
								
							}
							
						}
						
					}
					foreach (var win in data.windowAssets) {
						
						if (win.CanDirectCall() == true) {

							var caption = new GUIContent(string.Format("{0} ({1})", win.title, win.directory));

							var count = alreadyConnectedFunctionIds.Count((e) => e == win.id);
							if ((window.GetLinkerId() == win.id && count == 1) || count == 0) {

								var id = win.id;
								menu.AddItem(caption, win.id == window.GetLinkerId(), () => {

									onApply(id);

								});

							} else {

								if (win.id == window.GetLinkerId()) window.linkerId = 0;

								alreadyConnectedFunctionIds.Remove(win.id);
								menu.AddDisabledItem(caption);

							}

						}
						
					}

					menu.DropDown(rect);

				}

			}

		}
Ejemplo n.º 32
0
        void OnGUISpreadsheet(Rect r)
        {
            GUILayout.BeginArea(r);

            int currentTableView = (int)CurrentTableView;

            EditorGUILayout.BeginHorizontal(MemoryMapBase.Styles.ContentToolbar);

            if (GUILayout.Toggle(m_ActiveMode == m_UIState.FirstMode, "Snapshot A", EditorStyles.radioButton))
            {
                if (m_ActiveMode != m_UIState.FirstMode)
                {
                    m_ActiveMode = m_UIState.FirstMode as UIState.SnapshotMode;
                    m_MemoryMap.Reselect();
                }
            }

            if (GUILayout.Toggle(m_ActiveMode == m_UIState.SecondMode, "Snapshot B", EditorStyles.radioButton))
            {
                if (m_ActiveMode != m_UIState.SecondMode)
                {
                    m_ActiveMode = m_UIState.SecondMode as UIState.SnapshotMode;
                    m_MemoryMap.Reselect();
                }
            }

            if (r.width > 500)
            {
                GUILayout.Space(r.width - 500);
            }

            var popupRect = GUILayoutUtility.GetRect(Content.TableModesList[currentTableView], EditorStyles.toolbarPopup);

            if (EditorGUI.DropdownButton(popupRect, Content.TableModesList[currentTableView], FocusType.Passive, EditorStyles.toolbarPopup))
            {
                GenericMenu menu = new GenericMenu();
                for (int i = 0; i < Content.TableModesList.Length; i++)
                {
                    menu.AddItem(Content.TableModesList[i], (int)currentTableView == i, (object data) => { CurrentTableView = (TableDisplayMode)data; m_MemoryMap.Reselect(); }, i);
                }
                menu.DropDown(popupRect);
            }

            EditorGUILayout.EndHorizontal();

            if (m_Spreadsheet != null)
            {
                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.BeginVertical();

                EditorGUILayout.BeginHorizontal();
                GUILayout.Space(2);
                m_Spreadsheet.OnGUI(r.width - 4);
                GUILayout.Space(2);
                EditorGUILayout.EndHorizontal();

                GUILayout.Space(2);
                EditorGUILayout.EndVertical();
                EditorGUILayout.EndHorizontal();
            }

            GUILayout.EndArea();
        }
Ejemplo n.º 33
0
		public override void OnFlowWindowGUI(FlowWindow window) {

			var data = FlowSystem.GetData();
			if (data == null) return;

			var flag = (window.IsFunction() == true && 
					window.IsSmall() == true &&
					window.IsContainer() == false);

			if (flag == true) {
				
				var alreadyConnectedFunctionIds = new List<int>();

				// Find caller window
				var windowFrom = data.windows.FirstOrDefault((item) => item.HasAttach(window.id));
				if (windowFrom != null) {
					
					var attaches = windowFrom.GetAttachedWindows();
					foreach (var attachWindow in attaches) {
						
						if (attachWindow.IsFunction() == true) {
							
							alreadyConnectedFunctionIds.Add(attachWindow.GetFunctionId());
							
						}
						
					}
					
				}
				
				foreach (var win in data.windows) {
					
					if (win.IsFunction() == true &&
					    win.IsContainer() == true) {
						
						var count = alreadyConnectedFunctionIds.Count((e) => e == win.id);
						if ((window.GetFunctionId() == win.id && count == 1) || count == 0) {
							
						} else {
							
							if (win.id == window.functionId) window.functionId = 0;
							alreadyConnectedFunctionIds.Remove(win.id);
							
						}
						
					}
					
				}

				var functionId = window.GetFunctionId();
				var functionContainer = functionId == 0 ? null : data.GetWindow(functionId);
				var isActiveSelected = true;

				var oldColor = GUI.color;
				GUI.color = isActiveSelected ? Color.white : Color.grey;
				var result = GUILayoutExt.LargeButton(functionContainer != null ? functionContainer.title : "None", GUILayout.MaxHeight(60f), GUILayout.MaxWidth(150f));
				GUI.color = oldColor;
				var rect = GUILayoutUtility.GetLastRect();
				rect.y += rect.height;

				if (result == true) {

					var menu = new GenericMenu();
					menu.AddItem(new GUIContent("None"), window.functionId == 0, () => {

						window.functionId = 0;

					});

					if (windowFrom != null) {

						alreadyConnectedFunctionIds.Clear();
						var attaches = windowFrom.GetAttachedWindows();
						foreach (var attachWindow in attaches) {
							
							if (attachWindow.IsFunction() == true) {
								
								alreadyConnectedFunctionIds.Add(attachWindow.GetFunctionId());
								
							}
							
						}
						
					}
					foreach (var win in data.windows) {
						
						if (win.IsFunction() == true &&
						    win.IsContainer() == true) {

							var count = alreadyConnectedFunctionIds.Count((e) => e == win.id);
							if ((window.GetFunctionId() == win.id && count == 1) || count == 0) {

								var id = win.id;
								menu.AddItem(new GUIContent(win.title), win.id == window.functionId, () => {

									window.functionId = id;

								});

							} else {

								if (win.id == window.functionId) window.functionId = 0;

								alreadyConnectedFunctionIds.Remove(win.id);
								menu.AddDisabledItem(new GUIContent(win.title));

							}

						}
						
					}

					menu.DropDown(rect);

				}

			}

		}
Ejemplo n.º 34
0
        private void PopupTools(Rect position)
        {
            var           menu              = new GenericMenu();
            int           unboundTextures   = MaterialCleaner.CountUnusedProperties(MaterialCleaner.CleanPropertyType.Texture, Materials);
            int           unboundProperties = MaterialCleaner.CountAllUnusedProperties(Materials);
            List <string> unusedTextures    = new List <string>();

            MainGroup.FindUnusedTextures(unusedTextures, true);
            if (unboundTextures > 0 && !IsLockedMaterial)
            {
                menu.AddItem(new GUIContent($"Unbound Textures: {unboundTextures}/List in console"), false, delegate()
                {
                    MaterialCleaner.ListUnusedProperties(MaterialCleaner.CleanPropertyType.Texture, Materials);
                });
                menu.AddItem(new GUIContent($"Unbound Textures: {unboundTextures}/Remove"), false, delegate()
                {
                    MaterialCleaner.RemoveUnusedProperties(MaterialCleaner.CleanPropertyType.Texture, Materials);
                });
            }
            else
            {
                menu.AddDisabledItem(new GUIContent($"Unbound textures: 0"));
            }
            if (unusedTextures.Count > 0 && !IsLockedMaterial)
            {
                menu.AddItem(new GUIContent($"Unused Textures: {unusedTextures.Count}/List in console"), false, delegate()
                {
                    Out("Unused textures", unusedTextures.Select(s => $"↳{s}"));
                });
                menu.AddItem(new GUIContent($"Unused Textures: {unusedTextures.Count}/Remove"), false, delegate()
                {
                    foreach (string t in unusedTextures)
                    {
                        if (PropertyDictionary.ContainsKey(t))
                        {
                            PropertyDictionary[t].MaterialProperty.textureValue = null;
                        }
                    }
                });
            }
            else
            {
                menu.AddDisabledItem(new GUIContent($"Unused textures: 0"));
            }
            if (unboundProperties > 0 && !IsLockedMaterial)
            {
                menu.AddItem(new GUIContent($"Unbound properties: {unboundProperties}/List in console"), false, delegate()
                {
                    MaterialCleaner.ListUnusedProperties(MaterialCleaner.CleanPropertyType.Texture, Materials);
                    MaterialCleaner.ListUnusedProperties(MaterialCleaner.CleanPropertyType.Float, Materials);
                    MaterialCleaner.ListUnusedProperties(MaterialCleaner.CleanPropertyType.Color, Materials);
                });
                menu.AddItem(new GUIContent($"Unbound properties: {unboundProperties}/Remove"), false, delegate()
                {
                    MaterialCleaner.RemoveAllUnusedProperties(MaterialCleaner.CleanPropertyType.Texture, Materials);
                });
            }
            else
            {
                menu.AddDisabledItem(new GUIContent($"Unbound properties: 0"));
            }
            menu.DropDown(position);
        }
Ejemplo n.º 35
0
		public override void OnFlowWindowGUI(FD.FlowWindow window) {

			if (Social.settings == null) return;

			var socialFlag = (window.flags & Social.settings.uniqueTag) == Social.settings.uniqueTag;
			if (socialFlag == true) {

				var settings = Social.settings;
				if (settings == null) return;
				
				var data = settings.data.Get(window);
				var isActiveSelected = settings.IsPlatformActive(data.settings);

				var oldColor = GUI.color;
				GUI.color = isActiveSelected ? Color.white : Color.grey;
				var result = GUILayoutExt.LargeButton(data.settings ? data.settings.GetPlatformName() : "None", 60f, 150f);
				GUI.color = oldColor;
				var rect = GUILayoutUtility.GetLastRect();
				rect.y += rect.height;

				if (result == true) {

					var menu = new GenericMenu();
					menu.AddItem(new GUIContent("None"), data.settings == null, () => {

						data.settings = null;

					});

					foreach (var platform in settings.activePlatforms) {

						if (platform.active == true) {

							var item = platform.settings;
							menu.AddItem(new GUIContent(platform.GetPlatformName()), data.settings == platform.settings, () => {

								data.settings = item;

							});
							
						} else {

							menu.AddDisabledItem(new GUIContent(platform.GetPlatformName()));

						}
						
					}

					menu.DropDown(rect);

				}

			}

		}
Ejemplo n.º 36
0
 public static void Show(Rect buttonRect, int viewIndex, AudioMixerGroupViewList list)
 {
     GenericMenu menu = new GenericMenu();
     data userData = new data {
         viewIndex = viewIndex,
         list = list
     };
     menu.AddItem(new GUIContent("Rename"), false, new GenericMenu.MenuFunction2(AudioMixerGroupViewList.ViewsContexttMenu.Rename), userData);
     menu.AddItem(new GUIContent("Duplicate"), false, new GenericMenu.MenuFunction2(AudioMixerGroupViewList.ViewsContexttMenu.Duplicate), userData);
     menu.AddItem(new GUIContent("Delete"), false, new GenericMenu.MenuFunction2(AudioMixerGroupViewList.ViewsContexttMenu.Delete), userData);
     menu.DropDown(buttonRect);
 }