Ejemplo n.º 1
0
        /// <summary>
        /// Whether the mouse position is within the bounds of the axis snapping gizmo that appears in the top right or the bottom toolbar
        /// </summary>
        public static bool IsMousePositionInInvalidRects(Vector2 mousePosition)
        {
            float scale = 1;

#if UNITY_5_4_OR_NEWER
            mousePosition = EditorGUIUtility.PointsToPixels(mousePosition);
            scale         = EditorGUIUtility.pixelsPerPoint;
#endif

            if (mousePosition.x < Screen.width - 14 * scale &&
                mousePosition.x > Screen.width - 89 * scale &&
                mousePosition.y > 14 * scale &&
                mousePosition.y < 105 * scale)
            {
                // Mouse is near the scene alignment gizmo
                return(true);
            }
            else if (mousePosition.y > Screen.height - Toolbar.BOTTOM_TOOLBAR_HEIGHT * scale - TOOLBAR_HEIGHT * scale)
            {
                // Mouse is over the bottom toolbar
                return(true);
            }
            else if (Toolbar.viewMenuShowing && IsMousePositionInIMGUIRect(mousePosition, Toolbar.viewMenuRect))
            {
                return(true);
            }
            else if (Toolbar.primitiveMenuShowing && IsMousePositionInIMGUIRect(mousePosition, Toolbar.primitiveMenuRect))
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
        /// <summary>
        /// PICK A GAMEOBJECT FROM SCENE VIEW AT POSITION
        /// pick a gameObject from the sceneView at a given mouse position
        /// </summary>
        /// <param name="cam">current camera</param>
        /// <param name="layers">layer accepted</param>
        /// <param name="position">mouse position</param>
        /// <param name="ignore">ignored gameObjects</param>
        /// <param name="filter"></param>
        /// <param name="materialIndex"></param>
        /// <returns></returns>
        public static GameObject PickObjectOnPos(Camera cam, int layers, Vector2 position, GameObject[] ignore, GameObject[] filter, ref int materialIndex)
        {
            if (_internalUnclip == null || _internalPickClosestGameObject == null)
            {
                FindMethodByReflection();
                return(null);
            }
#if UNITY_2018_2_OR_NEWER
            position = (Vector2)_internalUnclip.Invoke(null, new object[] { position });
#else
            object[] arguments = new object[] { position };
            _internalUnclip.Invoke(null, arguments);
            position = (Vector2)arguments[0];
#endif

            position      = EditorGUIUtility.PointsToPixels(position);
            position.y    = Screen.height - position.y - cam.pixelRect.yMin;
            materialIndex = -1;

#if UNITY_2020_3_OR_NEWER
            return((GameObject)_internalPickClosestGameObject.Invoke(null, new object[] { cam, layers, position, ignore, filter, false, materialIndex }));
#else
            return((GameObject)_internalPickClosestGameObject.Invoke(null, new object[] { cam, layers, position, ignore, filter, materialIndex }));
#endif
        }
        protected virtual Vector2 GetMousePosition(Event evt, Rect rect)
        {
            var pos = EditorGUIUtility.PointsToPixels(evt.mousePosition);

            rect  = EditorGUIUtility.PointsToPixels(rect);
            pos.y = rect.height - pos.y; //GUI's (0,0) is top left, Camera is bottom left
            return(pos);
        }
Ejemplo n.º 4
0
        void OnGUI()
        {
            if (beforeOnGUI != null)
            {
                beforeOnGUI(this);
            }

            SceneViewUtilities.ResetOnGUIState();

            var rect = guiRect;

            rect.x      = 0;
            rect.y      = 0;
            rect.width  = position.width;
            rect.height = position.height;
            guiRect     = rect;
            var cameraRect = EditorGUIUtility.PointsToPixels(guiRect);

            PrepareCameraTargetTexture(cameraRect);

            m_Camera.cullingMask = m_CullingMask.HasValue ? m_CullingMask.Value.value : UnityEditor.Tools.visibleLayers;

            // Draw camera
            bool pushedGUIClip;

            DoDrawCamera(guiRect, out pushedGUIClip);

            if (m_ShowDeviceView)
            {
                SceneViewUtilities.DrawTexture(customPreviewCamera && customPreviewCamera.targetTexture ? customPreviewCamera.targetTexture : m_SceneTargetTexture, guiRect, pushedGUIClip);
            }

            GUILayout.BeginArea(guiRect);
            {
                if (GUILayout.Button("Toggle Device View", EditorStyles.toolbarButton))
                {
                    m_ShowDeviceView = !m_ShowDeviceView;
                }

                if (m_CustomPreviewCamera)
                {
                    GUILayout.FlexibleSpace();
                    GUILayout.BeginHorizontal();
                    {
                        GUILayout.FlexibleSpace();
                        m_UseCustomPreviewCamera = GUILayout.Toggle(m_UseCustomPreviewCamera, "Use Presentation Camera");
                    }
                    GUILayout.EndHorizontal();
                }
            }
            GUILayout.EndArea();

            if (afterOnGUI != null)
            {
                afterOnGUI(this);
            }
        }
Ejemplo n.º 5
0
        void OnGUI()
        {
            if (beforeOnGUI != null)
            {
                beforeOnGUI(this);
            }

            var height = position.height;
            var width  = position.width;
            var rect   = guiRect;

            rect.x      = 0;
            rect.y      = 0;
            rect.width  = width;
            rect.height = height;
            guiRect     = rect;
            var cameraRect = EditorGUIUtility.PointsToPixels(guiRect);

            PrepareCameraTargetTexture(cameraRect);

            m_Camera.cullingMask = m_CullingMask.HasValue ? m_CullingMask.Value.value : UnityEditor.Tools.visibleLayers;

            DoDrawCamera(guiRect);

            Event e = Event.current;

            if (m_ShowDeviceView)
            {
                if (e.type == EventType.Repaint)
                {
                    GL.sRGBWrite = (QualitySettings.activeColorSpace == ColorSpace.Linear);
                    var renderTexture = customPreviewCamera && customPreviewCamera.targetTexture ? customPreviewCamera.targetTexture : m_TargetTexture;
                    GUI.DrawTexture(guiRect, renderTexture, ScaleMode.StretchToFill, false);
                    GL.sRGBWrite = false;
                }
            }

            m_ToggleDeviceViewRect.width   = width;
            m_PresentationCameraRect.y     = height - m_PresentationCameraRect.height;
            m_PresentationCameraRect.width = width;

            if (GUI.Button(m_ToggleDeviceViewRect, "Toggle Device View", EditorStyles.toolbarButton))
            {
                m_ShowDeviceView = !m_ShowDeviceView;
            }

            if (m_CustomPreviewCamera)
            {
                m_UseCustomPreviewCamera = GUI.Toggle(m_PresentationCameraRect, m_UseCustomPreviewCamera, "Use Presentation Camera");
            }

            if (afterOnGUI != null)
            {
                afterOnGUI(this);
            }
        }
Ejemplo n.º 6
0
        void Start()
        {
            Type windowType  = null;
            Type guiViewType = null;

            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                var type = assembly.GetType(m_WindowClass);
                if (type != null)
                {
                    windowType = type;
                }

                type = assembly.GetType("UnityEditor.GUIView");
                if (type != null)
                {
                    guiViewType = type;
                }
            }

            if (windowType != null && guiViewType != null)
            {
                m_Window = ScriptableObject.CreateInstance(windowType) as EditorWindow;

                // AE: The first assignment is to undock the window if it was docked and the second is to position it off screen
                //window.position = rect;
                m_Window.Show();
                m_Window.position = m_Position;

                // NOTE: Uncomment To grab any and all GUIViews
                //foreach (UnityEngine.Object view in Resources.FindObjectsOfTypeAll(guiViewType))
                //{
                //    Debug.Log(view.name);
                //}

                var parentField = windowType.GetField("m_Parent", BindingFlags.Instance | BindingFlags.NonPublic);
                m_GuiView = (Object)parentField.GetValue(m_Window);

                // It's necessary to force a repaint on first start-up of window
                var repaint = windowType.GetMethod("RepaintImmediately", BindingFlags.Instance | BindingFlags.NonPublic);
                repaint.Invoke(m_Window, null);

                m_GrabPixels = guiViewType.GetMethod("GrabPixels", BindingFlags.Instance | BindingFlags.NonPublic);

                // Convert to GUI Rect (handles high-DPI screens)
                m_ScaledRect = EditorGUIUtility.PointsToPixels(m_Position);

                capture = true;
            }
            else
            {
                Debug.LogError("Could not load " + m_WindowClass);
            }
        }
        public static ChiselNode PickClosestNode(Vector2 position, out CSGTreeBrushIntersection intersection)
        {
            var camera       = Camera.current;
            int layers       = camera.cullingMask;
            var pickposition = GUIClip.GUIClipUnclip(position);

            pickposition   = EditorGUIUtility.PointsToPixels(pickposition);
            pickposition.y = Screen.height - pickposition.y - camera.pixelRect.yMin;

            GameObject[] ignore = new GameObject[0];
            GameObject[] filter = null;
            return(PickNode(camera, pickposition, layers, ref ignore, ref filter, out intersection));
        }
