public override void OnInspectorGUI()
        {
            SCPE_GUI.DisplayDocumentationButton("fog");

            if (RenderSettings.fog)
            {
                EditorGUILayout.BeginVertical();
                {
                    EditorGUILayout.HelpBox("Fog is currently enabled in the active scene, resulting in an overlapping fog effect", MessageType.Warning);
                    using (new EditorGUILayout.HorizontalScope())
                    {
                        if (GUILayout.Button("Disable scene fog"))
                        {
                            RenderSettings.fog = false;
                        }
                        GUILayout.FlexibleSpace();
                    }
                }
                EditorGUILayout.EndVertical();

                EditorGUILayout.Space();
            }
            PropertyField(useSceneSettings);
            EditorGUILayout.Space();

            m_showControls.target = !useSceneSettings.value.boolValue;
            if (EditorGUILayout.BeginFadeGroup(m_showControls.faded))
            {
                PropertyField(fogMode);
                PropertyField(fogStartDistance);
                if (fogMode.value.intValue == 1)
                {
                    PropertyField(fogEndDistance);
                }
                else
                {
                    PropertyField(fogDensity);
                }

                PropertyField(colorMode);
                if (colorMode.value.intValue == 0)
                {
                    PropertyField(fogColor);
                }
                else if (colorMode.value.intValue == 1) //gradient
                {
                    PropertyField(fogColorGradient);

                    if (fogColorGradient.value.objectReferenceValue)
                    {
                        SCPE.CheckGradientImportSettings(fogColorGradient);

                        GUILayout.Space(5f);
                        //Gradient preview
                        using (new EditorGUILayout.HorizontalScope())
                        {
                            EditorGUILayout.LabelField("Near", GUILayout.MaxWidth(32f));
                            Rect rect = GUILayoutUtility.GetRect(1, 12, "TextField");
                            EditorGUI.DrawTextureTransparent(rect, fogColorGradient.value.objectReferenceValue as Texture2D);
                            EditorGUILayout.LabelField("Far", GUILayout.MaxWidth(30f));
                        }

                        EditorGUILayout.BeginHorizontal();
                        {
                            EditorGUI.BeginDisabledGroup(!gradientUseFarClipPlane.value.boolValue);
                            {
                                PropertyField(gradientDistance, new GUIContent("Distance"));
                            }
                            EditorGUI.EndDisabledGroup();
                            gradientUseFarClipPlane.overrideState.boolValue = true;
                            gradientUseFarClipPlane.value.boolValue         = !GUILayout.Toggle(!gradientUseFarClipPlane.value.boolValue, new GUIContent("Automatic", "Distance will be set by the camera's far clipping plane"), EditorStyles.miniButton);
                        }
                        EditorGUILayout.EndHorizontal();

                        //EditorGUILayout.HelpBox("In scene view, the gradient will appear to look different due to the camera's dynamic far clipping value", MessageType.None);
                    }
                }
                else if (colorMode.value.intValue == 2) //Skybox
                {
#if !LWRP_5_7_2_OR_NEWER
                    if (UnityEngine.Rendering.GraphicsSettings.renderPipelineAsset)
                    {
                        if (UnityEngine.Rendering.GraphicsSettings.renderPipelineAsset.name.Contains("LWRP"))
                        {
                            EditorGUILayout.HelpBox("This feature requires atleast LWRP version 5.7.2. If you're using this version, rerun the installer through the Help window", MessageType.Error);
                        }
                    }
#endif
                    if (UnityEngine.Rendering.GraphicsSettings.renderPipelineAsset)
                    {
                        if (UnityEngine.Rendering.GraphicsSettings.renderPipelineAsset.name.Contains("HDR"))
                        {
                            EditorGUILayout.HelpBox("This feature is not supported in the HDRP", MessageType.Error);
                        }
                    }
#if SCPE_DEV  //Hide parameter, implementation isn't ideal and will cause pixel marching, won't look good in any case
                    PropertyField(skyboxMipLevel);
#endif
                }
            }
            EditorGUILayout.EndFadeGroup();

            PropertyField(distanceFog);
            if (colorMode.value.intValue == 1 && distanceFog.value.boolValue == false && heightFog.value.boolValue)
            {
                EditorGUILayout.HelpBox("Distance fog must be enabled when using the Gradient Texture color mode. Height fog only will not be colored correctly", MessageType.Warning);
            }
            if (distanceFog.value.boolValue)
            {
                PropertyField(useRadialDistance, new GUIContent("Radial"));
                PropertyField(distanceDensity);
            }

            //Always exclude skybox for skybox color mode
            PropertyField(skyboxInfluence, new GUIContent("Influence"));

            PropertyField(enableDirectionalLight);

            m_showSun.target = enableDirectionalLight.value.boolValue;
            if (EditorGUILayout.BeginFadeGroup(m_showSun.faded))
            {
                if (FogLightSource.sunDirection == Vector3.zero && (useLightDirection.value.boolValue || useLightColor.value.boolValue || useLightIntensity.value.boolValue))
                {
                    EditorGUILayout.HelpBox("No source Directional Light found!\n\nAdd the \"FogLightSource\" script to your main light", MessageType.Warning);

                    GUILayout.Space(-32);
                    using (new EditorGUILayout.HorizontalScope())
                    {
                        GUILayout.FlexibleSpace();
                        if (GUILayout.Button("Add", GUILayout.Width(60)))
                        {
                            FogLightSourceInspector.AddLightSource();
                        }
                        GUILayout.Space(8);
                    }
                    GUILayout.Space(11);
                }

                PropertyField(useLightDirection);
                if (!useLightDirection.value.boolValue)
                {
                    PropertyField(lightDirection);
                }
                PropertyField(useLightColor);
                if (!useLightColor.value.boolValue)
                {
                    PropertyField(lightColor);
                }
                PropertyField(useLightIntensity);
                if (!useLightIntensity.value.boolValue)
                {
                    PropertyField(lightIntensity);
                }
            }
            EditorGUILayout.EndFadeGroup();

            PropertyField(heightFog);
            m_showHeight.target = heightFog.value.boolValue;
            if (EditorGUILayout.BeginFadeGroup(m_showHeight.faded))
            {
                if (RuntimeUtilities.isSinglePassStereoSelected)
                {
                    EditorGUILayout.HelpBox("Not supported in VR", MessageType.Warning);
                }
                PropertyField(height);
                PropertyField(heightDensity);

                PropertyField(heightFogNoise);
                if (heightFogNoise.value.boolValue)
                {
#if UNITY_2018_1_OR_NEWER
                    //EditorGUILayout.HelpBox("Fog noise is currently bugged when using the Post Processing installed through the Package Manager.", MessageType.Warning);
#endif
                    PropertyField(heightNoiseTex);
                    if (heightNoiseTex.value.objectReferenceValue)
                    {
                        PropertyField(heightNoiseSize);
                        PropertyField(heightNoiseStrength);
                        PropertyField(heightNoiseSpeed);
                    }
                }
            }
            EditorGUILayout.EndFadeGroup();

            PropertyField(lightScattering);
            m_showScattering.target = lightScattering.value.boolValue;
            if (EditorGUILayout.BeginFadeGroup(m_showScattering.faded))
            {
                PropertyField(scatterIntensity);
                PropertyField(scatterThreshold);
                PropertyField(scatterDiffusion);
                PropertyField(scatterSoftKnee);
            }
            EditorGUILayout.EndFadeGroup();
        }
Exemple #2
0
        public override void OnInspectorGUI()
        {
            var oldSkin = GUI.skin;

            serializedObject.Update();
            if (skin)
            {
                GUI.skin = skin;
            }


            GUILayout.Space(10);

            GUI.skin = oldSkin;
            base.OnInspectorGUI();
            if (skin)
            {
                GUI.skin = skin;
            }
            bool   usingToolbar        = toolbars.Count > 1;
            string selectedToolbarName = toolbars[selectedToolBar].title;

            if (manager.itemListData && ((usingToolbar && selectedToolbarName.Equals("Item Collection")) || !usingToolbar))
            {
                GUILayout.BeginVertical("box");
                if (itemReferenceList.arraySize > manager.itemListData.items.Count)
                {
                    manager.items.Resize(manager.itemListData.items.Count);
                }
                GUILayout.Box("Item Collection " + manager.items.Count);
                filteredItems = manager.itemsFilter.Count > 0 ? GetItemByFilter(manager.itemListData.items, manager.itemsFilter) : manager.itemListData.items;

                if (!inAddItem && filteredItems.Count > 0 && GUILayout.Button("Add Item", EditorStyles.miniButton))
                {
                    inAddItem = true;
                }
                if (inAddItem && filteredItems.Count > 0)
                {
                    GUILayout.BeginVertical("box");
                    selectedItem = EditorGUILayout.Popup(new GUIContent("SelectItem"), selectedItem, GetItemContents(filteredItems));
                    bool isValid       = true;
                    var  indexSelected = manager.itemListData.items.IndexOf(filteredItems[selectedItem]);
                    if (manager.items.Find(i => i.id == manager.itemListData.items[indexSelected].id) != null)
                    {
                        isValid = false;
                        EditorGUILayout.HelpBox("This item already exist", MessageType.Error);
                    }
                    GUILayout.BeginHorizontal();

                    if (isValid && GUILayout.Button("Add", EditorStyles.miniButton))
                    {
                        itemReferenceList.arraySize++;
                        itemReferenceList.GetArrayElementAtIndex(itemReferenceList.arraySize - 1).FindPropertyRelative("id").intValue     = manager.itemListData.items[indexSelected].id;
                        itemReferenceList.GetArrayElementAtIndex(itemReferenceList.arraySize - 1).FindPropertyRelative("amount").intValue = 1;
                        EditorUtility.SetDirty(manager);
                        serializedObject.ApplyModifiedProperties();
                        inAddItem = false;
                    }
                    if (GUILayout.Button("Cancel", EditorStyles.miniButton))
                    {
                        inAddItem = false;
                    }
                    GUILayout.EndHorizontal();
                    GUILayout.EndVertical();
                }

                GUIStyle boxStyle = new GUIStyle(GUI.skin.box);
                scroll = GUILayout.BeginScrollView(scroll, GUILayout.MinHeight(200), GUILayout.ExpandHeight(false), GUILayout.ExpandWidth(false));
                for (int i = 0; i < manager.items.Count; i++)
                {
                    var item = manager.itemListData.items.Find(t => t.id.Equals(manager.items[i].id));
                    if (item)
                    {
                        GUILayout.BeginVertical("box");
                        GUILayout.BeginHorizontal();
                        GUILayout.BeginHorizontal();

                        var rect = GUILayoutUtility.GetRect(50, 50);

                        if (item.icon != null)
                        {
                            DrawTextureGUI(rect, item.icon, new Vector2(50, 50));
                        }

                        var name    = " ID " + item.id.ToString("00") + "\n - " + item.name + "\n - " + item.type.ToString();
                        var content = new GUIContent(name, null, "Click to Open");
                        GUILayout.Label(content, EditorStyles.miniLabel);
                        GUILayout.BeginVertical("box");
                        GUILayout.BeginHorizontal();
                        GUILayout.Label("Auto Equip", EditorStyles.miniLabel);
                        manager.items[i].autoEquip = EditorGUILayout.Toggle("", manager.items[i].autoEquip, GUILayout.Width(30));
                        if (manager.items[i].autoEquip)
                        {
                            GUILayout.Label("EquipArea", EditorStyles.miniLabel);
                            manager.items[i].indexArea = EditorGUILayout.IntField("", manager.items[i].indexArea, GUILayout.Width(30));
                        }
                        GUILayout.EndHorizontal();
                        GUILayout.BeginHorizontal();
                        GUILayout.Label("Amount", EditorStyles.miniLabel);
                        manager.items[i].amount = EditorGUILayout.IntField(manager.items[i].amount, GUILayout.Width(30));

                        if (manager.items[i].amount < 1)
                        {
                            manager.items[i].amount = 1;
                        }

                        GUILayout.EndHorizontal();
                        if (item.attributes.Count > 0)
                        {
                            manager.items[i].changeAttributes = GUILayout.Toggle(manager.items[i].changeAttributes, new GUIContent("Change Attributes", "This is a override of the original item attributes"), EditorStyles.miniButton, GUILayout.ExpandWidth(true));
                        }
                        GUILayout.EndVertical();

                        GUILayout.EndHorizontal();

                        if (GUILayout.Button("x", GUILayout.Width(25), GUILayout.Height(25)))
                        {
                            itemReferenceList.DeleteArrayElementAtIndex(i);
                            EditorUtility.SetDirty(target);
                            serializedObject.ApplyModifiedProperties();
                            break;
                        }

                        GUILayout.EndHorizontal();

                        Color backgroundColor = GUI.backgroundColor;
                        GUI.backgroundColor = Color.clear;
                        var _rec = GUILayoutUtility.GetLastRect();
                        _rec.width -= 100;

                        EditorGUIUtility.AddCursorRect(_rec, MouseCursor.Link);

                        if (GUI.Button(_rec, ""))
                        {
                            if (manager.itemListData.inEdition)
                            {
                                if (vItemListWindow.Instance != null)
                                {
                                    vItemListWindow.SetCurrentSelectedItem(manager.itemListData.items.IndexOf(item));
                                }
                                else
                                {
                                    vItemListWindow.CreateWindow(manager.itemListData, manager.itemListData.items.IndexOf(item));
                                }
                            }
                            else
                            {
                                vItemListWindow.CreateWindow(manager.itemListData, manager.itemListData.items.IndexOf(item));
                            }
                        }
                        GUILayout.Space(7);
                        GUI.backgroundColor = backgroundColor;
                        if (item.attributes != null && item.attributes.Count > 0)
                        {
                            if (manager.items[i].changeAttributes)
                            {
                                if (GUILayout.Button("Reset", EditorStyles.miniButton))
                                {
                                    manager.items[i].attributes = null;
                                }
                                if (manager.items[i].attributes == null)
                                {
                                    manager.items[i].attributes = item.attributes.CopyAsNew();
                                }
                                else if (manager.items[i].attributes.Count != item.attributes.Count)
                                {
                                    manager.items[i].attributes = item.attributes.CopyAsNew();
                                }
                                else
                                {
                                    for (int a = 0; a < manager.items[i].attributes.Count; a++)
                                    {
                                        GUILayout.BeginHorizontal();
                                        GUILayout.Label(manager.items[i].attributes[a].name.ToString());
                                        manager.items[i].attributes[a].value = EditorGUILayout.IntField(manager.items[i].attributes[a].value, GUILayout.MaxWidth(60));
                                        GUILayout.EndHorizontal();
                                    }
                                }
                            }
                        }

                        GUILayout.EndVertical();
                    }
                    else
                    {
                        itemReferenceList.DeleteArrayElementAtIndex(i);
                        EditorUtility.SetDirty(manager);
                        serializedObject.ApplyModifiedProperties();
                        break;
                    }
                }
                GUILayout.EndScrollView();
                GUI.skin.box = boxStyle;

                GUILayout.EndVertical();
                if (GUI.changed)
                {
                    EditorUtility.SetDirty(manager);
                    serializedObject.ApplyModifiedProperties();
                }
            }

            if (GUI.changed)
            {
                EditorUtility.SetDirty(target);
            }
            serializedObject.ApplyModifiedProperties();
            GUI.skin = oldSkin;
        }
Exemple #3
0
        void OnGUI()
        {
            if (!isInitialised)
            {
                Initialise();
            }

            if (!_selectedAC)
            {
                _SetCurrentAudioController(_FindAudioController());
            }

            if (_selectedAC == null && Selection.activeGameObject != null)
            {
                _SetCurrentAudioController(Selection.activeGameObject.GetComponent <AudioController>());
            }

            if (_audioControllerNameList == null)
            {
                _FindAudioController();

                if (_audioControllerNameList == null && _selectedAC != null)   // can happen if AC was selected by Show( AC )
                {
                    _audioControllerNameList = new string[1] {
                        _GetPrefabName(_selectedAC)
                    };
                }
            }

            if (!_selectedAC)
            {
                EditorGUILayout.LabelField("No AudioController found!");
                return;
            }

            EditorGUILayout.BeginHorizontal();

            int newACIndex = EditorGUILayout.Popup(_selectedACIndex, _audioControllerNameList, _headerStyleButton);

            if (newACIndex != _selectedACIndex)
            {
                _selectedACIndex = newACIndex;
                _SetCurrentAudioController(_audioControllerList[_selectedACIndex]);
                _SelectCurrentAudioController();
            }

            if (_foldoutsSetFromController != _selectedAC)
            {
                _SetCategoryFoldouts();
            }

            if (_searchString == null)
            {
                _searchString = "";
            }

            _searchString = EditorGUILayout.TextField("                  search item: ", _searchString);
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            GUILayout.Button("      ", _styleEmptyButton);
            EditorGUILayout.LabelField("Item", _headerStyle);
            EditorGUILayout.LabelField("Sub Item", _headerStyle);

            EditorGUILayout.EndHorizontal();

            _scrollPos = EditorGUILayout.BeginScrollView(_scrollPos);

            if (_selectedAC != null && _selectedAC.AudioCategories != null)
            {
                for (int categoryIndex = 0; categoryIndex < _selectedAC.AudioCategories.Length; categoryIndex++)
                {
                    var category = _selectedAC.AudioCategories[categoryIndex];

                    if (string.IsNullOrEmpty(category.Name))
                    {
                        Debug.LogWarning("empty category.Name");
                        continue;
                    }


                    if (!_foldedOutCategories.ContainsKey(category.Name))
                    {
                        Debug.LogWarning("can not find category.Name: " + category.Name);   // TODO: find out why this can happen sometimes
                        continue;
                    }

                    EditorGUILayout.BeginHorizontal();

                    if (GUILayout.Button((_foldedOutCategories[category.Name] ? "-\t" : "+\t") + category.Name, _styleCategoryButtonHeader))
                    {
                        _foldedOutCategories[category.Name] = !_foldedOutCategories[category.Name];
                    }

                    EditorGUILayout.EndHorizontal();

                    var filteredAudioItems = new List <AudioItem>(category.AudioItems);
                    if (!string.IsNullOrEmpty(_searchString))
                    {
                        bool catFoldedOut = false;
                        for (int i = 0; i < filteredAudioItems.Count; ++i)
                        {
                            AudioItem item = filteredAudioItems[i];
                            if (!item.Name.ToLowerInvariant().Contains(_searchString.ToLowerInvariant()))
                            {
                                filteredAudioItems.RemoveAt(i--);
                            }
                            else
                            {
                                catFoldedOut = true;
                            }
                        }
                        _foldedOutCategories[category.Name] = catFoldedOut && filteredAudioItems.Count > 0;
                    }

                    if (_foldedOutCategories[category.Name])
                    {
                        if (category.AudioItems == null)
                        {
                            continue;
                        }

                        var sortedAudioItems = filteredAudioItems.OrderBy(x => x.Name).ToArray();

                        for (int itemIndex = 0; itemIndex < sortedAudioItems.Length; itemIndex++)
                        {
                            var    item       = sortedAudioItems[itemIndex];
                            string emptySpace = "      ";

                            EditorGUILayout.BeginHorizontal();
                            GUILayout.Button(emptySpace, _styleEmptyButton);
                            GUILayout.Label(item.Name);
                            EditorGUILayout.EndHorizontal();

                            if (item.subItems == null)
                            {
                                continue;
                            }
                            for (int subitemIndex = 0; subitemIndex < item.subItems.Length; subitemIndex++)
                            {
                                var subItem = item.subItems[subitemIndex];

                                GUILayout.BeginHorizontal();
                                GUILayout.Button(emptySpace, _styleEmptyButton);
                                EditorGUILayout.BeginHorizontal();

                                string listItemDisplay     = "";
                                string listItemTypeDisplay = "     ";

                                if (subItem.SubItemType == AudioSubItemType.Clip)
                                {
                                    if (subItem.Clip != null)
                                    {
                                        listItemDisplay      = subItem.Clip.name;
                                        listItemTypeDisplay += "CLIP:";
                                    }
                                    else
                                    {
                                        listItemDisplay      = "*unset*";
                                        listItemTypeDisplay += "CLIP:";
                                    }
                                }
                                else
                                {
                                    listItemTypeDisplay += "ITEM:";
                                    listItemDisplay      = subItem.ItemModeAudioID;
                                }

                                EditorGUILayout.LabelField(listItemTypeDisplay, GUILayout.MaxWidth(_buttonSize));

                                if (GUILayout.Button(listItemDisplay, subitemIndex % 2 == 0 ? _styleListItemButton0 : _styleListItemButton1, GUILayout.ExpandWidth(true)))
                                {
                                    _selectedAC._currentInspectorSelection.currentCategoryIndex = categoryIndex;
                                    _selectedAC._currentInspectorSelection.currentItemIndex     = Array.FindIndex(category.AudioItems, x => x.Name == item.Name);
                                    _selectedAC._currentInspectorSelection.currentSubitemIndex  = subitemIndex;
                                    _SelectCurrentAudioController();
                                }

                                if (subItem.SubItemType == AudioSubItemType.Clip)
                                {
                                    if (subItem.Clip != null)
                                    {
                                        if (GUILayout.Button("Clip", subitemIndex % 2 == 0 ? _styleListItemButton0 : _styleListItemButton1, GUILayout.MaxWidth(50)))
                                        {
                                            Selection.activeObject = subItem.Clip;
                                            EditorGUIUtility.PingObject(subItem.Clip);
                                        }
                                    }
                                }


                                EditorGUILayout.EndHorizontal();
                                EditorGUILayout.EndHorizontal();
                            }
                        }
                    }
                }
            }

            EditorGUILayout.EndScrollView();
        }
