-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathVisualProfiler.cs
More file actions
1743 lines (1438 loc) · 70.2 KB
/
VisualProfiler.cs
File metadata and controls
1743 lines (1438 loc) · 70.2 KB
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Text;
using Unity.Profiling;
using UnityEngine;
using UnityEngine.Profiling;
using UnityEngine.Rendering;
#if UNITY_STANDALONE_WIN || UNITY_WSA
using UnityEngine.Windows.Speech;
#endif
#if WINDOWS_UWP
using Windows.System;
#endif
namespace Microsoft.MixedReality.Profiling
{
/// <summary>
///
/// ABOUT: The VisualProfiler provides a drop in solution for viewing your Mixed Reality
/// Unity application's frame rate and memory usage. Missed frames are displayed over time to
/// visually find problem areas. Draw calls, batches, and vertex (or triangle) counts are displayed to
/// diagnose scene complexity. Memory is reported as current, peak and max usage in a bar graph.
///
/// USAGE: To use this profiler simply add this script as a component of any GameObject in
/// your Unity scene. The profiler is initially active and visible (toggle-able via the
/// IsVisible property), but can be toggled via the enabled/disable voice commands keywords (in Windows/UWP).
///
/// IMPORTANT: Please make sure to add the microphone capability to your UWP app if you plan
/// on using the enable/disable keywords, in Unity under Edit -> Project Settings ->
/// Player -> Settings for Windows Store -> Publishing Settings -> Capabilities or in your
/// Visual Studio Package.appxmanifest capabilities.
///
/// </summary>
public sealed class VisualProfiler : MonoBehaviour, ISerializationCallbackReceiver
{
[Header("Profiler Settings")]
[SerializeField, Tooltip("Is the profiler currently visible? If disabled, prevents the profiler from rendering but still allows it to track memory usage.")]
private bool isVisible = true;
/// <summary>
/// Is the profiler currently visible? If disabled, prevents the profiler from rendering but still allows it to track memory usage.
/// </summary>
public bool IsVisible
{
get { return isVisible; }
set { isVisible = value; }
}
[SerializeField, Tooltip("The amount of time, in seconds, to collect frames before frame rate averaging.")]
private float frameSampleRate = 0.3f;
/// <summary>
/// The amount of time, in seconds, to collect frames before frame rate averaging.
/// </summary>
public float FrameSampleRate
{
get { return frameSampleRate; }
set
{
frameSampleRate = value;
frameSampleRateMS = frameSampleRate * 1000.0f;
}
}
[SerializeField, Min(0.0f), Tooltip("What frame rate should the app target if one cannot be determined by the XR device.")]
private float defaultFrameRate = 60.0f;
/// <summary>
/// What frame rate should the app target if one cannot be determined by the XR device.
/// </summary>
public float DefaultFrameRate
{
get { return defaultFrameRate; }
set { defaultFrameRate = Mathf.Max(value, 0.0f); }
}
[SerializeField, Range(0.0f, 1.0f), Tooltip("A missed frame is considered when the frame rate is less than the target frame rate times the missed frame percentage.")]
private float missedFramePercentage = 0.9f;
/// <summary>
/// A missed frame is considered when the frame rate is less than the target frame rate times the missed frame percentage."
/// </summary>
public float MissedFramePercentage
{
get { return missedFramePercentage; }
set { missedFramePercentage = Mathf.Clamp01(value); }
}
[SerializeField, Range(0, 2), Tooltip("How many decimal places to display on numeric strings.")]
private int displayedDecimalDigits = 1;
[SerializeField, Tooltip("Display triangle count instead of vertex count in the profiler.")]
private bool displayTriangleCount = false;
[SerializeField, Tooltip("Table of QualitySettings.GetQualityLevel index to batches budget. When values are above this budget the text will change color.")]
private int[] batchesQualityLevelBudget = new int[0];
/// <summary>
/// Table of QualitySettings.GetQualityLevel index to batches budget. When values are above this budget the text will change color.
/// </summary>
public int[] BatchesQualityLevelBudget
{
get { return batchesQualityLevelBudget; }
set { batchesQualityLevelBudget = value; }
}
[SerializeField, Tooltip("Table of QualitySettings.GetQualityLevel index to draw calls budget. When values are above this budget the text will change color.")]
private int[] drawCallsQualityLevelBudget = new int[0];
/// <summary>
/// Table of QualitySettings.GetQualityLevel index to draw calls budget. When values are above this budget the text will change color.
/// </summary>
public int[] DrawCallsQualityLevelBudget
{
get { return drawCallsQualityLevelBudget; }
set { drawCallsQualityLevelBudget = value; }
}
[SerializeField, Tooltip("Table of QualitySettings.GetQualityLevel index to vertex (or triangle) budget. When values are above this budget the text will change color.")]
private int[] meshStatsQualityLevelBudget = new int[0];
/// <summary>
/// Table of QualitySettings.GetQualityLevel index to vertex (or triangle) budget. When values are above this budget the text will change color.
/// </summary>
public int[] MeshStatsQualityLevelBudget
{
get { return meshStatsQualityLevelBudget; }
set { meshStatsQualityLevelBudget = value; }
}
[Header("Window Settings")]
[SerializeField, Tooltip("What part of the view port to anchor the window to.")]
private TextAnchor windowAnchor = TextAnchor.LowerCenter;
/// <summary>
/// What part of the view port to anchor the window to.
/// </summary>
public TextAnchor WindowAnchor
{
get { return windowAnchor; }
set { windowAnchor = value; }
}
[SerializeField, Tooltip("The offset from the view port center applied based on the window anchor selection.")]
private Vector2 windowOffset = new Vector2(0.1f, 0.1f);
/// <summary>
/// The offset from the view port center applied based on the window anchor selection.
/// </summary>
public Vector2 WindowOffset
{
get { return windowOffset; }
set { windowOffset = value; }
}
[SerializeField, Range(0.5f, 10.0f), Tooltip("Use to scale the window size up or down, can simulate a zooming effect.")]
private float windowScale = 1.0f;
/// <summary>
/// Use to scale the window size up or down, can simulate a zooming effect.
/// </summary>
public float WindowScale
{
get { return windowScale; }
set { windowScale = Mathf.Clamp(value, 0.5f, 10.0f); }
}
[SerializeField, Range(0.0f, 100.0f), Tooltip("How quickly to interpolate the window towards its target position and rotation.")]
private float windowFollowSpeed = 5.0f;
/// <summary>
/// How quickly to interpolate the window towards its target position and rotation.
/// </summary>
public float WindowFollowSpeed
{
get { return windowFollowSpeed; }
set { windowFollowSpeed = Mathf.Abs(value); }
}
[SerializeField, Tooltip("Should the window snap to location rather than interpolate?")]
private bool snapWindow = false;
/// <summary>
/// Should the window snap to location rather than interpolate?
/// </summary>
public bool SnapWindow
{
get { return snapWindow; }
set { snapWindow = value; }
}
[SerializeField, Tooltip("Should the window always align to the camera? (No local rotation.)")]
private bool alignToCamera = false;
/// <summary>
/// Should the window always align to the camera? (No local rotation.)
/// </summary>
public bool AlignToCamera
{
get { return alignToCamera; }
set { alignToCamera = value; }
}
[SerializeField, Tooltip("If specified, the profiler window will follow this transform instead of the main camera.")]
private Transform transformToFollow = null;
/// <summary>
/// If specified, the profiler window will follow this transform instead of the main camera.
/// </summary>
public Transform TransformToFollow
{
get { return transformToFollow; }
set { transformToFollow = value; }
}
/// <summary>
/// Access the CPU frame rate (in frames per second).
/// </summary>
public float SmoothCpuFrameRate { get; private set; }
/// <summary>
/// Access the GPU frame rate (in frames per second). Will return zero when GPU profiling is not available.
/// </summary>
public float SmoothGpuFrameRate { get; private set; }
/// <summary>
/// Returns the target frame rate for the current platform.
/// </summary>
public float TargetFrameRate
{
get
{
// If the current XR SDK does not report refresh rate information, assume 60Hz.
float refreshRate = 0;
#if ENABLE_VR
refreshRate = UnityEngine.XR.XRDevice.refreshRate;
#endif
return ((int)refreshRate == 0) ? defaultFrameRate : refreshRate;
}
}
/// <summary>
/// Returns the target frame time in milliseconds for the current platform.
/// </summary>
public float TargetFrameTime
{
get
{
return (1.0f / TargetFrameRate) * 1000.0f;
}
}
[SerializeField, Tooltip("Voice commands to toggle the profiler on and off. (Supported in UWP only.)")]
private string[] toggleKeyworlds = new string[] { "Profiler", "Toggle Profiler", "Show Profiler", "Hide Profiler" };
[Header("Visual Settings")]
[SerializeField, Range(0, 31), Tooltip("The layer index used for rendering the profiler (range between 0, 31 inclusive). Can be used in conjuction with a camera's \"Culling Mask\" to chose which camera renders the profiler.")]
private int layer = 0;
/// <summary>
/// The layer index used for rendering the profiler (range between 0, 31 inclusive). Can be used in conjuction with a camera's \"Culling Mask\" to chose which camera renders the profiler.
/// </summary>
public int Layer
{
get { return layer; }
set { layer = Mathf.Clamp(value, 0, 31); }
}
[SerializeField, Tooltip("The material to use when rendering the profiler. The material should use the \"Hidden / Visual Profiler\" shader and have a font texture.")]
private Material material;
[SerializeField, Tooltip("The color of the window backplate.")]
private Color baseColor = new Color(50 / 255.0f, 50 / 255.0f, 50 / 255.0f, 1.0f);
[SerializeField, Tooltip("The color to display on frames which meet or exceed the target frame rate.")]
private Color targetFrameRateColor = new Color(127 / 255.0f, 186 / 255.0f, 0 / 255.0f, 1.0f);
[SerializeField, Tooltip("The color to display on frames which fall below the target frame rate.")]
private Color missedFrameRateColor = new Color(242 / 255.0f, 80 / 255.0f, 34 / 255.0f, 1.0f);
[SerializeField, Tooltip("The color to display for current memory usage values.")]
private Color memoryUsedColor = new Color(0 / 255.0f, 164 / 255.0f, 239 / 255.0f, 1.0f);
[SerializeField, Tooltip("The color to display for peak (aka max) memory usage values.")]
private Color memoryPeakColor = new Color(255 / 255.0f, 185 / 255.0f, 0 / 255.0f, 1.0f);
[SerializeField, Tooltip("The color to display for the platforms memory usage limit.")]
private Color memoryLimitColor = new Color(100 / 255.0f, 100 / 255.0f, 100 / 255.0f, 1.0f);
[Header("Font Settings")]
[SerializeField, Tooltip("The width and height of a mono spaced character in the font texture (in pixels).")]
private Vector2Int fontCharacterSize = new Vector2Int(16, 30);
[SerializeField, Tooltip("The x and y scale to render a character at.")]
private Vector2 fontScale = new Vector2(0.00023f, 0.00028f);
[SerializeField, Min(1), Tooltip("How many characters are in a row of the font texture.")]
private int fontColumns = 32;
/// <summary>
/// Describes a group of Unity Profiler marker. Common markers are listed here: https://docs.unity3d.com/Manual/profiler-markers.html
/// </summary>
[Serializable]
private class ProfilerGroup
{
[Tooltip("The visible name of this group in the Visual Profiler. This should be no longer than 9 characters.")]
public string DisplayName;
[Serializable]
public class Marker : IDisposable
{
public enum OperationType
{
Add,
Subtract,
}
public void Init(int capacity)
{
recorder = new ProfilerRecorder(StatName, capacity: 1,
ProfilerRecorderOptions.WrapAroundWhenCapacityReached |
ProfilerRecorderOptions.SumAllSamplesInFrame |
ProfilerRecorderOptions.StartImmediately);
sampleBuffer = new long[capacity];
}
public void Update()
{
long nextSample = recorder.LastValue;
if (nextSample == 0) // ProfilerCounterValue doesn't update the LastValue.
{
nextSample = recorder.CurrentValue;
}
sumOfSamples -= sampleBuffer[nextSampleIndex];
sumOfSamples += nextSample;
sampleBuffer[nextSampleIndex] = nextSample;
++nextSampleIndex;
if (nextSampleIndex >= sampleBuffer.Length)
{
isBufferFull = true;
nextSampleIndex = 0;
}
}
public void Dispose()
{
recorder.Dispose();
}
[Tooltip("Profiler marker or counter name.")]
public string StatName;
[Tooltip("Select if this marker should be added to or subtracted from the total.")]
public OperationType Operation;
[NonSerialized]
public ProfilerRecorder recorder;
[NonSerialized]
public long sumOfSamples;
[NonSerialized]
public bool isBufferFull;
[NonSerialized]
private long[] sampleBuffer;
[NonSerialized]
private int nextSampleIndex;
}
[Tooltip("List of profiler markers which make up this group.")]
public Marker[] Markers = new Marker[0];
[Min(1), Tooltip("The amount of samples to collect then average when displaying the profiler marker.")]
public int SampleCapacity = 300;
[Range(0.0f, 1.0f), Tooltip("What % of the target frame time can this profiler take before being considered over budget?")]
public float BudgetPercentage = 1.0f;
public TextData Text { get; set; }
public float LastValuePresented { get; set; }
public bool HasEverPresented { get; set; }
public ProfilerMarkerDataUnit MarkerUnitType { get; private set; }
public string DisplayUnitSuffix { get; private set; }
private bool running = false;
public void Start()
{
foreach (var marker in Markers)
{
marker.Init(SampleCapacity);
}
if (Markers[0] != null)
{
MarkerUnitType = Markers[0].recorder.UnitType;
switch (MarkerUnitType)
{
case ProfilerMarkerDataUnit.TimeNanoseconds: DisplayUnitSuffix = "ms"; break;
case ProfilerMarkerDataUnit.Bytes: DisplayUnitSuffix = "kbps"; break;
case ProfilerMarkerDataUnit.Percent: DisplayUnitSuffix = "%"; break;
case ProfilerMarkerDataUnit.FrequencyHz: DisplayUnitSuffix = "hz"; break;
default: DisplayUnitSuffix = ""; break;
}
}
running = true;
}
public void Update()
{
foreach (var marker in Markers)
{
marker.Update();
}
}
public void Stop()
{
foreach (var marker in Markers)
{
marker.Dispose();
}
running = false;
}
public void Reset()
{
HasEverPresented = false;
LastValuePresented = -1.0f;
}
public bool ReadyToPresent()
{
if (running)
{
foreach (var marker in Markers)
{
if (marker.recorder.Valid &&
marker.isBufferFull)
{
return true;
}
}
}
return false;
}
public float CalculateAverage()
{
if (!running)
{
return 0.0f;
}
float sum = 0.0f;
foreach (var marker in Markers)
{
switch (marker.Operation)
{
case Marker.OperationType.Add: sum += marker.sumOfSamples; break;
case Marker.OperationType.Subtract: sum -= marker.sumOfSamples; break;
}
}
sum /= SampleCapacity;
return sum;
}
public float CalculateDisplayValue()
{
float average = CalculateAverage();
switch (MarkerUnitType)
{
case ProfilerMarkerDataUnit.TimeNanoseconds: return average * 1e-6f; // Milliseconds
case ProfilerMarkerDataUnit.Bytes: return average / 125.0f; // Kilobits/second
default: return average;
}
}
}
[Header("Profiler Groups")]
[SerializeField, Tooltip("If multiple rows of profiler groups are displayed, choose which order to display them in.")]
private ProfilerDisplayOrderType ProfilerDisplayOrder; // = ProfilerDisplayOrderType.Rows
public enum ProfilerDisplayOrderType
{
[InspectorName("Right, Then Down")]
Rows,
[InspectorName("Down, Then Right")]
Columns,
}
[SerializeField, Tooltip("Populate this list with ProfilerRecorder profiler markers to display timing information.")]
private ProfilerGroup[] ProfilerGroups = new ProfilerGroup[0];
// Constants.
private const int maxStringLength = 17;
private const int maxTargetFrameRate = 240;
private const int frameRange = 30;
// These offsets specify how many instances a portion of the UI uses as well as draw order.
private const int backplateInstanceOffset = 0;
private const int framesInstanceOffset = backplateInstanceOffset + 1;
private const int limitInstanceOffset = framesInstanceOffset + frameRange;
private const int peakInstanceOffset = limitInstanceOffset + 1;
private const int usedInstanceOffset = peakInstanceOffset + 1;
private const int cpuframeRateTextOffset = usedInstanceOffset + 1;
private const int qualityLevelTextOffset = cpuframeRateTextOffset + maxStringLength;
private const int gpuframeRateTextOffset = qualityLevelTextOffset + maxStringLength;
private const int batchesTextOffset = gpuframeRateTextOffset + maxStringLength;
private const int drawCallTextOffset = batchesTextOffset + maxStringLength;
private const int meshStatsTextOffset = drawCallTextOffset + maxStringLength;
private const int usedMemoryTextOffset = meshStatsTextOffset + maxStringLength;
private const int limitMemoryTextOffset = usedMemoryTextOffset + maxStringLength;
private const int peakMemoryTextOffset = limitMemoryTextOffset + maxStringLength;
private const int lastOffset = peakMemoryTextOffset + maxStringLength;
private static readonly int colorID = Shader.PropertyToID("_Color");
private static readonly int baseColorID = Shader.PropertyToID("_BaseColor");
private static readonly int fontScaleID = Shader.PropertyToID("_FontScale");
private static readonly int uvOffsetScaleXID = Shader.PropertyToID("_UVOffsetScaleX");
private static readonly int windowLocalToWorldID = Shader.PropertyToID("_WindowLocalToWorldMatrix");
// Pre computed state.
private char[][] qualityLevelStrings = new char[0][];
private char[][] frameRateStrings = new char[maxTargetFrameRate + 1][];
private char[][] gpuFrameRateStrings = new char[maxTargetFrameRate + 1][];
private Vector4[] characterUVs = new Vector4[128];
private Vector3 characterScale = Vector3.zero;
// UI state.
private Vector3 windowPosition = Vector3.zero;
private Quaternion windowRotation = Quaternion.identity;
private class TextData
{
public string Prefix;
public Vector3 Position;
public bool RightAligned;
public int Offset;
public int LastCount;
public TextData(Vector3 position, bool rightAligned, int offset, string prefix = "")
{
Position = position;
RightAligned = rightAligned;
Offset = offset;
Prefix = prefix;
LastCount = maxStringLength;
}
}
private TextData cpuFrameRateText = null;
private TextData qualityLevelText = null;
private TextData gpuFrameRateText = null;
private TextData batchesText = null;
private TextData drawCallText = null;
private TextData meshText = null;
private TextData usedMemoryText = null;
private TextData peakMemoryText = null;
private TextData limitMemoryText = null;
private Quaternion windowHorizontalRotation = Quaternion.identity;
private Quaternion windowHorizontalRotationInverse = Quaternion.identity;
private Quaternion windowVerticalRotation = Quaternion.identity;
private Quaternion windowVerticalRotationInverse = Quaternion.identity;
private char[] stringBuffer = new char[256];
private int qualityLevel = -1;
private int cpuFrameRate = -1;
private int gpuFrameRate = -1;
private long batches = 0;
private long drawCalls = 0;
private long meshStatsCount = 0;
private ulong memoryUsage = 0;
private ulong peakMemoryUsage = 0;
private ulong limitMemoryUsage = 0;
private bool peakMemoryUsageDirty = false;
// Profiling state.
private int frameCount = 0;
private float accumulatedFrameTimeCPU = 0.0f;
private float accumulatedFrameTimeGPU = 0.0f;
private float frameSampleRateMS = 0.0f;
private FrameTiming[] frameTimings = new FrameTiming[1];
#if !UNITY_EDITOR
private ProfilerRecorder batchesRecorder;
private ProfilerRecorder drawCallsRecorder;
private ProfilerRecorder meshStatsRecorder;
#endif
private Recorder[] srpBatchesRecorders;
private ProfilerRecorder systemUsedMemoryRecorder;
// Rendering state.
private Mesh quadMesh;
private MaterialPropertyBlock instancePropertyBlock;
private Matrix4x4[] instanceMatrices;
private Vector4[] instanceColors;
private Vector4[] instanceBaseColors;
private Vector4[] instanceUVOffsetScaleX;
private bool instanceColorsDirty = false;
private bool instanceBaseColorsDirty = false;
private bool instanceUVOffsetScaleXDirty = false;
private bool customUpdateInUse = false;
/// <summary>
/// Reset any stats the profiler is tracking. Call this if you would like to restart tracking
/// statistics like peak memory usage.
/// </summary>
public void Refresh()
{
SmoothCpuFrameRate = 0.0f;
SmoothGpuFrameRate = 0.0f;
qualityLevel = -1;
cpuFrameRate = -1;
gpuFrameRate = -1;
batches = 0;
drawCalls = 0;
meshStatsCount = 0;
memoryUsage = 0;
peakMemoryUsage = 0;
limitMemoryUsage = 0;
}
/// <summary>
/// Allows for an app to specific a custom point in the frame to call update. (Should be called once every frame.)
/// </summary>
public void CustomUpdate()
{
customUpdateInUse = true;
if (isActiveAndEnabled)
{
InternalUpdate();
}
}
private void OnEnable()
{
if (material == null)
{
Debug.LogError("The VisualProfiler is missing a material and will not display.");
}
// Create a quad mesh with artificially large bounds to disable culling for instanced rendering.
// TODO - [Cameron-Micka] Use shared mesh with normal bounds once Unity allows for more control over instance culling.
if (quadMesh == null)
{
MeshFilter quadMeshFilter = GameObject.CreatePrimitive(PrimitiveType.Quad).GetComponent<MeshFilter>();
quadMesh = quadMeshFilter.mesh;
quadMesh.bounds = new Bounds(Vector3.zero, Vector3.one * float.MaxValue);
Destroy(quadMeshFilter.gameObject);
}
instancePropertyBlock = new MaterialPropertyBlock();
Vector2 defaultWindowRotation = new Vector2(10.0f, 20.0f);
windowHorizontalRotation = Quaternion.AngleAxis(defaultWindowRotation.y, Vector3.right);
windowHorizontalRotationInverse = Quaternion.Inverse(windowHorizontalRotation);
windowVerticalRotation = Quaternion.AngleAxis(defaultWindowRotation.x, Vector3.up);
windowVerticalRotationInverse = Quaternion.Inverse(windowVerticalRotation);
#if !UNITY_EDITOR
batchesRecorder = ProfilerRecorder.StartNew(ProfilerCategory.Render, "Batches Count");
drawCallsRecorder = ProfilerRecorder.StartNew(ProfilerCategory.Render, "Draw Calls Count");
meshStatsRecorder = ProfilerRecorder.StartNew(ProfilerCategory.Render, displayTriangleCount ? "Triangles Count" : "Vertices Count");
#endif
#if ENABLE_PROFILER
var samplerNames = new string[] { "SRPBRender.ApplyShader", "SRPBShadow.ApplyShader", "StdRender.ApplyShader", "StdShadow.ApplyShader" };
srpBatchesRecorders = new Recorder[samplerNames.Length];
for (int i = 0; i < samplerNames.Length; ++i)
{
var recorder = Recorder.Get(samplerNames[i]);
if (recorder.isValid)
{
srpBatchesRecorders[i] = recorder;
}
}
foreach (var profilerGroup in ProfilerGroups)
{
profilerGroup.Start();
}
#endif
systemUsedMemoryRecorder = ProfilerRecorder.StartNew(ProfilerCategory.Memory, "System Used Memory");
BuildWindow();
#if UNITY_STANDALONE_WIN || UNITY_WSA
BuildKeywordRecognizer();
#endif
}
private void OnDisable()
{
#if UNITY_STANDALONE_WIN || UNITY_WSA
if (keywordRecognizer != null && keywordRecognizer.IsRunning)
{
keywordRecognizer.Stop();
keywordRecognizer.Dispose();
keywordRecognizer = null;
}
#endif
systemUsedMemoryRecorder.Dispose();
foreach (var profilerGroup in ProfilerGroups)
{
profilerGroup.Stop();
}
#if !UNITY_EDITOR
meshStatsRecorder.Dispose();
drawCallsRecorder.Dispose();
batchesRecorder.Dispose();
#endif
}
private void OnValidate()
{
BuildWindow();
}
public void OnBeforeSerialize()
{
// Default values for serializable classes in arrays/lists are not supported. This ensures correct construction.
for (int i = 0; i < ProfilerGroups.Length; ++i)
{
if (ProfilerGroups[i].SampleCapacity == 0)
{
ProfilerGroups[i] = new ProfilerGroup();
}
}
}
public void OnAfterDeserialize() { }
private void LateUpdate()
{
if (customUpdateInUse == false)
{
InternalUpdate();
}
}
private void InternalUpdate()
{
#if ENABLE_PROFILER
foreach (var profilerGroup in ProfilerGroups)
{
profilerGroup.Update();
}
#endif
if (IsVisible)
{
// Update window transformation.
Transform cameraTransform = Camera.main ? Camera.main.transform : null;
if (cameraTransform != null)
{
Vector3 targetPosition = CalculateWindowPosition(cameraTransform);
Quaternion targetRotaton = CalculateWindowRotation(cameraTransform);
if (snapWindow)
{
windowPosition = targetPosition;
windowRotation = targetRotaton;
}
else
{
float t = Time.deltaTime * windowFollowSpeed;
windowPosition = Vector3.Lerp(windowPosition, targetPosition, t);
// Lerp rather than slerp for speed over quality.
windowRotation = Quaternion.Lerp(windowRotation, targetRotaton, t);
}
}
// Update quality level text.
int lastQualityLevel = QualitySettings.GetQualityLevel();
if (lastQualityLevel != qualityLevel)
{
char[] text = qualityLevelStrings[lastQualityLevel];
SetText(qualityLevelText, text, text.Length, Color.white);
qualityLevel = lastQualityLevel;
}
// Many platforms do not yet support the FrameTimingManager. When timing data is returned from the FrameTimingManager we will use
// its timing data, else we will depend on the deltaTime. Wider support is coming in Unity 2022.1+
// https://blog.unity.com/technology/detecting-performance-bottlenecks-with-unity-frame-timing-manager
FrameTimingManager.CaptureFrameTimings();
uint frameTimingsCount = FrameTimingManager.GetLatestTimings(1, frameTimings);
if (frameTimingsCount != 0)
{
accumulatedFrameTimeCPU += (float)frameTimings[0].cpuFrameTime;
accumulatedFrameTimeGPU += (float)frameTimings[0].gpuFrameTime;
}
else
{
accumulatedFrameTimeCPU += Time.unscaledDeltaTime * 1000.0f;
// No GPU time to query.
}
++frameCount;
if (accumulatedFrameTimeCPU >= frameSampleRateMS)
{
if (accumulatedFrameTimeCPU != 0.0f)
{
SmoothCpuFrameRate = Mathf.Max(1.0f / ((accumulatedFrameTimeCPU * 0.001f) / frameCount), 0.0f);
}
int lastCpuFrameRate = Mathf.Min(Mathf.RoundToInt(SmoothCpuFrameRate), maxTargetFrameRate);
if (accumulatedFrameTimeGPU != 0.0f)
{
SmoothGpuFrameRate = Mathf.Max(1.0f / ((accumulatedFrameTimeGPU * 0.001f) / frameCount), 0.0f);
}
int lastGpuFrameRate = Mathf.Min(Mathf.RoundToInt(SmoothGpuFrameRate), maxTargetFrameRate);
// TODO - [Cameron-Micka] Ideally we would query a device specific API (like the HolographicFramePresentationReport) to detect missed frames.
bool missedFrame = lastCpuFrameRate < (int)(TargetFrameRate * missedFramePercentage);
Color frameColor = missedFrame ? missedFrameRateColor : targetFrameRateColor;
Vector4 frameIcon = missedFrame ? characterUVs['X'] : characterUVs[' '];
// Update frame rate text.
if (lastCpuFrameRate != cpuFrameRate)
{
char[] text = frameRateStrings[lastCpuFrameRate];
SetText(cpuFrameRateText, text, text.Length, frameColor);
cpuFrameRate = lastCpuFrameRate;
}
if (lastGpuFrameRate != gpuFrameRate)
{
char[] text = gpuFrameRateStrings[lastGpuFrameRate];
Color color = (lastGpuFrameRate < ((int)(TargetFrameRate) - 1)) ? missedFrameRateColor : targetFrameRateColor;
SetText(gpuFrameRateText, text, text.Length, color);
gpuFrameRate = lastGpuFrameRate;
}
// Animate frame colors and icons.
for (int i = frameRange - 1; i > 0; --i)
{
int write = framesInstanceOffset + i;
int read = framesInstanceOffset + i - 1;
instanceBaseColors[write] = instanceBaseColors[read];
instanceUVOffsetScaleX[write] = instanceUVOffsetScaleX[read];
}
instanceBaseColors[framesInstanceOffset + 0] = frameColor;
instanceUVOffsetScaleX[framesInstanceOffset + 0] = frameIcon;
instanceBaseColorsDirty = true;
instanceUVOffsetScaleXDirty = true;
// Reset timers.
frameCount = 0;
accumulatedFrameTimeCPU = 0.0f;
accumulatedFrameTimeGPU = 0.0f;
}
// Update scene statistics.
long lastBatches = 0;
if (GraphicsSettings.useScriptableRenderPipelineBatching)
{
if (srpBatchesRecorders != null)
{
foreach (var recorder in srpBatchesRecorders)
{
if (recorder != null)
{
lastBatches += recorder.sampleBlockCount;
}
// Some frames erroneously report zero batches, filter these frames out.
if (lastBatches == 0)
{
lastBatches = batches;
}
}
}
else // Recorders aren't available so reliable batch counts cannot be displayed.
{
lastBatches = -1;
}
}
else
{
#if UNITY_EDITOR
lastBatches = UnityEditor.UnityStats.batches;
#else
lastBatches = batchesRecorder.LastValue;
#endif
}
if (lastBatches != batches)
{
SceneStatsToString(stringBuffer, batchesText, lastBatches, QualityLevelBudgetToColor(BatchesQualityLevelBudget, lastBatches));
batches = lastBatches;
}
#if UNITY_EDITOR
long lastDrawCalls = UnityEditor.UnityStats.drawCalls;
#else
long lastDrawCalls = drawCallsRecorder.LastValue;
#endif
if (lastDrawCalls != drawCalls)
{
SceneStatsToString(stringBuffer, drawCallText, lastDrawCalls, QualityLevelBudgetToColor(DrawCallsQualityLevelBudget, lastDrawCalls));
drawCalls = lastDrawCalls;
}
#if UNITY_EDITOR
long lastMeshStatsCount = displayTriangleCount ? UnityEditor.UnityStats.triangles : UnityEditor.UnityStats.vertices;
#else
long lastMeshStatsCount = meshStatsRecorder.LastValue;
#endif
if (lastMeshStatsCount != meshStatsCount)
{
if (WillDisplayedMeshStatsCountDiffer(lastMeshStatsCount, meshStatsCount, displayedDecimalDigits))
{
MeshStatsToString(stringBuffer, displayedDecimalDigits, meshText, lastMeshStatsCount, QualityLevelBudgetToColor(MeshStatsQualityLevelBudget, lastMeshStatsCount));
}
meshStatsCount = lastMeshStatsCount;
}
// Update memory statistics.
ulong limit = AppMemoryUsageLimit;
if (limit != limitMemoryUsage)
{
if (WillDisplayedMemoryUsageDiffer(limitMemoryUsage, limit, displayedDecimalDigits))
{
MemoryUsageToString(stringBuffer, displayedDecimalDigits, limitMemoryText, limit, Color.white);
}
limitMemoryUsage = limit;
}
ulong usage = AppMemoryUsage;
if (usage != memoryUsage)
{
Vector4 offsetScale = instanceUVOffsetScaleX[usedInstanceOffset];
offsetScale.z = -1.0f + (float)usage / limitMemoryUsage;
instanceUVOffsetScaleX[usedInstanceOffset] = offsetScale;
instanceUVOffsetScaleXDirty = true;
if (WillDisplayedMemoryUsageDiffer(memoryUsage, usage, displayedDecimalDigits))
{
MemoryUsageToString(stringBuffer, displayedDecimalDigits, usedMemoryText, usage, memoryUsedColor);
}
memoryUsage = usage;
}
if (memoryUsage > peakMemoryUsage || peakMemoryUsageDirty)
{
Vector4 offsetScale = instanceUVOffsetScaleX[peakInstanceOffset];