Ejemplo n.º 8
0
        void LateUpdate()
        {
            m_SmoothCamera.CopyFrom(m_VRCamera); // This copies the transform as well
            var vrCameraTexture = m_VRCamera.targetTexture;

#if UNITY_EDITOR
            if (vrCameraTexture && (!m_RenderTexture || m_RenderTexture.width != vrCameraTexture.width || m_RenderTexture.height != vrCameraTexture.height))
            {
                var guiRect    = new Rect(0f, 0f, vrCameraTexture.width, vrCameraTexture.height);
                var cameraRect = EditorGUIUtility.PointsToPixels(guiRect);
                VRView.activeView.CreateCameraTargetTexture(ref m_RenderTexture, cameraRect, false);
                m_RenderTexture.name = "Smooth Camera RT";
            }
#endif

            m_SmoothCamera.targetTexture   = m_RenderTexture;
            m_SmoothCamera.targetDisplay   = m_TargetDisplay;
            m_SmoothCamera.cameraType      = CameraType.Game;
            m_SmoothCamera.cullingMask    &= ~hmdOnlyLayerMask;
            m_SmoothCamera.rect            = k_DefaultCameraRect;
            m_SmoothCamera.stereoTargetEye = StereoTargetEyeMask.None;
            m_SmoothCamera.fieldOfView     = m_FieldOfView;

            m_Position = Vector3.Lerp(m_Position, m_VRCamera.transform.localPosition, Time.deltaTime * m_SmoothingMultiplier);
            m_Rotation = Quaternion.Slerp(m_Rotation, m_VRCamera.transform.localRotation, Time.deltaTime * m_SmoothingMultiplier);

            transform.localRotation = Quaternion.LookRotation(m_Rotation * Vector3.forward, Vector3.up);
            transform.localPosition = m_Position - transform.localRotation * Vector3.forward * m_PullBackDistance;

            // Don't render any HMD-related visual proxies
            k_Renderers.Clear();
            m_VRCamera.GetComponentsInChildren(k_Renderers);
            var count = k_Renderers.Count;

            k_HiddenEnabled.Clear();
            for (var i = 0; i < count; i++)
            {
                var h = k_Renderers[i];
                k_HiddenEnabled.Add(h.enabled);
                h.enabled = false;
            }

            RenderTexture.active = m_SmoothCamera.targetTexture;
            m_SmoothCamera.Render();
            RenderTexture.active = null;

            for (var i = 0; i < count; i++)
            {
                k_Renderers[i].enabled = k_HiddenEnabled[i];
            }
        }
        internal static GameObject PickClosestGameObjectDelegated(Vector2 position, ref GameObject[] ignore, ref GameObject[] filter, out CSGTreeBrushIntersection intersection)
        {
            var camera       = Camera.current;
            int layers       = camera.cullingMask;
            var pickposition = GUIClip.GUIClipUnclip(position);

            pickposition   = EditorGUIUtility.PointsToPixels(pickposition);
            pickposition.y = Screen.height - pickposition.y - camera.pixelRect.yMin;

            /*
             * GameObject picked = null;
             * if (pickClosestGameObjectDelegate != null)
             * {
             *  // TODO: figure out how to call a delegate through reflection with an out parameter ...
             * }*/

            intersection = new CSGTreeBrushIntersection
            {
                surfaceID   = -1,
                brushUserID = -1
            };

            //if (picked == null)
            {
                ChiselNode  node;
                ChiselModel model;
                var         gameObject = PickNodeOrGameObject(camera, pickposition, layers, ref ignore, ref filter, out model, out node, out intersection);
                if (!model)
                {
                    return(gameObject);
                }

                if (node)
                {
                    return(gameObject);
                }

                return(null);
            }

            /*
             * if (CSGGeneratedComponentManager.IsObjectGenerated(picked))
             * {
             *  if (ignore == null)
             *      return null;
             *  ArrayUtility.Add(ref ignore, picked);
             *  return PickClosestGameObjectDelegated(position, ref ignore, ref filter, out intersection);
             * }
             * return picked;*/
        }