Exemple #4
0
        void DrawControls()
        {
            GUILayout.BeginVertical();
            GUILayout.Label("<b>TextMeshPro - Font Asset Creator</b>", SectionLabel, GUILayout.Width(300));
            GUILayout.Label("Font Settings", SectionLabel, GUILayout.Width(300));

            GUILayout.BeginVertical(textureAreaBox, GUILayout.Width(300));
            EditorGUIUtility.LookLikeControls(120f, 160f);

            // FONT TTF SELECTION
            font_TTF = EditorGUILayout.ObjectField("Font Source", font_TTF, typeof(Font), false, GUILayout.Width(290)) as Object;

            // FONT SIZING
            if (FontSizingOption_Selection == 0)
            {
                FontSizingOption_Selection = EditorGUILayout.Popup("Font Size", FontSizingOption_Selection, FontSizingOptions, GUILayout.Width(290));
            }
            else
            {
                EditorGUIUtility.LookLikeControls(120f, 40f);
                GUILayout.BeginHorizontal(GUILayout.Width(290));
                FontSizingOption_Selection = EditorGUILayout.Popup("Font Size", FontSizingOption_Selection, FontSizingOptions, GUILayout.Width(225));
                font_size = EditorGUILayout.IntField(font_size);
                GUILayout.EndHorizontal();
            }

            EditorGUIUtility.LookLikeControls(120f, 160f);

            // FONT PADDING
            font_padding = EditorGUILayout.IntField("Font Padding", font_padding, GUILayout.Width(290));
            font_padding = (int)Mathf.Clamp(font_padding, 0f, 64f);


            //font_renderingMode = (FontRenderingMode)EditorGUILayout.EnumPopup("Rendering Mode", font_renderingMode, GUILayout.Width(290));

            // FONT ATLAS RESOLUTION SELECTION
            GUILayout.BeginHorizontal(GUILayout.Width(290));
            GUI.changed = false;
            EditorGUIUtility.LookLikeControls(120f, 40f);

            GUILayout.Label("Atlas Resolution:", GUILayout.Width(116));
            font_atlas_width  = EditorGUILayout.IntPopup(font_atlas_width, FontResolutionLabels, FontAtlasResolutions);  //, GUILayout.Width(80));
            font_atlas_height = EditorGUILayout.IntPopup(font_atlas_height, FontResolutionLabels, FontAtlasResolutions); //, GUILayout.Width(80));

            GUILayout.EndHorizontal();


            // FONT CHARACTER SET SELECTION
            GUI.changed = false;
            font_CharacterSet_Selection = EditorGUILayout.Popup("Character Set", font_CharacterSet_Selection, FontCharacterSets, GUILayout.Width(290));
            if (GUI.changed)
            {
                characterSequence = "";
                //Debug.Log("Resetting Sequence!");
            }

            switch (font_CharacterSet_Selection)
            {
            case 0:     // ASCII
                characterSequence = "32 - 126";
                break;

            case 1:     // Lowercase
                characterSequence = "32 - 64, 91 - 126";
                break;

            case 2:     // Uppercase
                characterSequence = "32 - 96, 123 - 126";
                break;

            case 3:     // Numbers & Symbols
                characterSequence = "32 - 64, 91 - 96, 123 - 126";
                break;

            case 4:     // Custom Range
                GUILayout.BeginHorizontal(GUILayout.Width(290));
                GUILayout.Label("Custom Range", GUILayout.Width(116));

                // Filter out unwanted characters.
                char chr = Event.current.character;
                if ((chr < '0' || chr > '9') && (chr < ',' || chr > '-'))
                {
                    Event.current.character = '\0';
                }
                characterSequence = EditorGUILayout.TextArea(characterSequence, textAreaBox, GUILayout.Height(32), GUILayout.MaxWidth(170));

                GUILayout.EndHorizontal();
                break;

            case 5:     // Custom Characters
                GUILayout.BeginHorizontal(GUILayout.Width(290));

                GUILayout.Label("Custom Characters", GUILayout.Width(116));
                characterSequence = EditorGUILayout.TextArea(characterSequence, textAreaBox, GUILayout.Height(32), GUILayout.MaxWidth(170));
                GUILayout.EndHorizontal();
                break;

            case 6:     // Character List from File
                characterList = EditorGUILayout.ObjectField("Character File", characterList, typeof(TextAsset), false, GUILayout.Width(290)) as TextAsset;
                if (characterList != null)
                {
                    characterSequence = characterList.text;
                }
                break;
            }

            EditorGUIUtility.LookLikeControls(120f, 40f);

            // FONT STYLE SELECTION
            GUILayout.BeginHorizontal(GUILayout.Width(290));
            font_style     = (FaceStyles)EditorGUILayout.EnumPopup("Font Style:", font_style, GUILayout.Width(225));
            font_style_mod = EditorGUILayout.IntField((int)font_style_mod); //, 0f, 5.0f); //, GUILayout.MaxWidth(290));
            GUILayout.EndHorizontal();

            // Render Mode Selection
            font_renderMode = (RenderModes)EditorGUILayout.EnumPopup("Font Render Mode:", font_renderMode, GUILayout.Width(290));

            includeKerningPairs = EditorGUILayout.Toggle("Get Kerning Pairs?", includeKerningPairs, GUILayout.MaxWidth(290));

            EditorGUIUtility.LookLikeControls(120f, 160f);

            GUILayout.Space(20);

            GUI.enabled = font_TTF == null || isProcessing ? false : true;    // Enable Preview if we are not already rendering a font.
            if (GUILayout.Button("Generate Font Atlas", GUILayout.Width(290)) && characterSequence.Length != 0 && GUI.enabled)
            {
                if (font_TTF != null)
                {
                    int error_Code;

                    error_Code = TMPro_FontPlugin.Initialize_FontEngine(); // Initialize Font Engine
                    if (error_Code != 0)
                    {
                        if (error_Code == 99)
                        {
                            //Debug.Log("Font Library was already initialized!");
                            error_Code = 0;
                        }
                        else
                        {
                            Debug.Log("Error Code: " + error_Code + "  occurred while Initializing the FreeType Library.");
                        }
                    }

                    string fontPath = AssetDatabase.GetAssetPath(font_TTF); // Get file path of TTF Font.

                    if (error_Code == 0)
                    {
                        error_Code = TMPro_FontPlugin.Load_TrueType_Font(fontPath); // Load the selected font.

                        if (error_Code != 0)
                        {
                            if (error_Code == 99)
                            {
                                //Debug.Log("Font was already loaded!");
                                error_Code = 0;
                            }
                            else
                            {
                                Debug.Log("Error Code: " + error_Code + "  occurred while Loading the font.");
                            }
                        }
                    }

                    if (error_Code == 0)
                    {
                        error_Code = TMPro_FontPlugin.FT_Size_Font(font_size); // Load the selected font and size it accordingly.
                        if (error_Code != 0)
                        {
                            Debug.Log("Error Code: " + error_Code + "  occurred while Sizing the font.");
                        }
                    }

                    // Define an array containing the characters we will render.
                    if (error_Code == 0)
                    {
                        int[] character_Set = null;
                        if (font_CharacterSet_Selection == 5 || font_CharacterSet_Selection == 6)
                        {
                            List <int> char_List = new List <int>();

                            for (int i = 0; i < characterSequence.Length; i++)
                            {
                                // Check to make sure we don't include duplicates
                                if (char_List.FindIndex(item => item == characterSequence[i]) == -1)
                                {
                                    char_List.Add(characterSequence[i]);
                                }
                                else
                                {
                                    Debug.Log(characterSequence[i] + " is a duplicate.");
                                }
                            }

                            character_Set = char_List.ToArray();
                        }
                        else
                        {
                            character_Set = ParseNumberSequence(characterSequence);
                        }

                        m_character_Count = character_Set.Length;

                        m_texture_buffer = new byte[font_atlas_width * font_atlas_height];

                        m_font_faceInfo = new FT_FaceInfo();

                        m_font_glyphInfo = new FT_GlyphInfo[m_character_Count];

                        int padding = font_padding;

                        bool autoSizing = FontSizingOption_Selection == 0 ? true : false;


                        isProcessing = true;

                        ThreadPool.QueueUserWorkItem(SomeTask =>
                        {
                            isRenderingDone = false;
                            error_Code      = TMPro_FontPlugin.Render_Characters(m_texture_buffer, font_atlas_width, font_atlas_height, padding, character_Set, m_character_Count, font_style, font_style_mod, autoSizing, font_renderMode, 4, ref m_font_faceInfo, m_font_glyphInfo);
                            isRenderingDone = true;
                            //Debug.Log("Font Rendering is completed.");
                        });

                        previewSelection = PreviewSelectionTypes.PreviewFont;
                    }
                }
            }


            // FONT RENDERING PROGRESS BAR
            GUILayout.Space(1);
            progressRect = GUILayoutUtility.GetRect(288, 20, textAreaBox, GUILayout.Width(288), GUILayout.Height(20));

            GUI.BeginGroup(progressRect);
            GUI.DrawTextureWithTexCoords(new Rect(2, 0, 288, 20), progressTexture, new Rect(1 - m_renderingProgress, 0, 1, 1));
            GUI.EndGroup();


            // FONT STATUS & INFORMATION
            GUILayout.Space(5);
            EditorGUILayout.LabelField(output_feedback, textAreaBox, GUILayout.Height(48), GUILayout.MaxWidth(290));

            GUILayout.Space(10);


            // SAVE TEXTURE & CREATE and SAVE FONT XML FILE
            GUI.enabled = m_font_Atlas != null ? true : false;    // Enable Save Button if font_Atlas is not Null.
            if (GUILayout.Button("Save TextMeshPro Font Asset", GUILayout.Width(290)) && GUI.enabled)
            {
                string filePath = string.Empty;

                if (font_renderMode == RenderModes.HintedSmooth || font_renderMode == RenderModes.RasterHinted)
                {
                    filePath = EditorUtility.SaveFilePanel("Save TextMesh Pro! Font Asset File", new FileInfo(AssetDatabase.GetAssetPath(font_TTF)).DirectoryName, font_TTF.name, "asset");

                    if (filePath.Length == 0)
                    {
                        return;
                    }

                    Save_Normal_FontAsset(filePath);
                }
                else if (font_renderMode >= RenderModes.DistanceField16)
                {
                    filePath = EditorUtility.SaveFilePanel("Save TextMesh Pro! Font Asset File", new FileInfo(AssetDatabase.GetAssetPath(font_TTF)).DirectoryName, font_TTF.name + " SDF", "asset");

                    if (filePath.Length == 0)
                    {
                        return;
                    }

                    Save_SDF_FontAsset(filePath);
                }
            }

            GUI.enabled = true; // Re-enable GUI

            GUILayout.Space(5);

            GUILayout.EndVertical();

            GUILayout.Space(25);

            /*
             * // GENERATE DISTANCE FIELD TEXTURE
             * GUILayout.Label("Distance Field Options", SectionLabel, GUILayout.Width(300));
             *
             * GUILayout.BeginVertical(textureAreaBox, GUILayout.Width(300));
             *
             * GUILayout.Space(5);
             *
             *
             * font_spread = EditorGUILayout.IntField("Spread", font_spread, GUILayout.Width(280));
             * font_scaledownFactor = EditorGUILayout.IntField("Scale down factor", font_scaledownFactor, GUILayout.Width(280));
             * if (GUI.changed)
             * {
             *  EditorPrefs.SetInt("Font_Spread", font_spread);
             *  EditorPrefs.SetInt("Font_ScaleDownFactor", font_scaledownFactor);
             * }
             *
             * GUILayout.Space(20);
             *
             * GUI.enabled = m_font_Atlas != null ? true : false;    // Enable Save Button if font_Atlas is not Null.
             * if (GUILayout.Button("Preview Distance Field Font Atlas", GUILayout.Width(290)))
             * {
             *
             *  if (m_font_Atlas != null && isProcessing == false)
             *  {
             *      // Generate Distance Field
             *      int width = m_font_Atlas.width;
             *      int height = m_font_Atlas.height;
             *      Color[] colors = m_font_Atlas.GetPixels(); // Should modify this to use Color32 instead
             *
             *      isProcessing = true;
             *
             *      ThreadPool.QueueUserWorkItem(SomeTask => { TMPro_DistanceTransform.Generate(colors, width, height, font_spread, font_scaledownFactor); });
             *
             *      previewSelection = PreviewSelectionTypes.PreviewDistanceField;
             *  }
             * }
             *
             * GUILayout.Space(1);
             *
             * progressRect = GUILayoutUtility.GetRect(290, 20, textAreaBox, GUILayout.Width(290), GUILayout.Height(20));
             *
             * GUI.BeginGroup(progressRect);
             *
             * GUI.DrawTextureWithTexCoords(new Rect(0, 0, 290, 20), progressTexture, new Rect(1 - ProgressPercentage, 0, 1, 1));
             * GUI.EndGroup();
             *
             * //GUILayout.Space(5);
             *
             * GUI.enabled = m_destination_Atlas != null ? true : false;    // Enable Save Button if font_Atlas is not Null.
             * if (GUILayout.Button("Save TextMeshPro (SDF) Font Asset", GUILayout.Width(290)))
             * {
             *  string filePath = EditorUtility.SaveFilePanel("Save TextMesh Pro! Font Asset File", new FileInfo(AssetDatabase.GetAssetPath(font_TTF)).DirectoryName, font_TTF.name + " SDF", "asset");
             *
             *  if (filePath.Length == 0)
             *      return;
             *
             *  Save_SDF_FontAsset(filePath);
             *
             * }
             *
             * GUILayout.EndVertical();
             */

            // Figure out the size of the current UI Panel
            Rect rect = EditorGUILayout.GetControlRect(false, 5);

            if (Event.current.type == EventType.Repaint)
            {
                m_UI_Panel_Size = rect;
            }

            GUILayout.EndVertical();
        }
