private void DropAreaGUI(Rect dropArea)
    {
        var evt = Event.current;

        if (evt.type == EventType.DragUpdated)
        {
            if (dropArea.Contains(evt.mousePosition))
            {
                DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
            }
        }

        if (evt.type == EventType.DragPerform)
        {
            if (dropArea.Contains(evt.mousePosition))
            {
                DragAndDrop.AcceptDrag();

                UnityEngine.Object[] draggedObjects = DragAndDrop.objectReferences as UnityEngine.Object[];
                var slots    = new List <SlotData>();
                var overlays = new List <OverlayData>();

                for (int i = 0; i < draggedObjects.Length; i++)
                {
                    if (draggedObjects[i])
                    {
                        SlotData tempSlotData = draggedObjects[i] as SlotData;
                        if (tempSlotData)
                        {
                            slots.Add(tempSlotData);
                        }

                        OverlayData tempOverlayData = draggedObjects[i] as OverlayData;
                        if (tempOverlayData)
                        {
                            overlays.Add(tempOverlayData);
                        }
                    }
                }
                if (slots.Count > 0 && overlays.Count > 0)
                {
                    var randomSet        = target as UMACrowdRandomSet;
                    var crowdSlotElement = new UMACrowdRandomSet.CrowdSlotElement();
                    crowdSlotElement.possibleSlots = new UMACrowdRandomSet.CrowdSlotData[slots.Count];
                    for (int i = 0; i < slots.Count; i++)
                    {
                        var crowdSlotData = new UMACrowdRandomSet.CrowdSlotData();
                        crowdSlotData.slotID          = slots[i].slotName;
                        crowdSlotData.overlayElements = new UMACrowdRandomSet.CrowdOverlayElement[overlays.Count];
                        for (int j = 0; j < overlays.Count; j++)
                        {
                            var crowdOverlayElement = new UMACrowdRandomSet.CrowdOverlayElement();
                            crowdOverlayElement.possibleOverlays = new UMACrowdRandomSet.CrowdOverlayData[]
                            {
                                new UMACrowdRandomSet.CrowdOverlayData()
                                {
                                    maxRGB = Color.white, minRGB = Color.white, overlayID = overlays[j].overlayName
                                }
                            };
                            crowdSlotData.overlayElements[j] = crowdOverlayElement;
                        }
                        crowdSlotElement.possibleSlots[i] = crowdSlotData;
                    }
                    Undo.RecordObject(randomSet, "Drag and Drop into RandomSet");
                    ArrayUtility.Add(ref randomSet.data.slotElements, crowdSlotElement);
                    EditorUtility.SetDirty(randomSet);
                }
            }
        }
    }
        public void OnInspectorGUI()
        {
            GUILayout.BeginVertical("box");
            {
                EditorGUILayout.LabelField("Prefabs", GUIStyles.BoxTitleStyle);

                #region template drop targets
                GUILayout.BeginHorizontal();
                {
                    GUILayout.BeginVertical();
                    {
                        // change background color in case there are no prefabs yet
                        if (editorTarget.prefabSettingsList.Count == 0)
                        {
                            EditorGUILayout.HelpBox("Drop prefabs on the prefab template boxes in order to use them.", MessageType.Info);

                            editor.SetErrorBackgroundColor();
                        }

                        int gridRows = Mathf.CeilToInt((float)templateCollection.templates.Count / Constants.PrefabTemplateGridColumnCount);

                        for (int row = 0; row < gridRows; row++)
                        {
                            GUILayout.BeginHorizontal();
                            {
                                for (int column = 0; column < Constants.PrefabTemplateGridColumnCount; column++)
                                {
                                    int index = column + row * Constants.PrefabTemplateGridColumnCount;

                                    PrefabSettingsTemplate template = index < templateCollection.templates.Count ? templateCollection.templates[index] : defaultTemplate;

                                    // drop area
                                    Rect prefabDropArea = GUILayoutUtility.GetRect(0.0f, 34.0f, GUIStyles.DropAreaStyle, GUILayout.ExpandWidth(true));

                                    bool hasDropArea = index < templateCollection.templates.Count;
                                    if (hasDropArea)
                                    {
                                        // drop area box with background color and info text
                                        GUI.color = GUIStyles.DropAreaBackgroundColor;
                                        GUI.Box(prefabDropArea, template.templateName, GUIStyles.DropAreaStyle);
                                        GUI.color = GUIStyles.DefaultBackgroundColor;

                                        Event evt = Event.current;
                                        switch (evt.type)
                                        {
                                        case EventType.DragUpdated:
                                        case EventType.DragPerform:

                                            if (prefabDropArea.Contains(evt.mousePosition))
                                            {
                                                DragAndDrop.visualMode = DragAndDropVisualMode.Copy;

                                                if (evt.type == EventType.DragPerform)
                                                {
                                                    DragAndDrop.AcceptDrag();

                                                    // list of new prefabs that should be created via drag/drop
                                                    // we can't do it in the drag/drop code itself, we'd get exceptions like
                                                    //   ArgumentException: Getting control 12's position in a group with only 12 controls when doing dragPerform. Aborting
                                                    // followed by
                                                    //   Unexpected top level layout group! Missing GUILayout.EndScrollView/EndVertical/EndHorizontal? UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)
                                                    // they must be added when everything is done (currently at the end of this method)
                                                    editor.newDraggedPrefabs = new List <PrefabSettings>();

                                                    foreach (Object droppedObject in DragAndDrop.objectReferences)
                                                    {
                                                        // allow only prefabs
                                                        if (PrefabUtility.GetPrefabAssetType(droppedObject) == PrefabAssetType.NotAPrefab)
                                                        {
                                                            Debug.Log("Not a prefab: " + droppedObject);
                                                            continue;
                                                        }

                                                        // add the prefab to the list using the template
                                                        AddPrefab(droppedObject as GameObject, template);
                                                    }
                                                }
                                            }
                                            break;
                                        }
                                    }
                                }
                            }
                            GUILayout.EndHorizontal();
                        }

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

                #endregion template drop targets

                if (editorTarget.prefabSettingsList.Count > 0)
                {
                    EditorGUILayout.Space();
                }

                for (int i = 0; i < editorTarget.prefabSettingsList.Count; i++)
                {
                    // horizontal separator
                    editor.AddGUISeparator(i == 0 ? 0f : 10f, 10f);

                    PrefabSettings prefabSettings = this.editorTarget.prefabSettingsList[i];

                    GUILayout.BeginHorizontal();
                    {
                        // preview

                        // try to get the asset preview
                        Texture2D previewTexture = AssetPreview.GetAssetPreview(prefabSettings.prefab);

                        // if no asset preview available, try to get the mini thumbnail
                        if (!previewTexture)
                        {
                            previewTexture = AssetPreview.GetMiniThumbnail(prefabSettings.prefab);
                        }

                        // if a preview is available, paint it
                        if (previewTexture)
                        {
                            //GUILayout.Label(previewTexture, EditorStyles.objectFieldThumb, GUILayout.Width(50), GUILayout.Height(50)); // without border, but with size
                            GUILayout.Label(previewTexture, GUILayout.Width(50), GUILayout.Height(50)); // without border, but with size

                            //GUILayout.Box(previewTexture); // with border
                            //GUILayout.Label(previewTexture); // no border
                            //GUILayout.Box(previewTexture, GUILayout.Width(50), GUILayout.Height(50)); // with border and size
                            //EditorGUI.DrawPreviewTexture(new Rect(25, 60, 100, 100), previewTexture); // draws it in absolute coordinates
                        }

                        // right align the buttons
                        GUILayout.FlexibleSpace();

                        if (GUILayout.Button("Add", EditorStyles.miniButton))
                        {
                            this.editorTarget.prefabSettingsList.Insert(i + 1, new PrefabSettings());
                        }
                        if (GUILayout.Button("Duplicate", EditorStyles.miniButton))
                        {
                            PrefabSettings newPrefabSettings = prefabSettings.Clone();
                            this.editorTarget.prefabSettingsList.Insert(i + 1, newPrefabSettings);
                        }
                        if (GUILayout.Button("Reset", EditorStyles.miniButton))
                        {
                            // remove existing
                            this.editorTarget.prefabSettingsList.RemoveAt(i);

                            // add new
                            this.editorTarget.prefabSettingsList.Insert(i, new PrefabSettings());
                        }
                        if (GUILayout.Button("Remove", EditorStyles.miniButton))
                        {
                            this.editorTarget.prefabSettingsList.Remove(prefabSettings);
                        }
                    }
                    GUILayout.EndHorizontal();

                    GUILayout.Space(4);

                    prefabSettings.prefab = (GameObject)EditorGUILayout.ObjectField("Prefab", prefabSettings.prefab, typeof(GameObject), true);

                    prefabSettings.active      = EditorGUILayout.Toggle("Active", prefabSettings.active);
                    prefabSettings.probability = EditorGUILayout.Slider("Probability", prefabSettings.probability, 0, 1);

                    // scale
                    if (editorTarget.brushSettings.distribution == BrushSettings.Distribution.Fluent)
                    {
                        // use the brush scale, hide the change scale option
                    }
                    else
                    {
                        prefabSettings.changeScale = EditorGUILayout.Toggle("Change Scale", prefabSettings.changeScale);

                        if (prefabSettings.changeScale)
                        {
                            prefabSettings.scaleMin = EditorGUILayout.FloatField("Scale Min", prefabSettings.scaleMin);
                            prefabSettings.scaleMax = EditorGUILayout.FloatField("Scale Max", prefabSettings.scaleMax);
                        }
                    }
                    // position
                    prefabSettings.positionOffset = EditorGUILayout.Vector3Field("Position Offset", prefabSettings.positionOffset);

                    // rotation
                    prefabSettings.rotationOffset = EditorGUILayout.Vector3Field("Rotation Offset", prefabSettings.rotationOffset);
                    GUILayout.BeginHorizontal();
                    {
                        prefabSettings.randomRotation = EditorGUILayout.Toggle("Random Rotation", prefabSettings.randomRotation);

                        // right align the buttons
                        GUILayout.FlexibleSpace();

                        if (GUILayout.Button("X", EditorStyles.miniButton))
                        {
                            QuickRotationSetting(prefabSettings, 1f, 0f, 0f);
                        }
                        if (GUILayout.Button("Y", EditorStyles.miniButton))
                        {
                            QuickRotationSetting(prefabSettings, 0f, 1f, 0f);
                        }
                        if (GUILayout.Button("Z", EditorStyles.miniButton))
                        {
                            QuickRotationSetting(prefabSettings, 0f, 0f, 1f);
                        }
                        if (GUILayout.Button("XYZ", EditorStyles.miniButton))
                        {
                            QuickRotationSetting(prefabSettings, 1f, 1f, 1f);
                        }
                    }
                    GUILayout.EndHorizontal();

                    // rotation limits
                    if (prefabSettings.randomRotation)
                    {
                        EditorGuiUtilities.MinMaxEditor("  Rotation Limit X", ref prefabSettings.rotationMinX, ref prefabSettings.rotationMaxX, 0, 360);
                        EditorGuiUtilities.MinMaxEditor("  Rotation Limit Y", ref prefabSettings.rotationMinY, ref prefabSettings.rotationMaxY, 0, 360);
                        EditorGuiUtilities.MinMaxEditor("  Rotation Limit Z", ref prefabSettings.rotationMinZ, ref prefabSettings.rotationMaxZ, 0, 360);
                    }

                    // VS Pro Id
#if VEGETATION_STUDIO_PRO
                    EditorGUI.BeginDisabledGroup(true);
                    EditorGUILayout.TextField("Asset GUID", prefabSettings.assetGUID);
                    EditorGUILayout.TextField("VSPro Id", prefabSettings.vspro_VegetationItemID);
                    EditorGUI.EndDisabledGroup();
#endif
                }
            }

            GUILayout.EndVertical();
        }
Example #3
0
        public override void OnInspectorGUI()
        {
            var proCamera2D = (ProCamera2D)target;

            serializedObject.Update();


            EditorGUILayout.Space();

            // Draw User Guide link
            if (ProCamera2DEditorResources.UserGuideIcon != null)
            {
                var rect = GUILayoutUtility.GetRect(0f, 0f);
                rect.width  = ProCamera2DEditorResources.UserGuideIcon.width;
                rect.height = ProCamera2DEditorResources.UserGuideIcon.height;
                if (GUI.Button(new Rect(15, rect.y, 32, 32), new GUIContent(ProCamera2DEditorResources.UserGuideIcon, "User Guide")))
                {
                    Application.OpenURL("http://www.procamera2d.com/user-guide/");
                }
            }

            // Draw header
            if (ProCamera2DEditorResources.InspectorHeader != null)
            {
                var rect = GUILayoutUtility.GetRect(0f, 0f);
                rect.x     += 37;
                rect.width  = ProCamera2DEditorResources.InspectorHeader.width;
                rect.height = ProCamera2DEditorResources.InspectorHeader.height;
                GUILayout.Space(rect.height);
                GUI.DrawTexture(rect, ProCamera2DEditorResources.InspectorHeader);
            }

            EditorGUILayout.Space();


            // Review prompt
            if (_showReviewMessage)
            {
                EditorGUILayout.HelpBox("Sorry for the intrusion, but I need you for a second. Reviews on the Asset Store are very important for me to keep improving this product. Please take a minute to write a review and support ProCamera2D.", MessageType.Warning, true);
                EditorGUILayout.BeginHorizontal();
                if (GUILayout.Button("Sure, I'll write a review!"))
                {
                    _showReviewMessage = false;
                    EditorPrefs.SetInt("ProCamera2DReview", -1);
                    Application.OpenURL("http://u3d.as/i7L");
                }
                if (GUILayout.Button("No, thanks."))
                {
                    _showReviewMessage = false;
                    EditorPrefs.SetInt("ProCamera2DReview", -1);
                }
                EditorGUILayout.EndHorizontal();
                AddSpace();
            }


            // Assign game camera
            if (proCamera2D.GameCamera == null)
            {
                proCamera2D.GameCamera = proCamera2D.GetComponent <Camera>();
            }


            // Targets Drop Area
            Event evt       = Event.current;
            Rect  drop_area = GUILayoutUtility.GetRect(0.0f, 50.0f, GUILayout.ExpandWidth(true));
            var   style     = new GUIStyle("box");

            if (EditorGUIUtility.isProSkin)
            {
                style.normal.textColor = Color.white;
            }
            GUI.Box(drop_area, "\nDROP CAMERA TARGETS HERE", style);

            switch (evt.type)
            {
            case EventType.DragUpdated:
            case EventType.DragPerform:
                if (!drop_area.Contains(evt.mousePosition))
                {
                    return;
                }

                DragAndDrop.visualMode = DragAndDropVisualMode.Copy;

                if (evt.type == EventType.DragPerform)
                {
                    DragAndDrop.AcceptDrag();

                    foreach (Object dragged_object in DragAndDrop.objectReferences)
                    {
                        var newCameraTarget = new CameraTarget
                        {
                            TargetTransform = ((GameObject)dragged_object).transform,
                            TargetInfluence = 1f
                        };

                        proCamera2D.CameraTargets.Add(newCameraTarget);
                        EditorUtility.SetDirty(proCamera2D);
                    }
                }
                break;
            }

            EditorGUILayout.Space();



            // Remove empty targets
            for (int i = 0; i < proCamera2D.CameraTargets.Count; i++)
            {
                if (proCamera2D.CameraTargets[i].TargetTransform == null)
                {
                    proCamera2D.CameraTargets.RemoveAt(i);
                }
            }



            // Targets List
            _targetsList.DoLayoutList();
            AddSpace();



            // Center target on start
            _tooltip = new GUIContent("Center target on start", "Should the camera move instantly to the target on game start?");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("CenterTargetOnStart"), _tooltip);

            AddSpace();



            // Axis
            _tooltip = new GUIContent("Axis", "Choose the axis in which the camera should move.");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("Axis"), _tooltip);

            AddSpace();



            // UpdateType
            _tooltip = new GUIContent("Update Type", "LateUpdate: Non physics based game\nFixedUpdate: Physics based game");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("UpdateType"), _tooltip);

            AddSpace();



            // Show correct axis name
            switch (proCamera2D.Axis)
            {
            case MovementAxis.XY:
                hAxis = "X";
                vAxis = "Y";
                break;

            case MovementAxis.XZ:
                hAxis = "X";
                vAxis = "Z";
                break;

            case MovementAxis.YZ:
                hAxis = "Y";
                vAxis = "Z";
                break;
            }



            // Follow horizontal
            EditorGUILayout.BeginHorizontal();
            _tooltip = new GUIContent("Follow " + hAxis, "Should the camera move on the horizontal axis?");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("FollowHorizontal"), _tooltip);
            if (proCamera2D.FollowHorizontal)
            {
                // Follow smoothness
                _tooltip = new GUIContent("Smoothness", "How long it takes the camera to reach the target horizontal position.");
                EditorGUILayout.PropertyField(serializedObject.FindProperty("HorizontalFollowSmoothness"), _tooltip);

                if (proCamera2D.HorizontalFollowSmoothness < 0f)
                {
                    proCamera2D.HorizontalFollowSmoothness = 0f;
                }
            }
            EditorGUILayout.EndHorizontal();


            // Follow vertical
            EditorGUILayout.BeginHorizontal();
            _tooltip = new GUIContent("Follow " + vAxis, "Should the camera move on the vertical axis?");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("FollowVertical"), _tooltip);

            if (proCamera2D.FollowVertical)
            {
                // Follow smoothness
                _tooltip = new GUIContent("Smoothness", "How long it takes the camera to reach the target vertical position.");
                EditorGUILayout.PropertyField(serializedObject.FindProperty("VerticalFollowSmoothness"), _tooltip);

                if (proCamera2D.VerticalFollowSmoothness < 0f)
                {
                    proCamera2D.VerticalFollowSmoothness = 0f;
                }
            }
            EditorGUILayout.EndHorizontal();

            if (!proCamera2D.FollowHorizontal && !proCamera2D.FollowVertical)
            {
                EditorGUILayout.HelpBox("Camera won't move if it's not following the targets on any axis.", MessageType.Error, true);
            }

            AddSpace();



            // Overall offset
            EditorGUILayout.LabelField("Offset");
            EditorGUI.indentLevel = 1;

            _tooltip = new GUIContent(hAxis, "Horizontal offset");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("OverallOffset.x"), _tooltip);

            _tooltip = new GUIContent(vAxis, "Vertical offset");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("OverallOffset.y"), _tooltip);

            EditorGUI.indentLevel = 0;

            AddSpace();



            // Zoom with FOV
            if (!proCamera2D.GameCamera.orthographic)
            {
                GUI.enabled = !Application.isPlaying;
                _tooltip    = new GUIContent("Zoom With FOV", "If enabled, when using a perspective camera, the camera will zoom by changing the FOV instead of moving the camera closer/further from the objects.");
                EditorGUILayout.PropertyField(serializedObject.FindProperty("ZoomWithFOV"), _tooltip);
                GUI.enabled = true;
                AddSpace();
            }



            // Divider
            GUILayout.Box("", new GUILayoutOption[] { GUILayout.ExpandWidth(true), GUILayout.Height(1) });
            GUILayout.Label("EXTENSIONS", EditorStyles.boldLabel);



            // Extensions
            for (int i = 0; i < _extensions.Count; i++)
            {
                EditorGUILayout.BeginHorizontal();

                EditorGUILayout.LabelField(_extensions[i].ExtName);
                if (_extensions[i].Component == null)
                {
                    GUI.color = Color.green;
                    if (GUILayout.Button("Enable"))
                    {
                        _extensions[i].Component             = proCamera2D.gameObject.AddComponent(_extensions[i].ExtType) as BasePC2D;
                        _extensions[i].Component.ProCamera2D = proCamera2D;
                    }
                }
                else
                {
                    GUI.color = Color.red;
                    if (GUILayout.Button("Disable"))
                    {
                        if (EditorUtility.DisplayDialog("Warning!", "Are you sure you want to remove this plugin?", "Yes", "No"))
                        {
                            DestroyImmediate(_extensions[i].Component);
                            EditorGUIUtility.ExitGUI();
                        }
                    }
                }
                GUI.color = Color.white;
                EditorGUILayout.EndHorizontal();
            }



            // Divider
            EditorGUILayout.Space();
            GUI.color = Color.white;
            GUILayout.Box("", new GUILayoutOption[] { GUILayout.ExpandWidth(true), GUILayout.Height(1) });
            GUILayout.Label("TRIGGERS", EditorStyles.boldLabel);



            // Triggers
            for (int i = 0; i < _triggers.Count; i++)
            {
                EditorGUILayout.BeginHorizontal();

                EditorGUILayout.LabelField(_triggers[i].TriggerName + " (" + _triggers[i].AllTriggers.Count() + ")");

                if (GUILayout.Button("Add"))
                {
                    var newGo = new GameObject(_triggers[i].TriggerType.Name);
                    newGo.transform.localScale = new Vector3(5, 5, 5);
                    var trigger = newGo.AddComponent(_triggers[i].TriggerType) as BasePC2D;
                    trigger.ProCamera2D = proCamera2D;
                    _triggers[i].AllTriggers.Add(trigger);
                }

                GUI.enabled = _triggers[i].AllTriggers.Count() > 0;

                if (GUILayout.Button(">"))
                {
                    Selection.activeGameObject = ((BasePC2D)_triggers[i].AllTriggers[_triggers[i].TriggerCurrentIndex]).gameObject;
                    SceneView.FrameLastActiveSceneView();
                    EditorGUIUtility.PingObject(((BasePC2D)_triggers[i].AllTriggers[_triggers[i].TriggerCurrentIndex]).gameObject);

                    Selection.activeGameObject = proCamera2D.gameObject;

                    _triggers[i].TriggerCurrentIndex = _triggers[i].TriggerCurrentIndex >= _triggers[i].AllTriggers.Count - 1 ? 0 : _triggers[i].TriggerCurrentIndex + 1;
                }

                GUI.enabled = true;

                EditorGUILayout.EndHorizontal();
            }

            AddSpace();


            serializedObject.ApplyModifiedProperties();
        }
        public override void OnInspectorGUI()
        {
            var settings         = UMPSettings.Instance;
            var cachedLabelWidth = EditorGUIUtility.labelWidth;

            var installedMobilePlatforms = settings.GetInstalledPlatforms(UMPSettings.Mobile);

            if (_buttonStyleToggled == null)
            {
                _buttonStyleToggled = new GUIStyle(EditorStyles.miniButton);
                _buttonStyleToggled.normal.background = _buttonStyleToggled.active.background;
            }

            if (_warningLabel == null)
            {
                _warningLabel          = new GUIStyle(EditorStyles.label);
                _warningLabel.padding  = new RectOffset();
                _warningLabel.margin   = new RectOffset();
                _warningLabel.wordWrap = true;
            }

            if (playersAndroid == null)
            {
                playersAndroid = new bool[Enum.GetNames(typeof(PlayerOptionsAndroid.PlayerTypes)).Length];
                for (int i = 0; i < playersAndroid.Length; i++)
                {
                    var playerType = (PlayerOptionsAndroid.PlayerTypes)((i * 2) + (i == 0 ? 1 : 0));
                    if ((settings.PlayersAndroid & playerType) == playerType)
                    {
                        playersAndroid[i] = true;
                    }
                }
            }

            if (playersIPhone == null)
            {
                playersIPhone = new bool[Enum.GetNames(typeof(PlayerOptionsIPhone.PlayerTypes)).Length];
                for (int i = 0; i < playersIPhone.Length; i++)
                {
                    var playerType = (PlayerOptionsIPhone.PlayerTypes)((i * 2) + (i == 0 ? 1 : 0));
                    if ((settings.PlayersIPhone & playerType) == playerType)
                    {
                        playersIPhone[i] = true;
                    }
                }
            }

            // Display the asset path
            #region Asset Path
            EditorGUILayout.BeginVertical(GUI.skin.box);

            EditorGUILayout.LabelField("Asset Path", EditorStyles.boldLabel);
            EditorGUI.BeginDisabledGroup(true);
            ShowMessageBox(MessageType.None, _assetPathProp.stringValue);
            EditorGUI.EndDisabledGroup();

            if (settings.IsValidAssetPath)
            {
                ShowMessageBox(MessageType.Info, "Path is correct");
            }
            else
            {
                ShowMessageBox(MessageType.Error, "Can't find asset folder");
            }


            GUI.color = Color.green;
            if (!settings.IsValidAssetPath)
            {
                if (GUILayout.Button("Find Asset Folder"))
                {
                    GUI.FocusControl(null);
                    _assetPathProp.stringValue = FindAssetFolder("Assets");
                }
            }
            GUI.color = Color.white;

            EditorGUILayout.EndVertical();
            #endregion

            // Display the Editor/Desktop options
            #region Editor/Desktop
            EditorGUILayout.BeginVertical(GUI.skin.box);
            EditorGUILayout.LabelField("Editor/Desktop", EditorStyles.boldLabel);
            EditorGUILayout.PropertyField(_useAudioSourceProp, new GUIContent("Use 'Audio Source'", "Will be using Unity 'Audio Source' component for audio output for all UMP instances (global) by default (supported only on desktop platforms)"));

            /*EditorGUILayout.BeginHorizontal();
             * GUILayout.Label(new GUIContent("Use 'Audio Source' component", "Will be using Unity 'Audio Source' component for audio output for all UMP instances (global) by default."));
             * _useAudioSourceProp.boolValue = EditorGUILayout.Toggle(_useAudioSourceProp.boolValue);
             * EditorGUILayout.EndHorizontal();*/


            var useInstalled = !UMPSettings.ContainsLibVLC(settings.GetLibrariesPath(UMPSettings.RuntimePlatform, false));

            if (useInstalled)
            {
                ShowMessageBox(MessageType.Warning, "Can't find internal LibVLC libraries in current project, so will be used installed VLC player software by default. To have possibility to use internal libraries please correctly import UMP (Win, Mac, Linux) package");
            }


            if (_useExternalLibrariesProp.boolValue)
            {
                EditorGUILayout.BeginVertical(GUI.skin.box);
            }

            EditorGUILayout.PropertyField(_useExternalLibrariesProp, new GUIContent("Use installed VLC", "Use external/installed VLC player libraries for all UMP instances (global). Path to installed VLC player directory will be obtained automatically"));

            if (useInstalled)
            {
                _useExternalLibrariesProp.boolValue = true;
            }

            if (settings.UseExternalLibraries)
            {
                var librariesPath = settings.GetLibrariesPath(UMPSettings.RuntimePlatform, true);

                if (!UMPSettings.ContainsLibVLC(librariesPath))
                {
                    librariesPath = string.Empty;

                    GUI.color = Color.yellow;
                    EditorGUILayout.BeginVertical(EditorStyles.textArea);

                    EditorGUILayout.LabelField("Warning: Can't find installed VLC player software, please make sure that:\n" +
                                               "* Installed VLC player bit equals Unity Editor bit, eg., 'VLC Player 64 bit' == 'Unity Editor 64 bit'\n\n" +
                                               "* Use installer version from official site", _warningLabel);

                    GUI.color = Color.white;
                    var vlcUrl = string.Empty;

                    switch (UMPSettings.RuntimePlatform)
                    {
                    case UMPSettings.Platforms.Win:
                        vlcUrl = string.Format("http://get.videolan.org/vlc/{0}/win64/vlc-{0}-win64.exe", VLC_VERSION);

                        if (UMPSettings.EditorBitMode == UMPSettings.BitModes.x86)
                        {
                            vlcUrl = string.Format("http://get.videolan.org/vlc/{0}/win32/vlc-{0}-win32.exe", VLC_VERSION);
                        }
                        break;

                    case UMPSettings.Platforms.Mac:
                        vlcUrl = string.Format("http://get.videolan.org/vlc/{0}/macosx/vlc-{0}.dmg", VLC_VERSION);
                        break;
                    }

                    if (!string.IsNullOrEmpty(vlcUrl))
                    {
                        _warningLabel.normal.textColor = Color.blue;
                        EditorGUILayout.LabelField(string.Format("{0} (Editor {1})", vlcUrl, UMPSettings.EditorBitModeFolderName), _warningLabel);
                        _warningLabel.normal.textColor = Color.black;
                        Rect urlRect = GUILayoutUtility.GetLastRect();

                        if (Event.current.type == EventType.MouseUp && urlRect.Contains(Event.current.mousePosition))
                        {
                            Application.OpenURL(vlcUrl);
                        }
                    }

                    EditorGUILayout.EndVertical();
                }

                EditorGUILayout.Space();
                EditorGUILayout.LabelField(new GUIContent("Libraries path", @"Path to installed VLC player libraries, eg., 'C:\Program Files\VideoLAN\VLC'"));

                if (!librariesPath.Equals(string.Empty))
                {
                    _librariesPathProp.stringValue = librariesPath;

                    EditorGUI.BeginDisabledGroup(true);
                    ShowMessageBox(MessageType.None, _librariesPathProp.stringValue);
                    EditorGUI.EndDisabledGroup();
                }
                else
                {
                    ShowMessageBox(MessageType.Warning, "Path to installed VLC player directory can't be obtained automatically, try to use custom path to your libVLC libraries");
                    _librariesPathProp.stringValue = EditorGUILayout.TextField(_librariesPathProp.stringValue);
                }

                if (UMPSettings.ContainsLibVLC(_librariesPathProp.stringValue))
                {
                    ShowMessageBox(MessageType.Info, "Path is correct");
                }
                else
                {
                    ShowMessageBox(MessageType.Error, @"Can't find VLC player libraries, try to check if your path is correct, eg., 'C:\Program Files\VideoLAN\VLC'");
                }
            }

            if (_useExternalLibrariesProp.boolValue)
            {
                EditorGUILayout.EndVertical();
            }

            EditorGUILayout.EndVertical();
            #endregion

            // Display the Mobile options
            #region Mobile
            EditorGUILayout.BeginVertical(GUI.skin.box);

            if (installedMobilePlatforms.Length > 0)
            {
                EditorGUILayout.LabelField("Mobile", EditorStyles.boldLabel);
                _chosenMobilePlatform = GUILayout.SelectionGrid(_chosenMobilePlatform, installedMobilePlatforms, installedMobilePlatforms.Length, EditorStyles.miniButton);

                EditorGUILayout.BeginVertical(GUI.skin.box);
                EditorGUILayout.LabelField(new GUIContent("Player Types", "Choose player types that will be used in your project"));
                ShowMessageBox(MessageType.Info, "Disabled players will be not included into your build (reducing the file size of your build)");

                GUILayout.BeginHorizontal();

                if (installedMobilePlatforms[_chosenMobilePlatform] == UMPSettings.Platforms.Android.ToString())
                {
                    for (int i = 0; i < playersAndroid.Length; i++)
                    {
                        if (GUILayout.Button(Enum.GetName(typeof(PlayerOptionsAndroid.PlayerTypes), (i * 2) + (i == 0 ? 1 : 0)), playersAndroid[i] ? _buttonStyleToggled : EditorStyles.miniButton))
                        {
                            var playerType = (PlayerOptionsAndroid.PlayerTypes)((i * 2) + (i == 0 ? 1 : 0));

                            if ((settings.PlayersAndroid & ~playerType) > 0)
                            {
                                playersAndroid[i]       = !playersAndroid[i];
                                settings.PlayersAndroid = playersAndroid[i] ? settings.PlayersAndroid | playerType : settings.PlayersAndroid & ~playerType;

                                UpdateMobileLibraries(UMPSettings.Platforms.Android, settings.PlayersAndroid);
                            }
                        }
                    }
                }

                if (installedMobilePlatforms[_chosenMobilePlatform] == UMPSettings.Platforms.iOS.ToString())
                {
                    for (int i = 0; i < playersIPhone.Length; i++)
                    {
                        if (GUILayout.Button(Enum.GetName(typeof(PlayerOptionsIPhone.PlayerTypes), (i * 2) + (i == 0 ? 1 : 0)), playersIPhone[i] ? _buttonStyleToggled : EditorStyles.miniButton))
                        {
                            var playerType = (PlayerOptionsIPhone.PlayerTypes)((i * 2) + (i == 0 ? 1 : 0));

                            if ((settings.PlayersIPhone & ~playerType) > 0)
                            {
                                playersIPhone[i]       = !playersIPhone[i];
                                settings.PlayersIPhone = playersIPhone[i] ? settings.PlayersIPhone | playerType : settings.PlayersIPhone & ~playerType;

                                UpdateMobileLibraries(UMPSettings.Platforms.iOS, settings.PlayersIPhone);
                            }
                        }
                    }
                }

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

                if (installedMobilePlatforms[_chosenMobilePlatform] == UMPSettings.Platforms.Android.ToString())
                {
                    GUILayout.BeginVertical(GUI.skin.box);

                    if (GUILayout.Button(new GUIContent("Exported Video Paths", "'StreamingAssets' videos (or video parts) that will be copied to special cached destination on device (for possibilities to use playlist: videos that contains many parts)"), _showExportedPaths ? _buttonStyleToggled : EditorStyles.miniButton))
                    {
                        _showExportedPaths = !_showExportedPaths;
                    }

                    if (_showExportedPaths)
                    {
                        scrollPos          = EditorGUILayout.BeginScrollView(scrollPos, GUILayout.ExpandHeight(false));
                        _exportedPathsSize = EditorGUILayout.IntField(new GUIContent("Size", "Amount of exported videos"), settings.AndroidExportedPaths.Length, GUILayout.ExpandWidth(true));

                        if (_exportedPathsSize < 0)
                        {
                            _exportedPathsSize = 0;
                        }

                        _cachedExportedPaths = new string[_exportedPathsSize];

                        if (_exportedPathsSize >= 0)
                        {
                            _cachedExportedPaths = new string[_exportedPathsSize];

                            for (int i = 0; i < settings.AndroidExportedPaths.Length; i++)
                            {
                                if (i < _exportedPathsSize)
                                {
                                    _cachedExportedPaths[i] = settings.AndroidExportedPaths[i];
                                }
                            }
                        }

                        EditorGUIUtility.labelWidth = 60;

                        for (int i = 0; i < _cachedExportedPaths.Length; i++)
                        {
                            _cachedExportedPaths[i] = EditorGUILayout.TextField("Path " + i + ":", _cachedExportedPaths[i]);
                        }

                        EditorGUIUtility.labelWidth = cachedLabelWidth;

                        settings.AndroidExportedPaths = _cachedExportedPaths;

                        EditorGUILayout.EndScrollView();

                        var evt = Event.current;

                        switch (evt.type)
                        {
                        case EventType.DragUpdated:
                        case EventType.DragPerform:

                            DragAndDrop.visualMode = DragAndDropVisualMode.Copy;

                            if (evt.type == EventType.DragPerform)
                            {
                                DragAndDrop.AcceptDrag();

                                var filePaths = DragAndDrop.paths;

                                if (filePaths.Length > 0)
                                {
                                    var arrayLength = settings.AndroidExportedPaths.Length > filePaths.Length ? settings.AndroidExportedPaths.Length : filePaths.Length;
                                    _cachedExportedPaths = new string[arrayLength];

                                    for (int i = 0; i < arrayLength; i++)
                                    {
                                        if (i < settings.AndroidExportedPaths.Length)
                                        {
                                            _cachedExportedPaths[i] = settings.AndroidExportedPaths[i];
                                        }

                                        if (i < filePaths.Length)
                                        {
                                            _cachedExportedPaths[i] = filePaths[i];
                                        }
                                    }

                                    settings.AndroidExportedPaths = _cachedExportedPaths;
                                }
                            }
                            break;
                        }
                    }
                    GUILayout.EndVertical();
                }
            }

            EditorGUILayout.EndVertical();
            #endregion

            // Display the Services options
            #region Services
            EditorGUILayout.BeginVertical(GUI.skin.box);
            EditorGUILayout.LabelField("Services", EditorStyles.boldLabel);
            EditorGUILayout.LabelField(new GUIContent("Youtube Decrypt Function", "Uses for decrypt the direct links to Youtube video"));
            _youtubeDecryptFunctionProp.stringValue = EditorGUILayout.TextField(_youtubeDecryptFunctionProp.stringValue);
            EditorGUILayout.EndVertical();
            #endregion

            serializedObject.ApplyModifiedProperties();
        }