Ejemplo n.º 10
0
        private void OnGUI()
        {
            if (onGUIDelegate != null)
            {
                onGUIDelegate(this);
            }

            var e = Event.current;

            if (e.type != EventType.ExecuteCommand && e.type != EventType.used)
            {
                SceneViewUtilities.ResetOnGUIState();

                var guiRect    = new Rect(0, 0, position.width, position.height);
                var cameraRect = EditorGUIUtility.PointsToPixels(guiRect);
                PrepareCameraTargetTexture(cameraRect);

                m_Camera.cullingMask = m_CullingMask.HasValue ? m_CullingMask.Value.value : UnityEditor.Tools.visibleLayers;

                // Draw camera
                bool pushedGUIClip;
                DoDrawCamera(guiRect, out pushedGUIClip);

                if (m_ShowDeviceView)
                {
                    SceneViewUtilities.DrawTexture(customPreviewCamera && customPreviewCamera.targetTexture ? customPreviewCamera.targetTexture : m_SceneTargetTexture, guiRect, pushedGUIClip);
                }

                GUILayout.BeginArea(guiRect);
                {
                    if (GUILayout.Button("Toggle Device View", EditorStyles.toolbarButton))
                    {
                        m_ShowDeviceView = !m_ShowDeviceView;
                    }

                    if (m_CustomPreviewCamera)
                    {
                        GUILayout.FlexibleSpace();
                        GUILayout.BeginHorizontal();
                        {
                            GUILayout.FlexibleSpace();
                            m_UseCustomPreviewCamera = GUILayout.Toggle(m_UseCustomPreviewCamera, "Use Presentation Camera");
                        }
                        GUILayout.EndHorizontal();
                    }
                }
                GUILayout.EndArea();
            }
        }