Exemple #5
0
    void ShowTest()
    {
        bool change = false;

        EditorGUILayout.BeginHorizontal();
        if (_AssetType != null)
        {
            _SelectAssetType = EditorGUILayout.Popup("查询文件类型:", _SelectAssetType, _AssetType, GUILayout.MaxWidth(300));
            if (GUI.changed)
            {
                change = true;
                EditorGUILayout.EndHorizontal();
                _artFindSet._onlyShowNoUsed = false;
                _AllAssetsData.GetDepend(_SelectAssetType, _prefabs);
            }
        }
        if (!change)
        {
            EditorGUILayout.EndHorizontal();
        }
        if (_AssetUsedData != null)
        {
            if (GUILayout.Button("查看全局数据"))
            {
                _AssetUsedData = null;
            }
            if (_AssetUsedData != null)
            {
                _AssetUsedData.OnGUI();
            }
        }
        if (_AssetUsedData == null && _SelectAssetType != -1)
        {
            _artFindSet._onlyShowNoUsed = EditorGUILayout.Toggle(!_artFindSet._onlyShowNoUsed?"显示使用的":"显示未使用的", _artFindSet._onlyShowNoUsed);
            EditorGUILayout.LabelField(_AssetType[_SelectAssetType] + "总资源数:" + _AllAssetsData._data[_SelectAssetType]._allAssets);
            EditorGUILayout.LabelField(_AssetType[_SelectAssetType] + "被使用数:" + _AllAssetsData._data[_SelectAssetType]._allUsedAssets);
            EditorGUILayout.LabelField(_AssetType[_SelectAssetType] + "未使用数:" + _AllAssetsData._data[_SelectAssetType]._allUnUsedAssets);
            pos = EditorGUILayout.BeginScrollView(pos);
            _AllAssetsData.OnGUI(_SelectAssetType, _artFindSet);
            EditorGUILayout.EndScrollView();
        }
    }
        public static bool DrawShapeEditor(this Editor target, BlendSystem blendSystem, string[] blendables, bool useBones, bool allowCreationFromAnimClip, Shape shape, string name, int id, string invalidError = "")
        {
            bool markedForDeletion = false;

            // Add names if missing
            if (shape.blendableNames == null || shape.blendableNames.Count < shape.blendShapes.Count)
            {
                shape.blendableNames = new List <string>();
                for (int i = 0; i < shape.blendShapes.Count; i++)
                {
                    shape.blendableNames.Add(blendables[shape.blendShapes[i]]);
                }
            }

            // Create AnimBool if not defined
            if (!showBoneOptions.ContainsKey(target))
            {
                showBoneOptions.Add(target, new AnimBool(useBones, target.Repaint));
            }
            showBoneOptions[target].target = useBones;

            // Create styles if not defined
            if (lightToolbar == null)
            {
                lightToolbar = new GUIStyle(EditorStyles.toolbarDropDown);
                lightToolbar.normal.background = lightToolbarTexture;

                miniLabelDark = new GUIStyle(EditorStyles.miniLabel);
                miniLabelDark.normal.textColor = Color.black;
            }

            if (currentToggle == id && currentTarget == target.target)
            {
                Undo.RecordObject(target.target, "Change " + name + " Pose");
                Rect box = EditorGUILayout.BeginHorizontal();

                if (shape.verified)
                {
                    GUI.backgroundColor = new Color(1f, 0.77f, 0f);
                }
                else
                {
                    GUI.backgroundColor = new Color(0.4f, 0.4f, 0.4f);
                }

                if (GUI.Button(box, "", lightToolbar))
                {
                    currentSearchBlendable = -1;
                    searchString           = "";
                    currentToggle          = -1;
                }
                GUI.backgroundColor = Color.white;

                GUILayout.Box(name, miniLabelDark, GUILayout.Width(250));
                if (shape.weights.Count == 1)
                {
                    GUILayout.Box("1 " + blendSystem.blendableDisplayName, miniLabelDark);
                }
                else if (shape.weights.Count > 1)
                {
                    GUILayout.Box(shape.weights.Count.ToString() + " " + blendSystem.blendableDisplayNamePlural, miniLabelDark);
                }

                if (shape.bones.Count == 1 && useBones)
                {
                    GUILayout.Box("1 Bone Transform", miniLabelDark);
                }
                else if (shape.bones.Count > 1 && useBones)
                {
                    GUILayout.Box(shape.bones.Count.ToString() + " Bone Transforms", miniLabelDark);
                }
                if (!shape.verified)
                {
                    GUILayout.FlexibleSpace();
                    GUILayout.Box("Missing", miniLabelDark);
                    GUILayout.FlexibleSpace();
                }

                EditorGUILayout.EndHorizontal();

                if (!shape.verified)
                {
                    if (invalidError != "")
                    {
                        EditorGUILayout.HelpBox(invalidError, MessageType.Warning);
                    }
                    else
                    {
                        EditorGUILayout.HelpBox("There is no matching " + shape.GetType().Name + " in the project settings. It will still function correctly, but it is advised you add it to the project settings for compatibility. Alternatively, you can delete it from here.", MessageType.Warning);
                    }
                    if (GUILayout.Button("Delete Pose"))
                    {
                        markedForDeletion = true;
                    }
                }

                box = EditorGUILayout.BeginVertical();
                GUI.Box(new Rect(box.x + 4, box.y, box.width - 7, box.height), "", EditorStyles.helpBox);
                GUILayout.Space(20);
                for (int b = 0; b < shape.weights.Count; b++)
                {
                    Rect newBox = EditorGUILayout.BeginHorizontal();
                    GUI.Box(new Rect(newBox.x + 5, newBox.y, newBox.width - 11, newBox.height), "", EditorStyles.toolbar);
                    GUILayout.Space(5);


                    // Check if blendables have become out-of-sync
                    // (blend system started reporting different blendables)
                    if (blendables[shape.blendShapes[b]] != shape.blendableNames[b] && blendSystem.allowResyncing)
                    {
                        bool matched = false;
                        for (int i = 0; i < blendables.Length; i++)
                        {
                            if (blendables[i] == shape.blendableNames[b])
                            {
                                shape.blendShapes[b] = i;
                                matched = true;
                            }
                            else if (blendables[i].Remove(blendables[i].Length - 5).Contains(shape.blendableNames[b].Remove(shape.blendableNames[b].Length - 5)))
                            {
                                shape.blendShapes[b]    = i;
                                shape.blendableNames[b] = blendables[i];
                                matched = true;
                            }
                        }
                        if (!matched)
                        {
                            shape.blendableNames[b] = blendables[shape.blendShapes[b]];
                        }
                    }

                    int oldShape = shape.blendShapes[b];

                    if (currentSearchBlendable == b)
                    {
                        EditorGUI.BeginChangeCheck();
                        searchString = EditorGUILayout.TextField(bestSearchMatch == -1 ? "No Match" : blendables[bestSearchMatch], searchString, EditorStyles.toolbarTextField, GUILayout.ExpandWidth(true));
                        if (EditorGUI.EndChangeCheck())
                        {
                            bestSearchMatch = -1;
                            if (searchString != "")
                            {
                                for (int i = 0; i < blendables.Length; i++)
                                {
                                    if (Match(searchString.ToLowerInvariant(), blendables[i].ToLowerInvariant()))
                                    {
                                        bestSearchMatch = i;
                                    }
                                }
                            }
                        }
                        EditorGUI.BeginDisabledGroup(bestSearchMatch == -1);
                        if (GUILayout.Button("Set", EditorStyles.toolbarButton, GUILayout.MaxWidth(45)))
                        {
                            shape.blendShapes[b]   = bestSearchMatch;
                            currentSearchBlendable = -1;
                            bestSearchMatch        = -1;
                            searchString           = "";
                        }
                        EditorGUI.EndDisabledGroup();
                    }
                    else
                    {
                        shape.blendShapes[b] = EditorGUILayout.Popup(blendSystem.blendableDisplayName + " " + b.ToString(), shape.blendShapes[b], blendables, EditorStyles.toolbarPopup);
                    }

                    if (shape.blendShapes[b] != oldShape)
                    {
                        shape.blendableNames[b] = blendables[b];
                        blendSystem.SetBlendableValue(oldShape, 0);
                    }

                    if (GUILayout.Button(search, EditorStyles.toolbarButton, GUILayout.MaxWidth(30)))
                    {
                        currentSearchBlendable = currentSearchBlendable == b ? -1 : b;
                    }

                    GUI.backgroundColor = new Color(0.8f, 0.3f, 0.3f);
                    if (GUILayout.Button(delete, EditorStyles.toolbarButton, GUILayout.MaxWidth(50)))
                    {
                        Undo.RecordObject(target.target, "Delete " + blendSystem.blendableDisplayName);

                        shape.blendShapes.RemoveAt(b);
                        blendSystem.SetBlendableValue(oldShape, 0);
                        selectedBone = 0;
                        shape.weights.RemoveAt(b);
                        shape.blendableNames.RemoveAt(b);
                        EditorUtility.SetDirty(target.target);
                        break;
                    }

                    GUILayout.Space(4);
                    GUI.backgroundColor = Color.white;
                    EditorGUILayout.EndHorizontal();
                    EditorGUILayout.BeginHorizontal();
                    GUILayout.Space(15);
                    shape.weights[b] = EditorGUILayout.Slider(shape.weights[b], blendSystem.blendRangeLow, blendSystem.blendRangeHigh);
                    GUILayout.Space(10);
                    EditorGUILayout.EndHorizontal();
                    GUILayout.Space(10);
                }

                if (EditorGUILayout.BeginFadeGroup(showBoneOptions[target].faded))
                {
                    for (int b = 0; b < shape.bones.Count; b++)
                    {
                        Rect newBox = EditorGUILayout.BeginHorizontal();
                        GUI.Box(new Rect(newBox.x + 5, newBox.y, newBox.width - 11, newBox.height), "", EditorStyles.toolbar);
                        GUILayout.Space(10);
                        bool selected = EditorGUILayout.ToggleLeft(new GUIContent("Bone Transform " + b.ToString(), EditorGUIUtility.FindTexture("Transform Icon"), "Show Transform Handles"), selectedBone == b, GUILayout.Width(170));
                        selectedBone = selected ? b : selectedBone;

                        Transform oldBone = shape.bones[b].bone;
                        shape.bones[b].bone = (Transform)EditorGUILayout.ObjectField("", shape.bones[b].bone, typeof(Transform), true);

                        if (oldBone != shape.bones[b].bone)
                        {
                            if (shape.bones[b].bone != null)
                            {
                                Transform newbone = shape.bones[b].bone;
                                shape.bones[b].bone = oldBone;
                                if (shape.bones[b].bone != null)
                                {
                                    shape.bones[b].bone.localPosition    = shape.bones[b].neutralPosition;
                                    shape.bones[b].bone.localEulerAngles = shape.bones[b].neutralRotation;
                                }

                                shape.bones[b].bone = newbone;

                                shape.bones[b].SetNeutral();

                                shape.bones[b].endRotation = shape.bones[b].bone.localEulerAngles;
                                shape.bones[b].endPosition = shape.bones[b].bone.localPosition;

                                shape.bones[b].bone.localPosition    = shape.bones[b].endPosition;
                                shape.bones[b].bone.localEulerAngles = shape.bones[b].endRotation;
                            }
                        }

                        GUI.backgroundColor = new Color(0.8f, 0.3f, 0.3f);
                        if (GUILayout.Button(delete, EditorStyles.toolbarButton, GUILayout.MaxWidth(50)))
                        {
                            Undo.RecordObject(target.target, "Delete Bone Transform");
                            if (shape.bones[b].bone != null)
                            {
                                shape.bones[b].bone.localPosition    = shape.bones[b].neutralPosition;
                                shape.bones[b].bone.localEulerAngles = shape.bones[b].neutralRotation;
                            }
                            shape.bones.RemoveAt(b);
                            if (selectedBone >= shape.bones.Count)
                            {
                                selectedBone -= 1;
                            }
                            EditorUtility.SetDirty(target.target);
                            break;
                        }
                        GUILayout.Space(4);
                        GUI.backgroundColor = Color.white;
                        EditorGUILayout.EndHorizontal();
                        GUILayout.Space(5);
                        EditorGUILayout.BeginHorizontal();
                        GUILayout.Space(10);
                        GUILayout.Box("Position", EditorStyles.label, GUILayout.MaxWidth(80));

                        EditorGUI.BeginDisabledGroup(shape.bones[b].bone == null);
                        EditorGUI.BeginDisabledGroup(shape.bones[b].lockPosition);
                        Vector3 newBonePosition = EditorGUILayout.Vector3Field("", shape.bones[b].endPosition);
                        EditorGUI.EndDisabledGroup();
                        GUILayout.Space(10);
                        if (GUILayout.Button(shape.bones[b].lockPosition ? locked : unlocked, GUILayout.Width(30), GUILayout.Height(16)))
                        {
                            shape.bones[b].lockPosition = !shape.bones[b].lockPosition;
                        }
                        EditorGUI.EndDisabledGroup();

                        if (shape.bones[b].bone != null)
                        {
                            if (newBonePosition != shape.bones[b].endPosition)
                            {
                                Undo.RecordObject(shape.bones[b].bone, "Move");
                                shape.bones[b].endPosition        = newBonePosition;
                                shape.bones[b].bone.localPosition = shape.bones[b].endPosition;
                            }
                            else if (shape.bones[b].bone.localPosition != shape.bones[b].endPosition)
                            {
                                shape.bones[b].endPosition = shape.bones[b].bone.localPosition;
                            }
                        }

                        GUILayout.Space(10);
                        EditorGUILayout.EndHorizontal();
                        EditorGUILayout.BeginHorizontal();
                        GUILayout.Space(10);
                        GUILayout.Box("Rotation", EditorStyles.label, GUILayout.MaxWidth(80));

                        EditorGUI.BeginDisabledGroup(shape.bones[b].bone == null);
                        EditorGUI.BeginDisabledGroup(shape.bones[b].lockRotation);
                        Vector3 newBoneRotation = EditorGUILayout.Vector3Field("", shape.bones[b].endRotation);
                        EditorGUI.EndDisabledGroup();
                        GUILayout.Space(10);
                        if (GUILayout.Button(shape.bones[b].lockRotation ? locked : unlocked, GUILayout.Width(30), GUILayout.Height(16)))
                        {
                            shape.bones[b].lockRotation = !shape.bones[b].lockRotation;
                        }
                        EditorGUI.EndDisabledGroup();
                        if (shape.bones[b].bone != null)
                        {
                            if (newBoneRotation != shape.bones[b].endRotation)
                            {
                                Undo.RecordObject(shape.bones[b].bone, "Rotate");
                                shape.bones[b].endRotation           = newBoneRotation;
                                shape.bones[b].bone.localEulerAngles = shape.bones[b].endRotation;
                            }
                            else if (shape.bones[b].bone.localEulerAngles != shape.bones[b].endRotation)
                            {
                                shape.bones[b].endRotation = shape.bones[b].bone.localEulerAngles;
                            }
                        }

                        GUILayout.Space(10);
                        EditorGUILayout.EndHorizontal();
                        GUILayout.Space(10);
                    }
                }
                FixedEndFadeGroup(showBoneOptions[target].faded);

                EditorGUILayout.Space();

                GUILayout.BeginHorizontal();
                GUILayout.FlexibleSpace();
                if (blendSystem.blendableCount > 0)
                {
                    if (GUILayout.Button("Add " + blendSystem.blendableDisplayName, GUILayout.MaxWidth(200)))
                    {
                        Undo.RecordObject(target.target, "Add " + blendSystem.blendableDisplayName);
                        shape.blendShapes.Add(0);
                        shape.weights.Add(0);
                        shape.blendableNames.Add(blendables[0]);

                        EditorUtility.SetDirty(target.target);
                    }
                    if (useBones)
                    {
                        EditorGUILayout.Space();
                    }
                }

                if (useBones)
                {
                    if (GUILayout.Button("Add Bone Transform", GUILayout.MaxWidth(240)))
                    {
                        Undo.RecordObject(target.target, "Add Bone Shape");
                        shape.bones.Add(new BoneShape());
                        selectedBone = shape.bones.Count - 1;
                        EditorUtility.SetDirty(target.target);
                    }
                    GUILayout.FlexibleSpace();
                    GUILayout.EndHorizontal();
                    if (allowCreationFromAnimClip)
                    {
                        GUILayout.Space(5);
                        GUILayout.BeginHorizontal();
                        GUILayout.FlexibleSpace();
                        if (GUILayout.Button("Create Pose from AnimationClip", GUILayout.MaxWidth(240)))
                        {
                            PoseExtractorWizard.ShowWindow(blendSystem.transform, shape, name);
                        }
                        GUILayout.FlexibleSpace();
                        GUILayout.EndHorizontal();
                    }
                }
                else
                {
                    GUILayout.FlexibleSpace();
                    GUILayout.EndHorizontal();
                }

                if (blendSystem.blendableCount == 0 && !useBones)
                {
                    GUILayout.BeginHorizontal();
                    GUILayout.Space(10);
                    EditorGUILayout.HelpBox(blendSystem.noBlendablesMessage, MessageType.Warning);
                    GUILayout.Space(10);
                    GUILayout.EndHorizontal();
                }
                GUILayout.Space(14);
                EditorGUILayout.EndVertical();
            }
            else
            {
                Rect box = EditorGUILayout.BeginHorizontal();
                if (shape.verified)
                {
                    GUI.backgroundColor = Color.white;
                }
                else
                {
                    GUI.backgroundColor = new Color(0.7f, 0.7f, 0.7f);
                }

                if (GUI.Button(box, "", EditorStyles.toolbarDropDown))
                {
                    currentToggle = id;
                    currentTarget = target.target;
                    selectedBone  = 0;

                    searchString           = "";
                    currentSearchBlendable = -1;
                }

                GUILayout.Box(name, EditorStyles.miniLabel, GUILayout.Width(250));
                if (shape.weights.Count == 1)
                {
                    GUILayout.Box("1 " + blendSystem.blendableDisplayName, EditorStyles.miniLabel);
                }
                else if (shape.weights.Count > 1)
                {
                    GUILayout.Box(shape.weights.Count.ToString() + " " + blendSystem.blendableDisplayNamePlural, EditorStyles.miniLabel);
                }
                if (shape.bones.Count == 1 && useBones)
                {
                    GUILayout.Box("1 Bone Transform", EditorStyles.miniLabel);
                }
                else if (shape.bones.Count > 1 && useBones)
                {
                    GUILayout.Box(shape.bones.Count.ToString() + " Bone Transforms", EditorStyles.miniLabel);
                }

                if (!shape.verified)
                {
                    GUILayout.FlexibleSpace();
                    GUILayout.Box("Missing", EditorStyles.miniLabel);
                    GUILayout.FlexibleSpace();
                }

                EditorGUILayout.EndHorizontal();
            }

            return(markedForDeletion);
        }
        public override void OnInspectorGUI()
        {
            if (target == null)
            {
                return;
            }

            var proCamera2DPixelPerfect = (ProCamera2DPixelPerfect)target;

            if (proCamera2DPixelPerfect.ProCamera2D == null)
            {
                EditorGUILayout.HelpBox("ProCamera2D is not set.", MessageType.Error, true);
                return;
            }

            var isOrthographic = false;

#if PC2D_TK2D_SUPPORT
            if (proCamera2DPixelPerfect.ProCamera2D.Tk2dCam != null && proCamera2DPixelPerfect.ProCamera2D.Tk2dCam.CameraSettings.projection == tk2dCameraSettings.ProjectionType.Orthographic)
            {
                isOrthographic = true;
            }
            else
            {
#endif
            isOrthographic = proCamera2DPixelPerfect.ProCamera2D.GameCamera.orthographic;
#if PC2D_TK2D_SUPPORT
        }
#endif
            if (!isOrthographic)
            {
                EditorGUILayout.HelpBox("Pixel perfect only works with orthographic cameras!", MessageType.Error, true);
            }

            serializedObject.Update();

            // Show script link
            GUI.enabled = false;
            _script     = EditorGUILayout.ObjectField("Script", _script, typeof(MonoScript), false) as MonoScript;
            GUI.enabled = true;

            // ProCamera2D
            _tooltip = new GUIContent("Pro Camera 2D", "");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("_pc2D"), _tooltip);

            EditorGUI.BeginChangeCheck();

            // Pixels per unit
            _tooltip = new GUIContent("Pixels per Unit", "How many pixels in a sprite correspond to one unit in the world");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("PixelsPerUnit"), _tooltip);

#if PC2D_TK2D_SUPPORT
            if (proCamera2DPixelPerfect.GetComponent <tk2dCamera>() != null)
            {
                // Pixels per meter
                _tooltip = new GUIContent("TK2D Sprites PPM", "The pixels per meter value of your TK2D sprite collections.");
                EditorGUILayout.PropertyField(serializedObject.FindProperty("Tk2DPixelsPerMeter"), _tooltip);

                if (proCamera2DPixelPerfect.Tk2DPixelsPerMeter < 1f)
                {
                    proCamera2DPixelPerfect.Tk2DPixelsPerMeter = 1f;
                }
            }
#endif

            // Viewport auto-scale
            EditorGUILayout.BeginHorizontal();

            _tooltip = new GUIContent("Viewport AutoScale", "If not None, the camera will automatically calculate the best scale across all resolutions based on the art viewport.");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("ViewportAutoScale"), _tooltip);

            // Viewport Scale
            if (proCamera2DPixelPerfect.ViewportAutoScale != AutoScaleMode.None)
            {
                GUI.enabled = false;
                EditorGUILayout.LabelField(proCamera2DPixelPerfect.CalculateViewportScale() + "x", GUILayout.MaxWidth(60));
                GUI.enabled = true;
            }

            EditorGUILayout.EndHorizontal();

            // Viewport size in pixels
            if (proCamera2DPixelPerfect.ViewportAutoScale != AutoScaleMode.None)
            {
                _tooltip = new GUIContent("Game Viewport (pixels)", "Set it that if the screen was of this size, each pixel on the screen would correspond to a pixel on your art. On a pixel-art game this probably has low values.");
                EditorGUILayout.PropertyField(serializedObject.FindProperty("TargetViewportSizeInPixels"), _tooltip);
            }

            // Zoom
            _tooltip = new GUIContent("Zoom", "The zoom level of the camera");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("_zoom"), _tooltip);

            // Snap movement to grid
            EditorGUILayout.BeginHorizontal();
            _tooltip = new GUIContent("Snap Movement to Grid", "If checked, the the sprites will snap to the grid. Might create some stuttering on your camera targets, especially if you're using a large grid and a follow smoothness greater than zero.");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("SnapMovementToGrid"), _tooltip);

            if (proCamera2DPixelPerfect.SnapMovementToGrid)
            {
                _tooltip = new GUIContent("Snap Camera", "If checked, the camera will also snap to the grid. If you notice some stuttering in your game elements try to leave this on.");
                EditorGUILayout.PropertyField(serializedObject.FindProperty("SnapCameraToGrid"), _tooltip);
            }
            EditorGUILayout.EndHorizontal();

            // Draw grid
            EditorGUILayout.BeginHorizontal();

            _tooltip = new GUIContent("Draw Grid", "If checked, the camera will draw a pixel grid. 'Gizmos' button must be enabled on the Game window.");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("DrawGrid"), _tooltip);

            if (proCamera2DPixelPerfect.DrawGrid)
            {
                _tooltip = new GUIContent("Grid Color", "");
                EditorGUILayout.PropertyField(serializedObject.FindProperty("GridColor"), _tooltip);
            }

            EditorGUILayout.EndHorizontal();

            // Grid density warning
            if (proCamera2DPixelPerfect.DrawGrid && proCamera2DPixelPerfect.GridDensity < 4)
            {
                EditorGUILayout.HelpBox("Grid density is too high to draw, so we're skipping it to avoid performance issues with the editor.", MessageType.None, true);
            }

            // Save properties
            serializedObject.ApplyModifiedProperties();

            // Limit values
            if (proCamera2DPixelPerfect.PixelsPerUnit < 1f)
            {
                proCamera2DPixelPerfect.PixelsPerUnit = 1f;
            }

            if (proCamera2DPixelPerfect.TargetViewportSizeInPixels.x < 1)
            {
                proCamera2DPixelPerfect.TargetViewportSizeInPixels.x = 1;
            }

            if (proCamera2DPixelPerfect.TargetViewportSizeInPixels.y < 1)
            {
                proCamera2DPixelPerfect.TargetViewportSizeInPixels.y = 1;
            }

            // Resize camera
            if (EditorGUI.EndChangeCheck() || !Application.isPlaying)
            {
                proCamera2DPixelPerfect.ResizeCameraToPixelPerfect();
            }
        }
Exemple #8
0
 //draws presets if exists
 public void drawPresets(MaterialProperty[] props, Material[] materials)
 {
     if (hasPresets && presetsLoaded)
     {
         int pressetPreset = EditorGUILayout.Popup(selectedPreset, presetOptions, GUILayout.MaxWidth(100));
         if (pressetPreset != selectedPreset)
         {
             ;
             if (pressetPreset < presetOptions.Length - 2)
             {
                 applyPreset(presetOptions[pressetPreset], props, materials);
             }
             if (pressetPreset == presetOptions.Length - 2)
             {
                 PresetEditor.open();
             }
         }
         if (pressetPreset == presetOptions.Length - 1)
         {
             selectedPreset = pressetPreset;
         }
         else
         {
             selectedPreset = 0;
         }
         if (pressetPreset == presetOptions.Length - 1)
         {
             drawNewPreset(props, materials);
         }
     }
     else if (hasPresets && !presetsLoaded)
     {
         GUILayout.Label(Locale.editor.Get("message_presets_file_missing"));
     }
 }
Exemple #9
0
    public void ShowGUI()
    {
        GUILayout.Space(10);

        EditorStyles.label.wordWrap = true;
        GUILayout.Label("Path to Action subclass scripts (Relative to Asset folder)", EditorStyles.label);

        GUILayout.BeginHorizontal();

        folderPath = GUILayout.TextField(folderPath, GUILayout.MaxWidth(260));

        if (GUILayout.Button("Refresh list"))
        {
            RefreshList();
        }

        GUILayout.EndHorizontal();

        if (AllActions.Count > 0)
        {
            GUILayout.Space(10);

            defaultClass = EditorGUILayout.Popup("Default action:", defaultClass, GetDefaultPopUp());
            GUILayout.Space(10);

            GUILayout.BeginHorizontal();

            GUILayout.Label("Title", titleWidth);
            GUILayout.Label("Filename", nameWidth);
            GUILayout.Label("Enabled?", GUILayout.MaxWidth(50));

            GUILayout.EndHorizontal();

            foreach (ActionType subclass in AllActions)
            {
                GUILayout.BeginVertical("Button");
                GUILayout.BeginHorizontal();

                GUILayout.Label(subclass.title, titleWidth);
                GUILayout.Label(subclass.fileName, nameWidth);

                subclass.isEnabled = GUILayout.Toggle(subclass.isEnabled, "");

                GUILayout.EndHorizontal();
                GUILayout.EndVertical();
            }

            SetEnabled();

            if (defaultClass > EnabledActions.Count - 1)
            {
                defaultClass = EnabledActions.Count - 1;
            }
        }
        else
        {
            EditorStyles.label.wordWrap = true;
            GUILayout.Label("No Action subclass files found.", EditorStyles.label);
        }

        EditorUtility.SetDirty(this);
    }