Example #5
0
        private void    HandleDrag(Rect r, int i)
        {
            if (Event.current.type == EventType.Used)
            {
                return;
            }

            if (Event.current.type == EventType.MouseDrag)
            {
                if ((Utility.position2D - Event.current.mousePosition).sqrMagnitude >= Constants.MinStartDragDistance &&
                    DragAndDrop.GetGenericData(GUIListDrawer <T> .GenericDataKey) != null)
                {
                    DragAndDrop.StartDrag("Drag Element");
                    Event.current.Use();
                }
            }
            else if (Event.current.type == EventType.MouseDown)
            {
                if (r.Contains(Event.current.mousePosition) == true)
                {
                    Utility.position2D = Event.current.mousePosition;
                    DragAndDrop.PrepareStartDrag();
                    DragAndDrop.paths            = new string[0];
                    DragAndDrop.objectReferences = new Object[0];
                    DragAndDrop.SetGenericData(GUIListDrawer <T> .GenericDataKey, i);
                }
                else
                {
                    DragAndDrop.SetGenericData(GUIListDrawer <T> .GenericDataKey, null);
                }
            }

            if (DragAndDrop.GetGenericData(GUIListDrawer <T> .GenericDataKey) == null)
            {
                return;
            }

            int origin = (int)DragAndDrop.GetGenericData(GUIListDrawer <T> .GenericDataKey);

            if (Event.current.type == EventType.Repaint && r.Contains(Event.current.mousePosition) == true)
            {
                if (DragAndDrop.visualMode == DragAndDropVisualMode.Move)
                {
                    float h = r.height;
                    r.height = 1F;
                    EditorGUI.DrawRect(r, Color.blue);
                    r.height = h;
                }
            }
            else if (Event.current.type == EventType.DragUpdated && r.Contains(Event.current.mousePosition) == true)
            {
                if (i != origin &&
                    i - 1 != origin)
                {
                    DragAndDrop.visualMode = DragAndDropVisualMode.Move;
                }
                else
                {
                    DragAndDrop.visualMode = DragAndDropVisualMode.Rejected;
                }

                Event.current.Use();
            }
            else if (Event.current.type == EventType.DragPerform && r.Contains(Event.current.mousePosition) == true)
            {
                DragAndDrop.SetGenericData(GUIListDrawer <T> .GenericDataKey, null);
                DragAndDrop.AcceptDrag();

                if (this.array != null)
                {
                    T t = this.array[origin];

                    if (i > origin)
                    {
                        for (int j = origin; j < i; ++j)
                        {
                            this.array[j] = this.array[j + 1];
                        }

                        this.array[i - 1] = t;
                    }
                    else
                    {
                        for (int j = origin; j > i; --j)
                        {
                            this.array[j] = this.array[j - 1];
                        }

                        this.array[i] = t;
                    }
                }
                else
                {
                    T e = this.list[origin];

                    this.list.RemoveAt(origin);

                    if (origin < i)
                    {
                        this.list.Insert(i, e);
                    }
                    else
                    {
                        this.list.Insert(i - 1, e);
                    }
                }

                if (this.ArrayReordered != null)
                {
                    this.ArrayReordered(this);
                }

                Event.current.Use();
            }
        }
