BlueGit

blue-star ggj-2020

Files

ggj-2020 / Assets / Oculus / VR / Editor / OVRLint.cs

OVRLint.cs

Project Import
timfa Tim Falken · pushed by timfa · 6 years ago
b77834a1 History
OVRLint.cs 32.9 KiB Download Raw
1/************************************************************************************
2Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved.
3
4Licensed under the Oculus Utilities SDK License Version 1.31 (the "License"); you may not use
5the Utilities SDK except in compliance with the License, which is provided at the time of installation
6or download, or which otherwise accompanies this software in either electronic or hard copy form.
7
8You may obtain a copy of the License at
9https://developer.oculus.com/licenses/utilities-1.31
10
11Unless required by applicable law or agreed to in writing, the Utilities SDK distributed
12under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
13ANY KIND, either express or implied. See the License for the specific language governing
14permissions and limitations under the License.
15************************************************************************************/
16
17#if UNITY_EDITOR
18
19using UnityEngine;
20using UnityEditor;
21using System.Collections.Generic;
22using Assets.OVR.Scripts;
23
24/// <summary>
25///Scans the project and warns about the following conditions:
26///Audio sources > 16
27///Using MSAA levels other than recommended level
28///Excessive pixel lights (>1 on Gear VR; >3 on Rift)
29///Directional Lightmapping Modes (on Gear; use Non-Directional)
30///Preload audio setting on individual audio clips
31///Decompressing audio clips on load
32///Disabling occlusion mesh
33///Android target API level set to 21 or higher
34///Unity skybox use (on by default, but if you can't see the skybox switching to Color is much faster on Gear)
35///Lights marked as "baked" but that were not included in the last bake (and are therefore realtime).
36///Lack of static batching and dynamic batching settings activated.
37///Full screen image effects (Gear)
38///Warn about large textures that are marked as uncompressed.
39///32-bit depth buffer (use 16)
40///Use of projectors (Gear; can be used carefully but slow enough to warrant a warning)
41///Maybe in the future once quantified: Graphics jobs and IL2CPP on Gear.
42///Real-time global illumination
43///No texture compression, or non-ASTC texture compression as a global setting (Gear).
44///Using deferred rendering
45///Excessive texture resolution after LOD bias (>2k on Gear VR; >4k on Rift)
46///Not using trilinear or aniso filtering and not generating mipmaps
47///Excessive render scale (>1.2)
48///Slow physics settings: Sleep Threshold < 0.005, Default Contact Offset < 0.01, Solver Iteration Count > 6
49///Shadows on when approaching the geometry or draw call limits
50///Non-static objects with colliders that are missing rigidbodies on themselves or in the parent chain.
51///No initialization of GPU/CPU throttling settings, or init to dangerous values (-1 or > 3) (Gear)
52///Using inefficient effects: SSAO, motion blur, global fog, parallax mapping, etc.
53///Too many Overlay layers
54///Use of Standard shader or Standard Specular shader on Gear. More generally, excessive use of multipass shaders (legacy specular, etc).
55///Multiple cameras with clears (on Gear, potential for excessive fill cost)
56///Excessive shader passes (>2)
57///Material pointers that have been instanced in the editor (esp. if we could determine that the instance has no deltas from the original)
58///Excessive draw calls (>150 on Gear VR; >2000 on Rift)
59///Excessive tris or verts (>100k on Gear VR; >1M on Rift)
60///Large textures, lots of prefabs in startup scene (for bootstrap optimization)
61///GPU skinning: testing Android-only, as most Rift devs are GPU-bound.
62/// </summary>
63[InitializeOnLoadAttribute]
64public class OVRLint : EditorWindow
65{
66 //TODO: The following require reflection or static analysis.
67 ///Use of ONSP reflections (Gear)
68 ///Use of LoadLevelAsync / LoadLevelAdditiveAsync (on Gear, this kills frame rate so dramatically it's probably better to just go to black and load synchronously)
69 ///Use of Linq in non-editor assemblies (common cause of GCs). Minor: use of foreach.
70 ///Use of Unity WWW (exceptionally high overhead for large file downloads, but acceptable for tiny gets).
71 ///Declared but empty Awake/Start/Update/OnCollisionEnter/OnCollisionExit/OnCollisionStay. Also OnCollision* star methods that declare the Collision argument but do not reference it (omitting it short-circuits the collision contact calculation).
72
73 private static List<FixRecord> mRecords = new List<FixRecord>();
74 private static List<FixRecord> mRuntimeEditModeRequiredRecords = new List<FixRecord>();
75#if !UNITY_2017_2_OR_NEWER
76 private static bool mWasPlaying = false;
77#endif
78 private Vector2 mScrollPosition;
79
80 [MenuItem("Oculus/Tools/OVR Performance Lint Tool")]
81 static void Init()
82 {
83 // Get existing open window or if none, make a new one:
84 EditorWindow.GetWindow(typeof(OVRLint));
85 OVRPlugin.SendEvent("perf_lint", "activated");
86 OVRLint.RunCheck();
87#if !UNITY_2017_2_OR_NEWER
88 mWasPlaying = EditorApplication.isPlaying;
89#endif
90 }
91
92 OVRLint()
93 {
94#if UNITY_2017_2_OR_NEWER
95 EditorApplication.playModeStateChanged += HandlePlayModeState;
96#else
97 EditorApplication.playmodeStateChanged += () =>
98 {
99 // When Unity starts playing, it would also trigger play mode changed event with isPlaying == false
100 // Fixes should only be applied when it was transitioned from playing mode
101 if (!EditorApplication.isPlaying && mWasPlaying)
102 {
103 ApplyEditModeRequiredFix();
104 mWasPlaying = false;
105 }
106 else
107 {
108 mWasPlaying = true;
109 }
110 };
111#endif
112 }
113
114#if UNITY_2017_2_OR_NEWER
115 private static void HandlePlayModeState(PlayModeStateChange state)
116 {
117 if (state == PlayModeStateChange.EnteredEditMode)
118 {
119 ApplyEditModeRequiredFix();
120 }
121 }
122#endif
123
124 private static void ApplyEditModeRequiredFix()
125 {
126 // Apply runtime fixes that require edit mode when applying fix
127 foreach (FixRecord record in mRuntimeEditModeRequiredRecords)
128 {
129 record.fixMethod(null, false, 0);
130 OVRPlugin.SendEvent("perf_lint_apply_fix", record.category);
131 record.complete = true;
132 }
133 mRuntimeEditModeRequiredRecords.Clear();
134 }
135
136 void OnGUI()
137 {
138 GUILayout.Label("OVR Performance Lint Tool", EditorStyles.boldLabel);
139 if (GUILayout.Button("Refresh", EditorStyles.toolbarButton, GUILayout.ExpandWidth(false)))
140 {
141 RunCheck();
142 }
143
144 string lastCategory = "";
145
146 mScrollPosition = EditorGUILayout.BeginScrollView(mScrollPosition);
147
148 for (int x = 0; x < mRecords.Count; x++)
149 {
150 FixRecord record = mRecords[x];
151
152 if (!record.category.Equals(lastCategory)) // new category
153 {
154 lastCategory = record.category;
155 EditorGUILayout.Separator();
156 EditorGUILayout.BeginHorizontal();
157 GUILayout.Label(lastCategory, EditorStyles.label, GUILayout.Width(200));
158 bool moreThanOne = (x + 1 < mRecords.Count && mRecords[x + 1].category.Equals(lastCategory));
159 if (record.buttonNames != null && record.buttonNames.Length > 0)
160 {
161 if (moreThanOne)
162 {
163 GUILayout.Label("Apply to all:", EditorStyles.label, GUILayout.Width(75));
164 for (int y = 0; y < record.buttonNames.Length; y++)
165 {
166 if (GUILayout.Button(record.buttonNames[y], EditorStyles.toolbarButton, GUILayout.Width(200)))
167 {
168 List<FixRecord> recordsToProcess = new List<FixRecord>();
169
170 for (int z = x; z < mRecords.Count; z++)
171 {
172 FixRecord thisRecord = mRecords[z];
173 bool isLast = false;
174 if (z + 1 >= mRecords.Count || !mRecords[z + 1].category.Equals(lastCategory))
175 {
176 isLast = true;
177 }
178
179 if (!thisRecord.complete)
180 {
181 recordsToProcess.Add(thisRecord);
182 }
183
184 if (isLast)
185 {
186 break;
187 }
188 }
189
190 UnityEngine.Object[] undoObjects = new UnityEngine.Object[recordsToProcess.Count];
191 for (int z = 0; z < recordsToProcess.Count; z++)
192 {
193 undoObjects[z] = recordsToProcess[z].targetObject;
194 }
195 Undo.RecordObjects(undoObjects, record.category + " (Multiple)");
196 for (int z = 0; z < recordsToProcess.Count; z++)
197 {
198 FixRecord thisRecord = recordsToProcess[z];
199 thisRecord.fixMethod(thisRecord.targetObject, (z + 1 == recordsToProcess.Count), y);
200 OVRPlugin.SendEvent("perf_lint_apply_fix", thisRecord.category);
201 thisRecord.complete = true;
202 }
203 }
204 }
205 }
206 }
207 EditorGUILayout.EndHorizontal();
208 if (moreThanOne || record.targetObject)
209 {
210 GUILayout.Label(record.message);
211 }
212 }
213
214 EditorGUILayout.BeginHorizontal();
215 GUI.enabled = !record.complete;
216 if (record.targetObject)
217 {
218 EditorGUILayout.ObjectField(record.targetObject, record.targetObject.GetType(), true);
219 }
220 else
221 {
222 GUILayout.Label(record.message);
223 }
224 if (record.buttonNames != null)
225 {
226 for (int y = 0; y < record.buttonNames.Length; y++)
227 {
228 if (GUILayout.Button(record.buttonNames[y], EditorStyles.toolbarButton, GUILayout.Width(200)))
229 {
230 if (record.targetObject != null)
231 {
232 Undo.RecordObject(record.targetObject, record.category);
233 }
234
235 if (record.editModeRequired)
236 {
237 // Add to the fix record list that requires edit mode
238 mRuntimeEditModeRequiredRecords.Add(record);
239 }
240 else
241 {
242 // Apply the fix directly
243 record.fixMethod(record.targetObject, true, y);
244 OVRPlugin.SendEvent("perf_lint_apply_fix", record.category);
245 record.complete = true;
246 }
247
248 if (mRuntimeEditModeRequiredRecords.Count != 0)
249 {
250 // Stop the scene to apply edit mode required records
251 EditorApplication.ExecuteMenuItem("Edit/Play");
252 }
253 }
254 }
255
256 }
257 GUI.enabled = true;
258 EditorGUILayout.EndHorizontal();
259 }
260
261 EditorGUILayout.EndScrollView();
262 }
263
264
265 public static int RunCheck()
266 {
267 mRecords.Clear();
268 mRuntimeEditModeRequiredRecords.Clear();
269
270 CheckStaticCommonIssues();
271#if UNITY_ANDROID
272 CheckStaticAndroidIssues();
273#endif
274
275 if (EditorApplication.isPlaying)
276 {
277 CheckRuntimeCommonIssues();
278#if UNITY_ANDROID
279 CheckRuntimeAndroidIssues();
280#endif
281 }
282
283 mRecords.Sort(delegate (FixRecord record1, FixRecord record2)
284 {
285 return record1.category.CompareTo(record2.category);
286 });
287 return mRecords.Count;
288 }
289
290 static void AddFix(string category, string message, FixMethodDelegate method, UnityEngine.Object target, bool editModeRequired, params string[] buttons)
291 {
292 OVRPlugin.SendEvent("perf_lint_add_fix", category);
293 mRecords.Add(new FixRecord(category, message, method, target, editModeRequired, buttons));
294 }
295
296 static void CheckStaticCommonIssues()
297 {
298 if (OVRManager.IsUnityAlphaOrBetaVersion())
299 {
300 AddFix("General", OVRManager.UnityAlphaOrBetaVersionWarningMessage, null, null, false);
301 }
302
303 if (QualitySettings.anisotropicFiltering != AnisotropicFiltering.Enable && QualitySettings.anisotropicFiltering != AnisotropicFiltering.ForceEnable)
304 {
305 AddFix("Optimize Aniso", "Anisotropic filtering is recommended for optimal image sharpness and GPU performance.", delegate (UnityEngine.Object obj, bool last, int selected)
306 {
307 // Ideally this would be multi-option: offer Enable or ForceEnable.
308 QualitySettings.anisotropicFiltering = AnisotropicFiltering.Enable;
309 }, null, false, "Fix");
310 }
311
312#if UNITY_ANDROID
313 int recommendedPixelLightCount = 1;
314#else
315 int recommendedPixelLightCount = 3;
316#endif
317
318 if (QualitySettings.pixelLightCount > recommendedPixelLightCount)
319 {
320 AddFix("Optimize Pixel Light Count", "For GPU performance set no more than " + recommendedPixelLightCount + " pixel lights in Quality Settings (currently " + QualitySettings.pixelLightCount + ").", delegate (UnityEngine.Object obj, bool last, int selected)
321 {
322 QualitySettings.pixelLightCount = recommendedPixelLightCount;
323 }, null, false, "Fix");
324 }
325
326#if false
327 // Should we recommend this? Seems to be mutually exclusive w/ dynamic batching.
328 if (!PlayerSettings.graphicsJobs)
329 {
330 AddFix ("Optimize Graphics Jobs", "For CPU performance, please use graphics jobs.", delegate(UnityEngine.Object obj, bool last, int selected)
331 {
332 PlayerSettings.graphicsJobs = true;
333 }, null, false, "Fix");
334 }
335#endif
336
337#if UNITY_2017_2_OR_NEWER
338 if ((!PlayerSettings.MTRendering || !PlayerSettings.GetMobileMTRendering(BuildTargetGroup.Android)))
339#else
340 if ((!PlayerSettings.MTRendering || !PlayerSettings.mobileMTRendering))
341#endif
342 {
343 AddFix("Optimize MT Rendering", "For CPU performance, please enable multithreaded rendering.", delegate (UnityEngine.Object obj, bool last, int selected)
344 {
345#if UNITY_2017_2_OR_NEWER
346 PlayerSettings.SetMobileMTRendering(BuildTargetGroup.Standalone, true);
347 PlayerSettings.SetMobileMTRendering(BuildTargetGroup.Android, true);
348#else
349 PlayerSettings.MTRendering = PlayerSettings.mobileMTRendering = true;
350#endif
351 }, null, false, "Fix");
352 }
353
354#if UNITY_ANDROID
355 if (!PlayerSettings.use32BitDisplayBuffer)
356 {
357 AddFix("Optimize Display Buffer Format", "We recommend to enable use32BitDisplayBuffer.", delegate (UnityEngine.Object obj, bool last, int selected)
358 {
359 PlayerSettings.use32BitDisplayBuffer = true;
360 }, null, false, "Fix");
361 }
362#endif
363
364#if UNITY_2017_3_OR_NEWER && !UNITY_ANDROID
365 if (!PlayerSettings.VROculus.dashSupport)
366 {
367 AddFix("Enable Dash Integration", "We recommend to enable Dash Integration for better user experience.", delegate (UnityEngine.Object obj, bool last, int selected)
368 {
369 PlayerSettings.VROculus.dashSupport = true;
370 }, null, false, "Fix");
371 }
372
373 if (!PlayerSettings.VROculus.sharedDepthBuffer)
374 {
375 AddFix("Enable Depth Buffer Sharing", "We recommend to enable Depth Buffer Sharing for better user experience on Oculus Dash.", delegate (UnityEngine.Object obj, bool last, int selected)
376 {
377 PlayerSettings.VROculus.sharedDepthBuffer = true;
378 }, null, false, "Fix");
379 }
380#endif
381
382 BuildTargetGroup target = EditorUserBuildSettings.selectedBuildTargetGroup;
383 var tier = UnityEngine.Rendering.GraphicsTier.Tier1;
384 var tierSettings = UnityEditor.Rendering.EditorGraphicsSettings.GetTierSettings(target, tier);
385
386 if ((tierSettings.renderingPath == RenderingPath.DeferredShading ||
387 tierSettings.renderingPath == RenderingPath.DeferredLighting))
388 {
389 AddFix("Optimize Rendering Path", "For CPU performance, please do not use deferred shading.", delegate (UnityEngine.Object obj, bool last, int selected)
390 {
391 tierSettings.renderingPath = RenderingPath.Forward;
392 UnityEditor.Rendering.EditorGraphicsSettings.SetTierSettings(target, tier, tierSettings);
393 }, null, false, "Use Forward");
394 }
395
396 if (PlayerSettings.stereoRenderingPath == StereoRenderingPath.MultiPass)
397 {
398 AddFix("Optimize Stereo Rendering", "For CPU performance, please enable single-pass or instanced stereo rendering.", delegate (UnityEngine.Object obj, bool last, int selected)
399 {
400 PlayerSettings.stereoRenderingPath = StereoRenderingPath.Instancing;
401 }, null, false, "Fix");
402 }
403
404 if (LightmapSettings.lightmaps.Length > 0 && LightmapSettings.lightmapsMode != LightmapsMode.NonDirectional)
405 {
406 AddFix("Optimize Lightmap Directionality", "Switching from directional lightmaps to non-directional lightmaps can save a small amount of GPU time.", delegate (UnityEngine.Object obj, bool last, int selected)
407 {
408 LightmapSettings.lightmapsMode = LightmapsMode.NonDirectional;
409 }, null, false, "Switch to non-directional lightmaps");
410 }
411
412 if (Lightmapping.realtimeGI)
413 {
414 AddFix("Disable Realtime GI", "Disabling real-time global illumination can improve GPU performance.", delegate (UnityEngine.Object obj, bool last, int selected)
415 {
416 Lightmapping.realtimeGI = false;
417 }, null, false, "Set Lightmapping.realtimeGI = false.");
418 }
419
420 var lights = GameObject.FindObjectsOfType<Light>();
421 for (int i = 0; i < lights.Length; ++i)
422 {
423#if UNITY_2017_3_OR_NEWER
424 if (lights [i].type != LightType.Directional && !lights [i].bakingOutput.isBaked && IsLightBaked(lights[i]))
425#else
426 if (lights[i].type != LightType.Directional && !lights[i].isBaked && IsLightBaked(lights[i]))
427#endif
428 {
429 AddFix("Unbaked Lights", "The following lights in the scene are marked as Baked, but they don't have up to date lightmap data. Generate the lightmap data, or set it to auto-generate, in Window->Lighting->Settings.", null, lights[i], false, null);
430 }
431
432 if (lights[i].shadows != LightShadows.None && !IsLightBaked(lights[i]))
433 {
434 AddFix("Optimize Shadows", "For CPU performance, consider disabling shadows on realtime lights.", delegate (UnityEngine.Object obj, bool last, int selected)
435 {
436 Light thisLight = (Light)obj;
437 thisLight.shadows = LightShadows.None;
438 }, lights[i], false, "Set \"Shadow Type\" to \"No Shadows\"");
439 }
440 }
441
442 var sources = GameObject.FindObjectsOfType<AudioSource>();
443 if (sources.Length > 16)
444 {
445 List<AudioSource> playingAudioSources = new List<AudioSource>();
446 foreach (var audioSource in sources)
447 {
448 if (audioSource.isPlaying)
449 {
450 playingAudioSources.Add(audioSource);
451 }
452 }
453
454 if (playingAudioSources.Count > 16)
455 {
456 // Sort playing audio sources by priority
457 playingAudioSources.Sort(delegate (AudioSource x, AudioSource y)
458 {
459 return x.priority.CompareTo(y.priority);
460 });
461 for (int i = 16; i < playingAudioSources.Count; ++i)
462 {
463 AddFix("Optimize Audio Source Count", "For CPU performance, please disable all but the top 16 AudioSources.", delegate (UnityEngine.Object obj, bool last, int selected)
464 {
465 AudioSource audioSource = (AudioSource)obj;
466 audioSource.enabled = false;
467 }, playingAudioSources[i], false, "Disable");
468 }
469 }
470 }
471
472 var clips = GameObject.FindObjectsOfType<AudioClip>();
473 for (int i = 0; i < clips.Length; ++i)
474 {
475 if (clips[i].loadType == AudioClipLoadType.DecompressOnLoad)
476 {
477 AddFix("Audio Loading", "For fast loading, please don't use decompress on load for audio clips", delegate (UnityEngine.Object obj, bool last, int selected)
478 {
479 AudioClip thisClip = (AudioClip)obj;
480 if (selected == 0)
481 {
482 SetAudioLoadType(thisClip, AudioClipLoadType.CompressedInMemory, last);
483 }
484 else
485 {
486 SetAudioLoadType(thisClip, AudioClipLoadType.Streaming, last);
487 }
488
489 }, clips[i], false, "Change to Compressed in Memory", "Change to Streaming");
490 }
491
492 if (clips[i].preloadAudioData)
493 {
494 AddFix("Audio Preload", "For fast loading, please don't preload data for audio clips.", delegate (UnityEngine.Object obj, bool last, int selected)
495 {
496 SetAudioPreload(clips[i], false, last);
497 }, clips[i], false, "Fix");
498 }
499 }
500
501 if (Physics.defaultContactOffset < 0.01f)
502 {
503 AddFix("Optimize Contact Offset", "For CPU performance, please don't use default contact offset below 0.01.", delegate (UnityEngine.Object obj, bool last, int selected)
504 {
505 Physics.defaultContactOffset = 0.01f;
506 }, null, false, "Fix");
507 }
508
509 if (Physics.sleepThreshold < 0.005f)
510 {
511 AddFix("Optimize Sleep Threshold", "For CPU performance, please don't use sleep threshold below 0.005.", delegate (UnityEngine.Object obj, bool last, int selected)
512 {
513 Physics.sleepThreshold = 0.005f;
514 }, null, false, "Fix");
515 }
516
517 if (Physics.defaultSolverIterations > 8)
518 {
519 AddFix("Optimize Solver Iterations", "For CPU performance, please don't use excessive solver iteration counts.", delegate (UnityEngine.Object obj, bool last, int selected)
520 {
521 Physics.defaultSolverIterations = 8;
522 }, null, false, "Fix");
523 }
524
525 var materials = Resources.FindObjectsOfTypeAll<Material>();
526 for (int i = 0; i < materials.Length; ++i)
527 {
528 if (materials[i].shader.name.Contains("Parallax") || materials[i].IsKeywordEnabled("_PARALLAXMAP"))
529 {
530 AddFix("Optimize Shading", "For GPU performance, please don't use parallax-mapped materials.", delegate (UnityEngine.Object obj, bool last, int selected)
531 {
532 Material thisMaterial = (Material)obj;
533 if (thisMaterial.IsKeywordEnabled("_PARALLAXMAP"))
534 {
535 thisMaterial.DisableKeyword("_PARALLAXMAP");
536 }
537
538 if (thisMaterial.shader.name.Contains("Parallax"))
539 {
540 var newName = thisMaterial.shader.name.Replace("-ParallaxSpec", "-BumpSpec");
541 newName = newName.Replace("-Parallax", "-Bump");
542 var newShader = Shader.Find(newName);
543 if (newShader)
544 {
545 thisMaterial.shader = newShader;
546 }
547 else
548 {
549 Debug.LogWarning("Unable to find a replacement for shader " + materials[i].shader.name);
550 }
551 }
552 }, materials[i], false, "Fix");
553 }
554 }
555
556 var renderers = GameObject.FindObjectsOfType<Renderer>();
557 for (int i = 0; i < renderers.Length; ++i)
558 {
559 if (renderers[i].sharedMaterial == null)
560 {
561 AddFix("Instanced Materials", "Please avoid instanced materials on renderers.", null, renderers[i], false);
562 }
563 }
564
565 var overlays = GameObject.FindObjectsOfType<OVROverlay>();
566 if (overlays.Length > 4)
567 {
568 AddFix("Optimize VR Layer Count", "For GPU performance, please use 4 or fewer VR layers.", delegate (UnityEngine.Object obj, bool last, int selected)
569 {
570 for (int i = 4; i < OVROverlay.instances.Length; ++i)
571 {
572 OVROverlay.instances[i].enabled = false;
573 }
574 }, null, false, "Fix");
575 }
576
577 var splashScreen = PlayerSettings.virtualRealitySplashScreen;
578 if (splashScreen != null)
579 {
580 if (splashScreen.filterMode != FilterMode.Trilinear)
581 {
582 AddFix("Optimize VR Splash Filtering", "For visual quality, please use trilinear filtering on your VR splash screen.", delegate (UnityEngine.Object obj, bool last, int EditorSelectedRenderState)
583 {
584 var assetPath = AssetDatabase.GetAssetPath(splashScreen);
585 var importer = (TextureImporter)TextureImporter.GetAtPath(assetPath);
586 importer.filterMode = FilterMode.Trilinear;
587 AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate);
588 }, null, false, "Fix");
589 }
590
591 if (splashScreen.mipmapCount <= 1)
592 {
593 AddFix("Generate VR Splash Mipmaps", "For visual quality, please use mipmaps with your VR splash screen.", delegate (UnityEngine.Object obj, bool last, int EditorSelectedRenderState)
594 {
595 var assetPath = AssetDatabase.GetAssetPath(splashScreen);
596 var importer = (TextureImporter)TextureImporter.GetAtPath(assetPath);
597 importer.mipmapEnabled = true;
598 AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate);
599 }, null, false, "Fix");
600 }
601 }
602 }
603
604 static void CheckRuntimeCommonIssues()
605 {
606 if (!OVRPlugin.occlusionMesh)
607 {
608 AddFix("Occlusion Mesh", "Enabling the occlusion mesh saves substantial GPU resources, generally with no visual impact. Enable unless you have an exceptional use case.", delegate (UnityEngine.Object obj, bool last, int selected)
609 {
610 OVRPlugin.occlusionMesh = true;
611 }, null, false, "Set OVRPlugin.occlusionMesh = true");
612 }
613
614 if (OVRManager.instance != null && !OVRManager.instance.useRecommendedMSAALevel)
615 {
616 AddFix("Optimize MSAA", "OVRManager can select the optimal antialiasing for the installed hardware at runtime. Recommend enabling this.", delegate (UnityEngine.Object obj, bool last, int selected)
617 {
618 var ovrManagers = GameObject.FindObjectsOfType<OVRManager>();
619 foreach (var ovrManager in ovrManagers)
620 {
621 ovrManager.useRecommendedMSAALevel = true;
622 }
623 }, null, true, "Stop Play and Fix");
624 }
625
626#if UNITY_2017_2_OR_NEWER
627 if (UnityEngine.XR.XRSettings.eyeTextureResolutionScale > 1.5)
628#else
629 if (UnityEngine.VR.VRSettings.renderScale > 1.5)
630#endif
631 {
632 AddFix("Optimize Render Scale", "Render scale above 1.5 is extremely expensive on the GPU, with little if any positive visual benefit.", delegate (UnityEngine.Object obj, bool last, int selected)
633 {
634#if UNITY_2017_2_OR_NEWER
635 UnityEngine.XR.XRSettings.eyeTextureResolutionScale = 1.5f;
636#else
637 UnityEngine.VR.VRSettings.renderScale = 1.5f;
638#endif
639 }, null, false, "Fix");
640 }
641 }
642
643 static void CheckStaticAndroidIssues()
644 {
645 // Check that the minSDKVersion meets requirement, 21 for Gear and Go, 23 for Quest
646 AndroidSdkVersions recommendedAndroidMinSdkVersion = AndroidSdkVersions.AndroidApiLevel21;
647 if (OVRDeviceSelector.isTargetDeviceQuest)
648 {
649 recommendedAndroidMinSdkVersion = AndroidSdkVersions.AndroidApiLevel23;
650 }
651 if ((int)PlayerSettings.Android.minSdkVersion < (int)recommendedAndroidMinSdkVersion)
652 {
653 AddFix("Set Min Android API Level", "Please require at least API level " + (int)recommendedAndroidMinSdkVersion, delegate (UnityEngine.Object obj, bool last, int selected)
654 {
655 PlayerSettings.Android.minSdkVersion = recommendedAndroidMinSdkVersion;
656 }, null, false, "Fix");
657 }
658
659 // Check that compileSDKVersion meets minimal version 26 as required for Quest's headtracking feature
660 // Unity Sets compileSDKVersion in Gradle as the value used in targetSdkVersion
661 AndroidSdkVersions requiredAndroidTargetSdkVersion = AndroidSdkVersions.AndroidApiLevel26;
662 if (OVRDeviceSelector.isTargetDeviceQuest &&
663 (int)PlayerSettings.Android.targetSdkVersion < (int)requiredAndroidTargetSdkVersion)
664 {
665 AddFix("Set Android Target SDK Level", "Oculus Quest apps require at least target API level " +
666 (int)requiredAndroidTargetSdkVersion, delegate (UnityEngine.Object obj, bool last, int selected)
667 {
668 PlayerSettings.Android.targetSdkVersion = requiredAndroidTargetSdkVersion;
669 }, null, false, "Fix");
670 }
671
672 if (!PlayerSettings.gpuSkinning)
673 {
674 AddFix("Optimize GPU Skinning", "If you are CPU-bound, consider using GPU skinning.",
675 delegate (UnityEngine.Object obj, bool last, int selected)
676 {
677 PlayerSettings.gpuSkinning = true;
678 }, null, false, "Fix");
679 }
680
681
682 if (RenderSettings.skybox)
683 {
684 AddFix("Optimize Clearing", "For GPU performance, please don't use Unity's built-in Skybox.", delegate (UnityEngine.Object obj, bool last, int selected)
685 {
686 RenderSettings.skybox = null;
687 }, null, false, "Clear Skybox");
688 }
689
690 var materials = Resources.FindObjectsOfTypeAll<Material>();
691 for (int i = 0; i < materials.Length; ++i)
692 {
693 if (materials[i].IsKeywordEnabled("_SPECGLOSSMAP") || materials[i].IsKeywordEnabled("_METALLICGLOSSMAP"))
694 {
695 AddFix("Optimize Specular Material", "For GPU performance, please don't use specular shader on materials.", delegate (UnityEngine.Object obj, bool last, int selected)
696 {
697 Material thisMaterial = (Material)obj;
698 thisMaterial.DisableKeyword("_SPECGLOSSMAP");
699 thisMaterial.DisableKeyword("_METALLICGLOSSMAP");
700 }, materials[i], false, "Fix");
701 }
702
703 if (materials[i].passCount > 1)
704 {
705 AddFix("Material Passes", "Please use 2 or fewer passes in materials.", null, materials[i], false);
706 }
707 }
708
709 ScriptingImplementation backend = PlayerSettings.GetScriptingBackend(UnityEditor.BuildTargetGroup.Android);
710 if (backend != UnityEditor.ScriptingImplementation.IL2CPP)
711 {
712 AddFix("Optimize Scripting Backend", "For CPU performance, please use IL2CPP.", delegate (UnityEngine.Object obj, bool last, int selected)
713 {
714 PlayerSettings.SetScriptingBackend(UnityEditor.BuildTargetGroup.Android, UnityEditor.ScriptingImplementation.IL2CPP);
715 }, null, false, "Fix");
716 }
717
718 var monoBehaviours = GameObject.FindObjectsOfType<MonoBehaviour>();
719 System.Type effectBaseType = System.Type.GetType("UnityStandardAssets.ImageEffects.PostEffectsBase");
720 if (effectBaseType != null)
721 {
722 for (int i = 0; i < monoBehaviours.Length; ++i)
723 {
724 if (monoBehaviours[i].GetType().IsSubclassOf(effectBaseType))
725 {
726 AddFix("Image Effects", "Please don't use image effects.", null, monoBehaviours[i], false);
727 }
728 }
729 }
730
731 var textures = Resources.FindObjectsOfTypeAll<Texture2D>();
732
733 int maxTextureSize = 1024 * (1 << QualitySettings.masterTextureLimit);
734 maxTextureSize = maxTextureSize * maxTextureSize;
735
736 for (int i = 0; i < textures.Length; ++i)
737 {
738 if (textures[i].filterMode == FilterMode.Trilinear && textures[i].mipmapCount == 1)
739 {
740 AddFix("Optimize Texture Filtering", "For GPU performance, please generate mipmaps or disable trilinear filtering for textures.", delegate (UnityEngine.Object obj, bool last, int selected)
741 {
742 Texture2D thisTexture = (Texture2D)obj;
743 if (selected == 0)
744 {
745 thisTexture.filterMode = FilterMode.Bilinear;
746 }
747 else
748 {
749 SetTextureUseMips(thisTexture, true, last);
750 }
751 }, textures[i], false, "Switch to Bilinear", "Generate Mipmaps");
752 }
753 }
754
755 var projectors = GameObject.FindObjectsOfType<Projector>();
756 if (projectors.Length > 0)
757 {
758 AddFix("Optimize Projectors", "For GPU performance, please don't use projectors.", delegate (UnityEngine.Object obj, bool last, int selected)
759 {
760 Projector[] thisProjectors = GameObject.FindObjectsOfType<Projector>();
761 for (int i = 0; i < thisProjectors.Length; ++i)
762 {
763 thisProjectors[i].enabled = false;
764 }
765 }, null, false, "Disable Projectors");
766 }
767
768 if (EditorUserBuildSettings.androidBuildSubtarget != MobileTextureSubtarget.ASTC)
769 {
770 AddFix("Optimize Texture Compression", "For GPU performance, please use ASTC.", delegate (UnityEngine.Object obj, bool last, int selected)
771 {
772 EditorUserBuildSettings.androidBuildSubtarget = MobileTextureSubtarget.ASTC;
773 }, null, false, "Fix");
774 }
775
776 var cameras = GameObject.FindObjectsOfType<Camera>();
777 int clearCount = 0;
778 for (int i = 0; i < cameras.Length; ++i)
779 {
780 if (cameras[i].clearFlags != CameraClearFlags.Nothing && cameras[i].clearFlags != CameraClearFlags.Depth)
781 ++clearCount;
782 }
783
784 if (clearCount > 2)
785 {
786 AddFix("Camera Clears", "Please use 2 or fewer clears.", null, null, false);
787 }
788
789 for (int i = 0; i < cameras.Length; ++i)
790 {
791 if (cameras[i].forceIntoRenderTexture)
792 {
793 AddFix("Optimize Mobile Rendering", "For GPU performance, please don't enable forceIntoRenderTexture on your camera, this might be a flag pollution created by post process stack you used before, \nif your post process had already been turned off, we strongly encourage you to disable forceIntoRenderTexture. If you still want to use post process for some reasons, \nyou can leave this one on, but be warned, enabling this flag will introduce huge GPU performance cost. To view your flag status, please turn on you inspector's debug mode",
794 delegate (UnityEngine.Object obj, bool last, int selected)
795 {
796 Camera thisCamera = (Camera)obj;
797 thisCamera.forceIntoRenderTexture = false;
798 }, cameras[i], false, "Disable forceIntoRenderTexture");
799 }
800 }
801 }
802
803 static void CheckRuntimeAndroidIssues()
804 {
805 if (UnityStats.usedTextureMemorySize + UnityStats.vboTotalBytes > 1000000)
806 {
807 AddFix("Graphics Memory", "Please use less than 1GB of vertex and texture memory.", null, null, false);
808 }
809
810 if (OVRManager.cpuLevel < 0 || OVRManager.cpuLevel > 3)
811 {
812 AddFix("Optimize CPU level", "For battery life, please use a safe CPU level.", delegate (UnityEngine.Object obj, bool last, int selected)
813 {
814 OVRManager.cpuLevel = 2;
815 }, null, false, "Set to CPU2");
816 }
817
818 if (OVRManager.gpuLevel < 0 || OVRManager.gpuLevel > 3)
819 {
820 AddFix("Optimize GPU level", "For battery life, please use a safe GPU level.", delegate (UnityEngine.Object obj, bool last, int selected)
821 {
822 OVRManager.gpuLevel = 2;
823 }, null, false, "Set to GPU2");
824 }
825
826 if (UnityStats.triangles > 100000 || UnityStats.vertices > 100000)
827 {
828 AddFix("Triangles and Verts", "Please use less than 100000 triangles or vertices.", null, null, false);
829 }
830
831 // Warn for 50 if in non-VR mode?
832 if (UnityStats.drawCalls > 100)
833 {
834 AddFix("Draw Calls", "Please use less than 100 draw calls.", null, null, false);
835 }
836 }
837
838
839 enum LightmapType { Realtime = 4, Baked = 2, Mixed = 1 };
840
841 static bool IsLightBaked(Light light)
842 {
843 return light.lightmapBakeType == LightmapBakeType.Baked;
844 }
845
846 static void SetAudioPreload(AudioClip clip, bool preload, bool refreshImmediately)
847 {
848 if (clip != null)
849 {
850 string assetPath = AssetDatabase.GetAssetPath(clip);
851 AudioImporter importer = AssetImporter.GetAtPath(assetPath) as AudioImporter;
852 if (importer != null)
853 {
854 if (preload != importer.preloadAudioData)
855 {
856 importer.preloadAudioData = preload;
857
858 AssetDatabase.ImportAsset(assetPath);
859 if (refreshImmediately)
860 {
861 AssetDatabase.Refresh();
862 }
863 }
864 }
865 }
866 }
867
868 static void SetAudioLoadType(AudioClip clip, AudioClipLoadType loadType, bool refreshImmediately)
869 {
870 if (clip != null)
871 {
872 string assetPath = AssetDatabase.GetAssetPath(clip);
873 AudioImporter importer = AssetImporter.GetAtPath(assetPath) as AudioImporter;
874 if (importer != null)
875 {
876 if (loadType != importer.defaultSampleSettings.loadType)
877 {
878 AudioImporterSampleSettings settings = importer.defaultSampleSettings;
879 settings.loadType = loadType;
880 importer.defaultSampleSettings = settings;
881
882 AssetDatabase.ImportAsset(assetPath);
883 if (refreshImmediately)
884 {
885 AssetDatabase.Refresh();
886 }
887 }
888 }
889 }
890 }
891
892 public static void SetTextureUseMips(Texture texture, bool useMips, bool refreshImmediately)
893 {
894 if (texture != null)
895 {
896 string assetPath = AssetDatabase.GetAssetPath(texture);
897 TextureImporter tImporter = AssetImporter.GetAtPath(assetPath) as TextureImporter;
898 if (tImporter != null && tImporter.mipmapEnabled != useMips)
899 {
900 tImporter.mipmapEnabled = useMips;
901
902 AssetDatabase.ImportAsset(assetPath);
903 if (refreshImmediately)
904 {
905 AssetDatabase.Refresh();
906 }
907 }
908 }
909 }
910
911 static T FindComponentInParents<T>(GameObject obj) where T : Component
912 {
913 T component = null;
914 if (obj != null)
915 {
916 Transform parent = obj.transform.parent;
917 if (parent != null)
918 {
919 do
920 {
921 component = parent.GetComponent(typeof(T)) as T;
922 parent = parent.parent;
923 } while (parent != null && component == null);
924 }
925 }
926 return component;
927 }
928}
929
930#endif