Exemple #10
0
        private void DrawStats()
        {
            GUILayout.BeginHorizontal(GUILayout.MaxWidth(750));

            GUILayout.BeginVertical(GUILayout.Width(300));
            SectionHeader("Local Stat Values");
            statsPos = GUILayout.BeginScrollView(statsPos);
            int editId = statsEditor.DrawStatsList();

            if (editId > -1)
            {
                editStat   = stats.stats[editId];
                statEditor = (StatValueEditor)Editor.CreateEditor(editStat);
            }

            GUILayout.EndScrollView();
            GUILayout.EndVertical();

            GUILayout.Space(32);

            GUILayout.BeginVertical(GUILayout.Width(300));
            if (editStat == null)
            {
                if (addStat == null)
                {
                    addStat      = (StatValue)ScriptableObject.CreateInstance(typeof(StatValue));
                    addStat.name = "New Stat";
                    statEditor   = (StatValueEditor)Editor.CreateEditor(addStat);
                }

                statEditor.serializedObject.Update();
                SectionHeader("Create Stat");
                statPos = GUILayout.BeginScrollView(statPos);
                statEditor.DrawInspector();

                GUILayout.Space(16);
                if (GUILayout.Button("Create and Add"))
                {
                    if (string.IsNullOrWhiteSpace(stats.statFolder))
                    {
                        stats.statFolder = Application.dataPath;
                    }
                    string path = EditorUtility.SaveFilePanelInProject("Save Stat", addStat.displayName, "asset", "Select a location to save the stat", stats.statFolder);
                    if (path.Length != 0)
                    {
                        stats.statFolder = System.IO.Path.GetDirectoryName(path);

                        addStat.name = System.IO.Path.GetFileNameWithoutExtension(path);
                        AssetDatabase.CreateAsset(addStat, path);
                        AssetDatabase.SaveAssets();

                        if (stats.stats == null)
                        {
                            stats.stats = new System.Collections.Generic.List <StatValue>();
                        }
                        stats.stats.Add(AssetDatabase.LoadAssetAtPath(path, typeof(StatValue)) as StatValue);
                        addStat = null;
                        statPos = Vector2.zero;
                        GUI.FocusControl("Clear");
                    }
                }
                GUILayout.EndScrollView();

                statEditor.serializedObject.ApplyModifiedProperties();
            }
            else
            {
                statEditor.serializedObject.Update();
                SectionHeader("Edit Stat");
                statPos = GUILayout.BeginScrollView(statPos);
                statEditor.DrawInspector();

                GUILayout.Space(16);
                if (GUILayout.Button("Done"))
                {
                    addStat  = null;
                    editStat = null;
                    GUI.FocusControl("Clear");
                    Repaint();
                }
                else
                {
                    statEditor.serializedObject.ApplyModifiedProperties();
                }
                GUILayout.EndScrollView();
            }
            GUILayout.EndVertical();


            GUILayout.EndHorizontal();
        }
Exemple #11
0
        public override void OnInspectorGUI()
        {
            if (_imageFrameContainer)
            {
                serializedObject.Update();
                EditorGUILayout.PropertyField(frame);

                showSprites = EditorGUILayout.Foldout(showSprites, "图片集");
                if (showSprites)
                {
                    Sprite[] sprites = _imageFrameContainer.sprites;
                    for (int i = 0; i < sprites.Length; ++i)
                    {
                        GUILayout.BeginHorizontal();

                        using (var color = new ContentColor(Color.green))
                        {
                            GUILayout.Label(i.ToString(), GUILayout.MaxWidth(20));
                        }

                        sprites[i] = EditorGUILayout.ObjectField(sprites[i], typeof(Sprite), false, GUILayout.Height(32), GUILayout.Width(32)) as Sprite;

                        // ReSharper disable once UnusedVariable
                        using (var color = new BgColor(Color.red))
                        {
                            if (GUILayout.Button("X", GUILayout.Width(22f)))
                            {
                                ArrayUtility.RemoveAt(ref sprites, i);
                                _imageFrameContainer.sprites = sprites;
                            }
                        }

                        GUILayout.EndHorizontal();
                    }

                    GUILayout.BeginHorizontal();
                    newSprite = EditorGUILayout.ObjectField(newSprite, typeof(Sprite), false, GUILayout.Height(32), GUILayout.Width(32)) as Sprite;

                    // ReSharper disable once UnusedVariable
                    using (var color = new BgColor(Color.green))
                    {
                        if (GUILayout.Button("添加", GUILayout.Width(35f)))
                        {
                            if (sprites.Length > 0)
                            {
                                Sprite[] arr = new Sprite[sprites.Length + 1];
                                sprites.CopyTo(arr, 0);
                                arr[sprites.Length]          = newSprite;
                                _imageFrameContainer.sprites = arr;
                            }
                            else
                            {
                                _imageFrameContainer.sprites = new[] { newSprite };
                            }
                            newSprite = null;
                        }
                    }

                    GUILayout.EndHorizontal();
                }

                serializedObject.ApplyModifiedProperties();

                _imageFrameContainer.frame = frame.intValue;
            }
        }
Exemple #12
0
        private void DrawEffects()
        {
            GUILayout.BeginHorizontal(GUILayout.MaxWidth(750));

            GUILayout.BeginVertical(GUILayout.Width(300));
            effectsPos = GUILayout.BeginScrollView(effectsPos);
            statsEditor.DrawEffectsList();

            if (stats.effectList != lastEffects)
            {
                lastEffects = stats.effectList;
                if (lastEffects != null)
                {
                    effectListEditor = (StatEffectListEditor)Editor.CreateEditor(stats.effectList, typeof(StatEffectListEditor));
                }
            }

            if (effectListEditor == null)
            {
                return;
            }

            int editId = effectListEditor.DrawEffectList();

            if (editId > -1)
            {
                editEffect   = lastEffects.availableEffects[editId];
                effectEditor = (StatEffectEditor)Editor.CreateEditor(editEffect);
            }

            GUILayout.EndScrollView();
            GUILayout.EndVertical();

            GUILayout.Space(32);

            GUILayout.BeginVertical(GUILayout.Width(300));
            if (editEffect == null)
            {
                if (addEffect == null)
                {
                    addEffect      = (StatEffect)ScriptableObject.CreateInstance(typeof(StatEffect));
                    addEffect.name = "New Effect";
                    effectEditor   = (StatEffectEditor)Editor.CreateEditor(addEffect);
                }

                effectEditor.serializedObject.Update();
                SectionHeader("Create Effect");
                effectPos = GUILayout.BeginScrollView(effectPos);
                effectEditor.DrawInspector();
                GUILayout.EndScrollView();

                GUILayout.Space(16);
                if (GUILayout.Button("Create and Add"))
                {
                    if (string.IsNullOrWhiteSpace(stats.effectFolder))
                    {
                        stats.effectFolder = Application.dataPath;
                    }
                    string path = EditorUtility.SaveFilePanelInProject("Save Effect", addEffect.displayName, "asset", "Select a location to save the effect", stats.effectFolder);
                    if (path.Length != 0)
                    {
                        effectListEditor.serializedObject.Update();
                        stats.effectFolder = System.IO.Path.GetDirectoryName(path);

                        addEffect.name = System.IO.Path.GetFileNameWithoutExtension(path);
                        AssetDatabase.CreateAsset(addEffect, path);
                        AssetDatabase.SaveAssets();

                        effectListEditor.AddEffect(AssetDatabase.LoadAssetAtPath(path, typeof(StatEffect)) as StatEffect);
                        addEffect = null;
                        effectPos = Vector2.zero;
                        GUI.FocusControl("Clear");
                        effectListEditor.serializedObject.ApplyModifiedProperties();
                    }
                }

                effectEditor.serializedObject.ApplyModifiedProperties();
            }
            else
            {
                effectEditor.serializedObject.Update();
                SectionHeader("Edit Effect");
                effectPos = GUILayout.BeginScrollView(effectPos);
                effectEditor.DrawInspector();
                GUILayout.EndScrollView();

                GUILayout.Space(16);
                if (GUILayout.Button("Done"))
                {
                    addEffect  = null;
                    editEffect = null;
                    GUI.FocusControl("Clear");
                    Repaint();
                }
                else
                {
                    effectEditor.serializedObject.ApplyModifiedProperties();
                }
            }
            GUILayout.EndVertical();

            GUILayout.EndHorizontal();
        }
Exemple #13
0
        void RenderQueueGUIDraw()
        {
            using (new EditorGUILayout.HorizontalScope())
            {
                EditorGUI.BeginChangeCheck();
                RenderQueue rq = isRenderQueueCustom ? RenderQueue.Custom : (RenderQueue)geometryRenderQueue.intValue;
                rq = (RenderQueue)EditorGUILayout.EnumPopup(EditorStrings.ConfigGeometryRenderQueue, rq);
                if (EditorGUI.EndChangeCheck())
                {
                    isRenderQueueCustom = (rq == RenderQueue.Custom);

                    if (!isRenderQueueCustom)
                    {
                        geometryRenderQueue.intValue = (int)rq;
                    }
                }

                EditorGUI.BeginDisabledGroup(!isRenderQueueCustom);
                {
                    geometryRenderQueue.intValue = EditorGUILayout.IntField(geometryRenderQueue.intValue, GUILayout.MaxWidth(65.0f));
                }
                EditorGUI.EndDisabledGroup();
            }
        }
Exemple #14
0
        void OnGUI()
        {
            GUILayout.BeginVertical();

            for (int i = 0; i < SelectedObjects.Length; ++i)
            {
                GUILayout.BeginHorizontal();
                GUILayout.Space(10);

                SelectedObjects[i] = (GameObject)EditorGUILayout.ObjectField(SelectedObjects[i], typeof(GameObject), true);
                Sections[i]        = (SectionID)EditorGUILayout.EnumPopup(Sections[i], GUILayout.MaxWidth(150));

                GUILayout.Space(10);
                GUILayout.EndHorizontal();
            }

            GUILayout.FlexibleSpace();


            GUILayout.BeginHorizontal();
            GUILayout.Space(10);

            if (GUILayout.Button("Create Blockout Prefabs"))
            {
                OnWizardCreate();
            }

            GUILayout.Space(10);
            GUILayout.EndHorizontal();
            GUILayout.Space(10);
            GUILayout.EndVertical();
        }
Exemple #15
0
        //public void DrawItem()
        //{
        //    if (!item) return;
        //    SerializedObject _item = new SerializedObject(item);
        //    _item.Update();

        //    GUILayout.BeginVertical("box");
        //    GUILayout.BeginHorizontal("box");
        //    var name = " ID " + item.id.ToString("00") + "\n - " + item.name + "\n - " + item.type.ToString();
        //    var content = new GUIContent(name);
        //    GUILayout.Label(content, GUILayout.ExpandWidth(true));
        //    GUILayout.EndHorizontal();
        //    EditorGUILayout.LabelField("Description");

        //    item.description = EditorGUILayout.TextArea(item.description);
        //    item.type = (vItemType)EditorGUILayout.EnumPopup("Item Type", item.type);
        //    item.stackable = EditorGUILayout.Toggle("Stackable", item.stackable);

        //    if (item.stackable)
        //    {
        //        if (item.maxStack <= 0) item.maxStack = 1;
        //        item.maxStack = EditorGUILayout.IntField("Max Stack", item.maxStack);
        //    }
        //    else item.maxStack = 1;

        //    GUILayout.EndVertical();

        //    GUILayout.BeginVertical("box");
        //    GUILayout.BeginHorizontal();
        //    GUILayout.Label("Icon");
        //    item.icon = (Sprite)EditorGUILayout.ObjectField(item.icon, typeof(Sprite), false);
        //    var rect = GUILayoutUtility.GetRect(40, 40);

        //    if (item.icon != null)
        //    {
        //        DrawTextureGUI(rect, item.icon, new Vector2(40, 40));
        //    }
        //    GUILayout.EndHorizontal();
        //    GUILayout.BeginHorizontal();
        //    GUILayout.BeginVertical("box");
        //    GUILayout.Label("Original Object");
        //    item.originalObject = (GameObject)EditorGUILayout.ObjectField(item.originalObject, typeof(GameObject), false);
        //    GUILayout.EndVertical();
        //    GUILayout.BeginVertical("box");
        //    GUILayout.Label("Drop Object");
        //    item.dropObject = (GameObject)EditorGUILayout.ObjectField(item.dropObject, typeof(GameObject), false);
        //    GUILayout.EndVertical();
        //    GUILayout.EndHorizontal();

        //    GUILayout.EndVertical();
        //    Debug.Log("OPA");
        //    DrawAttributes();
        //    GUILayout.BeginVertical("box");
        //    GUILayout.Box(new GUIContent("Custom Settings", "This area is used for additional properties\n in vItem Properties in defaultInspector region"));
        //    defaultInspector.DrawDefaultInspector();
        //    GUILayout.EndVertical();
        //    if (GUI.changed || _item.ApplyModifiedProperties())
        //    {
        //        EditorUtility.SetDirty(item);
        //    }
        //}

        void DrawAttributes()
        {
            try
            {
                GUILayout.BeginVertical("box");
                GUILayout.Box("Attributes", GUILayout.ExpandWidth(true));
                EditorGUILayout.Space();
                if (!inAddAttribute && GUILayout.Button("Add Attribute", EditorStyles.miniButton))
                {
                    inAddAttribute = true;
                }
                if (inAddAttribute)
                {
                    GUILayout.BeginHorizontal("box");
                    attribute = (vItemAttributes)EditorGUILayout.EnumPopup(attribute);
                    EditorGUILayout.LabelField("Value", GUILayout.MinWidth(60));
                    attributeValue = EditorGUILayout.IntField(attributeValue);
                    GUILayout.EndHorizontal();
                    if (item.attributes != null && item.attributes.Contains(attribute))
                    {
                        EditorGUILayout.HelpBox("This attribute already exist ", MessageType.Error);
                        if (GUILayout.Button("Cancel", EditorStyles.miniButton, GUILayout.MinWidth(60)))
                        {
                            inAddAttribute = false;
                        }
                    }
                    else
                    {
                        GUILayout.BeginHorizontal("box");
                        if (GUILayout.Button("Add", EditorStyles.miniButton, GUILayout.MinWidth(60)))
                        {
                            item.attributes.Add(new vItemAttribute(attribute, attributeValue));

                            attributeValue = 0;
                            inAddAttribute = false;
                        }
                        if (GUILayout.Button("Cancel", EditorStyles.miniButton, GUILayout.MinWidth(60)))
                        {
                            attributeValue = 0;
                            inAddAttribute = false;
                        }
                        GUILayout.EndHorizontal();
                    }
                }
                EditorGUILayout.Space();
                for (int i = 0; i < item.attributes.Count; i++)
                {
                    GUILayout.BeginHorizontal("box");
                    EditorGUILayout.LabelField(item.attributes[i].name.ToString(), GUILayout.MinWidth(60));
                    item.attributes[i].value = EditorGUILayout.IntField(item.attributes[i].value);

                    EditorGUILayout.Space();
                    if (GUILayout.Button("x", GUILayout.MaxWidth(30)))
                    {
                        item.attributes.RemoveAt(i);
                        GUILayout.EndHorizontal();
                        break;
                    }
                    GUILayout.EndHorizontal();
                }

                GUILayout.EndVertical();
            }
            catch { }
        }
        public void OnGUI()
        {
            if (index == -1)
            {
                index = LaunchAssetBundleServer.ServerRootPath == AssetManagerSetting.EditorAssetBundleServerRoot_WWW ? 0 : 1;

                if (index == 0)
                {
                    selectRoot = AssetManagerSetting.EditorAssetBundleServerRoot_WWW;
                }
                else
                {
                    selectRoot = AssetManagerSetting.EditorAssetBundleServerRoot_StreamingAssets;
                }
            }

            GUILayout.BeginHorizontal(HGUILayout.boxMPStyle, GUILayout.Height(50));
            EditorGUILayout.LabelField("选择服务器目录", HGUILayout.labelCenterStyle, GUILayout.Width(150), GUILayout.Height(25));
            int preSelectIndex = index;

            index = EditorGUILayout.Popup(index, serverRoots);
            if (preSelectIndex != index)
            {
                preSelectIndex = index;
                if (index == 0)
                {
                    selectRoot = AssetManagerSetting.EditorAssetBundleServerRoot_WWW;
                }
                else
                {
                    selectRoot = AssetManagerSetting.EditorAssetBundleServerRoot_StreamingAssets;
                }
            }
            GUILayout.EndHorizontal();


            if (index == 0)
            {
                HGUILayout.BeginCenterHorizontal();
                if (GUILayout.Button("清除该目录数据", GUILayout.MinHeight(30), GUILayout.MaxWidth(200)))
                {
                    PathUtil.ClearDirectory(selectRoot + "/StreamingAssets");
                }

                GUILayout.Space(20);

                if (GUILayout.Button("复制更新数据到该目录", GUILayout.MinHeight(30), GUILayout.MaxWidth(200)))
                {
                    AssetBundleServerData.CopyUpdateAsset(selectRoot + "/StreamingAssets");
                }


                GUILayout.Space(20);

                if (GUILayout.Button("复制所有数据到该目录", GUILayout.MinHeight(30), GUILayout.MaxWidth(200)))
                {
                    AssetBundleServerData.CopyAlleAsset(selectRoot + "/StreamingAssets");
                }

                HGUILayout.EndCenterHorizontal();
            }


            if (LaunchAssetBundleServer.IsRunning())
            {
                GUILayout.BeginVertical(HGUILayout.boxMPStyle, GUILayout.Height(50));
                EditorGUILayout.LabelField("Host: ", LaunchAssetBundleServer.Host);
                EditorGUILayout.LabelField("RuningRoot: ", LaunchAssetBundleServer.ServerRootPath);
                EditorGUILayout.LabelField("SelectRoot: ", selectRoot);
                GUILayout.EndVertical();



                HGUILayout.BeginCenterHorizontal();
                if (GUILayout.Button("关闭服务器", GUILayout.MinHeight(50), GUILayout.MaxWidth(200)))
                {
                    LaunchAssetBundleServer.KillRunningAssetBundleServer();
                }

                GUILayout.Space(20);

                if (GUILayout.Button("重启服务器", GUILayout.MinHeight(50), GUILayout.MaxWidth(200)))
                {
                    LaunchAssetBundleServer.KillRunningAssetBundleServer();

                    LaunchAssetBundleServer.ServerRootPath = selectRoot;
                    LaunchAssetBundleServer.Run();
                }
                HGUILayout.EndCenterHorizontal();
            }
            else
            {
                GUILayout.BeginVertical(HGUILayout.boxMPStyle, GUILayout.Height(50));
                EditorGUILayout.LabelField("SelectRoot: ", selectRoot);
                GUILayout.EndVertical();

                HGUILayout.BeginCenterHorizontal();
                if (GUILayout.Button("启动服务器", GUILayout.MinHeight(50), GUILayout.MaxWidth(200)))
                {
                    LaunchAssetBundleServer.ServerRootPath = selectRoot;
                    LaunchAssetBundleServer.Run();
                }
                HGUILayout.EndCenterHorizontal();
            }


            GUILayout.Space(20);
        }