Example #6
0
        public static void drawStylizedBigTextureProperty(Rect position, MaterialProperty prop, GUIContent label, MaterialEditor editor, bool hasFoldoutProperties, bool skip_drag_and_drop_handling = false)
        {
            position.x     += (EditorGUI.indentLevel) * 15;
            position.width -= (EditorGUI.indentLevel) * 15;
            Rect rect = GUILayoutUtility.GetRect(label, Styles.bigTextureStyle);

            rect.x     += (EditorGUI.indentLevel) * 15;
            rect.width -= (EditorGUI.indentLevel) * 15;
            Rect border = new Rect(rect);

            border.position = new Vector2(border.x, border.y - position.height);
            border.height  += position.height;

            if (DrawingData.currentTexProperty.reference_properties_exist)
            {
                border.height += 8;
                foreach (string r_property in DrawingData.currentTexProperty.options.reference_properties)
                {
                    border.height += editor.GetPropertyHeight(ShaderEditor.active.propertyDictionary[r_property].materialProperty);
                }
            }
            if (DrawingData.currentTexProperty.reference_property_exists)
            {
                border.height += 8;
                border.height += editor.GetPropertyHeight(ShaderEditor.active.propertyDictionary[DrawingData.currentTexProperty.options.reference_property].materialProperty);
            }


            //background
            GUI.DrawTexture(border, Styles.rounded_texture, ScaleMode.StretchToFill, true);
            Rect quad = new Rect(border);

            quad.width = quad.height / 2;
            GUI.DrawTextureWithTexCoords(quad, Styles.rounded_texture, new Rect(0, 0, 0.5f, 1), true);
            quad.x += border.width - quad.width;
            GUI.DrawTextureWithTexCoords(quad, Styles.rounded_texture, new Rect(0.5f, 0, 0.5f, 1), true);

            quad.width  = border.height - 4;
            quad.height = quad.width;
            quad.x      = border.x + border.width - quad.width - 1;
            quad.y     += 2;

            DrawingData.currentTexProperty.tooltip.ConditionalDraw(border);

            Rect preview_rect_border = new Rect(position);

            preview_rect_border.height = rect.height + position.height - 6;
            preview_rect_border.width  = preview_rect_border.height;
            preview_rect_border.y     += 3;
            preview_rect_border.x     += position.width - preview_rect_border.width - 3;
            Rect preview_rect = new Rect(preview_rect_border);

            preview_rect.height -= 6;
            preview_rect.width  -= 6;
            preview_rect.x      += 3;
            preview_rect.y      += 3;
            if (prop.hasMixedValue)
            {
                Rect mixedRect = new Rect(preview_rect);
                mixedRect.y -= 5;
                mixedRect.x += mixedRect.width / 2 - 4;
                GUI.Label(mixedRect, "_");
            }
            else if (prop.textureValue != null)
            {
                GUI.DrawTexture(preview_rect, prop.textureValue);
            }
            GUI.DrawTexture(preview_rect_border, Texture2D.whiteTexture, ScaleMode.StretchToFill, false, 0, Color.grey, 3, 5);

            //selection button and pinging
            Rect select_rect = new Rect(preview_rect);

            select_rect.height = 12;
            select_rect.y     += preview_rect.height - 12;
            if (Event.current.commandName == "ObjectSelectorUpdated" && EditorGUIUtility.GetObjectPickerControlID() == texturePickerWindow && texturePickerWindowProperty.name == prop.name)
            {
                prop.textureValue = (Texture)EditorGUIUtility.GetObjectPickerObject();
                ShaderEditor.Repaint();
            }
            if (Event.current.commandName == "ObjectSelectorClosed" && EditorGUIUtility.GetObjectPickerControlID() == texturePickerWindow)
            {
                texturePickerWindow         = -1;
                texturePickerWindowProperty = null;
            }
            if (GUI.Button(select_rect, "Select", EditorStyles.miniButton))
            {
                EditorGUIUtility.ShowObjectPicker <Texture>(prop.textureValue, false, "", 0);
                texturePickerWindow         = EditorGUIUtility.GetObjectPickerControlID();
                texturePickerWindowProperty = prop;
            }
            else if (Event.current.type == EventType.MouseDown && preview_rect.Contains(Event.current.mousePosition))
            {
                EditorGUIUtility.PingObject(prop.textureValue);
            }

            if (!skip_drag_and_drop_handling)
            {
                if ((ShaderEditor.input.is_drag_drop_event) && preview_rect.Contains(ShaderEditor.input.mouse_position) && DragAndDrop.objectReferences[0] is Texture)
                {
                    DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                    if (ShaderEditor.input.is_drop_event)
                    {
                        DragAndDrop.AcceptDrag();
                        prop.textureValue = (Texture)DragAndDrop.objectReferences[0];
                    }
                }
            }

            //scale offset rect

            if (hasFoldoutProperties || DrawingData.currentTexProperty.options.reference_property != null)
            {
                EditorGUI.indentLevel += 2;

                if (DrawingData.currentTexProperty.hasScaleOffset)
                {
                    Rect scale_offset_rect = new Rect(position);
                    scale_offset_rect.y     += 37;
                    scale_offset_rect.width -= 2 + preview_rect.width + 10 + 30;
                    scale_offset_rect.x     += 30;
                    editor.TextureScaleOffsetProperty(scale_offset_rect, prop);
                    if (DrawingData.currentTexProperty.is_animatable)
                    {
                        DrawingData.currentTexProperty.HandleKajAnimatable();
                    }
                }
                float oldLabelWidth = EditorGUIUtility.labelWidth;
                EditorGUIUtility.labelWidth = 128;

                PropertyOptions options = DrawingData.currentTexProperty.options;
                if (options.reference_property != null)
                {
                    ShaderProperty property = ShaderEditor.active.propertyDictionary[options.reference_property];
                    property.Draw(useEditorIndent: true);
                }
                if (options.reference_properties != null)
                {
                    foreach (string r_property in options.reference_properties)
                    {
                        ShaderProperty property = ShaderEditor.active.propertyDictionary[r_property];
                        property.Draw(useEditorIndent: true);
                        if (DrawingData.currentTexProperty.is_animatable)
                        {
                            property.HandleKajAnimatable();
                        }
                    }
                }
                EditorGUIUtility.labelWidth = oldLabelWidth;
                EditorGUI.indentLevel      -= 2;
            }

            Rect label_rect = new Rect(position);

            label_rect.x += 2;
            label_rect.y += 2;
            GUI.Label(label_rect, label);

            GUILayoutUtility.GetRect(0, 5);

            DrawingData.lastGuiObjectRect = border;
        }
Example #7
0
            public bool DoLayoutProperty(SerializedProperty property)
            {
                if (propIndex.ContainsKey(property.propertyPath) == false)
                {
                    return(false);
                }

                // Draw the header
                string headerText = string.Format("{0} [{1}]", property.displayName, property.arraySize);

                EditorGUILayout.PropertyField(property, new GUIContent(headerText), false);

                // Save header rect for handling drag and drop
                Rect dropRect = GUILayoutUtility.GetLastRect();

                // Draw the reorderable list for the property
                if (property.isExpanded)
                {
                    int newArraySize = EditorGUILayout.IntField("Size", property.arraySize);
                    if (newArraySize != property.arraySize)
                    {
                        property.arraySize = newArraySize;
                    }
                    propIndex[property.propertyPath].DoLayoutList();
                }

                // Handle drag and drop into the header
                Event evt = Event.current;

                if (evt == null)
                {
                    return(true);
                }

                if (evt.type == EventType.DragUpdated || evt.type == EventType.DragPerform)
                {
                    if (dropRect.Contains(evt.mousePosition) == false)
                    {
                        return(true);
                    }

                    DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                    if (evt.type == EventType.DragPerform)
                    {
                        DragAndDrop.AcceptDrag();
                        Action <SerializedProperty, Object[]> handler = null;
                        if (propDropHandlers.TryGetValue(property.propertyPath, out handler))
                        {
                            if (handler != null)
                            {
                                handler(property, DragAndDrop.objectReferences);
                            }
                        }
                        else
                        {
                            foreach (Object dragged_object in DragAndDrop.objectReferences)
                            {
                                if (dragged_object.GetType() != property.GetType())
                                {
                                    continue;
                                }

                                int newIndex = property.arraySize;
                                property.arraySize++;

                                SerializedProperty target = property.GetArrayElementAtIndex(newIndex);
                                target.objectReferenceInstanceIDValue = dragged_object.GetInstanceID();
                            }
                        }
                        evt.Use();
                    }
                }
                return(true);
            }
        public void DropAreaGUI()
        {
            //Drop out if no resource selected
            if (m_resource == null)
            {
                return;
            }

            //Ok - set up for drag and drop
            Event evt       = Event.current;
            Rect  drop_area = GUILayoutUtility.GetRect(0.0f, 50.0f, GUILayout.ExpandWidth(true));

            GUI.Box(drop_area, "Drop Game Objects / Prefabs Here", m_boxStyle);

            switch (evt.type)
            {
            case EventType.DragUpdated:
            case EventType.DragPerform:
                if (!drop_area.Contains(evt.mousePosition))
                {
                    return;
                }

                DragAndDrop.visualMode = DragAndDropVisualMode.Copy;

                if (evt.type == EventType.DragPerform)
                {
                    DragAndDrop.AcceptDrag();


                    //Work out if we have prefab instances or prefab objects
                    bool havePrefabInstances = false;
                    foreach (UnityEngine.Object dragged_object in DragAndDrop.objectReferences)
                    {
                        PrefabType pt = PrefabUtility.GetPrefabType(dragged_object);

                        if (pt == PrefabType.PrefabInstance || pt == PrefabType.ModelPrefabInstance)
                        {
                            havePrefabInstances = true;
                            break;
                        }
                    }

                    if (havePrefabInstances)
                    {
                        List <GameObject> prototypes = new List <GameObject>();

                        foreach (UnityEngine.Object dragged_object in DragAndDrop.objectReferences)
                        {
                            PrefabType pt = PrefabUtility.GetPrefabType(dragged_object);

                            if (pt == PrefabType.PrefabInstance || pt == PrefabType.ModelPrefabInstance)
                            {
                                prototypes.Add(dragged_object as GameObject);
                            }
                            else
                            {
                                Debug.LogWarning("You may only add prefab instances!");
                            }
                        }

                        //Same them as a single entity
                        if (prototypes.Count > 0)
                        {
                            m_resource.AddGameObject(prototypes);
                        }
                    }
                    else
                    {
                        foreach (UnityEngine.Object dragged_object in DragAndDrop.objectReferences)
                        {
                            if (PrefabUtility.GetPrefabType(dragged_object) == PrefabType.Prefab)
                            {
                                m_resource.AddGameObject(dragged_object as GameObject);
                            }
                            else
                            {
                                Debug.LogWarning("You may only add prefabs or game objects attached to prefabs!");
                            }
                        }
                    }
                }
                break;
            }
        }