Ejemplo n.º 11
0
        public static Vector2 ConvertMousePointPosition(Vector2 sourceMousePosition, bool convertPointsToPixels = true)
        {
#if UNITY_5_4_OR_NEWER
            if (convertPointsToPixels)
            {
                sourceMousePosition = EditorGUIUtility.PointsToPixels(sourceMousePosition);
            }
            // Flip the direction of Y and remove the Scene View top toolbar's height
            sourceMousePosition.y = Screen.height - sourceMousePosition.y - (TOOLBAR_HEIGHT * EditorGUIUtility.pixelsPerPoint);
#else
            // Flip the direction of Y and remove the Scene View top toolbar's height
            sourceMousePosition.y = Screen.height - sourceMousePosition.y - TOOLBAR_HEIGHT;
#endif
            return(sourceMousePosition);
        }
Ejemplo n.º 12
0
        void LateUpdate()
        {
            m_SmoothCamera.CopyFrom(m_VRCamera);             // This copies the transform as well
            var vrCameraTexture = m_VRCamera.targetTexture;

            if (vrCameraTexture && (!m_RenderTexture || m_RenderTexture.width != vrCameraTexture.width || m_RenderTexture.height != vrCameraTexture.height))
            {
                Rect guiRect    = new Rect(0f, 0f, vrCameraTexture.width, vrCameraTexture.height);
                Rect cameraRect = EditorGUIUtility.PointsToPixels(guiRect);
                VRView.activeView.CreateCameraTargetTexture(ref m_RenderTexture, cameraRect, false);
                m_RenderTexture.name = "Smooth Camera RT";
            }
            m_SmoothCamera.targetTexture   = m_RenderTexture;
            m_SmoothCamera.targetDisplay   = m_TargetDisplay;
            m_SmoothCamera.cameraType      = CameraType.Game;
            m_SmoothCamera.cullingMask    &= ~hmdOnlyLayerMask;
            m_SmoothCamera.rect            = new Rect(0f, 0f, 1f, 1f);
            m_SmoothCamera.stereoTargetEye = StereoTargetEyeMask.None;
            m_SmoothCamera.fieldOfView     = m_FieldOfView;

            m_Position = Vector3.Lerp(m_Position, m_VRCamera.transform.position, Time.deltaTime * m_SmoothingMultiplier);
            m_Forward  = Vector3.Lerp(m_Forward, m_VRCamera.transform.forward, Time.deltaTime * m_SmoothingMultiplier);

            const float kPullBackDistance = 1.1f;

            transform.forward  = m_Forward;
            transform.position = m_Position - transform.forward * kPullBackDistance * this.GetViewerScale();

            // Don't render any HMD-related visual proxies
            var hidden = m_VRCamera.GetComponentsInChildren <Renderer>();

            bool[] hiddenEnabled = new bool[hidden.Length];
            for (int i = 0; i < hidden.Length; i++)
            {
                var h = hidden[i];
                hiddenEnabled[i] = h.enabled;
                h.enabled        = false;
            }

            RenderTexture.active = m_SmoothCamera.targetTexture;
            m_SmoothCamera.Render();
            RenderTexture.active = null;

            for (int i = 0; i < hidden.Length; i++)
            {
                hidden[i].enabled = hiddenEnabled[i];
            }
        }
Ejemplo n.º 13
0
        public static Vector2 GUIPointToWorld(Vector2 gui)
        {
            Camera current = Camera.current;

            if (current)
            {
                #if UNITY_5_4_OR_NEWER
                gui   = EditorGUIUtility.PointsToPixels(gui);
                gui.y = (float)Screen.height - gui.y - (35f * EditorGUIUtility.pixelsPerPoint);
                #else
                gui.y = (float)Screen.height - gui.y - 35f;
                #endif
                return(current.ScreenToWorldPoint(new Vector3(gui.x, gui.y, current.nearClipPlane)));
            }
            return(gui);
        }
Ejemplo n.º 14
0
        private static Rect ClearCamera(SceneView sceneView, Color clearColor)
        {
            Rect cameraRect = GetCameraRect(sceneView: sceneView);

            Rect groupSpaceCameraRect         = new Rect(x: 0, y: 0, width: cameraRect.width, height: cameraRect.height);
            Rect groupSpaceCameraRectInPixels = EditorGUIUtility.PointsToPixels(rect: groupSpaceCameraRect);

            CameraClearFlags oldClearFlags = sceneView.camera.clearFlags;
            Color            oldClearColor = sceneView.camera.backgroundColor;

            sceneView.camera.clearFlags      = CameraClearFlags.SolidColor;
            sceneView.camera.backgroundColor = clearColor;
            Handles.ClearCamera(position: groupSpaceCameraRectInPixels, camera: sceneView.camera);
            sceneView.camera.clearFlags      = oldClearFlags;
            sceneView.camera.backgroundColor = oldClearColor;

            return(cameraRect);
        }