Exemple #17
0
    //重写Inspector进行绘制
    public override void OnInspectorGUI()
    {
        // base.OnInspectorGUI(); 使用原本的GUI进行绘制
        serializedObject.Update(); //最初更新绑定的序列化对象
        EditorGUILayout.BeginVertical();

        GUILayout.Space(10);
        //标题
        EditorGUILayout.LabelField("玩家基本信息", new GUIStyle()
        {
            fontStyle = FontStyle.Bold
        });

        /******EditorGUIUtility.labelWidth = 50;*****/
        //对于lable和field一起显示的控件,上述命令可以控制lable标签的统一宽度,该自动标签可以通过GUIContext.None参数取消;
        //若将lable和field分成两部分并排显示,上述的命令无法控制;
        //下面的例子对于两种方式都有运用;

        //Head Icon
        //EditorGUILayout.ObjectField(headIcon); // warning:头像框目前无能为力,在多选操作和显示图片上的问题;
        EditorGUILayout.PropertyField(headIcon);
        GUILayout.Space(2);
        EditorGUILayout.BeginHorizontal();
        //playerName
        EditorGUILayout.LabelField("Name", GUILayout.MaxWidth(40));
        EditorGUILayout.DelayedTextField(playerName, GUIContent.none);


        //playerAge
        GUILayout.Space(20);
        EditorGUILayout.LabelField("Age", GUILayout.MaxWidth(30));
        EditorGUILayout.DelayedIntField(playerAge, GUIContent.none);
        EditorGUILayout.EndHorizontal();

        //playerTel
        GUILayout.Space(2);
        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("Tele", GUILayout.MaxWidth(40));
        EditorGUILayout.DelayedTextField(playerTel, GUIContent.none);
        EditorGUILayout.EndHorizontal();

        //playerWeight
        GUILayout.Space(2);
        EditorGUILayout.Slider(playerWeight, 20f, 180f, new GUIContent("Weight(Kg)"));
        if (playerWeight.floatValue < 30f)
        {
            EditorGUILayout.HelpBox("player is too slight.", MessageType.Info);
        }
        else if (playerWeight.floatValue > 150f)
        {
            EditorGUILayout.HelpBox("player is too fat...", MessageType.Warning);
        }


        //playerSkinColor
        GUILayout.Space(2);
        Color color = GUI.color;

        //GUI.color = skinColor.colorValue;
        //skinColor.colorValue = EditorGUILayout.ColorField("Skin Color", skinColor.colorValue);
        /*更新:使用 EditorGUILayout.PropertyField(),这个是万能框,解决多选bug问题。*/
        EditorGUILayout.PropertyField(skinColor);
        GUILayout.Space(2);
        if (!skinColor.hasMultipleDifferentValues)
        {
            Rect lastColorRect = GUILayoutUtility.GetRect(10, 20);
            EditorGUI.ProgressBar(lastColorRect, 1f, "进度条的使用");
        }
        GUI.color = color;


        GUILayout.Space(10);
        EditorGUILayout.LabelField("游戏角色信息", new GUIStyle()
        {
            fontStyle = FontStyle.Bold
        });

        //可控区域勾选框
        if (!enable.hasMultipleDifferentValues)
        {
            GUILayout.Space(2);
            EditorGUILayout.BeginHorizontal();
            //error : BeginToggleGroup不存在使用SerializedProperty的API,因此在多选上存在Bug
            enable.boolValue = EditorGUILayout.BeginToggleGroup("自定义游戏职业", enable.boolValue);

            //selection,控制职业pop框选择
            if (!selection.hasMultipleDifferentValues)
            {
                selection.intValue = EditorGUILayout.Popup(selection.intValue, selections);//error : Popup不存在使用SerializedProperty的API,因此在多选上存在Bug
            }
            EditorGUILayout.EndHorizontal();
            EditorGUILayout.EndToggleGroup();
            if (!selection.hasMultipleDifferentValues)
            {
                GUILayout.Space(2);
                if (enable.boolValue)
                {
                    EditorGUILayout.HelpBox("你选择了第 " + (selection.intValue + 1) + " 种自定义职业", MessageType.Info);
                }
            }
        }

        //账号playerIDs列表
        GUILayout.Space(5);
        playerIDs.DoLayoutList();

        //角色技能skill列表
        GUILayout.Space(5);
        playerSkills.DoLayoutList();

        EditorGUILayout.EndVertical();
        serializedObject.ApplyModifiedProperties();
    }
    public override void OnPreviewSettings()
    {
        if (!m_initialized)
        {
            GUILayout.HorizontalSlider(0, 0, 2, GUILayout.MaxWidth(64));
        }
        else
        {
            float speed = GUILayout.HorizontalSlider(m_skeletonAnimation.timeScale, 0, 2, GUILayout.MaxWidth(64));

            //snap to nearest 0.25
            float y = speed / 0.25f;
            int   q = Mathf.RoundToInt(y);
            speed = q * 0.25f;

            m_skeletonAnimation.timeScale = speed;
        }
    }
        private int DoQualityLevelSelection(int currentQualitylevel, IList <QualitySetting> qualitySettings, Dictionary <string, int> platformDefaultQualitySettings)
        {
            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            GUILayout.BeginVertical();
            var selectedLevel = currentQualitylevel;

            //Header row
            GUILayout.BeginHorizontal();

            Rect header = GUILayoutUtility.GetRect(GUIContent.none, Styles.kToggle, GUILayout.ExpandWidth(false), GUILayout.Width(Styles.kLabelWidth), GUILayout.Height(Styles.kHeaderRowHeight));

            header.x     += EditorGUI.indent;
            header.width -= EditorGUI.indent;
            GUI.Label(header, "Levels", EditorStyles.boldLabel);

            //Header row icons
            foreach (var platform in m_ValidPlatforms)
            {
                var iconRect = GUILayoutUtility.GetRect(GUIContent.none, Styles.kToggle, GUILayout.MinWidth(Styles.kMinToggleWidth), GUILayout.MaxWidth(Styles.kMaxToggleWidth), GUILayout.Height(Styles.kHeaderRowHeight));
                var temp     = EditorGUIUtility.TempContent(platform.smallIcon);
                temp.tooltip = platform.title.text;
                GUI.Label(iconRect, temp);
                temp.tooltip = "";
            }

            //Extra column for deleting setting button
            GUILayoutUtility.GetRect(GUIContent.none, Styles.kToggle, GUILayout.MinWidth(Styles.kMinToggleWidth), GUILayout.MaxWidth(Styles.kMaxToggleWidth), GUILayout.Height(Styles.kHeaderRowHeight));

            GUILayout.EndHorizontal();

            //Draw the row for each quality setting
            var currentEvent = Event.current;

            for (var i = 0; i < qualitySettings.Count; i++)
            {
                GUILayout.BeginHorizontal();
                var  bgStyle  = i % 2 == 0 ? Styles.kListEvenBg : Styles.kListOddBg;
                bool selected = (selectedLevel == i);

                //Draw the selected icon if required
                Rect r = GUILayoutUtility.GetRect(GUIContent.none, Styles.kToggle, GUILayout.ExpandWidth(false), GUILayout.Width(Styles.kLabelWidth));

                switch (currentEvent.type)
                {
                case EventType.Repaint:
                    bgStyle.Draw(r, GUIContent.none, false, false, selected, false);
                    GUI.Label(r, EditorGUIUtility.TempContent(qualitySettings[i].m_Name));
                    break;

                case EventType.MouseDown:
                    if (r.Contains(currentEvent.mousePosition))
                    {
                        selectedLevel = i;
                        GUIUtility.keyboardControl = 0;
                        GUIUtility.hotControl      = m_QualityElementHash;
                        GUI.changed = true;
                        m_Dragging  = new Dragging {
                            m_StartPosition = i, m_Position = i
                        };
                        currentEvent.Use();
                    }
                    break;

                case EventType.MouseDrag:
                    if (GUIUtility.hotControl == m_QualityElementHash)
                    {
                        if (r.Contains(currentEvent.mousePosition))
                        {
                            m_Dragging.m_Position = i;
                            currentEvent.Use();
                        }
                    }
                    break;

                case EventType.MouseUp:
                    if (GUIUtility.hotControl == m_QualityElementHash)
                    {
                        GUIUtility.hotControl = 0;
                        currentEvent.Use();
                    }
                    break;

                case EventType.KeyDown:
                    if (currentEvent.keyCode == KeyCode.UpArrow || currentEvent.keyCode == KeyCode.DownArrow)
                    {
                        selectedLevel += currentEvent.keyCode == KeyCode.UpArrow ? -1 : 1;
                        selectedLevel  = Mathf.Clamp(selectedLevel, 0, qualitySettings.Count - 1);
                        GUIUtility.keyboardControl = 0;
                        GUI.changed = true;
                        currentEvent.Use();
                    }
                    break;
                }

                //Build a list of the current platform selection and draw it.
                foreach (var platform in m_ValidPlatforms)
                {
                    bool isDefaultQuality = false;
                    if (platformDefaultQualitySettings.ContainsKey(platform.name) && platformDefaultQualitySettings[platform.name] == i)
                    {
                        isDefaultQuality = true;
                    }

                    var toggleRect = GUILayoutUtility.GetRect(Styles.kPlatformTooltip, Styles.kToggle, GUILayout.MinWidth(Styles.kMinToggleWidth), GUILayout.MaxWidth(Styles.kMaxToggleWidth));
                    if (Event.current.type == EventType.Repaint)
                    {
                        bgStyle.Draw(toggleRect, GUIContent.none, false, false, selected, false);
                    }

                    var color = GUI.backgroundColor;
                    if (isDefaultQuality && !EditorApplication.isPlayingOrWillChangePlaymode)
                    {
                        GUI.backgroundColor = Color.green;
                    }

                    var supported    = !qualitySettings[i].m_ExcludedPlatforms.Contains(platform.name);
                    var newSupported = GUI.Toggle(toggleRect, supported, Styles.kPlatformTooltip, isDefaultQuality ? Styles.kDefaultToggle : Styles.kToggle);
                    if (supported != newSupported)
                    {
                        if (newSupported)
                        {
                            qualitySettings[i].m_ExcludedPlatforms.Remove(platform.name);
                        }
                        else
                        {
                            qualitySettings[i].m_ExcludedPlatforms.Add(platform.name);
                        }
                    }

                    GUI.backgroundColor = color;
                }

                //Extra column for deleting quality button
                var deleteButton = GUILayoutUtility.GetRect(GUIContent.none, Styles.kToggle, GUILayout.MinWidth(Styles.kMinToggleWidth), GUILayout.MaxWidth(Styles.kMaxToggleWidth));
                if (Event.current.type == EventType.Repaint)
                {
                    bgStyle.Draw(deleteButton, GUIContent.none, false, false, selected, false);
                }
                if (GUI.Button(deleteButton, Styles.kIconTrash, GUIStyle.none))
                {
                    m_DeleteLevel = i;
                }
                GUILayout.EndHorizontal();
            }

            //Add a spacer line to separate the levels from the defaults
            GUILayout.BeginHorizontal();
            DrawHorizontalDivider();
            GUILayout.EndHorizontal();

            //Default platform selection dropdowns
            GUILayout.BeginHorizontal();

            var defaultQualityTitle = GUILayoutUtility.GetRect(GUIContent.none, Styles.kToggle, GUILayout.ExpandWidth(false), GUILayout.Width(Styles.kLabelWidth), GUILayout.Height(Styles.kHeaderRowHeight));

            defaultQualityTitle.x     += EditorGUI.indent;
            defaultQualityTitle.width -= EditorGUI.indent;
            GUI.Label(defaultQualityTitle, "Default", EditorStyles.boldLabel);

            // Draw default dropdown arrows
            foreach (var platform in m_ValidPlatforms)
            {
                var iconRect = GUILayoutUtility.GetRect(GUIContent.none, Styles.kToggle,
                                                        GUILayout.MinWidth(Styles.kMinToggleWidth),
                                                        GUILayout.MaxWidth(Styles.kMaxToggleWidth),
                                                        GUILayout.Height(Styles.kHeaderRowHeight));

                int position;
                if (!platformDefaultQualitySettings.TryGetValue(platform.name, out position))
                {
                    platformDefaultQualitySettings.Add(platform.name, 0);
                }

                position = EditorGUI.Popup(iconRect, position, qualitySettings.Select(x => x.m_Name).ToArray(), Styles.kDefaultDropdown);
                platformDefaultQualitySettings[platform.name] = position;
            }
            GUILayout.EndHorizontal();

            GUILayout.Space(10);

            //Add an extra row for 'Add' button
            GUILayout.BeginHorizontal();
            var addButtonRect = GUILayoutUtility.GetRect(Styles.kAddQualityLevel, Styles.kToggle, GUILayout.ExpandWidth(true));

            if (GUI.Button(addButtonRect, Styles.kAddQualityLevel))
            {
                m_ShouldAddNewLevel = true;
            }

            GUILayout.EndHorizontal();

            GUILayout.EndVertical();

            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();
            return(selectedLevel);
        }