Example #9
0
        private void DropAreaGUI()
        {
            //Ok - set up for drag and drop
            Event evt       = Event.current;
            Rect  drop_area = GUILayoutUtility.GetRect(0.0f, 50.0f, GUILayout.ExpandWidth(true));

            GUI.Box(drop_area, ">> Drop Objects Here To Scan <<", m_dropBoxStyle);
            EditorGUILayout.HelpBox(m_scanMessage, MessageType.Info);

            switch (evt.type)
            {
            case EventType.DragUpdated:
            case EventType.DragPerform:
            {
                if (!drop_area.Contains(evt.mousePosition))
                {
                    break;
                }

                DragAndDrop.visualMode = DragAndDropVisualMode.Copy;

                if (evt.type == EventType.DragPerform)
                {
                    DragAndDrop.AcceptDrag();
                    m_rawFilePath   = null;
                    m_assumedRawRes = 0;

                    //Is it a saved file - only raw files are processed this way
                    if (DragAndDrop.paths.Length > 0)
                    {
                        string filePath = DragAndDrop.paths[0];

                        //Update in case unity has messed with it
                        if (filePath.StartsWith("Assets"))
                        {
                            filePath = Path.Combine(Application.dataPath, filePath.Substring(7)).Replace('\\', '/');
                        }

                        //Check file type and process as we can
                        string fileType = Path.GetExtension(filePath).ToLower();

                        //Handle raw files
                        if (fileType == ".r16" || fileType == ".raw")
                        {
                            m_scanMessage = "Dropped Object recognized as a raw file";
                            m_scanner.m_scannerObjectType = ScannerObjectType.Raw;
                            m_scanner.m_objectScanned     = true;
                            m_rawFilePath = filePath;
                            m_scanner.LoadRawFile(filePath, m_rawByteOrder, ref m_rawBitDepth, ref m_assumedRawRes);
                            return;
                        }
                    }

                    //Is it something that unity knows about - may or may not have been saved
                    bool finished = false;
                    if (DragAndDrop.objectReferences.Length > 0)
                    {
                        switch (DragAndDrop.objectReferences[0])
                        {
                        //Check for textures
                        case Texture2D _:
                        {
                            EditorUtility.DisplayProgressBar("Processing Texture", "Processing texture to mask texture", 0.5f);
                            GaiaUtils.MakeTextureReadable(DragAndDrop.objectReferences[0] as Texture2D);
                            GaiaUtils.MakeTextureUncompressed(DragAndDrop.objectReferences[0] as Texture2D);
                            m_scanner.LoadTextureFile(DragAndDrop.objectReferences[0] as Texture2D);
                            m_scanMessage = "Dropped Object recognized as a texture";
                            m_scanner.m_scannerObjectType = ScannerObjectType.Texture;
                            finished = true;
                            EditorUtility.ClearProgressBar();
                            break;
                        }

                        //Check for terrains
                        case GameObject _:
                        {
                            GameObject go = DragAndDrop.objectReferences[0] as GameObject;
                            Terrain    t  = go.GetComponentInChildren <Terrain>();
                            //Handle a terrain
                            if (t != null)
                            {
                                EditorUtility.DisplayProgressBar("Processing Terrain", "Processing terrain to mask texture", 0.5f);
                                m_scanner.LoadTerain(t);
                                m_scanMessage = "Dropped Object recognized as terrain";
                                m_scanner.m_scannerObjectType = ScannerObjectType.Terrain;
                                finished = true;
                                EditorUtility.ClearProgressBar();
                            }

                            //Check for a mesh - this means we can scan it
                            if (!finished)
                            {
                                MeshFilter[] filters = go.GetComponentsInChildren <MeshFilter>();
                                for (int idx = 0; idx < filters.Length; idx++)
                                {
                                    if (filters[idx].sharedMesh != null)
                                    {
                                        m_scanMessage = "Dropped Object recognized as mesh";
                                        m_scanner.m_scannerObjectType = ScannerObjectType.Mesh;
                                        m_scanner.m_lastScannedMesh   = go;
                                        m_scanner.LoadGameObject(go);
                                        finished = true;
                                    }
                                }
                            }
                            break;
                        }
                        }
                    }

                    //If we got to here then we couldnt process it
                    if (!finished)
                    {
                        Debug.LogWarning("Object type not supported by scanner. Ignored");
                        m_scanMessage = "Object type not supported by scanner.";
                        m_scanner.m_scannerObjectType = ScannerObjectType.Unkown;
                        m_scanner.m_objectScanned     = false;
                    }
                    else
                    {
                        m_scanner.m_objectScanned = true;
                    }
                }
                break;
            }
            }
        }
Example #10
0
        protected virtual void  OnGUI()
        {
            if (this.hub == null || this.hub.Initialized == false)
            {
                return;
            }

            if (this.list == null)
            {
                this.list = new ReorderableList(this.hub.components, typeof(HubComponent), true, false, true, true);
                this.list.headerHeight          = 24F;
                this.list.drawHeaderCallback    = (r) => GUI.Label(r, "Components", GeneralStyles.Title1);
                this.list.showDefaultBackground = false;
                this.list.drawElementCallback   = this.DrawComponent;
                this.list.onAddCallback         = this.OpenAddComponentWizard;
                this.list.onRemoveCallback      = (l) => { l.list.RemoveAt(l.index); this.hub.SaveComponents(); };
                this.list.onReorderCallback     = (l) => this.hub.SaveComponents();
                this.list.onChangedCallback     = (l) => this.hub.Repaint();
            }

            MethodInfo[] droppableComponentsMethods = this.hub.DroppableComponents;

            if (droppableComponentsMethods.Length > 0 &&
                DragAndDrop.objectReferences.Length > 0)
            {
                for (int i = 0; i < droppableComponentsMethods.Length; i++)
                {
                    if ((bool)droppableComponentsMethods[i].Invoke(null, null) == true)
                    {
                        Rect r = GUILayoutUtility.GetRect(GUI.skin.label.CalcSize(new GUIContent(droppableComponentsMethods[i].DeclaringType.Name)).x, this.hub.height, GUI.skin.label);

                        if (Event.current.type == EventType.Repaint)
                        {
                            Utility.DropZone(r, Utility.NicifyVariableName(droppableComponentsMethods[i].DeclaringType.Name));
                            this.Repaint();
                        }
                        else if (Event.current.type == EventType.DragUpdated &&
                                 r.Contains(Event.current.mousePosition) == true)
                        {
                            DragAndDrop.visualMode = DragAndDropVisualMode.Move;
                        }
                        else if (Event.current.type == EventType.DragPerform &&
                                 r.Contains(Event.current.mousePosition) == true)
                        {
                            DragAndDrop.AcceptDrag();

                            HubComponent component = Activator.CreateInstance(droppableComponentsMethods[i].DeclaringType) as HubComponent;

                            if (component != null)
                            {
                                component.InitDrop(this.hub);
                                this.hub.components.Add(component);
                                this.hub.SaveComponents();
                            }

                            DragAndDrop.PrepareStartDrag();
                            Event.current.Use();
                        }
                    }
                }
            }

            Rect r2 = this.position;

            r2.x = 0F;

            if (this.hub.DockedAsMenu == false)
            {
                r2.y = 24F;

                using (LabelWidthRestorer.Get(50F))
                {
                    EditorGUI.BeginChangeCheck();
                    this.hub.height = EditorGUILayout.FloatField("Height", this.hub.height);
                    if (EditorGUI.EndChangeCheck() == true)
                    {
                        this.hub.Repaint();
                    }
                }
            }
            else
            {
                r2.y = 0F;
            }

            EditorGUI.BeginChangeCheck();
            this.hub.backgroundColor = EditorGUILayout.ColorField("Background Color", this.hub.backgroundColor);
            if (EditorGUI.EndChangeCheck() == true)
            {
                this.hub.Repaint();
            }

            this.headerRect = GUILayoutUtility.GetLastRect();

            this.scrollPosition = EditorGUILayout.BeginScrollView(this.scrollPosition);
            {
                this.list.DoLayoutList();
            }
            EditorGUILayout.EndScrollView();
        }
Example #11
0
    // Use this for initialization
    public override void OnInspectorGUI()
    {
        FontAnalyse script = (FontAnalyse)target;

        EditorGUI.indentLevel = 0;
        PGEditorUtils.LookLikeControls();


        Rect sfxPathRect = EditorGUILayout.GetControlRect();

        // 用刚刚获取的文本输入框的位置和大小参数,创建一个文本输入框,用于输入特效路径
        EditorGUI.TextField(sfxPathRect, "ImgPath", script.ImgPath);
        // 判断当前鼠标正拖拽某对象或者在拖拽的过程中松开了鼠标按键
        // 同时还需要判断拖拽时鼠标所在位置处于文本输入框内
        if ((Event.current.type == EventType.DragUpdated ||
             Event.current.type == EventType.DragExited) &&
            sfxPathRect.Contains(Event.current.mousePosition))
        {
            // 判断是否拖拽了文件
            if (DragAndDrop.paths != null && DragAndDrop.paths.Length > 0)
            {
                string sfxPath = DragAndDrop.paths [0];
                // 拖拽的过程中,松开鼠标之后,拖拽操作结束,此时就可以使用获得的 sfxPath 变量了
                                #if UNITY_EDITOR_OSX
                if (!string.IsNullOrEmpty(sfxPath) && Event.current.type == EventType.DragExited)
                {
                                #else
                if (!string.IsNullOrEmpty(sfxPath) && Event.current.type == EventType.DragUpdated)
                {
                                #endif
                    DragAndDrop.AcceptDrag();

                    script.ImgPath = common.TextUtil.cut(sfxPath, "Resources/", false, false);
                }
            }
        }

        sfxPathRect = EditorGUILayout.GetControlRect();
        // 用刚刚获取的文本输入框的位置和大小参数,创建一个文本输入框,用于输入特效路径
        EditorGUI.TextField(sfxPathRect, "DataPath", script.DataPath);
        // 判断当前鼠标正拖拽某对象或者在拖拽的过程中松开了鼠标按键
        // 同时还需要判断拖拽时鼠标所在位置处于文本输入框内
        if ((Event.current.type == EventType.DragUpdated ||
             Event.current.type == EventType.DragExited) &&
            sfxPathRect.Contains(Event.current.mousePosition))
        {
            // 判断是否拖拽了文件
            if (DragAndDrop.paths != null && DragAndDrop.paths.Length > 0)
            {
                string sfxPath = DragAndDrop.paths [0];
                // 拖拽的过程中,松开鼠标之后,拖拽操作结束,此时就可以使用获得的 sfxPath 变量了
                                #if UNITY_EDITOR_OSX
                if (!string.IsNullOrEmpty(sfxPath) && Event.current.type == EventType.DragExited)
                {
                                #else
                if (!string.IsNullOrEmpty(sfxPath) && Event.current.type == EventType.DragUpdated)
                {
                                #endif
                    DragAndDrop.AcceptDrag();

                    script.DataPath = common.TextUtil.cut(sfxPath, "Resources/", false, false);
                }
            }
        }

        script.advanceAddition = EditorGUILayout.IntField("advanceAddition", script.advanceAddition);
        script.pixelPerUnit    = EditorGUILayout.FloatField("pixelPerUnit", script.pixelPerUnit);
//
//		script.matchPoolScale = EditorGUILayout.Toggle("Match Pool Scale", script.matchPoolScale);
//		script.matchPoolLayer = EditorGUILayout.Toggle("Match Pool Layer", script.matchPoolLayer);
//
//		script.dontReparent = EditorGUILayout.Toggle("Don't Reparent", script.dontReparent);
//
//		script._dontDestroyOnLoad = EditorGUILayout.Toggle("Don't Destroy On Load", script._dontDestroyOnLoad);
//
//		script.logMessages = EditorGUILayout.Toggle("Log Messages", script.logMessages);
        EditorGUILayout.BeginHorizontal();           // 1/2 the item button width
        GUILayout.Space(0);

        // Master add at end button. List items will insert
        if (GUILayout.Button(new GUIContent("Generate", "Click to generate data"), EditorStyles.toolbarButton))
        {
            if (script.ImgPath != null && script.DataPath != null)
            {
                script.slice(script.ImgPath, script.DataPath);
                CharacterGroup[] groups = FindObjectsOfType <CharacterGroup>();
                for (int i = 0; i < groups.Length; i++)
                {
                    groups[i].setTextInEditor(false);
                }
            }
        }

        if (GUILayout.Button(new GUIContent("Clear", "Click to generate data"), EditorStyles.toolbarButton))
        {
            script.clear();
        }
        EditorGUILayout.EndHorizontal();

        this.expandPrefabs = PGEditorUtils.SerializedObjFoldOutList <FontData>
                             (
            "Per-Prefab Pool Options",
            script.fontDataList,
            this.expandPrefabs,
            ref script._editorListItemStates,
            true
                             );

        // Flag Unity to save the changes to to the prefab to disk
        if (GUI.changed)
        {
            EditorUtility.SetDirty(target);
        }
    }
}
        private void DrawPreComponents()
        {
            if (nodeInfo.GetPrefab() == null)
            {
                return;
            }

            using (var hor = new EditorGUILayout.HorizontalScope())
            {
                GUILayout.FlexibleSpace();
                if (GUILayout.Button(new GUIContent("←", "快速解析"), EditorStyles.toolbarButton, GUILayout.Width(20)))
                {
                    GenCodeUtil.ChoiseAnUserMonobehiver(nodeInfo.GetPrefab(), component =>
                    {
                        if (component == null)
                        {
                            EditorApplication.Beep();
                        }
                        else
                        {
                            //从旧的脚本解析出
                            GenCodeUtil.AnalysisComponent(component, components, rule);
                        }
                    });
                }
            }

            using (var hor = new EditorGUILayout.HorizontalScope())
            {
                EditorGUILayout.LabelField("BaseType:", GUILayout.Width(lableWidth));
                rule.baseTypeIndex = EditorGUILayout.Popup(rule.baseTypeIndex, GenCodeUtil.supportBaseTypes);
                if (GUILayout.Button(new GUIContent("update", "更新脚本控件信息"), EditorStyles.miniButton, GUILayout.Width(60)))
                {
                    var go = nodeInfo.GetPrefab();
                    GenCodeUtil.UpdateScripts(go, components, rule);
                }
            }

            if (preComponentList != null)
            {
                preComponentList.DoLayoutList();
            }

            var addRect = GUILayoutUtility.GetRect(BridgeUI.Drawer.BridgeEditorUtility.currentViewWidth, EditorGUIUtility.singleLineHeight);

            if (addRect.Contains(Event.current.mousePosition))
            {
                if (Event.current.type == EventType.DragUpdated)
                {
                    if (DragAndDrop.objectReferences.Length > 0)
                    {
                        foreach (var item in DragAndDrop.objectReferences)
                        {
                            if (item is GameObject)
                            {
                                DragAndDrop.visualMode = DragAndDropVisualMode.Move;
                            }
                        }
                    }
                }
                else if (Event.current.type == EventType.DragPerform)
                {
                    if (DragAndDrop.objectReferences.Length > 0)
                    {
                        foreach (var item in DragAndDrop.objectReferences)
                        {
                            if (item is GameObject)
                            {
                                var obj    = item as GameObject;
                                var parent = PrefabUtility.GetPrefabParent(obj);
                                if (parent)
                                {
                                    obj = parent as GameObject;
                                }
                                var c_item = new ComponentItem(obj);
                                c_item.components = GenCodeUtil.SortComponent(obj);
                                components.Add(c_item);
                            }
                            else if (item is ScriptableObject)
                            {
                                var c_item = new ComponentItem(item as ScriptableObject);
                                components.Add(c_item);
                            }
                        }
                        DragAndDrop.AcceptDrag();
                    }
                }
            }
        }
Example #13
0
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            Texture browseIcon = EditorGUIUtility.Load("FMOD/SearchIconBlack.png") as Texture;

            SerializedProperty pathProperty = property;

            EditorGUI.BeginProperty(position, label, property);

            Event e = Event.current;

            #if UNITY_2017_3_OR_NEWER
            if (e.type == EventType.DragPerform && position.Contains(e.mousePosition))
            #else
            if (e.type == EventType.dragPerform && position.Contains(e.mousePosition))
            #endif
            {
                if (DragAndDrop.objectReferences.Length > 0 &&
                    DragAndDrop.objectReferences[0] != null &&
                    DragAndDrop.objectReferences[0].GetType() == typeof(EditorBankRef))
                {
                    pathProperty.stringValue = ((EditorBankRef)DragAndDrop.objectReferences[0]).Name;

                    e.Use();
                }
            }
            if (e.type == EventType.DragUpdated && position.Contains(e.mousePosition))
            {
                if (DragAndDrop.objectReferences.Length > 0 &&
                    DragAndDrop.objectReferences[0] != null &&
                    DragAndDrop.objectReferences[0].GetType() == typeof(EditorBankRef))
                {
                    DragAndDrop.visualMode = DragAndDropVisualMode.Move;
                    DragAndDrop.AcceptDrag();
                    e.Use();
                }
            }

            float baseHeight = GUI.skin.textField.CalcSize(new GUIContent()).y;

            position = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label);

            var buttonStyle = new GUIStyle(GUI.skin.button);
            buttonStyle.padding.top = buttonStyle.padding.bottom = 1;

            Rect searchRect = new Rect(position.x + position.width - browseIcon.width - 15, position.y, browseIcon.width + 10, baseHeight);
            Rect pathRect   = new Rect(position.x, position.y, searchRect.x - position.x - 5, baseHeight);

            EditorGUI.PropertyField(pathRect, pathProperty, GUIContent.none);
            if (GUI.Button(searchRect, new GUIContent(browseIcon, "Select FMOD Bank"), buttonStyle))
            {
                var eventBrowser = EventBrowser.CreateInstance <EventBrowser>();

                eventBrowser.SelectBank(property);
                var windowRect = position;
                windowRect.position = GUIUtility.GUIToScreenPoint(windowRect.position);
                windowRect.height   = searchRect.height + 1;
                eventBrowser.ShowAsDropDown(windowRect, new Vector2(windowRect.width, 400));
            }

            EditorGUI.EndProperty();
        }