Ejemplo n.º 15
0
        private void OnGUI()
        {
            onGUIDelegate(this);
            SceneViewUtilities.ResetOnGUIState();

            SetupCamera();

            Rect guiRect    = new Rect(0, 0, position.width, position.height);
            Rect cameraRect = EditorGUIUtility.PointsToPixels(guiRect);

            PrepareCameraTargetTexture(cameraRect);
            Handles.ClearCamera(cameraRect, m_Camera);

            m_Camera.cullingMask = Tools.visibleLayers;

            // Draw camera
            bool pushedGUIClip;

            DoDrawCamera(guiRect, out pushedGUIClip);

            SceneViewUtilities.BlitRT(m_SceneTargetTexture, guiRect, pushedGUIClip);
        }
Ejemplo n.º 16
0
        public static Vector3 ScreenToLocal(Transform transform, Vector2 screenPosition, Plane plane)
        {
            Ray ray;

            if (Camera.current.orthographic)
            {
                Vector2 v = EditorGUIUtility.PointsToPixels(GUIClip.Unclip(screenPosition));
                v.y = (float)Screen.height - v.y;
                Vector3 origin = Camera.current.ScreenToWorldPoint(v);
                ray = new Ray(origin, Camera.current.transform.forward);
            }
            else
            {
                ray = HandleUtility.GUIPointToWorldRay(screenPosition);
            }
            float distance;

            plane.Raycast(ray, out distance);
            Vector3 point = ray.GetPoint(distance);

            return(transform.InverseTransformPoint(point));
        }