Exemple #20
0
    void OnGUI()
    {
        GUI.skin = _skin;
        GUILayout.BeginArea(new Rect(Screen.width - 512, 0, 512, Screen.height));
        GUILayout.BeginVertical();

        GUILayout.Label("Select webcam:");

        for (int i = 0; i < _instances.Length; i++)
        {
            Instance webcam = _instances[i];

            GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));

            if (_selectedWebcamIndex == i)
            {
                GUILayout.Label("->", GUILayout.Width(32f));
            }
            else
            {
                GUILayout.Label(" ", GUILayout.Width(32f));
            }

            if (webcam.capture.IsCapturing())
            {
                float t = Mathf.PingPong(Time.timeSinceLevelLoad, 0.25f) * 4f;
                GUI.backgroundColor = Color.Lerp(GUI.backgroundColor, Color.white, t);
                GUI.color           = Color.Lerp(Color.red, Color.white, t);
            }

            if (GUILayout.Button(webcam.name, GUILayout.Width(200), GUILayout.ExpandWidth(true)))
            {
                Change(i);
            }
            GUI.backgroundColor = Color.white;
            GUI.color           = Color.white;

            if (webcam.texture == null)
            {
                if (GUILayout.Button("Play", GUILayout.Width(64f)))
                {
                    StartWebcam(webcam);
                    Change(i);
                }
            }
            else
            {
                if (GUILayout.Button("Stop", GUILayout.Width(64f)))
                {
                    StopWebcam(webcam);
                    Change(i);
                }
            }

            if (webcam.texture != null)
            {
                Rect camRect = GUILayoutUtility.GetRect(256, 256.0f / (webcam.texture.width / (float)webcam.texture.height));
                GUI.DrawTexture(camRect, webcam.texture);
            }
            else
            {
                GUILayout.Label("No signal...", GUILayout.MinWidth(256.0f), GUILayout.MaxWidth(256.0f), GUILayout.ExpandWidth(false));
            }

            GUILayout.EndHorizontal();
        }

        GUILayout.EndVertical();
        GUILayout.EndArea();
    }
    void CreateRuleObjects()
    {
        if (previewObject == null)
        {
            previewObject = new GameObject("PreviewMeshBuilder", typeof(MeshFilter), typeof(MeshRenderer));
            topLayer      = new GameObject("TopLayer");
            topLayer.transform.SetParent(previewObject.transform);
            topLayer.transform.localPosition = UnityEngine.Vector3.zero;

            middleLayer = new GameObject("MiddleLayer");
            middleLayer.transform.SetParent(previewObject.transform);
            middleLayer.transform.localPosition = UnityEngine.Vector3.zero;

            bottomLayer = new GameObject("BottomLayer");
            bottomLayer.transform.SetParent(previewObject.transform);
            bottomLayer.transform.localPosition = UnityEngine.Vector3.zero;

            var view = SceneView.currentDrawingSceneView;
            if (view != null)
            {
                view.pivot = previewObject.transform.position;
            }
        }

        if (offsetObjects == null)
        {
            offsetObjects = new Dictionary <OffsetCondition.Offset, GameObject>();

            for (int y = -1; y <= 1; y++)
            {
                for (int x = -1; x <= 1; x++)
                {
                    for (int z = -1; z <= 1; z++)
                    {
                        if (x == 0 && y == 0 && z == 0)
                        {
                            continue;
                        }

                        GameObject offsetObj = GameObject.CreatePrimitive(PrimitiveType.Cube);
                        offsetObj.name = string.Format("OFFSET {0},{1},{2}", x, y, z);
                        var usageComponent = offsetObj.AddComponent <MeshUsageCaseEditorComponent>();

                        if (y == -1)
                        {
                            offsetObj.transform.SetParent(bottomLayer.transform);
                        }
                        else if (y == 0)
                        {
                            offsetObj.transform.SetParent(middleLayer.transform);
                        }
                        else if (y == 1)
                        {
                            offsetObj.transform.SetParent(topLayer.transform);
                        }

                        offsetObj.transform.localPosition = new UnityEngine.Vector3(x, y, z);

                        var renderer = offsetObj.GetComponent <MeshRenderer>();
                        var material = AssetDatabase.LoadAssetAtPath("Assets/EcoModKit/Materials/CustomBuilderPreview.mat", typeof(Material)) as Material;
                        if (material != null)
                        {
                            renderer.sharedMaterial = new Material(material);
                        }

                        OffsetCondition.Offset condition = OffsetCondition.GetFromVector(new Vector3(x, y, z));

                        offsetObjects[condition] = offsetObj;

                        int index = (x + 1) + ((1 - z) * 3);
                        if (y == 1)
                        {
                            usageComponent.OnSelected = () => { this.ResetSelectedOffset(); this.topLayerSelection = index; this.Repaint(); }
                        }
                        ;
                        if (y == 0)
                        {
                            usageComponent.OnSelected = () => { this.ResetSelectedOffset(); this.midLayerSelection = index; this.Repaint(); }
                        }
                        ;
                        if (y == -1)
                        {
                            usageComponent.OnSelected = () => { this.ResetSelectedOffset(); this.bottomLayerSelection = index; this.Repaint(); }
                        }
                        ;
                    }
                }
            }
        }

        UpdateRuleObjects();
    }

    void UpdateRuleObjects()
    {
        foreach (var offset in offsetObjects.Keys)
        {
            var obj = offsetObjects[offset];

            if (obj == null)
            {
                continue;
            }

            var usageComponent = obj.GetComponent <MeshUsageCaseEditorComponent>();

            usageComponent.condition = selectedUsageCase != null?selectedUsageCase.conditions.Find(cond => cond.offsetType == offset) : null;

            obj.SetActive(usageComponent.condition != null);
        }
    }

    // show the list of meshes, allowing selection of one
    void ShowMeshSet()
    {
        EditorGUILayout.BeginVertical(GUILayout.MaxWidth(400));
        {
            GUILayout.Label("CUBES", EditorStyles.boldLabel);

            int i             = 0;
            int removeIndex   = -1;
            int moveUpIndex   = -1;
            int moveDownIndex = -1;
            foreach (var usageCase in target.usageCases)
            {
                GUIStyle style = new GUIStyle(EditorStyles.miniButton);
                GUIStyle area  = new GUIStyle(EditorStyles.miniButton);

                if (selectedUsageCase == usageCase)
                {
                    style.fontStyle = FontStyle.Bold;

                    area.normal.background = new Texture2D(1, 1);
                    area.normal.background.SetPixel(0, 0, Color.green);
                    area.normal.background.Apply();
                }

                EditorGUILayout.BeginHorizontal();
                {
                    usageCase.foldout = EditorGUILayout.Foldout(usageCase.foldout, usageCase.meshAlternates.Length + " variants");
                    GUILayout.Space(20);

                    EditorGUILayout.BeginHorizontal(area);
                    {
                        GUILayout.Space(10);

                        usageCase.enabled = GUILayout.Toggle(usageCase.enabled, "", style, GUILayout.Width(20));

                        if (GUILayout.Button("X", style, GUILayout.Width(20)))
                        {
                            removeIndex = i;
                        }

                        if (GUILayout.Button("▲", style, GUILayout.Width(20)))
                        {
                            moveUpIndex = i;
                        }
                        if (GUILayout.Button("▼", style, GUILayout.Width(20)))
                        {
                            moveDownIndex = i;
                        }

                        GUILayout.Space(5);

                        usageCase.mesh = EditorGUILayout.ObjectField(usageCase.mesh, typeof(GameObject), false) as GameObject;

                        if (GUILayout.Button("Edit", style))
                        {
                            selectedUsageCase = usageCase;

                            UpdateSelectedMeshPreview();

                            ResetSelectedOffset();
                        }
                    }
                    EditorGUILayout.EndHorizontal();
                }
                EditorGUILayout.EndHorizontal();

                if (usageCase.foldout)
                {
                    int numVariants = usageCase.meshAlternates.Length;
                    int newVariants = EditorGUILayout.IntField("Variants: ", numVariants);
                    if (newVariants != numVariants)
                    {
                        var old = usageCase.meshAlternates;
                        usageCase.meshAlternates = new GameObject[newVariants];
                        if (old != null)
                        {
                            for (int idx = 0; idx < Math.Min(old.Length, newVariants); idx++)
                            {
                                usageCase.meshAlternates[idx] = old[idx];
                            }
                        }
                    }

                    if (usageCase.meshAlternates != null)
                    {
                        for (int idx = 0; idx < usageCase.meshAlternates.Length; idx++)
                        {
                            usageCase.meshAlternates[idx] = EditorGUILayout.ObjectField(usageCase.meshAlternates[idx], typeof(GameObject), false) as GameObject;
                        }
                    }
                }

                i++;
            }

            if (removeIndex != -1)
            {
                target.usageCases.RemoveAt(removeIndex);
                OnChange();
            }

            if (moveUpIndex != -1 && moveUpIndex > 0)
            {
                var src = target.usageCases[moveUpIndex];
                var dst = target.usageCases[moveUpIndex - 1];
                target.usageCases[moveUpIndex - 1] = src;
                target.usageCases[moveUpIndex]     = dst;
                OnChange();
            }

            if (moveDownIndex != -1 && moveDownIndex < target.usageCases.Count - 1)
            {
                var src = target.usageCases[moveDownIndex];
                var dst = target.usageCases[moveDownIndex + 1];
                target.usageCases[moveDownIndex + 1] = src;
                target.usageCases[moveDownIndex]     = dst;
                OnChange();
            }

            if (GUILayout.Button("Add New Cube"))
            {
                target.usageCases.Add(new MeshUsageCase());
                OnChange();
            }
        }
        EditorGUILayout.EndVertical();
    }

    void ResetSelectedOffset()
    {
        topLayerSelection    = -1;
        midLayerSelection    = -1;
        bottomLayerSelection = -1;
    }

    int topLayerSelection    = -1;
    int midLayerSelection    = -1;
    int bottomLayerSelection = -1;
    OffsetCondition.Offset selectedOffset = OffsetCondition.Offset.Offset_Null;

    // show the grid of neighbors to add conditions for, defaulting to all null (don't care)
    void ShowNeighborGrids()
    {
        if (selectedUsageCase == null)
        {
            return;
        }

        GUILayout.Space(10);

        EditorGUILayout.BeginVertical(GUILayout.MaxWidth(400));
        {
            GUILayout.Label("Usage Conditions", EditorStyles.largeLabel);
            GUILayout.Label(selectedUsageCase.ToString(), EditorStyles.label);

            topLayer.SetActive(ShowLayer(Vector3.up, "Top", ref topLayerSelection, topLayer.activeSelf));
            middleLayer.SetActive(ShowLayer(Vector3.zero, "Middle", ref midLayerSelection, middleLayer.activeSelf));
            bottomLayer.SetActive(ShowLayer(Vector3.down, "Bottom", ref bottomLayerSelection, bottomLayer.activeSelf));

            GUILayout.Space(10);

            GUILayout.BeginHorizontal();
            {
                selectedUsageCase.applyConditionsToAllRotations = EditorGUILayout.Toggle("Apply Rules To Rotations", selectedUsageCase.applyConditionsToAllRotations);
                selectedUsageCase.axis = (RotationAxis)EditorGUILayout.EnumPopup("Rotation Axis", selectedUsageCase.axis);
            }
            GUILayout.EndHorizontal();
            selectedUsageCase.dontRotateBaseMesh = EditorGUILayout.Toggle("Don't Rotate Mesh With Rules", selectedUsageCase.dontRotateBaseMesh);
            selectedUsageCase.importRotation     = EditorGUILayout.Vector3Field("Import Rotation", selectedUsageCase.importRotation);

            GUILayout.Space(10);

            int numDecoBuilders = selectedUsageCase.decorativeBuilders != null ? selectedUsageCase.decorativeBuilders.Length : 0;
            numDecoBuilders = EditorGUILayout.IntField("Decoration Builder Count", numDecoBuilders);
            if (numDecoBuilders != selectedUsageCase.decorativeBuilders.Length)
            {
                Array.Resize(ref selectedUsageCase.decorativeBuilders, numDecoBuilders);
            }

            for (int decoBuilderIdx = 0; decoBuilderIdx < numDecoBuilders; decoBuilderIdx++)
            {
                selectedUsageCase.decorativeBuilders[decoBuilderIdx] = EditorGUILayout.ObjectField("Decoration " + decoBuilderIdx, selectedUsageCase.decorativeBuilders[decoBuilderIdx], typeof(CustomBuilder), false) as CustomBuilder;
            }
        }
        EditorGUILayout.EndVertical();
    }

    bool ShowLayer(Vector3 layerOffset, string name, ref int selection, bool enabled)
    {
        string[]  layers  = new string[9];
        Vector3[] offsets = new Vector3[9];

        int i = 0;

        for (int z = 1; z >= -1; z--)
        {
            for (int x = -1; x <= 1; x++)
            {
                var pos = new Vector3(x, 0, z);

                Vector3 layerPos = layerOffset + pos;
                offsets[i] = layerPos;

                if (layerPos == Vector3.zero)
                {
                    layers[i] = "[  FREE  ]\r\n[ SPACE ]";
                }
                else
                {
                    var condition = OffsetCondition.GetFromVector(layerPos);

                    var usage = selectedUsageCase.conditions.Find(cond => cond.offsetType == condition);

                    if (usage != null)
                    {
                        layers[i] = layerPos.ToString() + "\r\n" + usage.ToString();
                    }
                    else
                    {
                        layers[i] = layerPos.ToString() + "\r\n" + "DontCare";
                    }
                }

                i++;
            }
        }

        bool result = GUILayout.Toggle(enabled, name);

        // so dumb, selection grid steals focus so have to do this crazy button layout
        i = 0;
        GUILayout.BeginVertical();
        int newSelection = selection;

        for (int r1 = 0; r1 < 3; r1++)
        {
            GUILayout.BeginHorizontal();
            for (int r2 = 0; r2 < 3; r2++)
            {
                bool hit    = selection == i;
                bool before = hit;
                hit = GUILayout.Toggle(hit, layers[i], "Button");

                if (before != hit)
                {
                    newSelection = i;
                }
                i++;
            }
            GUILayout.EndHorizontal();
        }
        GUILayout.EndVertical();

        if (newSelection != selection)
        {
            ResetSelectedOffset();
            selectedOffset = OffsetCondition.GetFromVector(offsets[newSelection]);

            selection = newSelection;
        }

        return(result);
    }

    // when selecting a location, show the list of conditions for that
    void ShowConditions()
    {
        if (selectedUsageCase == null)
        {
            return;
        }

        EditorGUILayout.BeginVertical(GUILayout.MaxWidth(400));
        {
            GUILayout.Label("Conditions for " + selectedOffset, EditorStyles.largeLabel);

            var condition = selectedUsageCase.conditions.Find(x => x.offsetType == selectedOffset);

            if (condition != null)
            {
                if (condition.rules == null)
                {
                    condition.rules = new List <BlockRule>();
                }

                int i           = 0;
                int removeIndex = -1;
                foreach (var rule in condition.rules)
                {
                    EditorGUILayout.BeginHorizontal();
                    {
                        if (GUILayout.Button("Remove"))
                        {
                            removeIndex = i;
                        }

                        rule.ruleType   = (BlockRule.RuleType)EditorGUILayout.EnumPopup(rule.ruleType);
                        rule.ruleString = EditorGUILayout.TextField(rule.ruleString);
                    }
                    EditorGUILayout.EndHorizontal();

                    i++;
                }

                if (removeIndex != -1)
                {
                    condition.rules.RemoveAt(removeIndex);

                    if (condition.rules.Count == 0)
                    {
                        selectedUsageCase.conditions.Remove(condition);
                    }

                    OnChange();
                }
            }

            if (GUILayout.Button("Add New Rule"))
            {
                if (condition == null)
                {
                    OffsetCondition newCondition = new OffsetCondition(selectedOffset);
                    selectedUsageCase.conditions.Add(newCondition);

                    condition = newCondition;
                }

                condition.rules.Add(new BlockRule());

                OnChange();
            }
        }
        EditorGUILayout.EndVertical();
    }
}
Exemple #22
0
        protected void DrawSharedElements(ActionList _target)
        {
            if (PrefabUtility.GetPrefabType(_target) == PrefabType.Prefab && _target.source == ActionListSource.InScene)
            {
                EditorGUILayout.HelpBox("Scene-based Actions can not live in prefabs - use ActionList assets instead.", MessageType.Info);
                return;
            }

            int numActions = 0;

            if (_target.source != ActionListSource.AssetFile)
            {
                numActions = _target.actions.Count;
                if (numActions < 1)
                {
                    numActions = 1;
                    AC.Action newAction = ActionList.GetDefaultAction();
                    _target.actions.Add(newAction);
                }
            }

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

            if (_target.source == ActionListSource.AssetFile)
            {
                GUI.enabled = false;
            }

            if (GUILayout.Button("Expand all", EditorStyles.miniButtonLeft))
            {
                Undo.RecordObject(_target, "Expand actions");
                foreach (AC.Action action in _target.actions)
                {
                    action.isDisplayed = true;
                }
            }
            if (GUILayout.Button("Collapse all", EditorStyles.miniButtonMid))
            {
                Undo.RecordObject(_target, "Collapse actions");
                foreach (AC.Action action in _target.actions)
                {
                    action.isDisplayed = false;
                }
            }

            GUI.enabled = true;

            if (GUILayout.Button("Action List Editor", EditorStyles.miniButtonMid))
            {
                if (_target.source == ActionListSource.AssetFile)
                {
                    if (_target.assetFile != null)
                    {
                        ActionListEditorWindow.Init(_target.assetFile);
                    }
                }
                else
                {
                    ActionListEditorWindow.Init(_target);
                }
            }
            if (!Application.isPlaying)
            {
                GUI.enabled = false;
            }
            if (GUILayout.Button("Run now", EditorStyles.miniButtonRight))
            {
                _target.Interact();
            }
            GUI.enabled = true;
            EditorGUILayout.EndHorizontal();
            EditorGUILayout.Space();

            if (_target.source == ActionListSource.AssetFile)
            {
                return;
            }

            ActionListEditor.ResetList(_target);

            if (actionsManager == null)
            {
                EditorGUILayout.HelpBox("An Actions Manager asset file must be assigned in the Game Editor Window", MessageType.Warning);
                OnEnable();
                return;
            }

            if (!actionsManager.displayActionsInInspector)
            {
                EditorGUILayout.HelpBox("As set by the Actions Manager, Actions are only displayed in the ActionList Editor window.", MessageType.Info);
                return;
            }

            for (int i = 0; i < _target.actions.Count; i++)
            {
                if (_target.actions[i] == null)
                {
                    ACDebug.LogWarning("An empty Action was found, and was deleted");
                    _target.actions.RemoveAt(i);
                    continue;
                }

                _target.actions[i].AssignParentList(_target);

                EditorGUILayout.BeginVertical("Button");
                EditorGUILayout.BeginHorizontal();
                int    typeIndex   = KickStarter.actionsManager.GetActionTypeIndex(_target.actions[i]);
                string actionLabel = " (" + (i).ToString() + ") " + actionsManager.EnabledActions[typeIndex].GetFullTitle() + _target.actions[i].SetLabel();
                _target.actions[i].isDisplayed = EditorGUILayout.Foldout(_target.actions[i].isDisplayed, actionLabel);
                if (!_target.actions[i].isEnabled)
                {
                    EditorGUILayout.LabelField("DISABLED", EditorStyles.boldLabel, GUILayout.MaxWidth(100f));
                }

                if (GUILayout.Button(Resource.CogIcon, GUILayout.Width(20f), GUILayout.Height(15f)))
                {
                    ActionSideMenu(i);
                }

                _target.actions[i].isAssetFile = false;

                EditorGUILayout.EndHorizontal();

                if (_target.actions[i].isBreakPoint)
                {
                    EditorGUILayout.HelpBox("Break point", MessageType.None);
                }

                if (_target.actions[i].isDisplayed)
                {
                    GUI.enabled = _target.actions[i].isEnabled;

                    if (!actionsManager.DoesActionExist(_target.actions[i].GetType().ToString()))
                    {
                        EditorGUILayout.HelpBox("This Action type has been disabled in the Actions Manager", MessageType.Warning);
                    }
                    else
                    {
                        int newTypeIndex = ActionListEditor.ShowTypePopup(_target.actions[i], typeIndex);
                        if (newTypeIndex >= 0)
                        {
                            // Rebuild constructor if Subclass and type string do not match
                            ActionEnd _end = new ActionEnd();
                            _end.resultAction   = _target.actions[i].endAction;
                            _end.skipAction     = _target.actions[i].skipAction;
                            _end.linkedAsset    = _target.actions[i].linkedAsset;
                            _end.linkedCutscene = _target.actions[i].linkedCutscene;

                            Undo.RecordObject(_target, "Change Action type");
                            _target.actions[i] = ActionListEditor.RebuildAction(_target.actions[i], newTypeIndex, _end.resultAction, _end.skipAction, _end.linkedAsset, _end.linkedCutscene);
                        }

                        if (_target.useParameters && _target.parameters != null && _target.parameters.Count > 0)
                        {
                            _target.actions[i].ShowGUI(_target.parameters);
                        }
                        else
                        {
                            _target.actions[i].ShowGUI(null);
                        }
                    }
                }

                if (_target.actions[i].endAction == AC.ResultAction.Skip || _target.actions[i].numSockets == 2 || _target.actions[i] is ActionCheckMultiple || _target.actions[i] is ActionParallel)
                {
                    _target.actions[i].SkipActionGUI(_target.actions, _target.actions[i].isDisplayed);
                }

                GUI.enabled = true;

                EditorGUILayout.EndVertical();
                EditorGUILayout.Space();
            }

            if (GUILayout.Button("Add new action"))
            {
                Undo.RecordObject(_target, "Create action");
                numActions += 1;
            }

            _target.actions = ActionListEditor.ResizeList(_target.actions, numActions);
        }
Exemple #23
0
    private void OnGUI()
    {
        EditorGUILayout.BeginHorizontal();
        GUILayout.Label("Filter:", GUILayout.MaxWidth(50));

        EditorGUIUtility.labelWidth = 80;
        GUILayout.ExpandWidth(false);

        filter     = GUILayout.TextField(filter, 25, GUILayout.MaxWidth(800));
        ignoreCase = GUILayout.Toggle(ignoreCase, "Ignore Case", options: GUILayout.MaxWidth(100));
        _orderBy   = (OrderType)EditorGUILayout.EnumPopup("Oder By:", _orderBy);
        EditorGUILayout.EndHorizontal();



        var bindings = FindObjectsOfType <DataBindingBase>().OrderBy(e => _orderBy == OrderType.GameObject ? e.gameObject.name : e.ViewModelName);

        var oneWays = bindings.Where(e => e is OneWayDataBinding && !(e is TwoWayDataBinding)).Select(e => e as OneWayDataBinding).Where(
            e =>
        {
            if (_filterBy == FilterType.None)
            {
                return(true);
            }
            if (e.Connection == null)
            {
                return(false);
            }
            return(_filterBy == FilterType.Bound ? e.Connection.IsBound : !e.Connection.IsBound);
        });
        var twoWays = bindings.Where(e => e is TwoWayDataBinding).Select(e => e as TwoWayDataBinding);

        var eventPropBindings = FindObjectsOfType <EventPropertyBinding>();
        var eventBindings     = FindObjectsOfType <EventBinding>();

        GUILayout.Label(string.Format("OneWayBindings: {0}", oneWays.Count()), EditorStyles.boldLabel);

        onewWayScrollPos = EditorGUILayout.BeginScrollView(onewWayScrollPos, GUILayout.MaxHeight(600));
        var style = new GUIStyle(GUI.skin.label);

        style.richText = true;

        foreach (var item in oneWays)
        {
            var str = string.Format("<b>{0}</b> Src: <b>{1}:{2}</b> Dst: <b>{3}:{4}</b> Bound: <b>{5}</b>", item.gameObject.name, item.ViewModelName, item.SrcPropertyName, item._dstView.GetType().Name, item.DstPropertyName.PropertyName, item.Connection == null ? false : item.Connection.IsBound);

            bool contains = ignoreCase ? str.ToLower().Contains(filter.ToLower()) : str.Contains(filter);

            if (string.IsNullOrEmpty(filter) || contains)
            {
                EditorGUILayout.LabelField(str, style);
            }
        }

        EditorGUILayout.EndScrollView();

        GUILayout.Label(string.Format("TwoWay Bindings: {0}", twoWays.Count()), EditorStyles.boldLabel);

        twoWayScrollPos = EditorGUILayout.BeginScrollView(twoWayScrollPos, GUILayout.MaxHeight(400));
        foreach (var item in twoWays)
        {
            var str = string.Format("<b>{0}</b> Src: <b>{1}/{2}</b> Dst: <b>{3}/{4}</b> Event: <b>{4}</b> Bound: <b>{5}</b>", item.gameObject.name, item.ViewModelName, item.SrcPropertyName, item._dstView.GetType().Name, item.DstPropertyName.PropertyName, item._dstChangedEventName, item.Connection == null ? false : item.Connection.IsBound);

            if (string.IsNullOrEmpty(filter) || str.Contains(filter))
            {
                EditorGUILayout.LabelField(str, style);
            }
        }
        EditorGUILayout.EndScrollView();


        GUILayout.Label(string.Format("Event Bindings: {0}", eventPropBindings.Count()), EditorStyles.boldLabel);

        eventPropScrollPos = EditorGUILayout.BeginScrollView(eventPropScrollPos, GUILayout.MaxHeight(400));
        foreach (var item in eventPropBindings)
        {
            var str = string.Format("<b>{0}</b> SrcEvent: <b>{1}/{2}</b> DstProp: <b>{3}/{4}</b>", item.gameObject.name, item._srcView.GetType().Name, item.SrcEventName, item.ViewModelName, item.DstPropName);

            if (string.IsNullOrEmpty(filter) || str.Contains(filter))
            {
                EditorGUILayout.LabelField(str, style);
            }
        }
        EditorGUILayout.EndScrollView();


        var conns = BindingMonitor.Connections;

        GUILayout.Label(string.Format("Active Connections: {0}", conns.Count()), EditorStyles.boldLabel);

        if (GUILayout.Button("Reset"))
        {
            BindingMonitor.Reset();
        }

        connectionScrollPos = EditorGUILayout.BeginScrollView(connectionScrollPos, GUILayout.MaxHeight(600));

        foreach (var item in conns)
        {
            var str = string.Format("<b>{0}</b> Src: <b>{1}/{2}</b> Dst: <b>{3}/{4}</b> Bound: <b>{5}</b>", item.Owner, item.SrcTarget.propertyOwner.GetType().Name, item.SrcTarget.propertyName, item.DstTarget.propertyOwner.GetType().Name, item.DstTarget.propertyName, item.IsBound);

            bool contains = ignoreCase ? str.ToLower().Contains(filter.ToLower()) : str.Contains(filter);

            if (string.IsNullOrEmpty(filter) || contains)
            {
                EditorGUILayout.LabelField(str, style);
            }
        }


        EditorGUILayout.EndScrollView();
    }