Example #14
0
        static void OnSceneGUI(SceneView sceneView)
        {
            Event e          = Event.current;
            bool  is_handled = false;

            if (Configure.IsEnableDragUIToScene && (Event.current.type == EventType.DragUpdated || Event.current.type == EventType.DragPerform))
            {
                //拉UI prefab或者图片入scene界面时帮它找到鼠标下的Canvas并挂在其上,若鼠标下没有画布就创建一个
                Object handleObj = DragAndDrop.objectReferences[0];
                if (!IsNeedHandleAsset(handleObj))
                {
                    //让系统自己处理
                    return;
                }
                DragAndDrop.visualMode = DragAndDropVisualMode.Copy;

                //当松开鼠标时
                if (Event.current.type == EventType.DragPerform)
                {
                    DragAndDrop.AcceptDrag();
                    foreach (var item in DragAndDrop.objectReferences)
                    {
                        HandleDragAsset(sceneView, item);
                    }
                }
                is_handled = true;
            }
            else if (e.type == EventType.KeyDown && Configure.IsMoveNodeByArrowKey)
            {
                //按上按下要移动节点,因为默认情况下只是移动Scene界面而已
                foreach (var item in Selection.transforms)
                {
                    Transform trans = item;
                    if (trans != null)
                    {
                        if (e.keyCode == KeyCode.UpArrow)
                        {
                            Vector3 newPos = new Vector3(trans.localPosition.x, trans.localPosition.y + 1, trans.localPosition.z);
                            trans.localPosition = newPos;
                            is_handled          = true;
                        }
                        else if (e.keyCode == KeyCode.DownArrow)
                        {
                            Vector3 newPos = new Vector3(trans.localPosition.x, trans.localPosition.y - 1, trans.localPosition.z);
                            trans.localPosition = newPos;
                            is_handled          = true;
                        }
                        else if (e.keyCode == KeyCode.LeftArrow)
                        {
                            Vector3 newPos = new Vector3(trans.localPosition.x - 1, trans.localPosition.y, trans.localPosition.z);
                            trans.localPosition = newPos;
                            is_handled          = true;
                        }
                        else if (e.keyCode == KeyCode.RightArrow)
                        {
                            Vector3 newPos = new Vector3(trans.localPosition.x + 1, trans.localPosition.y, trans.localPosition.z);
                            trans.localPosition = newPos;
                            is_handled          = true;
                        }
                    }
                }
            }
            else if (Event.current != null && Event.current.button == 1 && Event.current.type == EventType.MouseUp && Configure.IsShowSceneMenu)
            {
                if (Selection.gameObjects == null || Selection.gameObjects.Length == 0 || Selection.gameObjects[0].transform is RectTransform)
                {
                    ContextMenu.AddCommonItems(Selection.gameObjects);
                    ContextMenu.Show();
                    is_handled = true;
                }
            }
            //else if (e.type == EventType.MouseMove)//show cur mouse pos
            //{
            //    Camera cam = sceneView.camera;
            //    Vector3 mouse_abs_pos = e.mousePosition;
            //    mouse_abs_pos.y = cam.pixelHeight - mouse_abs_pos.y;
            //    mouse_abs_pos = sceneView.camera.ScreenToWorldPoint(mouse_abs_pos);
            //    Debug.Log("mouse_abs_pos : " + mouse_abs_pos.ToString());
            //}
            if (is_handled)
            {
                Event.current.Use();
            }
        }
Example #15
0
        public static bool HandleDragAndDrop(Rect position, SerializedObject obj, List <SerializedProperty> props)
        {
            var droppedObjects = false;

            if (!position.Contains(Event.current.mousePosition))
            {
                return(false);
            }
            if (Event.current.type == EventType.DragUpdated)
            {
                DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                Event.current.Use();
            }
            else if (Event.current.type == EventType.DragPerform)
            {
                DragAndDrop.AcceptDrag();
                foreach (var prop in props)
                {
                    var targetType = obj.targetObject.GetType().GetField(prop.name).FieldType.GetElementType();
                    if (targetType == null)
                    {
                        break;
                    }
                    var addingGo = targetType == typeof(GameObject);

                    foreach (var draggedObject in DragAndDrop.objectReferences)
                    {
                        if (!(draggedObject is GameObject addedGameObject))
                        {
                            continue;
                        }
                        var addIndex = prop.arraySize;
                        // Because GameObject is not a component, we skip the GetComponent part
                        if (addingGo)
                        {
                            prop.InsertArrayElementAtIndex(addIndex);
                            prop.GetArrayElementAtIndex(addIndex).objectReferenceValue = addedGameObject;
                            droppedObjects = true;
                            continue;
                        }

                        if (!targetType.IsSubclassOf(typeof(Component)) && !targetType.IsSubclassOf(typeof(MonoBehaviour)))
                        {
                            prop.InsertArrayElementAtIndex(addIndex);
                            droppedObjects = true;
                            continue;
                        }

                        var addedItem = addedGameObject.GetComponent(targetType);
                        if (!addedItem)
                        {
                            continue;
                        }
                        prop.InsertArrayElementAtIndex(addIndex);
                        prop.GetArrayElementAtIndex(addIndex).objectReferenceValue = addedItem;
                        droppedObjects = true;
                    }
                }
            }

            return(droppedObjects);
        }
Example #16
0
    public override void OnInspectorGUI()
    {
        EditorGUIUtility.LookLikeControls();

        EditorGUI.indentLevel = 0;
        var isDirty = false;

        _variation = (SoundGroupVariation)target;

        if (MasterAudioInspectorResources.logoTexture != null)
        {
            DTGUIHelper.ShowHeaderTexture(MasterAudioInspectorResources.logoTexture);
        }

//		if (Application.isPlaying) {
//			DTGUIHelper.ShowColorWarning(_variation.IsAvailableToPlay.ToString());
//		}

        EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);
        GUI.contentColor = Color.green;
        if (GUILayout.Button(new GUIContent("Back to Group", "Select Group in Hierarchy"), EditorStyles.toolbarButton, GUILayout.Width(120)))
        {
            Selection.activeObject = _variation.transform.parent.gameObject;
        }
        GUILayout.FlexibleSpace();
        GUI.contentColor = Color.white;

        var ma = MasterAudio.Instance;

        if (ma != null)
        {
            var buttonPressed = DTGUIHelper.AddVariationButtons();

            switch (buttonPressed)
            {
            case DTGUIHelper.DTFunctionButtons.Play:
                if (Application.isPlaying)
                {
                    MasterAudio.PlaySound(_variation.transform.parent.name, 1f, null, 0f, _variation.name);
                }
                else
                {
                    isDirty = true;
                    if (_variation.audLocation == MasterAudio.AudioLocation.ResourceFile)
                    {
                        MasterAudio.PreviewerInstance.Stop();
                        MasterAudio.PreviewerInstance.PlayOneShot(Resources.Load(_variation.resourceFileName) as AudioClip);
                    }
                    else
                    {
                        PlaySound(_variation.audio);
                    }
                }
                break;

            case DTGUIHelper.DTFunctionButtons.Stop:
                if (Application.isPlaying)
                {
                    MasterAudio.StopAllOfSound(_variation.transform.parent.name);
                }
                else
                {
                    if (_variation.audLocation == MasterAudio.AudioLocation.ResourceFile)
                    {
                        MasterAudio.PreviewerInstance.Stop();
                    }
                    else
                    {
                        StopSound(_variation.audio);
                    }
                }
                break;
            }
        }

        EditorGUILayout.EndHorizontal();

        if (ma != null && !Application.isPlaying)
        {
            DTGUIHelper.ShowColorWarning("*Fading & random settings are ignored by preview in edit mode.");
        }

        var oldLocation = _variation.audLocation;
        var newLocation = (MasterAudio.AudioLocation)EditorGUILayout.EnumPopup("Audio Origin", _variation.audLocation);

        if (newLocation != oldLocation)
        {
            UndoHelper.RecordObjectPropertyForUndo(_variation, "change Audio Origin");
            _variation.audLocation = newLocation;
        }

        switch (_variation.audLocation)
        {
        case MasterAudio.AudioLocation.Clip:
            var newClip = (AudioClip)EditorGUILayout.ObjectField("Audio Clip", _variation.audio.clip, typeof(AudioClip), false);

            if (newClip != _variation.audio.clip)
            {
                UndoHelper.RecordObjectPropertyForUndo(_variation.audio, "assign Audio Clip");
                _variation.audio.clip = newClip;
            }
            break;

        case MasterAudio.AudioLocation.ResourceFile:
            if (oldLocation != _variation.audLocation)
            {
                if (_variation.audio.clip != null)
                {
                    Debug.Log("Audio clip removed to prevent unnecessary memory usage on Resource file Variation.");
                }
                _variation.audio.clip = null;
            }

            EditorGUILayout.BeginVertical();
            var anEvent = Event.current;

            GUI.color = Color.yellow;
            var dragArea = GUILayoutUtility.GetRect(0f, 20f, GUILayout.ExpandWidth(true));
            GUI.Box(dragArea, "Drag Resource Audio clip here to use its name!");
            GUI.color = Color.white;

            var newFilename = string.Empty;

            switch (anEvent.type)
            {
            case EventType.DragUpdated:
            case EventType.DragPerform:
                if (!dragArea.Contains(anEvent.mousePosition))
                {
                    break;
                }

                DragAndDrop.visualMode = DragAndDropVisualMode.Copy;

                if (anEvent.type == EventType.DragPerform)
                {
                    DragAndDrop.AcceptDrag();

                    foreach (var dragged in DragAndDrop.objectReferences)
                    {
                        var aClip = dragged as AudioClip;
                        if (aClip == null)
                        {
                            continue;
                        }

                        newFilename = DTGUIHelper.GetResourcePath(aClip);
                        if (string.IsNullOrEmpty(newFilename))
                        {
                            newFilename = aClip.name;
                        }

                        if (newFilename != _variation.resourceFileName)
                        {
                            UndoHelper.RecordObjectPropertyForUndo(_variation, "change Resource filename");
                            _variation.resourceFileName = aClip.name;
                        }
                        break;
                    }
                }
                Event.current.Use();
                break;
            }
            EditorGUILayout.EndVertical();

            newFilename = EditorGUILayout.TextField("Resource Filename", _variation.resourceFileName);
            if (newFilename != _variation.resourceFileName)
            {
                UndoHelper.RecordObjectPropertyForUndo(_variation, "change Resource filename");
                _variation.resourceFileName = newFilename;
            }
            break;
        }

        var newVolume = EditorGUILayout.Slider("Volume", _variation.audio.volume, 0f, 1f);

        if (newVolume != _variation.audio.volume)
        {
            UndoHelper.RecordObjectPropertyForUndo(_variation.audio, "change Volume");
            _variation.audio.volume = newVolume;
        }

        var newPitch = EditorGUILayout.Slider("Pitch", _variation.audio.pitch, -3f, 3f);

        if (newPitch != _variation.audio.pitch)
        {
            UndoHelper.RecordObjectPropertyForUndo(_variation.audio, "change Pitch");
            _variation.audio.pitch = newPitch;
        }

        var newLoop = EditorGUILayout.Toggle("Loop Clip", _variation.audio.loop);

        if (newLoop != _variation.audio.loop)
        {
            UndoHelper.RecordObjectPropertyForUndo(_variation.audio, "toggle Loop");
            _variation.audio.loop = newLoop;
        }

        var newRandomPitch = EditorGUILayout.Slider("Random Pitch", _variation.randomPitch, 0f, 3f);

        if (newRandomPitch != _variation.randomPitch)
        {
            UndoHelper.RecordObjectPropertyForUndo(_variation, "change Random Pitch");
            _variation.randomPitch = newRandomPitch;
        }

        var newRandomVolume = EditorGUILayout.Slider("Random Volume", _variation.randomVolume, 0f, 1f);

        if (newRandomVolume != _variation.randomVolume)
        {
            UndoHelper.RecordObjectPropertyForUndo(_variation, "change Random Volume");
            _variation.randomVolume = newRandomVolume;
        }

        var newWeight = EditorGUILayout.IntSlider("Weight (Instances)", _variation.weight, 0, 100);

        if (newWeight != _variation.weight)
        {
            UndoHelper.RecordObjectPropertyForUndo(_variation, "change Weight");
            _variation.weight = newWeight;
        }

        if (_variation.HasActiveFXFilter)
        {
            var newFxTailTime = EditorGUILayout.Slider("FX Tail Time", _variation.fxTailTime, 0f, 10f);
            if (newFxTailTime != _variation.fxTailTime)
            {
                UndoHelper.RecordObjectPropertyForUndo(_variation, "change FX Tail Time");
                _variation.fxTailTime = newFxTailTime;
            }
        }

        var newSilence = EditorGUILayout.BeginToggleGroup("Use Random Delay", _variation.useIntroSilence);

        if (newSilence != _variation.useIntroSilence)
        {
            UndoHelper.RecordObjectPropertyForUndo(_variation, "toggle Use Random Delay");
            _variation.useIntroSilence = newSilence;
        }

        if (_variation.useIntroSilence)
        {
            var newSilenceMin = EditorGUILayout.Slider("Delay Min (sec)", _variation.introSilenceMin, 0f, 100f);
            if (newSilenceMin != _variation.introSilenceMin)
            {
                UndoHelper.RecordObjectPropertyForUndo(_variation, "change Delay Min (sec)");
                _variation.introSilenceMin = newSilenceMin;
                if (_variation.introSilenceMin > _variation.introSilenceMax)
                {
                    _variation.introSilenceMax = newSilenceMin;
                }
            }

            var newSilenceMax = EditorGUILayout.Slider("Delay Max (sec)", _variation.introSilenceMax, 0f, 100f);
            if (newSilenceMax != _variation.introSilenceMax)
            {
                UndoHelper.RecordObjectPropertyForUndo(_variation, "change Delay Max (sec)");
                _variation.introSilenceMax = newSilenceMax;
                if (_variation.introSilenceMax < _variation.introSilenceMin)
                {
                    _variation.introSilenceMin = newSilenceMax;
                }
            }
        }
        EditorGUILayout.EndToggleGroup();


        var newUseFades = EditorGUILayout.BeginToggleGroup("Use Custom Fading", _variation.useFades);

        if (newUseFades != _variation.useFades)
        {
            UndoHelper.RecordObjectPropertyForUndo(_variation, "toggle Use Custom Fading");
            _variation.useFades = newUseFades;
        }

        if (_variation.useFades)
        {
            var newFadeIn = EditorGUILayout.Slider("Fade In Time (sec)", _variation.fadeInTime, 0f, 10f);
            if (newFadeIn != _variation.fadeInTime)
            {
                UndoHelper.RecordObjectPropertyForUndo(_variation, "change Fade In Time");
                _variation.fadeInTime = newFadeIn;
            }

            if (_variation.audio.loop)
            {
                DTGUIHelper.ShowColorWarning("*Looped clips cannot have a custom fade out.");
            }
            else
            {
                var newFadeOut = EditorGUILayout.Slider("Fade Out time (sec)", _variation.fadeOutTime, 0f, 10f);
                if (newFadeOut != _variation.fadeOutTime)
                {
                    UndoHelper.RecordObjectPropertyForUndo(_variation, "change Fade Out Time");
                    _variation.fadeOutTime = newFadeOut;
                }
            }
        }

        EditorGUILayout.EndToggleGroup();

        var filterList = new List <string>()
        {
            MasterAudio.NO_GROUP_NAME,
            "Low Pass",
            "High Pass",
            "Distortion",
            "Chorus",
            "Echo",
            "Reverb"
        };

        var newFilterIndex = EditorGUILayout.Popup("Add Filter Effect", 0, filterList.ToArray());

        switch (newFilterIndex)
        {
        case 1:
            AddFilterComponent(typeof(AudioLowPassFilter));
            break;

        case 2:
            AddFilterComponent(typeof(AudioHighPassFilter));
            break;

        case 3:
            AddFilterComponent(typeof(AudioDistortionFilter));
            break;

        case 4:
            AddFilterComponent(typeof(AudioChorusFilter));
            break;

        case 5:
            AddFilterComponent(typeof(AudioEchoFilter));
            break;

        case 6:
            AddFilterComponent(typeof(AudioReverbFilter));
            break;
        }

        if (GUI.changed || isDirty)
        {
            EditorUtility.SetDirty(target);
        }

        this.Repaint();

        //DrawDefaultInspector();
    }
