BeginViewGUI() public method

public BeginViewGUI ( ) : void
return void
Beispiel #1
0
        private void OnGUI()
        {
            if (position.size * EditorGUIUtility.pixelsPerPoint != m_LastWindowPixelSize) // pixelsPerPoint only reliable in OnGUI()
            {
                UpdateZoomAreaAndParent();
            }

            if (showToolbar)
            {
                DoToolbarGUI();
            }

            // This isn't ideal. Custom Cursors set by editor extensions for other windows can leak into the game view.
            // To fix this we should probably stop using the global custom cursor (intended for runtime) for custom editor cursors.
            // This has been noted for Cursors tech debt.
            EditorGUIUtility.AddCursorRect(viewInWindow, MouseCursor.CustomCursor);

            EventType type = Event.current.type;

            // Gain mouse lock when clicking on game view content
            if (type == EventType.MouseDown && viewInWindow.Contains(Event.current.mousePosition))
            {
                AllowCursorLockAndHide(true);
            }
            // Lose mouse lock when pressing escape
            else if (type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape)
            {
                AllowCursorLockAndHide(false);
            }

            // We hide sliders when playing, and also when we are zoomed out beyond canvas edges
            var playing = EditorApplication.isPlaying && !EditorApplication.isPaused;
            var targetInContentCached = targetInContent;

            m_ZoomArea.hSlider          = !playing && m_ZoomArea.shownArea.width < targetInContentCached.width;
            m_ZoomArea.vSlider          = !playing && m_ZoomArea.shownArea.height < targetInContentCached.height;
            m_ZoomArea.enableMouseInput = !playing;
            ConfigureZoomArea();

            // We don't want controls inside the GameView (e.g. the toolbar) to have keyboard focus while playing.
            // The game should get the keyboard events.
            if (playing)
            {
                EditorGUIUtility.keyboardControl = 0;
            }

            GUI.color = Color.white; // Get rid of play mode tint

            var originalEventType = Event.current.type;

            m_ZoomArea.BeginViewGUI();

            // Window size might change on Layout event
            if (type == EventType.Layout)
            {
                targetSize = targetRenderSize;
            }

            // Setup game view dimensions, so that player loop can use it for input
            var gameViewTarget = GUIClip.UnclipToWindow(m_ZoomArea.drawRect);

            if (m_Parent)
            {
                var zoomedTarget = new Rect(targetInView.position + gameViewTarget.position, targetInView.size);
                SetParentGameViewDimensions(zoomedTarget, gameViewTarget, targetRenderSize);
            }

            var editorMousePosition = Event.current.mousePosition;
            var gameMousePosition   = (editorMousePosition + gameMouseOffset) * gameMouseScale;

            if (type == EventType.Repaint)
            {
                GUI.Box(m_ZoomArea.drawRect, GUIContent.none, Styles.gameViewBackgroundStyle);

                Vector2 oldOffset = GUIUtility.s_EditorScreenPointOffset;
                GUIUtility.s_EditorScreenPointOffset = Vector2.zero;
                SavedGUIState oldState = SavedGUIState.Create();


                var clearTexture = m_ClearInEditMode && !EditorApplication.isPlaying;

                var currentTargetDisplay = 0;
                if (ModuleManager.ShouldShowMultiDisplayOption())
                {
                    // Display Targets can have valid targets from 0 to 7.
                    System.Diagnostics.Debug.Assert(targetDisplay < 8, "Display Target is Out of Range");
                    currentTargetDisplay = targetDisplay;
                }

                targetDisplay = currentTargetDisplay;
                targetSize    = targetRenderSize;
                showGizmos    = m_Gizmos;
                clearColor    = kClearBlack;
                renderIMGUI   = true;

                if (!EditorApplication.isPlaying || (EditorApplication.isPlaying && Time.frameCount % OnDemandRendering.renderFrameInterval == 0))
                {
                    m_RenderTexture = RenderView(gameMousePosition, clearTexture);
                }

                if (m_TargetClamped)
                {
                    Debug.LogWarningFormat("GameView reduced to a reasonable size for this system ({0}x{1})", targetSize.x, targetSize.y);
                }
                EditorGUIUtility.SetupWindowSpaceAndVSyncInternal(GUIClip.Unclip(viewInWindow));

                if (m_RenderTexture != null && m_RenderTexture.IsCreated())
                {
                    oldState.ApplyAndForget();
                    GUIUtility.s_EditorScreenPointOffset = oldOffset;

                    GUI.BeginGroup(m_ZoomArea.drawRect);
                    // Actually draw the game view to the screen, without alpha blending
                    Rect drawRect = deviceFlippedTargetInView;
                    drawRect.x = Mathf.Round(drawRect.x);
                    drawRect.y = Mathf.Round(drawRect.y);
                    Graphics.DrawTexture(drawRect, m_RenderTexture, new Rect(0, 0, 1, 1), 0, 0, 0, 0, GUI.color, GUI.blitMaterial);
                    GUI.EndGroup();
                }
            }
            else if (type != EventType.Layout && type != EventType.Used)
            {
                if (Event.current.isKey && (!EditorApplication.isPlaying || EditorApplication.isPaused))
                {
                    return;
                }

                bool mousePosInGameViewRect = viewInWindow.Contains(Event.current.mousePosition);

                // MouseDown events outside game view rect are not send to scripts but MouseUp events are (see below)
                if (Event.current.rawType == EventType.MouseDown && !mousePosInGameViewRect)
                {
                    return;
                }

                var originalDisplayIndex = Event.current.displayIndex;

                // Transform events into local space, so the mouse position is correct
                // Then queue it up for playback during playerloop
                Event.current.mousePosition = gameMousePosition;
                Event.current.displayIndex  = targetDisplay;

                EditorGUIUtility.QueueGameViewInputEvent(Event.current);

                // Do not use mouse UP event if mousepos is outside game view rect (fix for case 380995: Gameview tab's context menu is not appearing on right click)
                // Placed after event queueing above to ensure scripts can react on mouse up events.
                bool useEvent = !(Event.current.rawType == EventType.MouseUp && !mousePosInGameViewRect);

                // Don't use command events, or they won't be sent to other views.
                if (type == EventType.ExecuteCommand || type == EventType.ValidateCommand)
                {
                    useEvent = false;
                }

                if (useEvent)
                {
                    Event.current.Use();
                }
                else
                {
                    Event.current.mousePosition = editorMousePosition;
                }

                // Reset display index
                Event.current.displayIndex = originalDisplayIndex;
            }

            m_ZoomArea.EndViewGUI();

            if (originalEventType == EventType.ScrollWheel && Event.current.type == EventType.Used)
            {
                EditorApplication.update -= SnapZoomDelayed;
                EditorApplication.update += SnapZoomDelayed;
                s_LastScrollTime          = EditorApplication.timeSinceStartup;
            }

            EnforceZoomAreaConstraints();

            if (m_RenderTexture)
            {
                if (m_ZoomArea.scale.y < 1f)
                {
                    m_RenderTexture.filterMode = FilterMode.Bilinear;
                }
                else
                {
                    m_RenderTexture.filterMode = FilterMode.Point;
                }
            }

            if (m_NoCameraWarning && !EditorGUIUtility.IsDisplayReferencedByCameras(targetDisplay))
            {
                GUI.Label(warningPosition, GUIContent.none, EditorStyles.notificationBackground);
                var displayName   = ModuleManager.ShouldShowMultiDisplayOption() ? DisplayUtility.GetDisplayNames()[targetDisplay].text : string.Empty;
                var cameraWarning = string.Format("{0}\nNo cameras rendering", displayName);
                EditorGUI.DoDropShadowLabel(warningPosition, EditorGUIUtility.TempContent(cameraWarning), EditorStyles.notificationText, .3f);
            }

            if (m_Stats)
            {
                GameViewGUI.GameViewStatsGUI();
            }
        }
        internal void DrawRenderUI()
        {
            var previewRect = EditorGUILayout.GetControlRect(GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true));

            GUI.Box(previewRect, GUIContent.none);
            m_ZoomablePreview.BeginViewGUI();
            bool first = true;

            if (m_UGUIProfilerTreeViewState != null && Event.current.type == EventType.Repaint)
            {
                IList <int> selection = m_TreeViewControl.GetSelection();
                if (selection.Count > 0)
                {
                    IList <TreeViewItem> selectedRows = m_TreeViewControl.GetRowsFromIDs(selection);
                    foreach (TreeViewItem row in selectedRows)
                    {
                        Texture2D image             = null;
                        var       batch             = row as UISystemProfilerTreeView.BatchTreeViewItem;
                        var       previewRenderMode = PreviewRenderMode;
                        if (m_RenderService == null)
                        {
                            m_RenderService = new UISystemProfilerRenderService();
                        }

                        if (batch != null)
                        {
                            image = m_RenderService.GetThumbnail(currentFrame, batch.renderDataIndex, 1, previewRenderMode != Styles.RenderMode.Standard);
                        }
                        var canvas = row as UISystemProfilerTreeView.CanvasTreeViewItem;
                        if (canvas != null)
                        {
                            image = m_RenderService.GetThumbnail(currentFrame, canvas.info.renderDataIndex, canvas.info.renderDataCount,
                                                                 previewRenderMode != Styles.RenderMode.Standard);
                        }

                        if (previewRenderMode == Styles.RenderMode.CompositeOverdraw)
                        {
                            if (m_CompositeOverdrawMaterial == null)
                            {
                                Shader shader = Shader.Find("Hidden/UI/CompositeOverdraw");
                                if (shader)
                                {
                                    m_CompositeOverdrawMaterial = new Material(shader);
                                }
                            }
                        }

                        if (image)
                        {
                            float w           = image.width;
                            float h           = image.height;
                            float scaleFactor = Math.Min(previewRect.width / w, previewRect.height / h);
                            w *= scaleFactor;
                            h *= scaleFactor;
                            var imageRect = new Rect(previewRect.x + (previewRect.width - w) / 2, previewRect.y + (previewRect.height - h) / 2,
                                                     w,
                                                     h);

                            if (first)
                            {
                                first = false;
                                m_ZoomablePreview.rect = imageRect;
                                var previewBackground = PreviewBackground;
                                if (previewBackground == Styles.PreviewBackgroundType.Checkerboard)
                                {
                                    EditorGUI.DrawTransparencyCheckerTexture(m_ZoomablePreview.drawRect, ScaleMode.ScaleAndCrop, 0f);
                                }
                                else
                                {
                                    EditorGUI.DrawRect(m_ZoomablePreview.drawRect,
                                                       previewBackground == Styles.PreviewBackgroundType.Black ? Color.black : Color.white);
                                }
                            }
                            Graphics.DrawTexture(m_ZoomablePreview.drawRect, image, m_ZoomablePreview.shownArea, 0, 0, 0, 0,
                                                 previewRenderMode == Styles.RenderMode.CompositeOverdraw ? m_CompositeOverdrawMaterial : EditorGUI.transparentMaterial);
                        }
                        if (previewRenderMode != Styles.RenderMode.Standard)
                        {
                            break;
                        }
                    }
                }
            }
            if (first && Event.current.type == EventType.Repaint)
            {
                m_ZoomablePreview.rect = previewRect;
            }
            m_ZoomablePreview.EndViewGUI();
        }
        private void DrawPreview(Rect r)
        {
            if (r.height <= 0)
            {
                return;
            }

            if (m_ZoomablePreview == null)
            {
                m_ZoomablePreview = new ZoomableArea(true);

                m_ZoomablePreview.hRangeMin = 0.0f;
                m_ZoomablePreview.vRangeMin = 0.0f;

                m_ZoomablePreview.hRangeMax = 1.0f;
                m_ZoomablePreview.vRangeMax = 1.0f;

                m_ZoomablePreview.SetShownHRange(0, 1);
                m_ZoomablePreview.SetShownVRange(0, 1);

                m_ZoomablePreview.uniformScale    = true;
                m_ZoomablePreview.scaleWithWindow = true;
            }

            m_ZoomablePreview.rect = r;

            m_ZoomablePreview.BeginViewGUI();

            m_ZoomablePreview.hSlider = m_ZoomablePreview.shownArea.width < 1;
            m_ZoomablePreview.vSlider = m_ZoomablePreview.shownArea.height < 1;

            Rect          drawableArea = m_ZoomablePreview.drawRect;
            GITextureType textureType  = GetSelectedTextureType();

            UpdateCachedTexture(textureType);

            if (m_CachedTexture.textureAvailability == GITextureAvailability.GITextureNotAvailable || m_CachedTexture.textureAvailability == GITextureAvailability.GITextureUnknown)
            {
                if (!isRealtimeLightmap)
                {
                    if (!LightmapVisualizationUtility.IsAtlasTextureType(textureType) && isIndexBased)
                    {
                        GUI.Label(drawableArea, Styles.TextureNotAvailableBakedAlbedoEmissive, Styles.PreviewLabel);
                    }
                    else if (textureType == GITextureType.BakedShadowMask)
                    {
                        GUI.Label(drawableArea, Styles.TextureNotAvailableBakedShadowmask, Styles.PreviewLabel);
                    }
                    else
                    {
                        GUI.Label(drawableArea, Styles.TextureNotAvailableBaked, Styles.PreviewLabel);
                    }
                }
                else
                {
                    GUI.Label(drawableArea, Styles.TextureNotAvailableRealtime, Styles.PreviewLabel);
                }

                return;
            }

            if (m_CachedTexture.textureAvailability == GITextureAvailability.GITextureLoading && m_CachedTexture.texture == null)
            {
                GUI.Label(drawableArea, Styles.TextureLoading, Styles.PreviewLabel);
                return;
            }

            LightmapType lightmapType = LightmapVisualizationUtility.GetLightmapType(textureType);

            switch (Event.current.type)
            {
            // 'F' will zoom to uv bounds
            case EventType.ValidateCommand:
            case EventType.ExecuteCommand:

                if (Event.current.commandName == EventCommandNames.FrameSelected && IsActiveGameObjectInLightmap(textureType))
                {
                    // There are instance based baked textures where we don't get any STs and can't do the framing
                    if (!isRealtimeLightmap && !LightmapVisualizationUtility.IsAtlasTextureType(textureType))
                    {
                        break;
                    }

                    Vector4 lightmapTilingOffset = LightmapVisualizationUtility.GetLightmapTilingOffset(lightmapType);

                    Vector2 min = new Vector2(lightmapTilingOffset.z, lightmapTilingOffset.w);
                    Vector2 max = min + new Vector2(lightmapTilingOffset.x, lightmapTilingOffset.y);

                    min = Vector2.Max(min, Vector2.zero);
                    max = Vector2.Min(max, Vector2.one);

                    Texture2D texture     = m_CachedTexture.texture;
                    Rect      textureRect = new Rect(r.x, r.y, texture.width, texture.height);
                    textureRect = ResizeRectToFit(textureRect, drawableArea);

                    float offsetX = 0.0f, offsetY = 0.0f;

                    if (textureRect.height == drawableArea.height)
                    {
                        offsetX = (drawableArea.width - textureRect.width) / drawableArea.width;
                    }
                    else
                    {
                        offsetY = (drawableArea.height - textureRect.height) / drawableArea.height;
                    }

                    // Make sure that the focus rectangle is a even square
                    Rect rect = new Rect(min.x, min.y, max.x - min.x, max.y - min.y);
                    rect.width = rect.height = Mathf.Max(rect.width, rect.height);
                    rect.x    -= (offsetX * min.x);
                    rect.y    += (offsetY * (1 - max.y));

                    m_ZoomablePreview.shownArea = rect;
                    Event.current.Use();
                }
                break;

            // Scale and draw texture and uv's
            case EventType.Repaint:
            {
                Texture2D texture = m_CachedTexture.texture;

                if (texture)
                {
                    Rect textureRect = new Rect(r.x, r.y, texture.width, texture.height);
                    textureRect = ResizeRectToFit(textureRect, drawableArea);
                    textureRect = ScaleRectByZoomableArea(textureRect, m_ZoomablePreview);

                    const int padding = 5;
                    textureRect.x      += padding;
                    textureRect.width  -= padding * 2;
                    textureRect.height -= padding;

                    // Texture shouldn't be filtered since it will make previewing really blurry
                    FilterMode prevMode = texture.filterMode;
                    texture.filterMode = FilterMode.Point;

                    LightmapVisualizationUtility.DrawTextureWithUVOverlay(texture,
                                                                          (m_ShowUVOverlay && IsActiveGameObjectInLightmap(textureType)) ? Selection.activeGameObject : null,
                                                                          m_ShowUVOverlay ? m_CachedTextureObjects : new GameObject[] {}, drawableArea, textureRect, textureType, exposure);
                    texture.filterMode = prevMode;
                }
            }
            break;
            }

            m_ZoomablePreview.EndViewGUI();
        }
        public void ObjectPreview(Rect r)
        {
            if (r.height <= 0)
            {
                return;
            }

            if (m_ZoomablePreview == null)
            {
                m_ZoomablePreview = new ZoomableArea(true);

                m_ZoomablePreview.hRangeMin = 0.0f;
                m_ZoomablePreview.vRangeMin = 0.0f;

                m_ZoomablePreview.hRangeMax = 1.0f;
                m_ZoomablePreview.vRangeMax = 1.0f;

                m_ZoomablePreview.SetShownHRange(0, 1);
                m_ZoomablePreview.SetShownVRange(0, 1);

                m_ZoomablePreview.uniformScale    = true;
                m_ZoomablePreview.scaleWithWindow = true;
            }

            // Draw background
            GUI.Box(r, "", "PreBackground");

            // Top menu rect
            Rect menuRect = new Rect(r);

            menuRect.y     += 1;
            menuRect.height = 18;
            GUI.Box(menuRect, "", EditorStyles.toolbar);

            // Top menu dropdown
            Rect dropRect = new Rect(r);

            dropRect.y     += 1;
            dropRect.height = 18;
            dropRect.width  = 120;

            // Drawable area
            Rect drawableArea = new Rect(r);

            drawableArea.yMin  += dropRect.height;
            drawableArea.yMax  -= 14;
            drawableArea.width -= 11;

            int index = Array.IndexOf(Styles.ObjectPreviewTextureOptions, m_SelectedObjectPreviewTexture);

            if (index < 0 || !LightmapVisualizationUtility.IsTextureTypeEnabled(kObjectPreviewTextureTypes[index]))
            {
                index = 0;
                m_SelectedObjectPreviewTexture = Styles.ObjectPreviewTextureOptions[index];
            }

            if (EditorGUI.DropdownButton(dropRect, m_SelectedObjectPreviewTexture, FocusType.Passive, EditorStyles.toolbarPopup))
            {
                GenericMenu menu = new GenericMenu();

                for (int i = 0; i < Styles.ObjectPreviewTextureOptions.Length; i++)
                {
                    if (LightmapVisualizationUtility.IsTextureTypeEnabled(kObjectPreviewTextureTypes[i]))
                    {
                        menu.AddItem(Styles.ObjectPreviewTextureOptions[i], index == i, SelectPreviewTextureOption, Styles.ObjectPreviewTextureOptions.ElementAt(i));
                    }
                    else
                    {
                        menu.AddDisabledItem(Styles.ObjectPreviewTextureOptions.ElementAt(i));
                    }
                }
                menu.DropDown(dropRect);
            }

            GITextureType textureType = kObjectPreviewTextureTypes[Array.IndexOf(Styles.ObjectPreviewTextureOptions, m_SelectedObjectPreviewTexture)];

            if (m_CachedTexture.type != textureType || m_CachedTexture.contentHash != LightmapVisualizationUtility.GetSelectedObjectGITextureHash(textureType) || m_CachedTexture.contentHash == new Hash128())
            {
                m_CachedTexture = LightmapVisualizationUtility.GetSelectedObjectGITexture(textureType);
            }

            if (m_CachedTexture.textureAvailability == GITextureAvailability.GITextureNotAvailable || m_CachedTexture.textureAvailability == GITextureAvailability.GITextureUnknown)
            {
                if (LightmapVisualizationUtility.IsBakedTextureType(textureType))
                {
                    if (textureType == GITextureType.BakedShadowMask)
                    {
                        GUI.Label(drawableArea, Styles.TextureNotAvailableBakedShadowmask);
                    }
                    else
                    {
                        GUI.Label(drawableArea, Styles.TextureNotAvailableBaked);
                    }
                }
                else
                {
                    GUI.Label(drawableArea, Styles.TextureNotAvailableRealtime);
                }

                return;
            }

            if (m_CachedTexture.textureAvailability == GITextureAvailability.GITextureLoading && m_CachedTexture.texture == null)
            {
                GUI.Label(drawableArea, Styles.TextureLoading);

                return;
            }

            LightmapType lightmapType = LightmapVisualizationUtility.GetLightmapType(textureType);

            // Framing and drawing
            var evt = Event.current;

            switch (evt.type)
            {
            // 'F' will zoom to uv bounds
            case EventType.ValidateCommand:
            case EventType.ExecuteCommand:

                if (Event.current.commandName == EventCommandNames.FrameSelected)
                {
                    Vector4 lightmapTilingOffset = LightmapVisualizationUtility.GetLightmapTilingOffset(lightmapType);

                    Vector2 min = new Vector2(lightmapTilingOffset.z, lightmapTilingOffset.w);
                    Vector2 max = min + new Vector2(lightmapTilingOffset.x, lightmapTilingOffset.y);

                    min = Vector2.Max(min, Vector2.zero);
                    max = Vector2.Min(max, Vector2.one);

                    float swap = 1f - min.y;
                    min.y = 1f - max.y;
                    max.y = swap;

                    // Make sure that the focus rectangle is a even square
                    Rect rect = new Rect(min.x, min.y, max.x - min.x, max.y - min.y);
                    rect.x    -= Mathf.Clamp(rect.height - rect.width, 0, float.MaxValue) / 2;
                    rect.y    -= Mathf.Clamp(rect.width - rect.height, 0, float.MaxValue) / 2;
                    rect.width = rect.height = Mathf.Max(rect.width, rect.height);

                    m_ZoomablePreview.shownArea = rect;
                    Event.current.Use();
                }
                break;

            // Scale and draw texture and uv's
            case EventType.Repaint:

                Texture2D texture = m_CachedTexture.texture;
                if (texture && Event.current.type == EventType.Repaint)
                {
                    Rect textureRect = new Rect(0, 0, texture.width, texture.height);
                    textureRect = ResizeRectToFit(textureRect, drawableArea);
                    //textureRect.x = -textureRect.width / 2;
                    //textureRect.y = -textureRect.height / 2;
                    textureRect = CenterToRect(textureRect, drawableArea);
                    textureRect = ScaleRectByZoomableArea(textureRect, m_ZoomablePreview);

                    // Draw texture and UV
                    Rect uvRect = new Rect(textureRect);
                    uvRect.x += 3;
                    uvRect.y += drawableArea.y + 20;

                    Rect clipRect = new Rect(drawableArea);
                    clipRect.y += dropRect.height + 3;

                    // fix 635838 - We need to offset the rects for rendering.
                    {
                        float offset = clipRect.y - 14;
                        uvRect.y   -= offset;
                        clipRect.y -= offset;
                    }

                    // Texture shouldn't be filtered since it will make previewing really blurry
                    FilterMode prevMode = texture.filterMode;
                    texture.filterMode = FilterMode.Point;

                    LightmapVisualizationUtility.DrawTextureWithUVOverlay(texture, Selection.activeGameObject, clipRect, uvRect, textureType);
                    texture.filterMode = prevMode;
                }
                break;
            }

            // Reset zoom if selection is changed
            if (m_PreviousSelection != Selection.activeInstanceID)
            {
                m_PreviousSelection = Selection.activeInstanceID;
                m_ZoomablePreview.SetShownHRange(0, 1);
                m_ZoomablePreview.SetShownVRange(0, 1);
            }

            // Handle zoomable area
            Rect zoomRect = new Rect(r);

            zoomRect.yMin         += dropRect.height;
            m_ZoomablePreview.rect = zoomRect;

            m_ZoomablePreview.BeginViewGUI();
            m_ZoomablePreview.EndViewGUI();

            GUILayoutUtility.GetRect(r.width, r.height);
        }