Exemple #24
0
        public static void ShowLocalParametersGUI(List <ActionParameter> localParameters, List <ActionParameter> assetParameters, bool isAssetFile)
        {
            int numParameters = assetParameters.Count;

            if (numParameters < localParameters.Count)
            {
                localParameters.RemoveRange(numParameters, localParameters.Count - numParameters);
            }
            else if (numParameters > localParameters.Count)
            {
                if (numParameters > localParameters.Capacity)
                {
                    localParameters.Capacity = numParameters;
                }
                for (int i = localParameters.Count; i < numParameters; i++)
                {
                    ActionParameter newParameter = new ActionParameter(ActionListEditor.GetParameterIDArray(localParameters));
                    localParameters.Add(newParameter);
                }
            }

            for (int i = 0; i < numParameters; i++)
            {
                string label = assetParameters[i].label;
                localParameters[i].parameterType = assetParameters[i].parameterType;

                if (assetParameters[i].parameterType == ParameterType.String)
                {
                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.LabelField(label + ":", GUILayout.Width(145f));
                    EditorStyles.textField.wordWrap = true;
                    localParameters[i].stringValue  = EditorGUILayout.TextArea(localParameters[i].stringValue, GUILayout.MaxWidth(400f));
                    EditorGUILayout.EndHorizontal();
                }
                else if (assetParameters[i].parameterType == ParameterType.Float)
                {
                    localParameters[i].floatValue = EditorGUILayout.FloatField(label + ":", localParameters[i].floatValue);
                }
                else if (assetParameters[i].parameterType == ParameterType.Integer)
                {
                    localParameters[i].intValue = EditorGUILayout.IntField(label + ":", localParameters[i].intValue);
                }
                else if (assetParameters[i].parameterType == ParameterType.Boolean)
                {
                    BoolValue boolValue = BoolValue.False;
                    if (localParameters[i].intValue == 1)
                    {
                        boolValue = BoolValue.True;
                    }

                    boolValue = (BoolValue)EditorGUILayout.EnumPopup(label + ":", boolValue);

                    if (boolValue == BoolValue.True)
                    {
                        localParameters[i].intValue = 1;
                    }
                    else
                    {
                        localParameters[i].intValue = 0;
                    }
                }
                else if (assetParameters[i].parameterType == ParameterType.GlobalVariable)
                {
                    if (AdvGame.GetReferences() && AdvGame.GetReferences().variablesManager)
                    {
                        VariablesManager variablesManager = AdvGame.GetReferences().variablesManager;
                        localParameters[i].intValue = ActionRunActionList.ShowVarSelectorGUI(label + ":", variablesManager.vars, localParameters[i].intValue);
                    }
                    else
                    {
                        EditorGUILayout.HelpBox("A Variables Manager is required to pass Global Variables.", MessageType.Warning);
                    }
                }
                else if (assetParameters[i].parameterType == ParameterType.InventoryItem)
                {
                    if (AdvGame.GetReferences() && AdvGame.GetReferences().inventoryManager)
                    {
                        InventoryManager inventoryManager = AdvGame.GetReferences().inventoryManager;
                        localParameters[i].intValue = ActionRunActionList.ShowInvItemSelectorGUI(label + ":", inventoryManager.items, localParameters[i].intValue);
                    }
                    else
                    {
                        EditorGUILayout.HelpBox("An Inventory Manager is required to pass Inventory items.", MessageType.Warning);
                    }
                }
                else if (assetParameters[i].parameterType == ParameterType.LocalVariable)
                {
                    if (KickStarter.localVariables)
                    {
                        localParameters[i].intValue = ActionRunActionList.ShowVarSelectorGUI(label + ":", KickStarter.localVariables.localVars, localParameters[i].intValue);
                    }
                    else
                    {
                        EditorGUILayout.HelpBox("A GameEngine prefab is required to pass Local Variables.", MessageType.Warning);
                    }
                }
                if (assetParameters[i].parameterType == ParameterType.GameObject)
                {
                    if (isAssetFile)
                    {
                        // ID
                        localParameters[i].intValue   = EditorGUILayout.IntField(label + " (ID):", localParameters[i].intValue);
                        localParameters[i].gameObject = null;
                    }
                    else
                    {
                        // Gameobject
                        localParameters[i].gameObject = (GameObject)EditorGUILayout.ObjectField(label + ":", localParameters[i].gameObject, typeof(GameObject), true);
                        localParameters[i].intValue   = 0;
                        if (localParameters[i].gameObject != null && localParameters[i].gameObject.GetComponent <ConstantID>() == null)
                        {
                            localParameters[i].gameObject.AddComponent <ConstantID>();
                        }
                    }
                }
                else if (assetParameters[i].parameterType == ParameterType.UnityObject)
                {
                    localParameters[i].objectValue = (Object)EditorGUILayout.ObjectField(label + ":", localParameters[i].objectValue, typeof(Object), true);
                }
            }
        }
 	void OnGUI()
 	{
 		//create an object field for the prefab/object
 		GUILayout.BeginHorizontal();
 		GameObject obj = (GameObject)EditorGUILayout.ObjectField( "Select or drop object:", mObject, typeof(GameObject), true );
 		// if something changed
 		if( obj != mObject )
 		{
 			// ignore model prefabs or
 			if( PrefabUtility.GetPrefabType( obj ) == PrefabType.ModelPrefab )
 			{
 				Debug.LogError( "ProcessMaterials, Object cannot be a model file. Please create a prefab first or select an instance from scene" );
 				mObject = null;
 			}
 			else
 			{
 				mObject = obj;
 			}
  
 			resetMaterialMap();
 		}
 		GUILayout.EndHorizontal();
  
 		GUILayout.Space( 7 );
  
 		// Material map //
 		if( mMaterialMap.Count > 0 )
 		{
 			// Create the Headings for displaying the material map
 			GUILayout.BeginHorizontal();
 			GUILayout.Label( "Current Material", GUILayout.MaxWidth( 250 ) );
 			GUILayout.Label( "Replacement" );
 			GUILayout.EndHorizontal();
  
 			//Create scroll view for the materials
 			mScrollPosition = GUILayout.BeginScrollView( mScrollPosition );
 			GUILayout.BeginVertical();
  
 			// remember user change and apply it after drawing
 			KeyValuePair<Material, Material> transition = new KeyValuePair<Material, Material>( null, null );
  
 			foreach( KeyValuePair<Material, Material> pair in mMaterialMap )
 			{
 				GUILayout.BeginHorizontal();
 				GUILayout.Label( pair.Key.name, GUILayout.MaxWidth( 250 ) );
 				Material newValue = ( (Material)EditorGUILayout.ObjectField( "", pair.Key != pair.Value ? pair.Value : null, typeof(Material), false ) );
 				GUILayout.EndHorizontal();
  
 				// although this would override previous changes in the list only one change is expected per update
 				if( ( newValue != null ) && ( newValue != pair.Value ) )
 					transition = new KeyValuePair<Material, Material>( pair.Key, newValue );
 			}
  
 			// update material map with new transition
 			if( transition.Key != null )
 				mMaterialMap[transition.Key] = transition.Value;
  
 			GUILayout.EndScrollView();
 			GUILayout.EndVertical();
  
 			GUILayout.BeginHorizontal();
  
 			// load previously saved transitions from xml file
 			if( GUILayout.Button( "Load" ) )
 				loadMaterialMap();
  
 			// save the current material map to xml file
 			if( GUILayout.Button( "Save" ) )
 				saveMaterialMap();
  
 			GUILayout.EndHorizontal();
  
 			// Buttons //
 			if( GUILayout.Button( "Apply Changes" ) ) // Save the material changes
 			{
 				applyChanges();
 				resetMaterialMap();
 			}
 		}
 	}
        void OnGUI()
        {
            //if (!HelperDemo.CheckSFExists()) return;
            // Set custom Style. Good for background color 3E619800
            if (myStyle == null)
            {
                myStyle = new CustomStyle();
            }

            if (midiStreamPlayer != null)
            {
                //GUILayout.BeginArea(new Rect(0, 0, 1080, 2280));
                scrollerWindow = GUILayout.BeginScrollView(scrollerWindow, false, false, GUILayout.Width(Screen.width));

                // If need, display the popup  before any other UI to avoid trigger it hidden
                if (HelperDemo.CheckSFExists())
                {
                    PopBankInstrument.Draw(MidiPlayerGlobal.MPTK_ListBank, MidiPlayerGlobal.ImSFCurrent.DefaultBankNumber, myStyle);
                    PopPatchInstrument.Draw(MidiPlayerGlobal.MPTK_ListPreset, CurrentPreset, myStyle);
                    PopBankDrum.Draw(MidiPlayerGlobal.MPTK_ListBank, MidiPlayerGlobal.ImSFCurrent.DrumKitBankNumber, myStyle);
                    PopPatchDrum.Draw(MidiPlayerGlobal.MPTK_ListPresetDrum, CurrentPatchDrum, myStyle);

                    MainMenu.Display("Test Midi Stream - A very simple Generated Music Stream ", myStyle);

                    // Display soundfont available and select a new one
                    GUISelectSoundFont.Display(scrollerWindow, myStyle);

                    // Select bank & Patch for Instrument
                    // ----------------------------------
                    //GUILayout.Space(spaceVertival);
                    //GUILayout.Space(spaceVertival);
                    GUILayout.BeginVertical(myStyle.BacgDemos);
                    GUILayout.BeginHorizontal();
                    GUILayout.Label("Instrument", myStyle.TitleLabel3, GUILayout.Width(widthFirstCol));

                    // Open the popup to select a bank
                    if (GUILayout.Button(MidiPlayerGlobal.ImSFCurrent.DefaultBankNumber + " - Bank", GUILayout.Width(buttonWidth)))
                    {
                        PopBankInstrument.Show = !PopBankInstrument.Show;
                    }
                    PopBankInstrument.Position(ref scrollerWindow);

                    // Open the popup to select an instrument
                    if (GUILayout.Button(
                            CurrentPreset.ToString() + " - " +
                            MidiPlayerGlobal.MPTK_GetPatchName(MidiPlayerGlobal.ImSFCurrent.DefaultBankNumber,
                                                               CurrentPreset),
                            GUILayout.Width(buttonWidth)))
                    {
                        PopPatchInstrument.Show = !PopPatchInstrument.Show;
                    }
                    PopPatchInstrument.Position(ref scrollerWindow);

                    GUILayout.EndHorizontal();

                    // Select bank & Patch for Drum
                    // ----------------------------
                    GUILayout.Space(spaceVertival);
                    GUILayout.BeginHorizontal();
                    GUILayout.Label("Drum", myStyle.TitleLabel3, GUILayout.Width(widthFirstCol));

                    // Open the popup to select a bank for drum
                    if (GUILayout.Button(MidiPlayerGlobal.ImSFCurrent.DrumKitBankNumber + " - Bank", GUILayout.Width(buttonWidth)))
                    {
                        PopBankDrum.Show = !PopBankDrum.Show;
                    }
                    PopBankDrum.Position(ref scrollerWindow);

                    // Open the popup to select an instrument for drum
                    if (GUILayout.Button(
                            CurrentPatchDrum.ToString() + " - " +
                            MidiPlayerGlobal.MPTK_GetPatchName(MidiPlayerGlobal.ImSFCurrent.DrumKitBankNumber, CurrentPatchDrum),
                            GUILayout.Width(buttonWidth)))
                    {
                        PopPatchDrum.Show = !PopPatchDrum.Show;
                    }
                    PopPatchDrum.Position(ref scrollerWindow);
                    GUILayout.EndHorizontal();
                }
                else
                {
                    GUILayout.BeginVertical(myStyle.BacgDemos);
                }

                GUILayout.Space(spaceVertival);

                HelperDemo.DisplayInfoSynth(midiStreamPlayer, 500, myStyle);

                GUILayout.Space(spaceVertival);

                GUILayout.BeginHorizontal(GUILayout.Width(350));
                GUILayout.Label("One Shot", myStyle.TitleLabel3, GUILayout.Width(widthFirstCol));
                if (GUILayout.Button("Play", myStyle.BtStandard, GUILayout.Width(buttonWidth * 0.666f)))
                {
                    Play(true);
                }

                if (GUILayout.Button("Stop", myStyle.BtStandard, GUILayout.Width(buttonWidth * 0.666f)))
                {
                    StopOneNote();
#if MPTK_PRO
                    StopChord();
#endif
                }
                if (GUILayout.Button("Clear", myStyle.BtStandard, GUILayout.Width(buttonWidth * 0.666f)))
                {
                    midiStreamPlayer.MPTK_ClearAllSound(true);
                }
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal(GUILayout.Width(500));
                CurrentNote = (int)Slider("Note", CurrentNote, 0, 127);
                int preset = (int)Slider("Preset", CurrentPreset, 0, 127, true);
                if (preset != CurrentPreset)
                {
                    CurrentPreset = preset;
                    midiStreamPlayer.MPTK_PlayEvent(new MPTKEvent()
                    {
                        Command = MPTKCommand.PatchChange,
                        Value   = CurrentPreset,
                        Channel = StreamChannel,
                    });
                }
                GUILayout.EndHorizontal();

                GUILayout.Space(spaceVertival);

                GUILayout.BeginHorizontal(GUILayout.Width(350));
                GUILayout.Label("Loop Notes", myStyle.TitleLabel3, GUILayout.Width(widthFirstCol));
                if (GUILayout.Button("Start / Stop", IsplayingLoopNotes ? myStyle.BtSelected : myStyle.BtStandard, GUILayout.Width(buttonWidth * 0.666f)))
                {
                    IsplayingLoopNotes = !IsplayingLoopNotes;
                }
                StartNote = (int)Slider("From", StartNote, 0, 127, true, 50);
                EndNote   = (int)Slider("To", EndNote, 0, 127, true, 50);
                GUILayout.EndHorizontal();

                GUILayout.Space(spaceVertival);

                GUILayout.BeginHorizontal(GUILayout.Width(350));
                GUILayout.Label("Loop Presets", myStyle.TitleLabel3, GUILayout.Width(widthFirstCol));
                if (GUILayout.Button("Start / Stop", IsplayingLoopPresets ? myStyle.BtSelected : myStyle.BtStandard, GUILayout.Width(buttonWidth * 0.666f)))
                {
                    IsplayingLoopPresets = !IsplayingLoopPresets;
                }
                StartPreset = (int)Slider("From", StartPreset, 0, 127, true, 50);
                EndPreset   = (int)Slider("To", EndPreset, 0, 127, true, 50);
                GUILayout.EndHorizontal();

                GUILayout.Space(spaceVertival);
#if DEBUG_MULTI
                GUILayout.BeginHorizontal();
                GUILayout.Label(" ", myStyle.TitleLabel3, GUILayout.Width(widthFirstCol));
                CountNoteToPlay = (int)Slider("Play Multiple Notes", CountNoteToPlay, 1, 200, false, 70);
                GUILayout.EndHorizontal();
#endif

                GUILayout.BeginHorizontal();
                GUILayout.Label(" ", myStyle.TitleLabel3, GUILayout.Width(widthFirstCol));
                //if (MidiPlayerGlobal.ImSFCurrent.DrumKitBankNumber >= 0)
                DrumKit      = GUILayout.Toggle(DrumKit, "Drum Kit", GUILayout.Width(120));
                RandomPlay   = GUILayout.Toggle(RandomPlay, "Random", GUILayout.Width(120));
                ChordPlay    = GUILayout.Toggle(ChordPlay, "Play Chord", GUILayout.Width(120));
                ChordLibPlay = GUILayout.Toggle(ChordLibPlay, "Play Chord Lib", GUILayout.Width(120));
                GUILayout.EndHorizontal();

#if MPTK_PRO
                if (ChordPlay)
                {
                    GUILayout.BeginVertical(myStyle.BacgDemos1);
                    GUILayout.BeginHorizontal();
                    GUILayout.Label("Chord from Degree", myStyle.TitleLabel3, GUILayout.Width(widthFirstCol));
                    CountNoteChord = (int)Slider("Count", CountNoteChord, 2, 17, false, 70);
                    DegreeChord    = (int)Slider("Degree", DegreeChord, 1, 7, false, 70);
                    ArpeggioPlay   = (int)Slider("Arpeggio (ms)", ArpeggioPlay, 0, 500, false, 70);
                    GUILayout.EndHorizontal();

                    GUILayout.BeginHorizontal();
                    GUILayout.Label(" ", myStyle.TitleLabel3, GUILayout.Width(widthFirstCol));
                    int range = (int)Slider("Range", RangeChord, 0, MPTKRangeLib.RangeCount - 1, false, 70);
                    if (RangeChord != range)
                    {
                        RangeChord = range;
                        midiStreamPlayer.MPTK_RangeSelected = RangeChord;
                    }
                    GUILayout.Label(midiStreamPlayer.MPTK_RangeName, myStyle.TitleLabel3, GUILayout.MaxWidth(200));
                    GUILayout.Label("See file GammeDefinition.csv in folder Resources/GeneratorTemplate", myStyle.TitleLabel3, GUILayout.Width(500));
                    GUILayout.EndHorizontal();
                    GUILayout.EndVertical();
                }

                if (ChordLibPlay)
                {
                    GUILayout.BeginVertical(myStyle.BacgDemos1);
                    GUILayout.BeginHorizontal();
                    GUILayout.Label("Chord from Lib", myStyle.TitleLabel3, GUILayout.Width(widthFirstCol));
                    CurrentChord = (int)Slider("Chord", CurrentChord, 0, MPTKChordLib.ChordCount - 1, false, 70);
                    GUILayout.Label(MPTKChordLib.Chords[CurrentChord].Name, myStyle.TitleLabel3, GUILayout.MaxWidth(200));
                    GUILayout.Label("See file ChordLib.csv in folder Resources/GeneratorTemplate", myStyle.TitleLabel3, GUILayout.Width(500));
                    GUILayout.EndHorizontal();
                    GUILayout.EndVertical();
                }
#else
                if (ChordPlay || ChordLibPlay)
                {
                    GUILayout.BeginVertical(myStyle.BacgDemos1);
                    GUILayout.Space(spaceVertival);
                    GUILayout.Label("Chord and Range are available only with MPTK PRO", myStyle.TitleLabel3);
                    GUILayout.Space(spaceVertival);
                    GUILayout.EndVertical();
                }
#endif
                GUILayout.Space(spaceVertival);

                GUILayout.BeginHorizontal(GUILayout.Width(350));
                Frequency    = Slider("Frequency", Frequency, 0.05f, 10f);
                NoteDuration = Slider("Duration", NoteDuration, -1f, 100f, true, 80);
                NoteDelay    = Slider("Delay", NoteDelay, 0f, 10f, true, 80);
                GUILayout.EndHorizontal();

                GUILayout.Space(spaceVertival);

                GUILayout.BeginHorizontal(GUILayout.Width(350));
                midiStreamPlayer.MPTK_Volume = Slider("Volume", midiStreamPlayer.MPTK_Volume, 0, 1);
                float pitchChange = Slider("Pitch", PitchChange, 0, 127, true, 80);
                if (pitchChange != PitchChange)
                {
                    LastTimePitchChange = Time.realtimeSinceStartup;
                    PitchChange         = pitchChange;
                    //Debug.Log("Slider " + PitchChange);
                    midiStreamPlayer.MPTK_PlayEvent(new MPTKEvent()
                    {
                        Command = MPTKCommand.PitchWheelChange, Value = (int)PitchChange << 7, Channel = StreamChannel
                    });
                }

                GUILayout.EndHorizontal();

                GUILayout.Space(spaceVertival);

                GUILayout.BeginHorizontal(GUILayout.Width(350));
                midiStreamPlayer.MPTK_Transpose = (int)Slider("Transpose", midiStreamPlayer.MPTK_Transpose, -24, 24);
                GUILayout.Space(spaceHorizontal);
                Velocity = (int)Slider("Velocity", (int)Velocity, 0f, 127f, true, 80);
                GUILayout.EndHorizontal();

                GUILayout.Space(spaceVertival);

                GUILayout.BeginHorizontal(GUILayout.Width(350));
                int panChange = (int)Slider("Panoramic", PanChange, 0, 127);
                if (panChange != PanChange)
                {
                    PanChange = panChange;
                    midiStreamPlayer.MPTK_PlayEvent(new MPTKEvent()
                    {
                        Command = MPTKCommand.ControlChange, Controller = MPTKController.Pan, Value = PanChange, Channel = StreamChannel
                    });
                }
                //GUILayout.Space(spaceHorizontal);
                //midiStreamPlayer.ReverbMix = Slider("Reverb", midiStreamPlayer.ReverbMix, 0, 1, true, 80);
                //GUILayout.EndHorizontal();

                GUILayout.Space(spaceVertival);

                GUILayout.BeginHorizontal(GUILayout.Width(350));
                int modChange = (int)Slider("Modulation", ModChange, 0, 127);
                if (modChange != ModChange)
                {
                    ModChange = modChange;
                    midiStreamPlayer.MPTK_PlayEvent(new MPTKEvent()
                    {
                        Command = MPTKCommand.ControlChange, Controller = MPTKController.Modulation, Value = ModChange, Channel = StreamChannel
                    });
                }
                GUILayout.Space(spaceHorizontal);
                int expChange = (int)Slider("Expression", ExpChange, 0, 127, true, 80);
                if (expChange != ExpChange)
                {
                    ExpChange = expChange;
                    midiStreamPlayer.MPTK_PlayEvent(new MPTKEvent()
                    {
                        Command = MPTKCommand.ControlChange, Controller = MPTKController.Expression, Value = ExpChange, Channel = StreamChannel
                    });
                }
                GUILayout.EndHorizontal();

                GUILayout.Space(spaceVertival);

                //GUILayout.BeginHorizontal(GUILayout.Width(350));
                //GUILayout.Label(" ", myStyle.TitleLabel3, GUILayout.Width(widthFirstCol));
                //midiStreamPlayer.MPTK_WeakDevice = GUILayout.Toggle(midiStreamPlayer.MPTK_WeakDevice, "Weak Device", GUILayout.Width(widthLabel));
                //GUILayout.EndHorizontal();


                // end zone des parametres
                GUILayout.EndVertical();

                GUILayout.Space(spaceVertival);

                GUILayout.BeginVertical(myStyle.BacgDemos);
                GUILayout.Label("Go to your Hierarchy, select GameObject MidiStreamPlayer: inspector contains a lot of parameters to control the sound.", myStyle.TitleLabel2);
                GUILayout.EndVertical();

                GUILayout.EndScrollView();
            }
            else
            {
                GUILayout.Space(spaceVertival);
                GUILayout.Label("MidiStreamPlayer not defined, check hierarchy.", myStyle.TitleLabel3);
            }
            //GUILayout.EndArea();
        }