Example #17
0
        private void HandleAngleSpriteListGUI(Rect rect)
        {
            if (m_CurrentAngleRange == null || !isSelectedIndexValid)
            {
                return;
            }

            var currentEvent = Event.current;
            var usedEvent    = false;
            var sprites      = m_AngleRangesProp.GetArrayElementAtIndex(selectedIndex).FindPropertyRelative("m_Sprites");

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

            case EventType.DragUpdated:
            case EventType.DragPerform:
                if (rect.Contains(currentEvent.mousePosition) && GUI.enabled)
                {
                    // Check each single object, so we can add multiple objects in a single drag.
                    var didAcceptDrag = false;
                    var references    = DragAndDrop.objectReferences;
                    foreach (var obj in references)
                    {
                        if (obj is Sprite)
                        {
                            Sprite spr = obj as Sprite;
                            if (spr.texture != null)
                            {
                                DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                                if (currentEvent.type == EventType.DragPerform && sprites.arraySize < 64)
                                {
                                    sprites.InsertArrayElementAtIndex(sprites.arraySize);
                                    var spriteProp = sprites.GetArrayElementAtIndex(sprites.arraySize - 1);
                                    spriteProp.objectReferenceValue = obj;
                                    didAcceptDrag = true;
                                    DragAndDrop.activeControlID = 0;
                                }
                            }
                        }
                    }

                    serializedObject.ApplyModifiedProperties();

                    if (didAcceptDrag)
                    {
                        GUI.changed = true;
                        DragAndDrop.AcceptDrag();
                        usedEvent = true;
                    }
                }
                break;
            }

            if (usedEvent)
            {
                currentEvent.Use();
            }
        }
    public override void OnInspectorGUI()
    {
        GUI.enabled = true;

        var editors = new List <Editor>(activeEditors.Keys);

        foreach (var editor in editors)
        {
            DrawInspectorTitlebar(editor);

            GUILayout.Space(-5f);

            if (activeEditors[editor] && editor.target != null)
            {
                editor.OnInspectorGUI();
            }

            DrawLine();
        }


        if (editors.All(e => e.target != null) == false)
        {
            InitActiveEditors();
            Repaint();
        }


        Rect dragAndDropRect = GUILayoutUtility.GetRect(GUIContent.none, GUIStyle.none, GUILayout.ExpandHeight(true), GUILayout.MinHeight(200));

        switch (Event.current.type)
        {
        case EventType.DragUpdated:
        case EventType.DragPerform:

            if (dragAndDropRect.Contains(Event.current.mousePosition) == false)
            {
                break;
            }


            DragAndDrop.visualMode = DragAndDropVisualMode.Copy;

            if (Event.current.type == EventType.DragPerform)
            {
                DragAndDrop.AcceptDrag();

                var components = DragAndDrop.objectReferences
                                 .Where(x => x.GetType() == typeof(MonoScript))
                                 .OfType <MonoScript>()
                                 .Select(m => m.GetClass());

                foreach (var component in components)
                {
                    Undo.AddComponent(scenePrefab, component);
                }
                InitActiveEditors();
            }
            break;
        }


        GUI.Label(dragAndDropRect, "");
    }
        private void HandlePackableListUI()
        {
            var currentEvent = Event.current;
            var usedEvent    = false;

            Rect rect = EditorGUILayout.GetControlRect();

            var controlID = EditorGUIUtility.s_LastControlID;

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

            case EventType.DragUpdated:
            case EventType.DragPerform:
                if (rect.Contains(currentEvent.mousePosition) && GUI.enabled)
                {
                    // Check each single object, so we can add multiple objects in a single drag.
                    var didAcceptDrag = false;
                    var references    = DragAndDrop.objectReferences;
                    foreach (var obj in references)
                    {
                        if (IsPackable(obj))
                        {
                            DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                            if (currentEvent.type == EventType.DragPerform)
                            {
                                m_Packables.AppendFoldoutPPtrValue(obj);
                                didAcceptDrag = true;
                                DragAndDrop.activeControlID = 0;
                            }
                            else
                            {
                                DragAndDrop.activeControlID = controlID;
                            }
                        }
                    }
                    if (didAcceptDrag)
                    {
                        GUI.changed = true;
                        DragAndDrop.AcceptDrag();
                        usedEvent = true;
                    }
                }
                break;

            case EventType.ValidateCommand:
                if (currentEvent.commandName == ObjectSelector.ObjectSelectorClosedCommand && ObjectSelector.get.objectSelectorID == s_Styles.packableSelectorHash)
                {
                    usedEvent = true;
                }
                break;

            case EventType.ExecuteCommand:
                if (currentEvent.commandName == ObjectSelector.ObjectSelectorClosedCommand && ObjectSelector.get.objectSelectorID == s_Styles.packableSelectorHash)
                {
                    var obj = ObjectSelector.GetCurrentObject();
                    if (IsPackable(obj))
                    {
                        m_Packables.AppendFoldoutPPtrValue(obj);
                        m_PackableList.index = m_Packables.arraySize - 1;
                    }

                    usedEvent = true;
                }
                break;
            }

            // Handle Foldout after we handle the current event because Foldout might process the drag and drop event and used it.
            m_PackableListExpanded = EditorGUI.Foldout(rect, m_PackableListExpanded, s_Styles.packableListLabel, true);

            if (usedEvent)
            {
                currentEvent.Use();
            }

            if (m_PackableListExpanded)
            {
                EditorGUI.indentLevel++;
                m_PackableList.DoLayoutList();
                EditorGUI.indentLevel--;
            }
        }
        /// <summary>
        /// A drop zone area for bot Unity and non-unity objects.
        /// </summary>
        public static object DropZone(Rect rect, object value, Type type, bool allowSceneObjects, int id)
        {
            if (rect.Contains(Event.current.mousePosition))
            {
                var t = Event.current.type;

                if (t == EventType.DragUpdated || t == EventType.DragPerform)
                {
                    // This bit disables all dropzones inside the provided preventDropAreaRect.
                    //
                    // RootNode1
                    //    ChileNode1
                    //    ChileNode2
                    //       ChileNode2.1
                    //       ChileNode2.2
                    //    ChileNode3
                    // RootNode2
                    //
                    // If the RootNode has provided a preventDropAreaRect, then that means that the RootNode won't be able to be dragged into any of its child nodes.

                    if (preventDropAreaRect.Contains(new Vector2(rect.x, rect.y)) && preventDropAreaRect.Contains(new Vector2(rect.xMax, rect.yMax)))
                    {
                        return(value);
                    }

                    object obj = null;

                    if (obj == null)
                    {
                        obj = dragginObjects.Where(x => x != null && x.GetType().InheritsFrom(type)).FirstOrDefault();
                    }
                    if (obj == null)
                    {
                        obj = DragAndDrop.objectReferences.Where(x => x != null && x.GetType().InheritsFrom(type)).FirstOrDefault();
                    }

                    if (type.InheritsFrom <Component>() || type.IsInterface)
                    {
                        if (obj == null)
                        {
                            obj = dragginObjects.OfType <GameObject>().Where(x => x != null).Select(x => x.GetComponent(type)).Where(x => x != null).FirstOrDefault();
                        }
                        if (obj == null)
                        {
                            obj = DragAndDrop.objectReferences.OfType <GameObject>().Where(x => x != null).Select(x => x.GetComponent(type)).Where(x => x != null).FirstOrDefault();
                        }
                    }

                    bool acceptsDrag = obj != null;

                    if (acceptsDrag && allowSceneObjects == false)
                    {
                        var uObj = obj as UnityEngine.Object;
                        if (uObj != null)
                        {
                            if (typeof(Component).IsAssignableFrom(uObj.GetType()))
                            {
                                uObj = ((Component)uObj).gameObject;
                            }

                            acceptsDrag = EditorUtility.IsPersistent(uObj);
                        }
                    }

                    if (acceptsDrag)
                    {
                        hoveringAcceptedDropZone = id;
                        bool move = Event.current.modifiers != EventModifiers.Control && draggingId != 0 && currentDragIsMove;
                        if (move)
                        {
                            DragAndDrop.visualMode = DragAndDropVisualMode.Move;
                        }
                        else
                        {
                            DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                        }

                        Event.current.Use();
                        if (t == EventType.DragPerform)
                        {
                            if (!move)
                            {
                                draggingId = 0;
                                //preventDropAreaRect = new Rect();
                            }

                            // Calling this here makes Unity crash on MacOS
                            // DragAndDrop.objectReferences = new UnityEngine.Object[] { };
                            DragAndDrop.AcceptDrag();
                            GUI.changed = true;
                            GUIHelper.RemoveFocusControl();
                            dragginObjects              = new object[] { };
                            currentDragIsMove           = false;
                            isAccepted                  = true;
                            dropZoneObject              = value;
                            preventDropAreaRect         = new Rect();
                            DragAndDrop.activeControlID = 0;
                            GUIHelper.RequestRepaint();
                            return(obj);
                        }
                        else
                        {
                            DragAndDrop.activeControlID = id;
                        }
                    }
                    else
                    {
                        hoveringAcceptedDropZone = 0;
                        DragAndDrop.visualMode   = DragAndDropVisualMode.Rejected;
                    }
                }
            }
            else
            {
                if (hoveringAcceptedDropZone == id)
                {
                    hoveringAcceptedDropZone = 0;
                }
            }

            return(value);
        }
