Assignment for RMIT Mixed Reality in 2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

943 lines
33 KiB

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