-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
GameView.cs
1008 lines (866 loc) · 43.2 KB
/
GameView.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine;
using UnityEditorInternal;
using UnityEditor.SceneManagement;
using UnityEditor.Modules;
using System.Globalization;
using UnityEngine.Rendering;
using System.Linq;
using System.Collections.Generic;
using JetBrains.Annotations;
using UnityEditor.ShortcutManagement;
using UnityEditorInternal.VR;
using UnityEngine.XR;
using FrameCapture = UnityEngine.Apple.FrameCapture;
using FrameCaptureDestination = UnityEngine.Apple.FrameCaptureDestination;
/*
The main GameView can be in the following states when entering playmode.
These states should be tested when changing the behavior when entering playmode.
GameView docked and visible
GameView docked and visible and maximizeOnPlay
GameView docked and hidden
GameView docked and hidden and maximizeOnPlay
GameView docked and hidden and resized
Maximized GameView (maximized from start)
No GameView but a SceneView exists
No GameView and no SceneView exists
Floating GameView in separate window
*/
namespace UnityEditor
{
[EditorWindowTitle(title = "Game", useTypeNameAsIconName = true)]
internal class GameView : PlayModeView, IHasCustomMenu, IGameViewSizeMenuUser
{
const int kScaleSliderMinWidth = 30;
const int kScaleSliderMaxWidth = 150;
const int kScaleSliderSnapThreshold = 4;
const int kScaleLabelWidth = 40;
readonly Vector2 kWarningSize = new Vector2(400f, 140f);
readonly Color kClearBlack = new Color(0, 0 , 0, 0);
const float kMinScale = 1f;
const float kMaxScale = 5f;
const float kScrollZoomSnapDelay = 0.2f;
// This will save the previous state which will be useful in case of platform switch
int prevSizeGroupType;
float minScale
{
get
{
var clampedMinScale = Mathf.Min(kMinScale, ScaleThatFitsTargetInView(targetRenderSize, viewInWindow.size));
if (m_LowResolutionForAspectRatios[(int)currentSizeGroupType] && currentGameViewSize.sizeType == GameViewSizeType.AspectRatio)
clampedMinScale = Mathf.Max(clampedMinScale, Mathf.Floor(EditorGUIUtility.pixelsPerPoint));
return clampedMinScale;
}
}
float maxScale
{
get { return Mathf.Max(kMaxScale * EditorGUIUtility.pixelsPerPoint, ScaleThatFitsTargetInView(targetRenderSize, viewInWindow.size)); }
}
[SerializeField] bool m_VSyncEnabled;
[SerializeField] bool m_Gizmos;
[SerializeField] bool m_Stats;
[SerializeField] int[] m_SelectedSizes = new int[0]; // We have a selection for each game view size group (e.g standalone, android etc)
[SerializeField] ZoomableArea m_ZoomArea;
[SerializeField] float m_defaultScale = -1f;
bool m_TargetClamped;
[SerializeField] Vector2 m_LastWindowPixelSize;
[SerializeField] bool m_ClearInEditMode = true;
[SerializeField] bool m_NoCameraWarning = true;
[SerializeField] bool[] m_LowResolutionForAspectRatios = new bool[0];
[SerializeField] int m_XRRenderMode = 0;
[SerializeField] RenderTexture m_RenderTexture;
int m_SizeChangeID = int.MinValue;
List<XRDisplaySubsystem> m_DisplaySubsystems = new List<XRDisplaySubsystem>();
internal static class Styles
{
public static GUIContent gizmosContent = EditorGUIUtility.TrTextContent("Gizmos");
public static GUIContent zoomSliderContent = EditorGUIUtility.TrTextContent("Scale", "Size of the game view on the screen.");
public static GUIContent vsyncContent = EditorGUIUtility.TrTextContent("VSync");
public static GUIContent maximizeOnPlayContent = EditorGUIUtility.TrTextContent("Maximize On Play");
public static GUIContent muteOffContent = EditorGUIUtility.TrIconContent("SceneviewAudio", "Mute Audio");
public static GUIContent muteOnContent = EditorGUIUtility.TrIconContent("SceneviewAudio Off", "Mute Audio");
public static GUIContent shortcutsOnContent = EditorGUIUtility.TrIconContent("Keyboard", "Unity Shortcuts");
public static GUIContent shortcutsOffContent = EditorGUIUtility.TrIconContent("KeyboardShortcutsDisabled", "Unity Shortcuts");
public static GUIContent statsContent = EditorGUIUtility.TrTextContent("Stats");
public static GUIContent frameDebuggerOnContent = EditorGUIUtility.TrTextContent("Frame Debugger On");
public static GUIContent loadRenderDocContent = EditorGUIUtility.TrTextContent(UnityEditor.RenderDocUtil.loadRenderDocLabel);
public static GUIContent noCameraWarningContextMenuContent = EditorGUIUtility.TrTextContent("Warn if No Cameras Rendering");
public static GUIContent clearEveryFrameContextMenuContent = EditorGUIUtility.TrTextContent("Clear Every Frame in Edit Mode");
public static GUIContent lowResAspectRatiosContextMenuContent = EditorGUIUtility.TrTextContent("Low Resolution Aspect Ratios");
public static GUIContent metalFrameCaptureContent = EditorGUIUtility.TrIconContent("FrameCapture", "Capture the current view and open in Xcode frame debugger");
public static GUIContent renderdocContent;
public static GUIStyle gameViewBackgroundStyle;
// The ordering here must correspond with ordering in UnityEngine.XR.GameViewRenderMode
public static GUIContent[] xrRenderingModes = { EditorGUIUtility.TextContent("Left Eye|Left eye is displayed in play mode."), EditorGUIUtility.TextContent("Right Eye|Right eye is displayed in play mode."), EditorGUIUtility.TextContent("Both Eyes|Both eyes are displayed in play mode."), EditorGUIUtility.TextContent("Occlusion Mesh|Both eyes are displayed in play mode along with the occlusion mesh.") };
static Styles()
{
gameViewBackgroundStyle = "GameViewBackground";
renderdocContent = EditorGUIUtility.TrIconContent("FrameCapture", UnityEditor.RenderDocUtil.openInRenderDocLabel);
}
}
static double s_LastScrollTime;
public GameView()
{
autoRepaintOnSceneChange = true;
InitializeZoomArea();
playModeViewName = "GameView";
clearColor = kClearBlack;
showGizmos = m_Gizmos;
targetDisplay = 0;
targetSize = new Vector2(640f, 480f);
textureFilterMode = FilterMode.Point;
textureHideFlags = HideFlags.HideAndDontSave;
}
public bool lowResolutionForAspectRatios
{
get
{
EnsureSelectedSizeAreValid();
return m_LowResolutionForAspectRatios[(int)currentSizeGroupType];
}
set
{
EnsureSelectedSizeAreValid();
if (value != m_LowResolutionForAspectRatios[(int)currentSizeGroupType])
{
m_LowResolutionForAspectRatios[(int)currentSizeGroupType] = value;
UpdateZoomAreaAndParent();
}
}
}
public bool forceLowResolutionAspectRatios => EditorGUIUtility.pixelsPerPoint == 1f;
public bool vSyncEnabled
{
get { return m_VSyncEnabled; }
set
{
if (value == m_VSyncEnabled)
return;
SetVSync(value);
m_VSyncEnabled = value;
}
}
int selectedSizeIndex
{
get
{
EnsureSelectedSizeAreValid();
return m_SelectedSizes[(int)currentSizeGroupType];
}
set
{
EnsureSelectedSizeAreValid();
m_SelectedSizes[(int)currentSizeGroupType] = value;
}
}
//This has been added to accomodate the test in PR for case 991291.
internal void SetTargetDisplay(int id)
{
if (id < 0 || id > 7)
return;
targetDisplay = id;
SetDisplayViewSize(id, targetSize);
}
static GameViewSizeGroupType currentSizeGroupType => GameViewSizes.instance.currentGroupType;
GameViewSize currentGameViewSize => GameViewSizes.instance.currentGroup.GetGameViewSize(selectedSizeIndex);
Rect GetViewInWindow(Rect pos)
{
if (showToolbar)
return new Rect(0, EditorGUI.kWindowToolbarHeight, pos.width, pos.height - EditorGUI.kWindowToolbarHeight);
return new Rect(0, 0, pos.width, pos.height);
}
Rect GetViewPixelRect(Rect viewRectInWindow)
{
return lowResolutionForAspectRatios ? viewRectInWindow : EditorGUIUtility.PointsToPixels(viewRectInWindow);
}
// The area of the window that the rendered game view is limited to
Rect viewInWindow
{
get
{
if (showToolbar)
return new Rect(0, EditorGUI.kWindowToolbarHeight, position.width, position.height - EditorGUI.kWindowToolbarHeight);
return new Rect(0, 0, position.width, position.height);
}
}
internal Vector2 targetRenderSize // Size of render target in pixels
{
get
{
var viewPixelRect = lowResolutionForAspectRatios ? viewInWindow : EditorGUIUtility.PointsToPixels(viewInWindow);
return GameViewSizes.GetRenderTargetSize(viewPixelRect, currentSizeGroupType, selectedSizeIndex, out m_TargetClamped);
}
}
// Area of the render target in zoom content space (it is centered in content space)
Rect targetInContent
{
get
{
var targetSizeCached = targetRenderSize;
return EditorGUIUtility.PixelsToPoints(new Rect(-0.5f * targetSizeCached, targetSizeCached));
}
}
Rect targetInView // Area of the render target in zoom view space
{
get
{
var targetInContentCached = targetInContent;
return new Rect(
m_ZoomArea.DrawingToViewTransformPoint(targetInContentCached.position),
m_ZoomArea.DrawingToViewTransformVector(targetInContentCached.size)
);
}
}
// The final image needs to be flipped upside-down if we use coordinates with zero at the top
Rect deviceFlippedTargetInView
{
get
{
if (!SystemInfo.graphicsUVStartsAtTop)
return targetInView;
else
{
var flippedTarget = targetInView;
flippedTarget.y += flippedTarget.height;
flippedTarget.height = -flippedTarget.height;
return flippedTarget;
}
}
}
Rect viewInParent // The view area in parent view space
{
get
{
var viewInParent = viewInWindow;
var parentBorder = m_Parent.borderSize;
viewInParent.x += parentBorder.left;
// Note: DockArea has extra space on top of the tab area which is accounted for strangely.
// It is stored in borderSize.bottom but it should be added to the top instead
// @TODO: Make DockArea.borderSize more sensible (requires fixing all usages)
viewInParent.y += parentBorder.top + parentBorder.bottom;
return viewInParent;
}
}
Rect targetInParent // Area of the render target in parent view space
{
get
{
var targetInViewCached = targetInView;
return new Rect(targetInViewCached.position + viewInParent.position, targetInViewCached.size);
}
}
// Area for warnings such as no cameras rendering
Rect warningPosition { get { return new Rect((viewInWindow.size - kWarningSize) * 0.5f, kWarningSize); } }
Vector2 gameMouseOffset { get { return -viewInWindow.position - targetInView.position; } }
float gameMouseScale { get { return EditorGUIUtility.pixelsPerPoint / m_ZoomArea.scale.y; } }
private bool showToolbar { get; set; }
internal bool drawGizmos
{
get => m_Gizmos;
set => m_Gizmos = value;
}
void InitializeZoomArea()
{
m_ZoomArea = new ZoomableArea(true, false) {uniformScale = true, upDirection = ZoomableArea.YDirection.Negative};
}
public void OnEnable()
{
wantsLessLayoutEvents = true;
prevSizeGroupType = (int)currentSizeGroupType;
titleContent = GetLocalizedTitleContent();
UpdateZoomAreaAndParent();
showToolbar = ModeService.HasCapability(ModeCapability.GameViewToolbar, true);
ModeService.modeChanged += OnEditorModeChanged;
EditorApplication.playModeStateChanged += OnPlayModeStateChanged;
targetSize = targetRenderSize;
}
public void OnDisable()
{
ModeService.modeChanged -= OnEditorModeChanged;
EditorApplication.playModeStateChanged -= OnPlayModeStateChanged;
if (m_RenderTexture)
{
DestroyImmediate(m_RenderTexture);
}
}
[UsedImplicitly] // This is here because NGUI uses it via reflection (noted in https://confluence.hq.unity3d.com/display/DEV/Game+View+Bucket)
internal static Vector2 GetSizeOfMainGameView()
{
return GetMainPlayModeViewTargetSize();
}
private void UpdateZoomAreaAndParent()
{
// Configure ZoomableArea for new resolution so that old resolution doesn't restrict scale
bool oldScaleWasDefault = Mathf.Approximately(m_ZoomArea.scale.y, m_defaultScale);
ConfigureZoomArea();
m_defaultScale = DefaultScaleForTargetInView(targetRenderSize, viewInWindow.size);
if (oldScaleWasDefault)
{
m_ZoomArea.SetTransform(Vector2.zero, Vector2.one * m_defaultScale);
EnforceZoomAreaConstraints();
}
m_LastWindowPixelSize = position.size * EditorGUIUtility.pixelsPerPoint;
EditorApplication.SetSceneRepaintDirty();
// update the scale according to new resolution
m_ZoomArea.UpdateZoomScale(maxScale, minScale);
}
protected void AllowCursorLockAndHide(bool enable)
{
Unsupported.SetAllowCursorLock(enable, Unsupported.DisallowCursorLockReasons.Other);
Unsupported.SetAllowCursorHide(enable);
}
private void OnFocus()
{
SetFocus(true);
targetSize = targetRenderSize;
}
private void OnLostFocus()
{
// We unlock the cursor when the game view loses focus to allow the user to regain cursor control.
// Fix for 389362: Ensure that we do not unlock cursor during init of play mode. Because we could
// be maximizing game view, which causes a lostfocus on the original game view, in these situations we do
// not unlock cursor.
if (!EditorApplicationLayout.IsInitializingPlaymodeLayout())
{
AllowCursorLockAndHide(false);
}
SetFocus(false);
}
internal override void OnResized()
{
targetSize = targetRenderSize;
}
internal override void OnBackgroundViewResized(Rect pos)
{
// Should only update the game view size if it's in Aspect Ratio mode, otherwise
// we keep the static size
Rect viewInWindow = GetViewInWindow(pos);
Rect viewPixelRect = GetViewPixelRect(viewInWindow);
var newTargetSize =
GameViewSizes.GetRenderTargetSize(viewPixelRect, currentSizeGroupType, selectedSizeIndex, out m_TargetClamped);
if (newTargetSize == GetDisplayViewSize(targetDisplay) && currentGameViewSize.sizeType != GameViewSizeType.AspectRatio)
return;
SetDisplayViewSize(targetDisplay, new Vector2(newTargetSize.x, newTargetSize.y));
UpdateZoomAreaAndParent();
}
// Call when number of available aspects can have changed (after deserialization or gui change)
private void EnsureSelectedSizeAreValid()
{
// Early out if no change was recorded
if (GameViewSizes.instance.GetChangeID() == m_SizeChangeID)
return;
m_SizeChangeID = GameViewSizes.instance.GetChangeID();
var sizeGroupTypes = System.Enum.GetValues(typeof(GameViewSizeGroupType));
// Ensure deserialized array is resized if needed
if (m_SelectedSizes.Length != sizeGroupTypes.Length)
System.Array.Resize(ref m_SelectedSizes, sizeGroupTypes.Length);
// Ensure deserialized selection index for each group is within valid range
foreach (GameViewSizeGroupType groupType in sizeGroupTypes)
{
var gvsg = GameViewSizes.instance.GetGroup(groupType);
var index = (int)groupType;
m_SelectedSizes[index] = Mathf.Clamp(m_SelectedSizes[index], 0, gvsg.GetTotalCount() - 1);
}
// Resize low resolution array as necessary, and fill in new indices with defaults
var lowResolutionSettingsLength = m_LowResolutionForAspectRatios.Length;
if (m_LowResolutionForAspectRatios.Length != sizeGroupTypes.Length)
System.Array.Resize(ref m_LowResolutionForAspectRatios, sizeGroupTypes.Length);
for (var groupIndex = lowResolutionSettingsLength; groupIndex < sizeGroupTypes.Length; ++groupIndex)
m_LowResolutionForAspectRatios[groupIndex] = GameViewSizes.DefaultLowResolutionSettingForSizeGroupType((GameViewSizeGroupType)sizeGroupTypes.GetValue(groupIndex));
}
private void OnSelectionChange()
{
if (m_Gizmos)
Repaint();
}
private void LoadRenderDoc()
{
if (EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
{
ShaderUtil.RequestLoadRenderDoc();
}
}
public virtual void AddItemsToMenu(GenericMenu menu)
{
if (RenderDoc.IsInstalled() && !RenderDoc.IsLoaded())
{
menu.AddItem(Styles.loadRenderDocContent, false, LoadRenderDoc);
}
menu.AddItem(Styles.noCameraWarningContextMenuContent, m_NoCameraWarning, ToggleNoCameraWarning);
menu.AddItem(Styles.clearEveryFrameContextMenuContent, m_ClearInEditMode, ToggleClearInEditMode);
}
private void ToggleNoCameraWarning()
{
m_NoCameraWarning = !m_NoCameraWarning;
}
private void ToggleClearInEditMode()
{
m_ClearInEditMode = !m_ClearInEditMode;
}
public void SizeSelectionCallback(int indexClicked, object objectSelected)
{
if (indexClicked != selectedSizeIndex)
{
selectedSizeIndex = indexClicked;
UpdateZoomAreaAndParent();
targetSize = targetRenderSize;
SceneView.RepaintAll();
}
}
void SnapZoomDelayed()
{
if (EditorApplication.timeSinceStartup > s_LastScrollTime + kScrollZoomSnapDelay)
{
EditorApplication.update -= SnapZoomDelayed;
SnapZoom(m_ZoomArea.scale.y);
Repaint();
}
}
void SnapZoom(float newZoom)
{
var logScale = Mathf.Log10(newZoom);
var logMin = Mathf.Log10(minScale);
var logMax = Mathf.Log10(maxScale);
var shortestSliderDistance = System.Single.MaxValue;
if (logScale > logMin && logScale < logMax)
{
for (var i = 1; i <= maxScale; ++i)
{
// Snap distance is defined in points, so convert difference back to UI space
var sliderDistanceToI = kScaleSliderMaxWidth * Mathf.Abs(logScale - Mathf.Log10(i)) / (logMax - logMin);
if (sliderDistanceToI < kScaleSliderSnapThreshold && sliderDistanceToI < shortestSliderDistance)
{
newZoom = i;
shortestSliderDistance = sliderDistanceToI;
}
}
}
var areaInMargins = m_ZoomArea.shownAreaInsideMargins;
var focalPoint = areaInMargins.position + areaInMargins.size * 0.5f;
m_ZoomArea.SetScaleFocused(focalPoint, Vector2.one * newZoom);
}
void DoZoomSlider()
{
GUILayout.Label(Styles.zoomSliderContent);
EditorGUI.BeginChangeCheck();
// Zooming feels more natural on a log scale
var logScale = Mathf.Log10(m_ZoomArea.scale.y);
var logMin = Mathf.Log10(minScale);
var logMax = Mathf.Log10(maxScale);
logScale = GUILayout.HorizontalSlider(logScale, logMin, logMax, GUILayout.MaxWidth(kScaleSliderMaxWidth), GUILayout.MinWidth(kScaleSliderMinWidth));
if (EditorGUI.EndChangeCheck())
{
var newZoom = Mathf.Pow(10f, logScale);
SnapZoom(newZoom);
}
var scaleContent = EditorGUIUtility.TempContent(UnityString.Format("{0}x", (m_ZoomArea.scale.y).ToString("G2", CultureInfo.InvariantCulture.NumberFormat)));
scaleContent.tooltip = Styles.zoomSliderContent.tooltip;
GUILayout.Label(scaleContent, GUILayout.Width(kScaleLabelWidth));
scaleContent.tooltip = string.Empty;
}
private bool ShouldShowMetalFrameCaptureGUI()
{
return FrameCapture.IsDestinationSupported(FrameCaptureDestination.DevTools)
|| FrameCapture.IsDestinationSupported(FrameCaptureDestination.GPUTraceDocument);
}
private void DoToolbarGUI()
{
if (Event.current.isKey || Event.current.type == EventType.Used)
return;
GameViewSizes.instance.RefreshStandaloneAndRemoteDefaultSizes();
GUILayout.BeginHorizontal(EditorStyles.toolbar);
{
var availableTypes = GetAvailableWindowTypes();
if (availableTypes.Count > 1)
{
var typeNames = availableTypes.Values.ToList();
var types = availableTypes.Keys.ToList();
int viewIndex = EditorGUILayout.Popup(typeNames.IndexOf(GetWindowTitle(GetType())), typeNames.ToArray(),
EditorStyles.toolbarPopup,
GUILayout.Width(90));
EditorGUILayout.Space();
if (types[viewIndex] != typeof(GameView))
{
SwapMainWindow(types[viewIndex]);
}
}
if (ModuleManager.ShouldShowMultiDisplayOption())
{
int display = EditorGUILayout.Popup(targetDisplay, DisplayUtility.GetDisplayNames(), EditorStyles.toolbarPopupLeft, GUILayout.Width(80));
if (display != targetDisplay)
{
targetDisplay = display;
Display.activeEditorGameViewTarget = targetDisplay;
UpdateZoomAreaAndParent();
}
}
EditorGUILayout.GameViewSizePopup(currentSizeGroupType, selectedSizeIndex, this, EditorStyles.toolbarPopup, GUILayout.Width(160f));
DoZoomSlider();
// If the previous platform and current does not match, update the scale
if ((int)currentSizeGroupType != prevSizeGroupType)
{
UpdateZoomAreaAndParent();
// Update the platform to the recent one
prevSizeGroupType = (int)currentSizeGroupType;
}
if (FrameDebuggerUtility.IsLocalEnabled())
{
GUILayout.FlexibleSpace();
Color oldCol = GUI.color;
// This has nothing to do with animation recording. Can we replace this color with something else?
GUI.color *= AnimationMode.recordedPropertyColor;
GUILayout.Label(Styles.frameDebuggerOnContent, EditorStyles.toolbarLabel);
GUI.color = oldCol;
// Make frame debugger windows repaint after each time game view repaints.
// We want them to always display the latest & greatest game view
// rendering state.
if (Event.current.type == EventType.Repaint)
FrameDebuggerWindow.RepaintAll();
}
GUILayout.FlexibleSpace();
if (ShouldShowMetalFrameCaptureGUI())
{
if (GUILayout.Button(Styles.metalFrameCaptureContent, EditorStyles.toolbarButton))
m_Parent.CaptureMetalScene();
}
if (RenderDoc.IsLoaded())
{
using (new EditorGUI.DisabledScope(!RenderDoc.IsSupported()))
{
if (GUILayout.Button(Styles.renderdocContent, EditorStyles.toolbarButton))
{
m_Parent.CaptureRenderDocScene();
GUIUtility.ExitGUI();
}
}
}
SubsystemManager.GetSubsystems(m_DisplaySubsystems);
// Allow the user to select how the XR device will be rendered during "Play In Editor"
if (VREditor.GetVREnabledOnTargetGroup(BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget)) || (m_DisplaySubsystems.Count != 0 && !m_DisplaySubsystems[0].disableLegacyRenderer))
{
EditorGUI.BeginChangeCheck();
GameViewRenderMode currentGameViewRenderMode = UnityEngine.XR.XRSettings.gameViewRenderMode;
int selectedRenderMode = EditorGUILayout.Popup(Mathf.Clamp(((int)currentGameViewRenderMode) - 1, 0, Styles.xrRenderingModes.Length - 1), Styles.xrRenderingModes, EditorStyles.toolbarPopup, GUILayout.Width(80));
if (EditorGUI.EndChangeCheck() && currentGameViewRenderMode != GameViewRenderMode.None)
{
SetXRRenderMode(selectedRenderMode);
}
}
// Handles the case where XRSDK is being used without the shim layer
else if (m_DisplaySubsystems.Count != 0 && m_DisplaySubsystems[0].disableLegacyRenderer)
{
EditorGUI.BeginChangeCheck();
int currentMirrorViewBlitMode = m_DisplaySubsystems[0].GetPreferredMirrorBlitMode();
int currentRenderMode = XRTranslateMirrorViewBlitModeToRenderMode(currentMirrorViewBlitMode);
int selectedRenderMode = EditorGUILayout.Popup(Mathf.Clamp(currentRenderMode , 0, Styles.xrRenderingModes.Length - 1), Styles.xrRenderingModes, EditorStyles.toolbarPopup, GUILayout.Width(80));
int selectedMirrorViewBlitMode = XRTranslateRenderModeToMirrorViewBlitMode(selectedRenderMode);
if (EditorGUI.EndChangeCheck() || currentMirrorViewBlitMode == 0)
{
m_DisplaySubsystems[0].SetPreferredMirrorBlitMode(selectedMirrorViewBlitMode);
if (selectedMirrorViewBlitMode != m_XRRenderMode)
ClearTargetTexture();
m_XRRenderMode = selectedMirrorViewBlitMode;
}
}
maximizeOnPlay = GUILayout.Toggle(maximizeOnPlay, Styles.maximizeOnPlayContent, EditorStyles.toolbarButton);
EditorUtility.audioMasterMute = GUILayout.Toggle(EditorUtility.audioMasterMute,
EditorUtility.audioMasterMute ? Styles.muteOnContent : Styles.muteOffContent, EditorStyles.toolbarButton);
ShortcutIntegration.ignoreWhenPlayModeFocused = GUILayout.Toggle(ShortcutIntegration.ignoreWhenPlayModeFocused,
ShortcutIntegration.ignoreWhenPlayModeFocused ? Styles.shortcutsOffContent : Styles.shortcutsOnContent, EditorStyles.toolbarButton);
m_Stats = GUILayout.Toggle(m_Stats, Styles.statsContent, EditorStyles.toolbarButton);
if (EditorGUILayout.DropDownToggle(ref m_Gizmos, Styles.gizmosContent, EditorStyles.toolbarDropDownToggleRight))
{
Rect rect = GUILayoutUtility.topLevel.GetLast();
if (AnnotationWindow.ShowAtPosition(rect, true))
{
GUIUtility.ExitGUI();
}
}
}
GUILayout.EndHorizontal();
}
private int XRTranslateMirrorViewBlitModeToRenderMode(int mirrorViewBlitMode)
{
switch (mirrorViewBlitMode)
{
default:
return 0;
case XRMirrorViewBlitMode.RightEye:
return 1;
case XRMirrorViewBlitMode.SideBySide:
return 2;
case XRMirrorViewBlitMode.SideBySideOcclusionMesh:
return 3;
}
}
private int XRTranslateRenderModeToMirrorViewBlitMode(int renderMode)
{
switch (renderMode)
{
default: // or 0
return XRMirrorViewBlitMode.LeftEye;
case 1:
return XRMirrorViewBlitMode.RightEye;
case 2:
return XRMirrorViewBlitMode.SideBySide;
case 3:
return XRMirrorViewBlitMode.SideBySideOcclusionMesh;
}
}
private void SetXRRenderMode(int mode)
{
switch (mode)
{
default: // or 0
UnityEngine.XR.XRSettings.gameViewRenderMode = UnityEngine.XR.GameViewRenderMode.LeftEye;
break;
case 1:
UnityEngine.XR.XRSettings.gameViewRenderMode = UnityEngine.XR.GameViewRenderMode.RightEye;
break;
case 2:
UnityEngine.XR.XRSettings.gameViewRenderMode = UnityEngine.XR.GameViewRenderMode.BothEyes;
break;
case 3:
UnityEngine.XR.XRSettings.gameViewRenderMode = UnityEngine.XR.GameViewRenderMode.OcclusionMesh;
break;
}
if (mode != m_XRRenderMode)
ClearTargetTexture();
m_XRRenderMode = mode;
}
private void ClearTargetTexture()
{
if (m_RenderTexture && m_RenderTexture.IsCreated())
{
var previousTarget = RenderTexture.active;
RenderTexture.active = m_RenderTexture;
GL.Clear(true, true, kClearBlack);
RenderTexture.active = previousTarget;
}
}
private float ScaleThatFitsTargetInView(Vector2 targetInPixels, Vector2 viewInPoints)
{
var targetInPoints = EditorGUIUtility.PixelsToPoints(targetInPixels);
var viewToTargetRatio = new Vector2(viewInPoints.x / targetInPoints.x, viewInPoints.y / targetInPoints.y);
return Mathf.Min(viewToTargetRatio.x, viewToTargetRatio.y);
}
private float DefaultScaleForTargetInView(Vector2 targetToFit, Vector2 viewSize)
{
var scale = ScaleThatFitsTargetInView(targetToFit, viewSize);
if (scale > 1f)
{
scale = Mathf.Min(maxScale * EditorGUIUtility.pixelsPerPoint, Mathf.FloorToInt(scale));
}
return scale;
}
private void ConfigureZoomArea()
{
m_ZoomArea.rect = viewInWindow;
// Sliders are sized with respect to canvas
var targetInContentCached = targetInContent;
m_ZoomArea.hBaseRangeMin = targetInContentCached.xMin;
m_ZoomArea.vBaseRangeMin = targetInContentCached.yMin;
m_ZoomArea.hBaseRangeMax = targetInContentCached.xMax;
m_ZoomArea.vBaseRangeMax = targetInContentCached.yMax;
// Restrict zooming
m_ZoomArea.hScaleMin = m_ZoomArea.vScaleMin = minScale;
m_ZoomArea.hScaleMax = m_ZoomArea.vScaleMax = maxScale;
}
private void EnforceZoomAreaConstraints()
{
var shownArea = m_ZoomArea.shownArea;
var targetInContentCached = targetInContent;
// When zoomed out, we disallow panning by automatically centering the view
if (shownArea.width > targetInContentCached.width)
{
shownArea.x = -0.5f * shownArea.width;
}
else
// When zoomed in, we prevent panning outside the render area
{
shownArea.x = Mathf.Clamp(shownArea.x, targetInContentCached.xMin, targetInContentCached.xMax - shownArea.width);
}
// Horizontal and vertical are separated because otherwise we get weird behaviour when only one is zoomed out
if (shownArea.height > targetInContent.height)
{
shownArea.y = -0.5f * shownArea.height;
}
else
{
shownArea.y = Mathf.Clamp(shownArea.y, targetInContentCached.yMin, targetInContentCached.yMax - shownArea.height);
}
m_ZoomArea.shownArea = shownArea;
}
public void RenderToHMDOnly()
{
var mousePos = Vector2.zero;
targetDisplay = 0;
targetSize = targetRenderSize;
showGizmos = false;
renderIMGUI = false;
m_RenderTexture = RenderView(mousePos, clearTexture: false);
}
private void OnPlayModeStateChanged(PlayModeStateChange state)
{
if (state == PlayModeStateChange.EnteredPlayMode)
{
// Enable vsync in play mode to get as much as possible frame rate consistency
m_Parent.EnableVSync(m_VSyncEnabled);
}
else if (state == PlayModeStateChange.ExitingPlayMode)
{
m_Parent.EnableVSync(false);
}
}
private void OnEditorModeChanged(ModeService.ModeChangedArgs args)
{
showToolbar = ModeService.HasCapability(ModeCapability.GameViewToolbar, true);
Repaint();
}
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 or touch events 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 isKey = Event.current.rawType == EventType.KeyDown || Event.current.rawType == EventType.KeyUp;
bool useEvent = mousePosInGameViewRect || isKey;
// 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);