Example #21
0
    void OnGUI()
    {
        if (null == m_ac)
        {
            // アニメーター・コントローラーを再取得。
            m_ac = AssetDatabase.LoadAssetAtPath <AnimatorController>(oldPath_animatorController);
        }
        bool repaint_allWindow = false;

        GUILayout.Label("Animator controller", EditorStyles.boldLabel);
        #region Drag and drop area
        var dropArea = GUILayoutUtility.GetRect(0.0f, 20.0f, GUILayout.ExpandWidth(true));
        GUI.Box(dropArea, "Animator Controller Drag & Drop");
        string droppedPath_animatorController = "";
        // マウス位置が GUI の範囲内であれば
        if (dropArea.Contains(Event.current.mousePosition))
        {
            switch (Event.current.type)
            {
            // マウス・ホバー中
            case EventType.DragUpdated:
            {
                // ドラッグしているのが参照可能なオブジェクトの場合
                if (0 < DragAndDrop.objectReferences.Length)
                {
                    //オブジェクトを受け入れる
                    DragAndDrop.AcceptDrag();

                    // マウス・カーソルの形状を、このオブジェクトを受け入れられるという見た目にする
                    DragAndDrop.visualMode = DragAndDropVisualMode.Generic;
                }
            }
            break;

            // ドロップしたら
            case EventType.DragPerform:
            {
                // ドラッグしているものを現在のコントロール ID と紐付ける
                DragAndDrop.activeControlID = DragAndDrop.objectReferences[0].GetInstanceID();

                // ドロップしているのが参照可能なオブジェクトの場合
                if (DragAndDrop.objectReferences.Length == 1)
                {
                    foreach (var draggedObject in DragAndDrop.objectReferences)
                    {
                        AnimatorController ac_temp = draggedObject as AnimatorController;
                        if (null != ac_temp)
                        {
                            droppedPath_animatorController = AssetDatabase.GetAssetPath(ac_temp.GetInstanceID());
                            Repaint();
                            repaint_allWindow = true;
                        }
                    }
                }
            }
            break;

                //case EventType.DragExited: // ?
            }
        }
        #endregion

        bool isChanged_animatorController = false;
        #region Animator controller path
        if ("" != droppedPath_animatorController && oldPath_animatorController != droppedPath_animatorController)
        {
            // 異なるアニメーター・コントローラーのパスがドロップされた
            oldPath_animatorController   = droppedPath_animatorController;
            isChanged_animatorController = true;
        }

        string newPath_animatorController;
        newPath_animatorController = EditorGUILayout.TextField(oldPath_animatorController);

        if (oldPath_animatorController != newPath_animatorController)
        {
            // 異なるアニメーター・コントローラーのパスが入力された
            oldPath_animatorController   = newPath_animatorController;
            isChanged_animatorController = true;
        }
        #endregion

        if (isChanged_animatorController)
        {
            // アニメーター・コントローラーを再取得。
            m_ac = AssetDatabase.LoadAssetAtPath <AnimatorController>(oldPath_animatorController);
        }

        #region Create full path constant button
        if (GUILayout.Button(BUTTON_LABEL_GENERATE_FULLPATH))
        {
            info_message.Append("Generate fullpath Start. filename(without extension) = "); info_message.Append(m_ac.name); info_message.AppendLine();
            FullpathConstantGenerator.WriteCshapScript(m_ac, info_message);
            info_message.Append("Generate fullpath End. filename(without extension) = "); info_message.Append(m_ac.name); info_message.AppendLine();
        }
        GUILayout.Space(4.0f);
        #endregion

        bool isActivate_aconState;
        #region Acon state readability judgment
        if (!UserSettings.Instance.AnimationControllerFilepath_to_userDefinedInstance.ContainsKey(oldPath_animatorController))
        {
            int step = 1;
            if ("" == oldPath_animatorController)
            {
                GUILayout.Label("Failure.", EditorStyles.boldLabel);
                GUILayout.Label(String.Concat("(", step, ") Please drag and drop"), EditorStyles.boldLabel);
                GUILayout.Label("    your animator controller", EditorStyles.boldLabel);
                GUILayout.Label("    to the box above.", EditorStyles.boldLabel);
                step++;
            }
            GUILayout.Label(String.Concat("(", step, ") Please add the"), EditorStyles.boldLabel);
            GUILayout.Label("    path of your animator controller", EditorStyles.boldLabel);
            GUILayout.Label(String.Concat("    to ", FileUtility_Engine.PATH_USER_SETTINGS), EditorStyles.boldLabel);
            step++;

            UserSettings.Instance.Dump_Presentable(info_message);
            isActivate_aconState = false;
        }
        else
        {
            isActivate_aconState = true;
        }
        #endregion
        if (isActivate_aconState)
        {
            #region Query text area
            {
                GUILayout.Label("Query (StellaQL)");
                scroll_commandBox = EditorGUILayout.BeginScrollView(scroll_commandBox);
                commandline       = EditorGUILayout.TextArea(commandline);//, GUILayout.Height(position.height - 30)
                EditorGUILayout.EndScrollView();
            }
            #endregion
            #region Execution button
            {
                if (GUILayout.Button("Execute"))
                {
                    info_message.Append("I pressed the Execute button."); info_message.AppendLine();
                    AControllable userDefinedStateTable = UserSettings.Instance.AnimationControllerFilepath_to_userDefinedInstance[oldPath_animatorController];
                    SequenceQuerier.Execute(m_ac, commandline, userDefinedStateTable, info_message);
                    Repaint();
                    repaint_allWindow = true;
                    info_message.Append("Execute end."); info_message.AppendLine();
                }
            }
            #endregion
            GUILayout.Space(4.0f);
            #region Export Spreadsheet button
            // 実際は CSV形式ファイルを出力する
            GUILayout.Space(4.0f);
            if (GUILayout.Button("Export spread sheet")) // Export CSV
            {
                info_message.Append("Export spread sheet Start. filename(without extension) = "); info_message.Append(m_ac.name); info_message.AppendLine();
                info_message.Append("Please, Use Libre Office Calc."); info_message.AppendLine();
                info_message.Append("And use macro application."); info_message.AppendLine();
                info_message.Append("location: "); info_message.Append(FileUtility_Editor.Filepath_StellaQLMacroApplicationOds()); info_message.AppendLine();

                AconScanner aconScanner = new AconScanner();
                aconScanner.ScanAnimatorController(m_ac, info_message);
                AconDocument aconDocument     = aconScanner.AconDocument;
                bool         outputDefinition = false;
                for (int i = 0; i < 2; i++)
                {
                    if (i == 1)
                    {
                        outputDefinition = true;
                    }

                    // 参照 : Cannot convert HashSet to IReadOnlyCollection : http://stackoverflow.com/questions/32762631/cannot-convert-hashset-to-ireadonlycollection
                    {
                        StringBuilder contents = new StringBuilder();
                        AconDataUtility.CreateCsvTable(AconDataUtility.ToHash(aconDocument.parameters), ParameterRecord.Empty, outputDefinition, contents);
                        FileUtility_Editor.Write(FileUtility_Editor.Filepath_LogParameters(m_ac.name, outputDefinition), contents, info_message);
                    }
                    {
                        StringBuilder contents = new StringBuilder();
                        AconDataUtility.CreateCsvTable(AconDataUtility.ToHash(aconDocument.layers), LayerRecord.Empty, outputDefinition, contents);
                        FileUtility_Editor.Write(FileUtility_Editor.Filepath_LogLayer(m_ac.name, outputDefinition), contents, info_message);
                    }
                    {
                        StringBuilder contents = new StringBuilder();
                        AconDataUtility.CreateCsvTable(AconDataUtility.ToHash(aconDocument.statemachines), StatemachineRecord.Empty, outputDefinition, contents);
                        FileUtility_Editor.Write(FileUtility_Editor.Filepath_LogStatemachine(m_ac.name, outputDefinition), contents, info_message);
                    }
                    {
                        StringBuilder contents = new StringBuilder();
                        AconDataUtility.CreateCsvTable(AconDataUtility.ToHash(aconDocument.states), StateRecord.Empty, outputDefinition, contents);
                        FileUtility_Editor.Write(FileUtility_Editor.Filepath_LogStates(m_ac.name, outputDefinition), contents, info_message);
                    }
                    {
                        StringBuilder contents = new StringBuilder();
                        AconDataUtility.CreateCsvTable(AconDataUtility.ToHash(aconDocument.transitions), TransitionRecord.Empty, outputDefinition, contents);
                        FileUtility_Editor.Write(FileUtility_Editor.Filepath_LogTransition(m_ac.name, outputDefinition), contents, info_message);
                    }
                    {
                        StringBuilder contents = new StringBuilder();
                        AconDataUtility.CreateCsvTable(AconDataUtility.ToHash(aconDocument.conditions), ConditionRecord.Empty, outputDefinition, contents);
                        FileUtility_Editor.Write(FileUtility_Editor.Filepath_LogConditions(m_ac.name, outputDefinition), contents, info_message);
                    }
                    {
                        StringBuilder contents = new StringBuilder();
                        AconDataUtility.CreateCsvTable(AconDataUtility.ToHash(aconDocument.positions), PositionRecord.Empty, outputDefinition, contents);
                        FileUtility_Editor.Write(FileUtility_Editor.Filepath_LogPositions(m_ac.name, outputDefinition), contents, info_message);
                    }
                    {
                        StringBuilder contents = new StringBuilder();
                        AconDataUtility.CreateCsvTable(AconDataUtility.ToHash(aconDocument.motions), MotionRecord.Empty, outputDefinition, contents);
                        FileUtility_Editor.Write(FileUtility_Editor.Filepath_LogMotions(m_ac.name, outputDefinition), contents, info_message);
                    }
                }
            }
            #endregion
            #region Import Spreadsheet button
            // 実際はCSV形式ファイルを出力する
            if (GUILayout.Button("Import spread sheet")) // Import CSV
            {
                info_message.Append("Import spread sheet Start. filename(without extension) = "); info_message.Append(m_ac.name); info_message.AppendLine();

                // 現状のデータ
                AconScanner aconScanner = new AconScanner();
                aconScanner.ScanAnimatorController(m_ac, info_message);
                AconDocument aconData_scanned = aconScanner.AconDocument;

                HashSet <DataManipulationRecord> updateRequest;
                // CSVファイル読取
                FileUtility_Editor.ReadUpdateRequestCsv(out updateRequest, info_message);
                AnimatorControllerWrapper acWrapper = new AnimatorControllerWrapper(m_ac);
                // 更新を実行
                Operation_Something.ManipulateData(acWrapper, aconData_scanned, updateRequest, info_message);

                // 編集したレイヤーのプロパティーを反映させる。
                //Operation_Layer.RefreshAllLayers(acWrapper);

                FileUtility_Editor.DeleteUpdateRequestCsv(info_message);

                // 他のウィンドウはリフレッシュしてくれないみたいだ。
                Repaint();
                repaint_allWindow = true;
                info_message.Append("Import spread sheet End. filename(without extension) = "); info_message.Append(m_ac.name); info_message.AppendLine();
                //info_message.AppendLine("Please, Refresh Animator window.");
                //info_message.AppendLine("  case 1: (1) mouse right button click on Animator window tab.");
                //info_message.AppendLine("          (2) [Close Tab] click.");
                //info_message.AppendLine("          (3) menu [Window] - [Animator] click.");
                //info_message.AppendLine("  case 2: Click [Auto Live Link] Button on right top corner, twice(toggle).");
            }
            #endregion
        }

        #region Various Refresh
        {
            if (repaint_allWindow)
            {
                UnityEditor.EditorApplication.isPlaying = true; // Play.
                info_message.AppendLine("I'm sorry!");
                info_message.AppendLine("    I clickeded the play button!");
                info_message.AppendLine("Because, This is for");
                info_message.AppendLine("    refreshing the animator window!");
                info_message.AppendLine("Please, Push back the play button.");

                // これ全部、アニメーター・ウィンドウには効かない
                //{
                //    Repaint();
                //    EditorApplication.RepaintAnimationWindow();
                //    EditorApplication.RepaintHierarchyWindow();
                //    EditorApplication.RepaintProjectWindow();
                //    UnityEditor.HandleUtility.Repaint();
                //    UnityEditorInternal.InternalEditorUtility.RepaintAllViews();
                //    EditorWindow animatorWindow = EditorWindow.GetWindow<EditorWindow>("Animator");
                //    animatorWindow.Repaint();
                //}
            }
        }
        #endregion

        #region Message output field
        {
            GUILayout.Label("Info");
            if (0 < info_message.Length)
            {
                // 更新
                info_message_ofTextbox = info_message.ToString();
                info_message.Length    = 0;
            }

            scroll_infoBox         = EditorGUILayout.BeginScrollView(scroll_infoBox);
            info_message_ofTextbox = EditorGUILayout.TextArea(info_message_ofTextbox); //, GUILayout.Height(position.height - 30)
                                                                                       // Repaint();
            EditorGUILayout.EndScrollView();
        }
        #endregion
    }
        // Drag and drop logic
        protected void DragDropGUI(BlockoutItemPreview targetPreview, Rect previewArea)
        {
            // Chache event data
            Event     currentEvent     = Event.current;
            EventType currentEventType = currentEvent.type;

            // The DragExited event does not have the same mouse position data as the other events,
            // so it must be checked now:
            if (currentEventType == EventType.DragExited)
            {
                DragAndDrop.PrepareStartDrag();                                          // Clear generic data when user pressed escape. (Unfortunately, DragExited is also called when the mouse leaves the drag area)
            }
            switch (currentEventType)
            {
            case EventType.MouseDown:
                if (!previewArea.Contains(currentEvent.mousePosition))
                {
                    return;
                }
                // Mouse is within the preview area and has been clicked. Reset drag data
                DragAndDrop.PrepareStartDrag();    // reset data
                dragging = false;
                currentEvent.Use();
                break;

            case EventType.MouseDrag:
                // If drag was started here:
                if (!previewArea.Contains(currentEvent.mousePosition))
                {
                    return;
                }
                // Start the drag event with drag references
                dragging = true;
                Object[] objectReferences = new Object[1] {
                    targetPreview.prefab
                };                                                  // Careful, null values cause exceptions in existing editor code.
                DragAndDrop.objectReferences = objectReferences;    // Note: this object won't be 'get'-able until the next GUI event.

                DragAndDrop.StartDrag(targetPreview.name);
                currentEvent.Use();
                break;

            case EventType.DragUpdated:
                // Drag positioning has been updated so check if its valid.
                if (IsDragTargetValid())
                {
                    DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                    // Spawn the asset if it doesnt exist
                    if (!spwanedAsset)
                    {
                        spwanedAsset = Instantiate(targetPreview.prefab);
                    }

                    PlaceDraggedAsset();
                }
                else
                {
                    DragAndDrop.visualMode = DragAndDropVisualMode.Rejected;
                }
                dragging = true;
                currentEvent.Use();
                break;

            case EventType.DragPerform:
                // When the drag event has finished, place it and end the event if its valid. If it isn't valid,
                // destroy the object
                if (IsDragTargetValid())
                {
                    DragAndDrop.AcceptDrag();
                    PlaceDraggedAsset();
                }
                else if (spwanedAsset != null)
                {
                    DestroyImmediate(spwanedAsset);
                }
                dragging = true;
                currentEvent.Use();
                break;

            case EventType.DragExited:
                // If the drag event has ben canceled, destroy the spawned asset if its already spawned
                if (spwanedAsset != null)
                {
                    DestroyImmediate(spwanedAsset);
                }
                dragging = false;
                break;

            case EventType.MouseUp:
                // Clean up, in case MouseDrag never occurred:
                DragAndDrop.PrepareStartDrag();
                if (!dragging && previewArea.Contains(currentEvent.mousePosition))
                {
                    // if the mouse is still within the preview area and no drag event has occured, then its only been clicked
                    // So selected it in the project window
                    Selection.activeGameObject = targetPreview.prefab;
                    EditorGUIUtility.PingObject(targetPreview.prefab);

                    repaint = true;
                }
                break;
            }
        }
Example #23
0
        private void    PostHandleDrag(Rect r)
        {
            if (DragAndDrop.GetGenericData(GUIListDrawer <T> .GenericDataKey) == null || r.y >= Event.current.mousePosition.y)
            {
                return;
            }

            if (Event.current.type == EventType.Repaint)
            {
                if (DragAndDrop.visualMode == DragAndDropVisualMode.Move)
                {
                    float h = r.height;
                    r.height = 1F;
                    EditorGUI.DrawRect(r, Color.blue);
                    r.height = h;
                }
            }
            else if (Event.current.type == EventType.DragUpdated)
            {
                int max;

                if (this.array != null)
                {
                    max = this.array.Length - 1;
                }
                else
                {
                    max = this.list.Count - 1;
                }

                if (max.Equals(DragAndDrop.GetGenericData(GUIListDrawer <T> .GenericDataKey)) == false)
                {
                    DragAndDrop.visualMode = DragAndDropVisualMode.Move;
                }
                else
                {
                    DragAndDrop.visualMode = DragAndDropVisualMode.Rejected;
                }

                Event.current.Use();
            }
            else if (Event.current.type == EventType.DragPerform)
            {
                DragAndDrop.AcceptDrag();

                int origin = (int)DragAndDrop.GetGenericData(GUIListDrawer <T> .GenericDataKey);

                if (this.array != null)
                {
                    T t = this.array[origin];

                    for (int j = origin; j < this.array.Length - 1; j += 1)
                    {
                        this.array[j] = this.array[j + 1];
                    }

                    this.array[this.array.Length - 1] = t;
                }
                else
                {
                    T e = this.list[origin];

                    this.list.RemoveAt(origin);
                    this.list.Add(e);
                }

                if (this.ArrayReordered != null)
                {
                    this.ArrayReordered(this);
                }

                Event.current.Use();
            }
        }