Exemple #27
0
        void OnGUI()
        {
            DoContextMenu();

            GUILayout.Label("Quick Material", EditorStyles.boldLabel);
            Rect r = GUILayoutUtility.GetLastRect();
            int left = Screen.width - 68;

            GUILayout.BeginHorizontal(GUILayout.MaxWidth(Screen.width - 74));
            GUILayout.BeginVertical();

            m_QueuedMaterial = (Material)EditorGUILayout.ObjectField(m_QueuedMaterial, typeof(Material), true);

            GUILayout.Space(2);

            if (GUILayout.Button("Apply (Ctrl+Shift+Click)"))
                ApplyMaterial(MeshSelection.topInternal, m_QueuedMaterial);

            GUI.enabled = editor != null && MeshSelection.selectedFaceCount > 0;
            if (GUILayout.Button("Match Selection"))
            {
                m_QueuedMaterial = EditorMaterialUtility.GetActiveSelection();
            }
            GUI.enabled = true;

            GUILayout.EndVertical();

            GUI.Box(new Rect(left, r.y + r.height + 2, 64, 64), "");

            var previewTexture = EditorMaterialUtility.GetPreviewTexture(m_QueuedMaterial);

            if (previewTexture != null)
            {
                GUI.Label(new Rect(left + 2, r.y + r.height + 4, 60, 60), previewTexture);
            }
            else
            {
                GUI.Box(new Rect(left + 2, r.y + r.height + 4, 60, 60), "");
                GUI.Label(new Rect(left + 2, r.height + 28, 120, 32), "None\n(Texture)");
            }

            GUILayout.EndHorizontal();

            GUILayout.Space(4);

            GUI.backgroundColor = PreferenceKeys.proBuilderDarkGray;
            UI.EditorGUIUtility.DrawSeparator(2);
            GUI.backgroundColor = Color.white;

            GUILayout.Label("Material Palette", EditorStyles.boldLabel);

            EditorGUI.BeginChangeCheck();

            m_CurrentPaletteIndex = EditorGUILayout.Popup("", m_CurrentPaletteIndex, m_AvailablePalettes_Str);

            if (EditorGUI.EndChangeCheck())
            {
                MaterialPalette newPalette = null;

                // Add a new material palette
                if (m_CurrentPaletteIndex >= m_AvailablePalettes.Length)
                {
                    string path = AssetDatabase.GenerateUniqueAssetPath("Assets/Material Palette.asset");
                    newPalette = FileUtility.LoadRequired<MaterialPalette>(path);
                    EditorGUIUtility.PingObject(newPalette);
                }
                else
                {
                    newPalette = m_AvailablePalettes[m_CurrentPaletteIndex];
                }

                SetMaterialPalette(newPalette);
            }

            EditorGUI.BeginChangeCheck();
            s_CurrentPalette = (MaterialPalette)EditorGUILayout.ObjectField(s_CurrentPalette, typeof(MaterialPalette), false);
            if (EditorGUI.EndChangeCheck())
                SetMaterialPalette(s_CurrentPalette);

            GUILayout.Space(4);

            Material[] materials = CurrentPalette;

            m_ViewScroll = GUILayout.BeginScrollView(m_ViewScroll);

            for (int i = 0; i < materials.Length; i++)
            {
                if (i == 10)
                {
                    GUILayout.Space(2);
                    GUI.backgroundColor = PreferenceKeys.proBuilderLightGray;
                    UI.EditorGUIUtility.DrawSeparator(1);
                    GUI.backgroundColor = Color.white;
                    GUILayout.Space(2);
                }

                GUILayout.BeginHorizontal();
                if (i < 10)
                {
                    if (GUILayout.Button("Alt + " + (i == 9 ? 0 : (i + 1)).ToString(), EditorStyles.miniButton, GUILayout.MaxWidth(58)))
                        ApplyMaterial(MeshSelection.topInternal, materials[i]);
                }
                else
                {
                    if (GUILayout.Button("Apply", EditorStyles.miniButtonLeft, GUILayout.MaxWidth(44)))
                        ApplyMaterial(MeshSelection.topInternal, materials[i]);

                    GUI.backgroundColor = Color.red;
                    if (GUILayout.Button("", EditorStyles.miniButtonRight, GUILayout.MaxWidth(14)))
                    {
                        Material[] temp = new Material[materials.Length - 1];
                        System.Array.Copy(materials, 0, temp, 0, materials.Length - 1);
                        materials = temp;
                        SaveUserMaterials(materials);
                        return;
                    }
                    GUI.backgroundColor = Color.white;
                }

                EditorGUI.BeginChangeCheck();
                materials[i] = (Material)EditorGUILayout.ObjectField(materials[i], typeof(Material), false);
                if (EditorGUI.EndChangeCheck())
                    SaveUserMaterials(materials);

                GUILayout.EndHorizontal();
            }


            if (GUILayout.Button("Add"))
            {
                Material[] temp = new Material[materials.Length + 1];
                System.Array.Copy(materials, 0, temp, 0, materials.Length);
                materials = temp;
                SaveUserMaterials(materials);
            }

            GUILayout.EndScrollView();
        }
Exemple #28
0
        void DrawAttributes()
        {
            try
            {
                GUILayout.BeginVertical("box");
                GUILayout.Box("Attributes", GUILayout.ExpandWidth(true));
                EditorGUILayout.Space();
                if (!inAddAttribute && GUILayout.Button("Add Attribute", EditorStyles.miniButton))
                {
                    inAddAttribute = true;
                }
                if (inAddAttribute)
                {
                    GUILayout.BeginHorizontal("box");
                    attribute = (vItemAttributes)EditorGUILayout.EnumPopup(attribute);
                    EditorGUILayout.LabelField("Value", GUILayout.MinWidth(60));
                    attributeValue = EditorGUILayout.IntField(attributeValue);
                    GUILayout.EndHorizontal();
                    if (item.attributes != null && item.attributes.Contains(attribute))
                    {
                        EditorGUILayout.HelpBox("This attribute already exist ", MessageType.Error);
                        if (GUILayout.Button("Cancel", EditorStyles.miniButton, GUILayout.MinWidth(60)))
                        {
                            inAddAttribute = false;
                        }
                    }
                    else
                    {
                        GUILayout.BeginHorizontal("box");
                        if (GUILayout.Button("Add", EditorStyles.miniButton, GUILayout.MinWidth(60)))
                        {
                            item.attributes.Add(new vItemAttribute(attribute, attributeValue));

                            attributeValue = 0;
                            inAddAttribute = false;
                        }
                        if (GUILayout.Button("Cancel", EditorStyles.miniButton, GUILayout.MinWidth(60)))
                        {
                            attributeValue = 0;
                            inAddAttribute = false;
                        }
                        GUILayout.EndHorizontal();
                    }
                }
                EditorGUILayout.Space();
                var attributesProp = serializedObject.FindProperty("attributes");
                for (int i = 0; i < item.attributes.Count; i++)
                {
                    GUILayout.BeginHorizontal("box");
                    var attributeValue = attributesProp.GetArrayElementAtIndex(i).FindPropertyRelative("value");
                    attributeValue.serializedObject.Update();
                    EditorGUILayout.LabelField(item.attributes[i].name.ToString(), GUILayout.MinWidth(60));
                    EditorGUILayout.PropertyField(attributeValue, new GUIContent(""));
                    //item.attributes[i].value = EditorGUILayout.IntField(item.attributes[i].value);

                    EditorGUILayout.Space();
                    if (GUILayout.Button("x", GUILayout.MaxWidth(30)))
                    {
                        item.attributes.RemoveAt(i);
                        GUILayout.EndHorizontal();

                        break;
                    }
                    attributeValue.serializedObject.ApplyModifiedProperties();
                    GUILayout.EndHorizontal();
                }

                GUILayout.EndVertical();
            }
            catch { }
        }
        public void OnGUI()
        {
            GUILayout.BeginVertical("box");
            GUILayout.BeginHorizontal();
            bool oldUseCustomDataPath = m_UseCustomDataPath;

            m_UseCustomDataPath = EditorGUILayout.Toggle(m_UseCustomDataPathContent, m_UseCustomDataPath);
            if (oldUseCustomDataPath != m_UseCustomDataPath)
            {
                EditorPrefs.SetBool(k_UseCustomDataPathKey, m_UseCustomDataPath);
            }
            if (GUILayout.Button("Open Folder"))
            {
                EditorUtility.RevealInFinder(m_DataPath);
            }
            GUILayout.EndHorizontal();

            if (!m_UseCustomDataPath)
            {
                m_DataPath = Application.persistentDataPath;
            }
            else
            {
                string oldDataPath = m_DataPath;
                m_DataPath = EditorGUILayout.TextField(m_DataPathContent, m_DataPath);
                if (string.IsNullOrEmpty(m_DataPath))
                {
                    m_DataPath = Application.persistentDataPath;
                }
                if (oldDataPath != m_DataPath)
                {
                    EditorPrefs.SetString(k_DataPathKey, m_DataPath);
                }
            }

            m_Aggregator.SetDataPath(m_DataPath);

            GUILayout.BeginHorizontal();
            EditorGUILayout.LabelField(m_DatesContent, GUILayout.Width(35));
            m_StartDate = EditorGUILayout.TextField(m_StartDate);
            EditorGUILayout.LabelField("-", GUILayout.Width(10));
            m_EndDate = EditorGUILayout.TextField(m_EndDate);
            GUILayout.EndHorizontal();


            // SMOOTHERS (SPACE, ROTATION, TIME)
            GUILayout.BeginVertical("box");
            GUILayout.Label("Smooth/Unionize", EditorStyles.boldLabel);
            GUILayout.BeginHorizontal();
            // SPACE
            SmootherControl(ref m_SmoothSpaceToggle, ref m_Space, "Space", "Divider to smooth out x/y/z data", k_SmoothSpaceKey, k_SpaceKey, 2);
            // ROTATION
            SmootherControl(ref m_SmoothRotationToggle, ref m_Rotation, "Rotation", "Divider to smooth out angular data", k_SmoothRotationKey, k_RotationKey);
            // TIME
            SmootherControl(ref m_SmoothTimeToggle, ref m_Time, "Time", "Divider to smooth out passage of game time", k_SmoothTimeKey, k_KeyToTime);
            GUILayout.EndHorizontal();
            GUILayout.EndVertical();

            // SEPARATION
            GUILayout.Label("Separate", EditorStyles.boldLabel);
            GUILayout.BeginHorizontal();
            GroupControl(ref m_SeparateUsers,
                         "Users", "Separate each user into their own list. NOTE: Separating user IDs can be quite slow!",
                         k_SeparateUsersKey);
            GroupControl(ref m_SeparateSessions,
                         "Sessions", "Separate each session into its own list. NOTE: Separating unique sessions can be astonishly slow!",
                         k_SeparateSessionKey);
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            GroupControl(ref m_SeparateDebug,
                         "Is Debug", "Separate debug devices from non-debug devices",
                         k_SeparateDebugKey);
            GroupControl(ref m_SeparatePlatform,
                         "Platform", "Separate data based on platform",
                         k_SeparatePlatformKey);
            GUILayout.EndHorizontal();


            GroupControl(ref m_SeparateCustomField,
                         "On Custom Field", "Separate based on one or more parameter fields",
                         k_SeparateCustomKey);


            if (m_SeparateCustomField)
            {
                string oldArbitraryFieldsString = string.Join("|", m_ArbitraryFields.ToArray());
                if (m_ArbitraryFields.Count == 0)
                {
                    m_ArbitraryFields.Add("Field name");
                }
                for (var a = 0; a < m_ArbitraryFields.Count; a++)
                {
                    GUILayout.BeginHorizontal();
                    if (GUILayout.Button("-", GUILayout.MaxWidth(20f)))
                    {
                        m_ArbitraryFields.RemoveAt(a);
                        break;
                    }
                    m_ArbitraryFields[a] = EditorGUILayout.TextField(m_ArbitraryFields[a]);
                    if (a == m_ArbitraryFields.Count - 1 && GUILayout.Button(m_AddFieldContent))
                    {
                        m_ArbitraryFields.Add("Field name");
                    }
                    GUILayout.EndHorizontal();
                }
                string currentArbitraryFieldsString = string.Join("|", m_ArbitraryFields.ToArray());
                if (oldArbitraryFieldsString != currentArbitraryFieldsString)
                {
                    EditorPrefs.SetString(k_ArbitraryFieldsKey, currentArbitraryFieldsString);
                }
            }
            GUILayout.EndVertical();

            GUILayout.BeginVertical("Box");
            bool oldRemapColor = m_RemapColor;

            m_RemapColor = EditorGUILayout.Toggle(m_RemapColorContent, m_RemapColor);
            if (oldRemapColor != m_RemapColor)
            {
                EditorPrefs.SetBool(k_RemapColorKey, m_RemapColor);
            }
            if (m_RemapColor)
            {
                string oldRemapField  = m_RemapColorField;
                int    oldOptionIndex = m_RemapOptionIndex;
                m_RemapColorField  = EditorGUILayout.TextField(m_RemapColorFieldContent, m_RemapColorField);
                m_RemapOptionIndex = EditorGUILayout.Popup(m_RemapOptionIndexContent, m_RemapOptionIndex, m_RemapOptions);

                if (m_RemapOptionIds[m_RemapOptionIndex] == AggregationMethod.Percentile)
                {
                    m_Percentile = Mathf.Clamp(EditorGUILayout.FloatField(m_PercentileContent, m_Percentile), 0, 100f);
                }
                if (oldRemapField != m_RemapColorField)
                {
                    EditorPrefs.SetString(k_RemapColorFieldKey, m_RemapColorField);
                }
                if (oldOptionIndex != m_RemapOptionIndex)
                {
                    EditorPrefs.SetInt(k_RemapOptionIndexKey, m_RemapOptionIndex);
                }
            }
            GUILayout.EndVertical();
        }
    protected virtual void DisplayInspectorGUI()
    {
        JellySprite targetObject = this.target as JellySprite;

        if (targetObject.renderer != null)
        {
            string sortingLayerName = SortingLayerNamePopup("Sorting Layer", targetObject.renderer.sortingLayerName);

            if (sortingLayerName != targetObject.renderer.sortingLayerName)
            {
                targetObject.renderer.sortingLayerName = sortingLayerName;
            }

            int sortingOrder = EditorGUILayout.IntField("Order In Layer", targetObject.renderer.sortingOrder);

            if (sortingOrder != targetObject.renderer.sortingOrder)
            {
                targetObject.renderer.sortingOrder = sortingOrder;
            }
        }

        EditorGUILayout.PropertyField(m_FlipX, new GUIContent("Flip Horizontal"));
        EditorGUILayout.PropertyField(m_FlipY, new GUIContent("Flip Vertical"));

        if (Application.isPlaying)
        {
            GUI.enabled = false;
        }

        EditorGUILayout.PropertyField(m_SpriteScale, new GUIContent("Sprite Scale"));

        GUI.enabled = true;

        if (Application.isPlaying)
        {
            GUI.enabled = false;
        }

        GUILayout.Space(15);

        EditorGUILayout.PropertyField(m_PhysicsMode, new GUIContent("Use 2D Physics"));

        JellySprite.PhysicsStyle selectedStyle = (JellySprite.PhysicsStyle)m_PhysicsStyle.enumValueIndex;

        if (selectedStyle != JellySprite.PhysicsStyle.Grid)
        {
            EditorGUILayout.PropertyField(m_AttachNeighbors, new GUIContent("Attach Neighbors"));
        }

        int initialStyle = m_PhysicsStyle.enumValueIndex;

        EditorGUILayout.PropertyField(m_PhysicsStyle, new GUIContent("Body Configuration"));

        if (m_PhysicsStyle.enumValueIndex != initialStyle && (JellySprite.PhysicsStyle)m_PhysicsStyle.enumValueIndex == JellySprite.PhysicsStyle.Free)
        {
            m_PhysicsStyle.enumValueIndex = initialStyle;
            Debug.LogError("Please use the 'Copy Configuration to Free Mode' button to switch Jelly Sprites to Free Mode");
        }

        switch (selectedStyle)
        {
        case JellySprite.PhysicsStyle.Circle:
            EditorGUILayout.IntSlider(m_CircleRadiusPoints, 8, 128, new GUIContent("Num Colliders"));
            break;

        case JellySprite.PhysicsStyle.Grid:
            m_GridRows.intValue    = EditorGUILayout.IntField("Grid Rows", m_GridRows.intValue);
            m_GridColumns.intValue = EditorGUILayout.IntField("Grid Columns", m_GridColumns.intValue);
            break;

        case JellySprite.PhysicsStyle.Rectangle:
            break;

        case JellySprite.PhysicsStyle.Triangle:
            break;

        case JellySprite.PhysicsStyle.Free:
            for (int i = 0; i < targetObject.m_FreeModeBodyPositions.Count; i++)
            {
                EditorGUILayout.BeginHorizontal();
                Vector2 point     = targetObject.m_FreeModeBodyPositions[i];
                float   radius    = targetObject.m_FreeModeBodyRadii[i];
                bool    kinematic = targetObject.m_FreeModeBodyKinematic[i];

                Vector3 result          = EditorGUILayout.Vector3Field(i == 0? "Centre" : "Body " + i.ToString(), new Vector3(point.x, point.y, radius), GUILayout.MaxWidth(1500f));
                Vector2 positionResult  = new Vector2(result.x, result.y);
                bool    kinematicResult = false;

                if (point != positionResult)
                {
                    Undo.RecordObject(targetObject, "Adjusted Jelly Sprite Body Position");
                    targetObject.m_FreeModeBodyPositions[i] = positionResult;
                    SceneView.RepaintAll();
                }

                if (result.z != radius)
                {
                    Undo.RecordObject(targetObject, "Adjusted Jelly Sprite Body Radius");
                    targetObject.m_FreeModeBodyRadii[i] = result.z;
                    SceneView.RepaintAll();
                }

                using (new FixedWidthLabel("Kinematic"))
                {
                    kinematicResult = EditorGUILayout.Toggle(kinematic);
                }

                if (kinematicResult != kinematic)
                {
                    Undo.RecordObject(targetObject, "Adjusted Jelly Sprite Body Kinematic Flag");
                    targetObject.m_FreeModeBodyKinematic[i] = kinematicResult;
                    SceneView.RepaintAll();
                }

                if (GUILayout.Button(new GUIContent("Delete", "delete this point"), EditorStyles.miniButtonRight, GUILayout.MaxWidth(100f)))
                {
                    if (i == 0)
                    {
                        Debug.LogWarning("Cannot remove central Jelly Sprite control point!");
                    }
                    else
                    {
                        Undo.RecordObject(targetObject, "Deleted Jelly Sprite Body");
                        targetObject.m_FreeModeBodyPositions.RemoveAt(i);
                        targetObject.m_FreeModeBodyRadii.RemoveAt(i);
                        SceneView.RepaintAll();
                        i--;
                    }
                }

                EditorGUILayout.EndHorizontal();
            }

            GUILayout.Space(5);

            if (GUILayout.Button(new GUIContent("Add New Body", "Add new body"), EditorStyles.miniButtonLeft))
            {
                Undo.RecordObject(targetObject, "Added New Jelly Sprite Body");
                targetObject.m_FreeModeBodyPositions.Add(new Vector2(0.0f, -1.0f));
                targetObject.m_FreeModeBodyRadii.Add(1.0f);
                targetObject.m_FreeModeBodyKinematic.Add(false);
                SceneView.RepaintAll();
            }

            break;
        }

        if (selectedStyle != JellySprite.PhysicsStyle.Free)
        {
            EditorGUILayout.Slider(m_ColliderRadius, 0.001f, 0.25f, new GUIContent("Collider Radius"));
            EditorGUILayout.PropertyField(m_SoftBodyScale, new GUIContent("Collider Scale"));

            GUILayout.Space(5);

            if (GUILayout.Button(new GUIContent("Copy Configuration To Free Mode", "Copy this configuration to the free mode layout"), EditorStyles.miniButtonRight))
            {
                Undo.RecordObject(target, "Converted Jelly Sprite to Free Mode");
                targetObject.OnCopyToFreeModeSelected();
                SceneView.RepaintAll();
            }
        }

        GUI.enabled = true;

        EditorGUILayout.PropertyField(m_LockRotation, new GUIContent("Lock Rotation"));

        if (selectedStyle != JellySprite.PhysicsStyle.Free)
        {
            EditorGUILayout.PropertyField(m_CentralBodyKinematic, new GUIContent("Kinematic Central Body"));
        }

        GUILayout.Space(15);

        if (m_PhysicsMode.boolValue)
        {
            EditorGUILayout.PropertyField(m_PhysicsMaterial2D, new GUIContent("Physics Material"));
            m_GravityScale.floatValue = EditorGUILayout.FloatField("Gravity Scale", m_GravityScale.floatValue);
            EditorGUILayout.PropertyField(m_CollideConnected, new GUIContent("Collide Connected"));
        }
        else
        {
            EditorGUILayout.PropertyField(m_PhysicsMaterial, new GUIContent("Physics Material"));
            m_Drag.floatValue        = EditorGUILayout.FloatField("Drag", m_Drag.floatValue);
            m_AngularDrag.floatValue = EditorGUILayout.FloatField("Angular Drag", m_AngularDrag.floatValue);
        }

        m_Stiffness.floatValue    = EditorGUILayout.FloatField("Spring Stiffness", m_Stiffness.floatValue);
        m_DampingRatio.floatValue = EditorGUILayout.FloatField("Spring Damping", m_DampingRatio.floatValue);
        EditorGUILayout.PropertyField(m_MassStyle, new GUIContent("Mass Type"));
        m_Mass.floatValue = EditorGUILayout.FloatField("Mass", m_Mass.floatValue);

        GUILayout.Space(15);

        if (Application.isPlaying)
        {
            GUI.enabled = false;
        }

        EditorGUILayout.Slider(m_DistanceExponent, 1.0f, 4.0f, new GUIContent("Ctrl Point Influence"));

        GUI.enabled = true;

        EditorGUILayout.IntSlider(m_VertexDensity, 2, 100, new GUIContent("Vertex Density"));

        GUILayout.Space(15);

        m_NumAttachPoints.intValue = EditorGUILayout.IntField("Num Attach Points", m_NumAttachPoints.intValue);

        for (int loop = 0; loop < targetObject.m_AttachPoints.Length; loop++)
        {
            targetObject.m_AttachPoints[loop] = (Transform)EditorGUILayout.ObjectField("Attach Point", targetObject.m_AttachPoints[loop], typeof(Transform), true, null);
        }
    }