Ejemplo n.º 17
0
        public static Vector3 ScreenToLocal(Transform transform, Vector2 screenPosition, Plane plane)
        {
            Ray ray;

            if (Camera.current.orthographic)
            {
                Vector2 screen = EditorGUIUtility.PointsToPixels(screenPosition);
                screen.y = Screen.height - screen.y;
                Vector3 cameraWorldPoint = Camera.current.ScreenToWorldPoint(screen);
                ray = new Ray(cameraWorldPoint, Camera.current.transform.forward);
            }
            else
            {
                ray = HandleUtility.GUIPointToWorldRay(screenPosition);
            }

            float result;

            plane.Raycast(ray, out result);
            Vector3 world = ray.GetPoint(result);

            return(transform.InverseTransformPoint(world));
        }
        static GameObject PickClosestGameObjectDelegated(Vector2 position, ref GameObject[] ignore, ref GameObject[] filter, out ChiselIntersection intersection)
        {
            var camera       = Camera.current;
            int layers       = camera.cullingMask;
            var pickposition = GUIClip.GUIClipUnclip(position);

            pickposition   = EditorGUIUtility.PointsToPixels(pickposition);
            pickposition.y = Screen.height - pickposition.y - camera.pixelRect.yMin;

            var gameObject = PickNodeOrGameObject(camera, pickposition, layers, ref ignore, ref filter, out var model, out var node, out intersection);

            if (!model)
            {
                return(gameObject);
            }

            if (node)
            {
                return(gameObject);
            }

            return(null);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Whether the mouse position is within the bounds of the axis snapping gizmo that appears in the top right
        /// </summary>
        public static bool IsMousePositionNearSceneGizmo(Vector2 mousePosition)
        {
            float scale = 1;

#if UNITY_5_4_OR_NEWER
            mousePosition = EditorGUIUtility.PointsToPixels(mousePosition);
            scale         = EditorGUIUtility.pixelsPerPoint;
#endif

            mousePosition.x = Screen.width - mousePosition.x;

            if (mousePosition.x > 14 * scale &&
                mousePosition.x < 89 * scale &&
                mousePosition.y > 14 * scale &&
                mousePosition.y < 105 * scale)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Ejemplo n.º 20
0
 public static Rect PointsToPixels(Rect rect)
 {
     return(EditorGUIUtility.PointsToPixels(rect));
 }
Ejemplo n.º 21
0
 public static Vector2 PointsToPixels(Vector2 position)
 {
     return(EditorGUIUtility.PointsToPixels(position));
 }
Ejemplo n.º 22
0
        void OnGUI()
        {
            if (beforeOnGUI != null)
            {
                beforeOnGUI(this);
            }

            var height = position.height;
            var width  = position.width;
            var rect   = guiRect;

            rect.x      = 0;
            rect.y      = 0;
            rect.width  = width;
            rect.height = height;
            guiRect     = rect;
            var cameraRect = EditorGUIUtility.PointsToPixels(guiRect);

            PrepareCameraTargetTexture(cameraRect);

            m_Camera.cullingMask = m_CullingMask.HasValue ? m_CullingMask.Value.value : UnityEditor.Tools.visibleLayers;

            DoDrawCamera(guiRect);

            MouseScrollDelta = Vector2.zero;
            var e = Event.current;

            MouseDelta = e.delta;
            switch (e.type)
            {
            case EventType.ScrollWheel:
                MouseScrollDelta = e.delta;
                break;

            case EventType.MouseDown:
                switch (e.button)
                {
                case 0:
                    LeftMouseButtonHeld = true;
                    break;

                case 1:
                    RightMouseButtonHeld = true;
                    break;

                case 2:
                    MiddleMouseButtonHeld = true;
                    break;
                }

                break;

            case EventType.MouseUp:
                switch (e.button)
                {
                case 0:
                    LeftMouseButtonHeld = false;
                    break;

                case 1:
                    RightMouseButtonHeld = false;
                    break;

                case 2:
                    MiddleMouseButtonHeld = false;
                    break;
                }

                break;
            }

            if (m_ShowDeviceView)
            {
                if (e.type == EventType.Repaint)
                {
                    // Legacy fix for dark colors in device view in Linear color space
#if !UNITY_2018_3_OR_NEWER
#if UNITY_2018_1_OR_NEWER
                    GL.sRGBWrite = false;
#else
                    GL.sRGBWrite = (QualitySettings.activeColorSpace == ColorSpace.Linear);
#endif
#endif

                    var renderTexture = customPreviewCamera && customPreviewCamera.targetTexture ? customPreviewCamera.targetTexture : m_TargetTexture;
                    GUI.DrawTexture(guiRect, renderTexture, ScaleMode.StretchToFill, false);

#if !UNITY_2018_3_OR_NEWER
                    GL.sRGBWrite = false;
#endif
                }
            }

            m_ToggleDeviceViewRect.y   = height - m_ToggleDeviceViewRect.height;
            m_PresentationCameraRect.x = width - m_PresentationCameraRect.width;
            m_PresentationCameraRect.y = height - m_PresentationCameraRect.height;

            const string deviceViewEnabled  = "Device View Enabled";
            const string deviceViewDisabled = "Device View Disabled";
            m_ShowDeviceView = GUI.Toggle(m_ToggleDeviceViewRect, m_ShowDeviceView, m_ShowDeviceView ? deviceViewEnabled : deviceViewDisabled);

            if (m_CustomPreviewCamera)
            {
                m_UseCustomPreviewCamera = GUI.Toggle(m_PresentationCameraRect, m_UseCustomPreviewCamera, "Use Presentation Camera");
            }

            if (afterOnGUI != null)
            {
                afterOnGUI(this);
            }
        }
        void UVPreviewWindow(Rect rect)
        {
            Event e         = Event.current;
            int   controlID = GUIUtility.GetControlID(s_UVPreviewWindowHash, FocusType.Passive, rect);

            switch (e.GetTypeForControl(controlID))
            {
            case EventType.MouseDown:
                if (rect.Contains(e.mousePosition) && e.alt)
                {
                    if (e.button == 0 || e.button == 1 || e.button == 2)
                    {
                        GUI.changed = true;

                        GUIUtility.keyboardControl = controlID;
                        GUIUtility.hotControl      = controlID;
                        e.Use();
                    }
                }
                break;

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

            case EventType.MouseDrag:
                if (GUIUtility.hotControl == controlID && e.alt)
                {
                    GUI.changed = true;

                    if (e.button == 0 || e.button == 2)
                    {
                        previewWindowPosition += new Vector2(e.delta.x, -e.delta.y) * (2.0f / rect.width) / previewWindowScale;
                    }

                    if (e.button == 1)
                    {
                        float aspect = Mathf.Min(viewportSize.x, viewportSize.y) / Mathf.Max(viewportSize.x, viewportSize.y, 1f);
                        previewWindowScale += e.delta.magnitude / aspect * Mathf.Sign(Vector2.Dot(e.delta, new Vector2(1.0f, 0.0f))) * (2.0f / rect.width) * (previewWindowScale) * 0.5f;
                        previewWindowScale  = Mathf.Max(previewWindowScale, 0.01f);
                    }

                    e.Use();
                }
                break;

            case EventType.ScrollWheel:
                if (rect.Contains(e.mousePosition))
                {
                    GUI.changed = true;

                    float aspect = Mathf.Min(viewportSize.x, viewportSize.y) / Mathf.Max(viewportSize.x, viewportSize.y, 1f);

                    previewWindowScale += e.delta.magnitude / aspect * Mathf.Sign(Vector2.Dot(e.delta, new Vector2(1.0f, -0.1f).normalized)) * (2.0f / rect.width) * (previewWindowScale) * 5.5f;
                    previewWindowScale  = Mathf.Max(previewWindowScale, 0.01f);

                    e.Use();
                }
                break;

            case EventType.Repaint:
            {
                GUI.BeginGroup(rect);


                Rect viewportRect = rect;

                viewportRect.position = viewportRect.position - scroolPosition;                        // apply scroll

                // clamp rect position zero
                if (viewportRect.position.x < 0f)
                {
                    viewportRect.width   += viewportRect.position.x;   // -= abs(x)
                    viewportRect.position = new Vector2(0f, viewportRect.position.y);

                    if (viewportRect.width <= 0f)
                    {
                        break;
                    }
                }
                if (viewportRect.position.y < 0f)
                {
                    viewportRect.height  += viewportRect.position.y;    // -= abs(y)
                    viewportRect.position = new Vector2(viewportRect.position.x, 0f);

                    if (viewportRect.height <= 0f)
                    {
                        break;
                    }
                }

                viewportSize = rect.size;     // save size

                // convert gui to screen coord
                Rect screenViewportRect = viewportRect;
                screenViewportRect.y = this.position.height - screenViewportRect.y - screenViewportRect.height;

                                        #if (UNITY_5_4_OR_NEWER)
                GL.Viewport(EditorGUIUtility.PointsToPixels(screenViewportRect));
                                        #else
                GL.Viewport(screenViewportRect);
                                        #endif
                GL.PushMatrix();

                // Clear bg
                {
                    GL.LoadIdentity();
                    GL.LoadProjectionMatrix(Matrix4x4.Ortho(0f, 1f, 0f, 1f, -1f, 1f));

                    SetMaterialKeyword(simpleMaterial, "_COLOR_MASK", false);
                    SetMaterialKeyword(simpleMaterial, "_NORMALMAP", false);
                    simpleMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
                    simpleMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
                    simpleMaterial.SetTexture("_MainTex", null);
                    simpleMaterial.SetColor("_Color", Color.white);
                    simpleMaterial.SetPass(0);

                    GL.Begin(GL.TRIANGLE_STRIP);
                    GL.Color(Styles.backgroundColor);
                    GL.Vertex3(1, 0, 0);
                    GL.Vertex3(0, 0, 0);
                    GL.Vertex3(1, 1, 0);
                    GL.Vertex3(0, 1, 0);
                    GL.End();
                }

                GL.LoadIdentity();
                //float aspect = Mathf.Min(GUIUtility.ScreenToGUIRect(this.position).height - rect.y, rect.height) / rect.width;
                float     aspect           = viewportRect.height / viewportRect.width;
                Matrix4x4 projectionMatrix = Matrix4x4.Ortho(-1f, 1f, -1f * aspect, 1f * aspect, -1f, 1f);
                GL.LoadProjectionMatrix(projectionMatrix);
                Matrix4x4 viewMatrix = Matrix4x4.Scale(new Vector3(previewWindowScale, previewWindowScale, previewWindowScale))
                                       * Matrix4x4.TRS(new Vector3(previewWindowPosition.x, previewWindowPosition.y, 0), Quaternion.identity, Vector3.one);          // u5.0 have no translate
                GL.MultMatrix(viewMatrix);


                // Preview texture
                if ((previewTextureSource == PreviewTextureSource.Custom && customPreviewTexture != null) ||
                    (previewTextureSource == PreviewTextureSource.FromMaterial && previewTexture != null))
                {
                    Texture2D texture = (previewTextureSource == PreviewTextureSource.Custom) ? customPreviewTexture : previewTexture;

                    SetMaterialKeyword(simpleMaterial, "_NORMALMAP", false);

                    string texPath = AssetDatabase.GetAssetPath(texture);
                    if (texPath != null)
                    {
                        TextureImporter textureImporter = (TextureImporter)TextureImporter.GetAtPath(texPath);
                        if (textureImporter != null)
                        {
                                                        #if (UNITY_5_5_OR_NEWER)
                            if (textureImporter.textureType == TextureImporterType.NormalMap)
                            {
                                SetMaterialKeyword(simpleMaterial, "_NORMALMAP", true);
                            }
                                                        #else
                            if (textureImporter.textureType == TextureImporterType.Bump)
                            {
                                SetMaterialKeyword(simpleMaterial, "_NORMALMAP", true);
                            }
                                                        #endif
                        }
                    }

                    switch (previewTextureChannels)
                    {
                    case ColorChannels.R:
                        SetMaterialKeyword(simpleMaterial, "_COLOR_MASK", true);
                        simpleMaterial.SetColor("_Color", new Color(1, 0, 0, 0));
                        break;

                    case ColorChannels.G:
                        SetMaterialKeyword(simpleMaterial, "_COLOR_MASK", true);
                        simpleMaterial.SetColor("_Color", new Color(0, 1, 0, 0));
                        break;

                    case ColorChannels.B:
                        SetMaterialKeyword(simpleMaterial, "_COLOR_MASK", true);
                        simpleMaterial.SetColor("_Color", new Color(0, 0, 1, 0));
                        break;

                    case ColorChannels.A:
                        SetMaterialKeyword(simpleMaterial, "_COLOR_MASK", true);
                        simpleMaterial.SetColor("_Color", new Color(0, 0, 0, 1));
                        break;

                    case ColorChannels.All:
                        SetMaterialKeyword(simpleMaterial, "_COLOR_MASK", false);
                        simpleMaterial.SetColor("_Color", new Color(1, 1, 1, 1));
                        break;
                    }

                    simpleMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
                    simpleMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);

                    simpleMaterial.SetTexture("_MainTex", texture);
                    simpleMaterial.SetPass(0);

                    float min = tilePreviewTexture ? -100f : 0;
                    float max = tilePreviewTexture ? 100f : 1;

                    GL.Begin(GL.TRIANGLE_STRIP);
                    GL.Color(previewTextureTintColor);
                    GL.TexCoord2(max, min);
                    GL.Vertex3(max, min, 0);
                    GL.TexCoord2(min, min);
                    GL.Vertex3(min, min, 0);
                    GL.TexCoord2(max, max);
                    GL.Vertex3(max, max, 0);
                    GL.TexCoord2(min, max);
                    GL.Vertex3(min, max, 0);
                    GL.End();
                }



                // grid
                if (showGrid)
                {
                    GL.wireframe = false;

                    SetMaterialKeyword(simpleMaterial, "_COLOR_MASK", false);
                    SetMaterialKeyword(simpleMaterial, "_NORMALMAP", false);
                    simpleMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
                    simpleMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
                    simpleMaterial.SetTexture("_MainTex", null);
                    simpleMaterial.SetColor("_Color", Color.white);
                    simpleMaterial.SetPass(0);


                    GL.Begin(GL.LINES);

                    float x = -1.0f;
                    GL.Color(Styles.gridColor);
                    for (int i = 0; i <= 20; i++, x += 0.1f)
                    {
                        GL.Vertex3(x, 1, 0);
                        GL.Vertex3(x, -1, 0);
                    }


                    float y = -1.0f;
                    GL.Color(Styles.gridColor);
                    for (int i = 0; i <= 20; i++, y += 0.1f)
                    {
                        GL.Vertex3(1, y, 0);
                        GL.Vertex3(-1, y, 0);
                    }

                    GL.Color(Color.gray);
                    GL.Vertex3(1, 0, 0);
                    GL.Vertex3(-1, 0, 0);
                    GL.Vertex3(0, 1, 0);
                    GL.Vertex3(0, -1, 0);

                    GL.Color(Color.red);
                    GL.Vertex3(0.3f, 0, 0);
                    GL.Vertex3(0, 0, 0);


                    GL.Color(Color.green);
                    GL.Vertex3(0, 0.3f, 0);
                    GL.Vertex3(0, 0, 0);

                    GL.End();
                }



                // mesh uvs
                {
                    SetMaterialKeyword(uvPreviewMaterial, "_UV1", false);
                    SetMaterialKeyword(uvPreviewMaterial, "_UV2", false);
                    SetMaterialKeyword(uvPreviewMaterial, "_UV3", false);

                    switch (previewUVSet)
                    {
                    case UVSet.UV2:
                        SetMaterialKeyword(uvPreviewMaterial, "_UV1", true);
                        break;

                    case UVSet.UV3:
                        SetMaterialKeyword(uvPreviewMaterial, "_UV2", true);
                        break;

                    case UVSet.UV4:
                        SetMaterialKeyword(uvPreviewMaterial, "_UV3", true);
                        break;
                    }


                    GL.wireframe = true;


                    for (int i = 0; i < inspectedObjects.Count; i++)
                    {
                        SetMaterialKeyword(uvPreviewMaterial, "_VERTEX_COLORS", showVertexColors && inspectedObjects[i].hasColors);

                        if (i == inspectedObjects.Count - 1)
                        {
                            uvPreviewMaterial.SetColor("_Color", Styles.wireframeColor);
                        }
                        else
                        {
                            uvPreviewMaterial.SetColor("_Color", Styles.wireframeColor2);
                        }

                        uvPreviewMaterial.SetPass(0);

                        if (inspectedObjects.Count == 1)
                        {
                            for (int j = 0; j < inspectedObjects[i].subMeshCount && j < 32; j++)
                            {
                                if (subMeshToggleField[j])
                                {
                                    Graphics.DrawMeshNow(inspectedObjects[i].mesh, viewMatrix, j);
                                }
                            }
                        }
                        else
                        {
                            Graphics.DrawMeshNow(inspectedObjects[i].mesh, viewMatrix);
                        }
                    }
                }

                GL.PopMatrix();
                GL.wireframe = false;

                GUI.EndGroup();

                // grid numbers
                if (showGrid)
                {
                    GUI.BeginGroup(rect);
                    Matrix4x4 MVPMatrix = (projectionMatrix * viewMatrix);
                    DrawLabel(new Vector3(0, 0, 0), rect, MVPMatrix, "0.0", EditorStyles.whiteMiniLabel, TextAnchor.MiddleLeft);
                    DrawLabel(new Vector3(0, 1, 0), rect, MVPMatrix, "1.0", EditorStyles.whiteMiniLabel, TextAnchor.MiddleLeft);
                    DrawLabel(new Vector3(0, -1, 0), rect, MVPMatrix, "-1.0", EditorStyles.whiteMiniLabel, TextAnchor.UpperLeft);
                    DrawLabel(new Vector3(1, 0, 0), rect, MVPMatrix, "1.0", EditorStyles.whiteMiniLabel, TextAnchor.MiddleLeft);
                    DrawLabel(new Vector3(-1, 0, 0), rect, MVPMatrix, "-1.0", EditorStyles.whiteMiniLabel, TextAnchor.MiddleRight);
                    GUI.EndGroup();
                }
            }
            break;
            }

            return;
        }