Example #24
0
        public void DropAreaGUI()
        {
            //Ok - set up for drag and drop
            Event evt       = Event.current;
            Rect  drop_area = GUILayoutUtility.GetRect(0.0f, 50.0f, GUILayout.ExpandWidth(true));

            GUI.Box(drop_area, "Drop Here To Scan", m_boxStyle);

            switch (evt.type)
            {
            case EventType.DragUpdated:
            case EventType.DragPerform:
            {
                if (!drop_area.Contains(evt.mousePosition))
                {
                    break;
                }

                DragAndDrop.visualMode = DragAndDropVisualMode.Copy;

                if (evt.type == EventType.DragPerform)
                {
                    DragAndDrop.AcceptDrag();
                    m_rawFilePath   = null;
                    m_assumedRawRes = 0;

                    //First lets determine whether we got something we are interested in

                    //Is it a saved file - only raw files are processed this way
                    if (DragAndDrop.paths.Length > 0)
                    {
                        string filePath = DragAndDrop.paths[0];

                        //Update in case unity has messed with it
                        if (filePath.StartsWith("Assets"))
                        {
                            filePath = Path.Combine(Application.dataPath, filePath.Substring(7)).Replace('\\', '/');
                        }

                        //Check file type and process as we can
                        string fileType = Path.GetExtension(filePath).ToLower();

                        //Handle raw files
                        if (fileType == ".r16" || fileType == ".raw")
                        {
                            m_rawFilePath = filePath;
                            m_scanner.LoadRawFile(filePath, m_rawByteOrder, ref m_rawBitDepth, ref m_assumedRawRes);
                            return;
                        }
                    }

                    //Is it something that unity knows about - may or may not have been saved
                    if (DragAndDrop.objectReferences.Length > 0)
                    {
                        //Debug.Log("Name is " + DragAndDrop.objectReferences[0].name);
                        //Debug.Log("Type is " + DragAndDrop.objectReferences[0].GetType());

                        //Check for textures
                        if (DragAndDrop.objectReferences[0].GetType() == typeof(UnityEngine.Texture2D))
                        {
                            GaiaUtils.MakeTextureReadable(DragAndDrop.objectReferences[0] as Texture2D);
                            GaiaUtils.MakeTextureUncompressed(DragAndDrop.objectReferences[0] as Texture2D);
                            m_scanner.LoadTextureFile(DragAndDrop.objectReferences[0] as Texture2D);
                            return;
                        }

                        //Check for terrains
                        if (DragAndDrop.objectReferences[0].GetType() == typeof(UnityEngine.GameObject))
                        {
                            GameObject go = DragAndDrop.objectReferences[0] as GameObject;
                            Terrain    t  = go.GetComponentInChildren <Terrain>();

                            //Handle a terrain
                            if (t != null)
                            {
                                m_scanner.LoadTerain(t);
                                return;
                            }
                        }

                        //Check for something with a mesh
                        if (DragAndDrop.objectReferences[0].GetType() == typeof(UnityEngine.GameObject))
                        {
                            GameObject go = DragAndDrop.objectReferences[0] as GameObject;

                            //Check for a mesh - this means we can scan it
                            MeshFilter[] filters = go.GetComponentsInChildren <MeshFilter>();
                            for (int idx = 0; idx < filters.Length; idx++)
                            {
                                if (filters[idx].mesh != null)
                                {
                                    m_scanner.LoadGameObject(go);
                                    return;
                                }
                            }
                        }
                    }

                    //If we got to here then we couldnt process it
                    Debug.LogWarning("Object type not supported by scanner. Ignored");
                }

                break;
            }
            }
        }
Example #25
0
        public void Controls()
        {
            wantsMouseMove = true;
            Event e = Event.current;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            case EventType.Ignore:
                // If release mouse outside window
                if (e.rawType == EventType.MouseUp && currentActivity == NodeActivity.DragGrid)
                {
                    Repaint();
                    currentActivity = NodeActivity.Idle;
                }
                break;
            }
        }
Example #26
0
        private void MaterialMasking(Rect Area, DynamicDecalSettings Settings)
        {
            if (Settings.maskMethod == DecalMaskMethod.Material || Settings.maskMethod == DecalMaskMethod.Both)
            {
                GUI.BeginGroup(Area);

                //Header
                if (Settings.maskMethod == DecalMaskMethod.Both)
                {
                    EditorGUI.LabelField(new Rect(0, 0, Area.width, 16), materials, EditorStyles.boldLabel);
                }

                //Background
                EditorGUI.DrawRect(new Rect(0, 16, Area.width, 108), LlockhamEditorUtility.BackgroundColor);

                //Create drop area
                Rect DropArea = new Rect(4, 20, Area.width - 8, 100);

                //Drag and drop materials
                if (DropArea.Contains(Event.current.mousePosition))
                {
                    switch (Event.current.type)
                    {
                    case EventType.DragUpdated:
                        if (DraggedMaterials.Count > 0)
                        {
                            DragAndDrop.visualMode = DragAndDropVisualMode.Link;
                        }
                        else
                        {
                            DragAndDrop.visualMode = DragAndDropVisualMode.Rejected;
                        }

                        Event.current.Use();
                        break;

                    case EventType.DragPerform:
                        DragAndDrop.AcceptDrag();
                        foreach (Material material in DraggedMaterials)
                        {
                            Settings.AddMaterial(material);
                        }
                        Event.current.Use();
                        break;

                    case EventType.MouseUp:
                        DragAndDrop.PrepareStartDrag();
                        break;
                    }
                }

                //Material scroll view
                materialScrollPosition = GUI.BeginScrollView(DropArea, materialScrollPosition, new Rect(0, 0, Area.width - 8, Settings.Materials.Count * 20), GUIStyle.none, GUIStyle.none);
                for (int i = 0; i < Settings.Materials.Count; i++)
                {
                    EditorGUI.DrawRect(new Rect(0, i * 20, Area.width - 8, 18), LlockhamEditorUtility.ForegroundColor);
                    EditorGUI.LabelField(new Rect(4, i * 20, 120, 18), Settings.Materials[i].name);
                    if (GUI.Button(new Rect(Area.width - 34, 3 + (i * 20), 20, 12), " - "))
                    {
                        Settings.RemoveMaterial(i);
                    }
                }

                GUI.EndScrollView();
                GUI.EndGroup();
            }
        }
Example #27
0
    public override void OnInspectorGUI()
    {
        EditorGUILayout.HelpBox("This allows Easy Save to maintain references to objects in your scene.\n\nIt is automatically updated when you enter Playmode or build your project.", MessageType.Info);

        var mgr = (ES3ReferenceMgr)serializedObject.targetObject;

        mgr.openReferences = EditorGUILayout.Foldout(mgr.openReferences, "References");
        // Make foldout drag-and-drop enabled for objects.
        if (GUILayoutUtility.GetLastRect().Contains(Event.current.mousePosition))
        {
            Event evt = Event.current;

            switch (evt.type)
            {
            case EventType.DragUpdated:
            case EventType.DragPerform:
                isDraggingOver = true;
                break;

            case EventType.DragExited:
                isDraggingOver = false;
                break;
            }

            if (isDraggingOver)
            {
                DragAndDrop.visualMode = DragAndDropVisualMode.Copy;

                if (evt.type == EventType.DragPerform)
                {
                    DragAndDrop.AcceptDrag();
                    Undo.RecordObject(mgr, "Add References to Easy Save 3 Reference List");
                    foreach (UnityEngine.Object obj in DragAndDrop.objectReferences)
                    {
                        mgr.Add(obj);
                    }
                    // Return now because otherwise we'll change the GUI during an event which doesn't allow it.
                    return;
                }
            }
        }

        if (mgr.openReferences)
        {
            EditorGUI.indentLevel++;

            var keys   = mgr.idRef.Keys;
            var values = mgr.idRef.Values;

            for (int i = 0; i < keys.Count; i++)
            {
                EditorGUILayout.BeginHorizontal();

                var value = EditorGUILayout.ObjectField(values[i], typeof(UnityEngine.Object), true);
                var key   = EditorGUILayout.LongField(keys[i]);

                EditorGUILayout.EndHorizontal();

                if (value != values[i] || key != keys[i])
                {
                    Undo.RecordObject(mgr, "Change Easy Save 3 References");

                    // If we're deleting a value, delete it.
                    if (value == null)
                    {
                        mgr.Remove(key);
                    }
                    // Else, update the ID.
                    else
                    {
                        mgr.idRef.ChangeKey(keys[i], key);
                    }
                }
            }

            EditorGUI.indentLevel--;
        }

        if (GUILayout.Button("Refresh References"))
        {
            mgr.GenerateReferences();
            mgr.GeneratePrefabReferences();
        }
    }
        public override void OnInspectorGUI()
        {
            var proCamera2DCinematics = (ProCamera2DCinematics)target;

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

            serializedObject.Update();

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

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

            // Targets Drop Area
            EditorGUILayout.Space();
            Event evt       = Event.current;
            Rect  drop_area = GUILayoutUtility.GetRect(0.0f, 50.0f, GUILayout.ExpandWidth(true));
            var   style     = new GUIStyle("box");

            if (EditorGUIUtility.isProSkin)
            {
                style.normal.textColor = Color.white;
            }
            GUI.Box(drop_area, "\nDROP CINEMATC TARGETS HERE", style);

            switch (evt.type)
            {
            case EventType.DragUpdated:
            case EventType.DragPerform:
                if (!drop_area.Contains(evt.mousePosition))
                {
                    return;
                }

                DragAndDrop.visualMode = DragAndDropVisualMode.Copy;

                if (evt.type == EventType.DragPerform)
                {
                    DragAndDrop.AcceptDrag();

                    foreach (Object dragged_object in DragAndDrop.objectReferences)
                    {
                        var newCinematicTarget = new CinematicTarget
                        {
                            TargetTransform = ((GameObject)dragged_object).transform,
                            EaseInDuration  = 1f,
                            HoldDuration    = 1f,
                            EaseType        = EaseType.EaseOut
                        };

                        proCamera2DCinematics.CinematicTargets.Add(newCinematicTarget);
                        EditorUtility.SetDirty(proCamera2DCinematics);
                    }
                }
                break;
            }

            EditorGUILayout.Space();

            // Remove empty targets
            for (int i = 0; i < proCamera2DCinematics.CinematicTargets.Count; i++)
            {
                if (proCamera2DCinematics.CinematicTargets[i].TargetTransform == null)
                {
                    proCamera2DCinematics.CinematicTargets.RemoveAt(i);
                }
            }

            // Camera targets list
            _cinematicTargetsList.DoLayoutList();
            EditorGUILayout.Space();

            // End duration
            _tooltip = new GUIContent("End Duration", "How long it takes for the camera to get back to its regular targets");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("EndDuration"), _tooltip);

            // End ease type
            _tooltip = new GUIContent("End Ease Type", "The ease type of the end animation");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("EndEaseType"), _tooltip);

            // Use numeric boundaries
            _tooltip = new GUIContent("Use Numeric Boundaries", "If existent, the camera movement will be limited by the numeric boundaries");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("UseNumericBoundaries"), _tooltip);

            // Letterbox
            _tooltip = new GUIContent("Use Letterbox", "If checked, the camera will show black bars on top and bottom during the cinematic sequence");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("UseLetterbox"), _tooltip);

            if (proCamera2DCinematics.UseLetterbox)
            {
                // Letterbox amount
                _tooltip = new GUIContent("Letterbox Amount", "");
                EditorGUILayout.PropertyField(serializedObject.FindProperty("LetterboxAmount"), _tooltip);

                // Letterbox animation duration
                _tooltip = new GUIContent("Letterbox Anim Duration", "");
                EditorGUILayout.PropertyField(serializedObject.FindProperty("LetterboxAnimDuration"), _tooltip);

                // Letterbox color
                _tooltip = new GUIContent("Letterbox Color", "");
                EditorGUILayout.PropertyField(serializedObject.FindProperty("LetterboxColor"), _tooltip);
            }

            // Test buttons
            EditorGUILayout.Space();
            EditorGUILayout.Space();

            GUI.enabled = Application.isPlaying;
            if (GUILayout.Button((proCamera2DCinematics.IsActive ? "Stop" : "Start") + " Cinematic"))
            {
                if (proCamera2DCinematics.IsActive)
                {
                    proCamera2DCinematics.Stop();
                }
                else
                {
                    proCamera2DCinematics.Play();
                }
            }
            GUI.enabled = true;

            serializedObject.ApplyModifiedProperties();
        }
Example #29
0
    public void DropAreaGUI()
    {
        var evt = Event.current;

        var dropArea = GUILayoutUtility.GetRect(0.0f, 50.0f, GUILayout.ExpandWidth(true));

        GUI.Box(dropArea, "Register New Icon");

        switch (evt.type)
        {
        case EventType.DragUpdated:
        case EventType.DragPerform:
            if (!dropArea.Contains(evt.mousePosition))
            {
                break;
            }

            DragAndDrop.visualMode = DragAndDropVisualMode.Copy;

            if (evt.type == EventType.DragPerform)
            {
                DragAndDrop.AcceptDrag();
                foreach (var draggedObject in DragAndDrop.objectReferences)
                {
                    var go = draggedObject as GameObject;
                    if (!go)
                    {
                        continue;
                    }
                    unityGameObjects.Add(go);
                    GameObject newObject = Instantiate(go, new Vector3(0.0f, 0.0f, 0.0f), Quaternion.identity) as GameObject;
                    // newObject.hideFlags = HideFlags.HideAndDontSave;
                    PrefabSettings pSetting = new PrefabSettings();
                    int            index    = iconData.settings.FindIndex(x => x.Go == go);
                    // load from icon data
                    if (index != -1)
                    {
                        pSetting.Go                        = go;
                        pSetting.cameraSize                = iconData.settings[index].cameraSize;
                        pSetting.offset                    = iconData.settings[index].offset;
                        pSetting.cameraRotate              = iconData.settings[index].cameraRotate;
                        pSetting.cameraTilt                = iconData.settings[index].cameraTilt;
                        _camTilt.transform.localRotation   = Quaternion.Euler(new Vector3(pSetting.cameraTilt, 45, 0));
                        _camRotate.transform.localRotation = Quaternion.Euler(new Vector3(0, pSetting.cameraRotate, 0));
                    }
                    // add to icon data
                    else
                    {
                        Bounds bb  = GetMaxBounds(newObject);
                        float  max = Mathf.Max(bb.size.x, bb.size.y, bb.size.z);
                        pSetting.Go           = go;
                        pSetting.originalY    = bb.center.y;
                        pSetting.cameraSize   = max;
                        pSetting.offset       = new Vector2(0, 0);
                        pSetting.cameraRotate = 0.0f;
                        pSetting.cameraTilt   = 0.0f;
                        iconData.settings.Add(pSetting);
                    }
                    controlToggles.Add(false);
                    prefabs.Add(pSetting);
                    inSceneObjects.Add(newObject);
                }
                UpdateScene(unityGameObjects.Count - 1);
                RenderNow();
            }
            Event.current.Use();
            break;
        }
    }
    void OnGUI()
    {
        // Description
        Rect descRect = EditorGUILayout.BeginVertical();

        EditorGUI.DrawRect(descRect, light);
        if (!string.IsNullOrEmpty(description))
        {
            GUIStyle multiLineBold = new GUIStyle();
            multiLineBold.font     = EditorStyles.boldFont;
            multiLineBold.wordWrap = true;
            multiLineBold.padding  = new RectOffset(8, 8, 16, 16);
            EditorGUILayout.LabelField(description, multiLineBold);
        }
        EditorGUI.DrawRect(new Rect(descRect.x, descRect.yMax, descRect.width, 1f), Color.grey);
        EditorGUILayout.EndVertical();

        // Selection
        if (selectionRoot.children.Count == 0)
        {
            EditorGUILayout.HelpBox("Nothing selected", MessageType.Info);
            GUILayout.FlexibleSpace();
        }
        else
        {
            scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition);
            foreach (AssetItem asset in selectionRoot.children)
            {
                DoItemGUI(asset);
            }
            EditorGUILayout.EndScrollView();
        }

        // DragAndDrop operation
        if (Event.current.type == EventType.DragUpdated)
        {
            Object[] objs = DragAndDrop.objectReferences;
            if (ArrayUtility.FindIndex(objs, (obj) => AssetDatabase.IsMainAsset(obj)) >= 0)
            {
                DragAndDrop.visualMode = DragAndDropVisualMode.Link;
            }
        }
        else if (Event.current.type == EventType.DragPerform)
        {
            DragAndDrop.AcceptDrag();
            Object[] objs = DragAndDrop.objectReferences;
            foreach (Object obj in objs)
            {
                string path = AssetDatabase.GetAssetPath(obj);
                SortedInsert(path, true);
            }
            ValidateSelection();
        }

        // Options
        Rect optionsRect = EditorGUILayout.BeginVertical();

        EditorGUI.DrawRect(optionsRect, light);
        EditorGUI.DrawRect(new Rect(optionsRect.x, optionsRect.yMin, optionsRect.width, 1f), lighter);
        EditorGUILayout.Space();
        if (OnOptionsGUI != null)
        {
            OnOptionsGUI(this);
        }
        else
        {
            GUILayout.Label("Please, reopen this window to reload the options", EditorStyles.centeredGreyMiniLabel);
        }
        EditorGUILayout.Space();
        EditorGUILayout.EndVertical();
    }