No Description
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.

VolumeManager.cs 37KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.Diagnostics;
  5. using System.Linq;
  6. using System.Reflection;
  7. using Unity.Profiling;
  8. using UnityEngine.Assertions;
  9. #if UNITY_EDITOR
  10. using UnityEditor;
  11. using UnityEditor.Rendering;
  12. #endif
  13. namespace UnityEngine.Rendering
  14. {
  15. /// <summary>
  16. /// A global manager that tracks all the Volumes in the currently loaded Scenes and does all the
  17. /// interpolation work.
  18. /// </summary>
  19. public sealed class VolumeManager
  20. {
  21. static readonly ProfilerMarker k_ProfilerMarkerUpdate = new ("VolumeManager.Update");
  22. static readonly ProfilerMarker k_ProfilerMarkerReplaceData = new ("VolumeManager.ReplaceData");
  23. static readonly ProfilerMarker k_ProfilerMarkerEvaluateVolumeDefaultState = new ("VolumeManager.EvaluateVolumeDefaultState");
  24. static readonly Lazy<VolumeManager> s_Instance = new Lazy<VolumeManager>(() => new VolumeManager());
  25. /// <summary>
  26. /// The current singleton instance of <see cref="VolumeManager"/>.
  27. /// </summary>
  28. public static VolumeManager instance => s_Instance.Value;
  29. /// <summary>
  30. /// A reference to the main <see cref="VolumeStack"/>.
  31. /// </summary>
  32. /// <seealso cref="VolumeStack"/>
  33. public VolumeStack stack { get; set; }
  34. /// <summary>
  35. /// The current list of all available types that derive from <see cref="VolumeComponent"/>.
  36. /// </summary>
  37. [Obsolete("Please use baseComponentTypeArray instead.")]
  38. public IEnumerable<Type> baseComponentTypes => baseComponentTypeArray;
  39. static readonly Dictionary<Type, List<(string, Type)>> s_SupportedVolumeComponentsForRenderPipeline = new();
  40. internal List<(string, Type)> GetVolumeComponentsForDisplay(Type currentPipelineAssetType)
  41. {
  42. if (currentPipelineAssetType == null)
  43. return new List<(string, Type)>();
  44. if (!currentPipelineAssetType.IsSubclassOf(typeof(RenderPipelineAsset)))
  45. throw new ArgumentException(nameof(currentPipelineAssetType));
  46. if (s_SupportedVolumeComponentsForRenderPipeline.TryGetValue(currentPipelineAssetType, out var supportedVolumeComponents))
  47. return supportedVolumeComponents;
  48. if (baseComponentTypeArray == null)
  49. LoadBaseTypes(currentPipelineAssetType);
  50. supportedVolumeComponents = BuildVolumeComponentDisplayList(baseComponentTypeArray);
  51. s_SupportedVolumeComponentsForRenderPipeline[currentPipelineAssetType] = supportedVolumeComponents;
  52. return supportedVolumeComponents;
  53. }
  54. List<(string, Type)> BuildVolumeComponentDisplayList(Type[] types)
  55. {
  56. if (types == null)
  57. throw new ArgumentNullException(nameof(types));
  58. var volumes = new List<(string, Type)>();
  59. foreach (var t in types)
  60. {
  61. string path = string.Empty;
  62. bool skipComponent = false;
  63. // Look for the attributes of this volume component and decide how is added and if it needs to be skipped
  64. var attrs = t.GetCustomAttributes(false);
  65. foreach (var attr in attrs)
  66. {
  67. switch (attr)
  68. {
  69. case VolumeComponentMenu attrMenu:
  70. {
  71. path = attrMenu.menu;
  72. break;
  73. }
  74. case HideInInspector:
  75. case ObsoleteAttribute:
  76. skipComponent = true;
  77. break;
  78. }
  79. }
  80. if (skipComponent)
  81. continue;
  82. // If no attribute or in case something went wrong when grabbing it, fallback to a
  83. // beautified class name
  84. if (string.IsNullOrEmpty(path))
  85. {
  86. #if UNITY_EDITOR
  87. path = ObjectNames.NicifyVariableName(t.Name);
  88. #else
  89. path = t.Name;
  90. #endif
  91. }
  92. volumes.Add((path, t));
  93. }
  94. return volumes
  95. .OrderBy(i => i.Item1)
  96. .ToList();
  97. }
  98. /// <summary>
  99. /// The current list of all available types that derive from <see cref="VolumeComponent"/>.
  100. /// </summary>
  101. public Type[] baseComponentTypeArray { get; internal set; } // internal only for tests
  102. /// <summary>
  103. /// Global default profile that provides default values for volume components. VolumeManager applies
  104. /// this profile to its internal component default state first, before <see cref="qualityDefaultProfile"/>
  105. /// and <see cref="customDefaultProfiles"/>.
  106. /// </summary>
  107. public VolumeProfile globalDefaultProfile { get; private set; }
  108. /// <summary>
  109. /// Quality level specific volume profile that is applied to the default state after
  110. /// <see cref="globalDefaultProfile"/> and before <see cref="customDefaultProfiles"/>.
  111. /// </summary>
  112. public VolumeProfile qualityDefaultProfile { get; private set; }
  113. /// <summary>
  114. /// Collection of additional default profiles that can be used to override default values for volume components
  115. /// in a way that doesn't cause any overhead at runtime. Unity applies these Volume Profiles to its internal
  116. /// component default state after <see cref="globalDefaultProfile"/> and <see cref="qualityDefaultProfile"/>.
  117. /// The custom profiles are applied in the order that they appear in the collection.
  118. /// </summary>
  119. public ReadOnlyCollection<VolumeProfile> customDefaultProfiles { get; private set; }
  120. // Max amount of layers available in Unity
  121. const int k_MaxLayerCount = 32;
  122. // Cached lists of all volumes (sorted by priority) by layer mask
  123. readonly Dictionary<int, List<Volume>> m_SortedVolumes = new();
  124. // Holds all the registered volumes
  125. readonly List<Volume> m_Volumes = new();
  126. // Keep track of sorting states for layer masks
  127. readonly Dictionary<int, bool> m_SortNeeded = new();
  128. // Internal list of default state for each component type - this is used to reset component
  129. // states on update instead of having to implement a Reset method on all components (which
  130. // would be error-prone)
  131. // The "Default State" is evaluated as follows:
  132. // Default-constructed VolumeComponents (VolumeParameter values coming from code)
  133. // + Values from globalDefaultProfile
  134. // + Values from qualityDefaultProfile
  135. // + Values from customDefaultProfiles
  136. // = Default State.
  137. VolumeComponent[] m_ComponentsDefaultState;
  138. // Flat list of every volume parameter in default state for faster per-frame stack reset.
  139. internal VolumeParameter[] m_ParametersDefaultState;
  140. /// <summary>
  141. /// Retrieve the default state for a given VolumeComponent type. Default state is defined as
  142. /// "default-constructed VolumeComponent + Default Profiles evaluated in order".
  143. /// </summary>
  144. /// <remarks>
  145. /// If you want just the VolumeComponent with default-constructed values without overrides from
  146. /// Default Profiles, use <see cref="ScriptableObject.CreateInstance(Type)"/>.
  147. /// </remarks>
  148. /// <param name="volumeComponentType">Type of VolumeComponent</param>
  149. /// <returns>VolumeComponent in default state, or null if the type is not found</returns>
  150. public VolumeComponent GetVolumeComponentDefaultState(Type volumeComponentType)
  151. {
  152. if (!typeof(VolumeComponent).IsAssignableFrom(volumeComponentType))
  153. return null;
  154. foreach (VolumeComponent component in m_ComponentsDefaultState)
  155. {
  156. if (component.GetType() == volumeComponentType)
  157. return component;
  158. }
  159. return null;
  160. }
  161. // Recycled list used for volume traversal
  162. readonly List<Collider> m_TempColliders = new(8);
  163. // The default stack the volume manager uses.
  164. // We cache this as users able to change the stack through code and
  165. // we want to be able to switch to the default one through the ResetMainStack() function.
  166. VolumeStack m_DefaultStack;
  167. // List of stacks created through VolumeManager.
  168. readonly List<VolumeStack> m_CreatedVolumeStacks = new();
  169. // Internal for tests
  170. internal VolumeManager()
  171. {
  172. }
  173. // Note: The "isInitialized" state and explicit Initialize/Deinitialize are only required because VolumeManger
  174. // is a singleton whose lifetime exceeds that of RenderPipelines. Thus it must be initialized & deinitialized
  175. // explicitly by the RP to handle pipeline switch gracefully. It would be better to get rid of singletons and
  176. // have the RP own the class instance instead.
  177. /// <summary>
  178. /// Returns whether <see cref="VolumeManager.Initialize(VolumeProfile,VolumeProfile)"/> has been called, and the
  179. /// class is in valid state. It is not valid to use VolumeManager before this returns true.
  180. /// </summary>
  181. public bool isInitialized { get; private set; }
  182. /// <summary>
  183. /// Initialize VolumeManager with specified global and quality default volume profiles that are used to evaluate
  184. /// the default state of all VolumeComponents. Should be called from <see cref="RenderPipeline"/> constructor.
  185. /// </summary>
  186. /// <param name="globalDefaultVolumeProfile">Global default volume profile.</param>
  187. /// <param name="qualityDefaultVolumeProfile">Quality default volume profile.</param>
  188. public void Initialize(VolumeProfile globalDefaultVolumeProfile = null, VolumeProfile qualityDefaultVolumeProfile = null)
  189. {
  190. Debug.Assert(!isInitialized);
  191. Debug.Assert(m_CreatedVolumeStacks.Count == 0);
  192. LoadBaseTypes(GraphicsSettings.currentRenderPipelineAssetType);
  193. InitializeVolumeComponents();
  194. globalDefaultProfile = globalDefaultVolumeProfile;
  195. qualityDefaultProfile = qualityDefaultVolumeProfile;
  196. EvaluateVolumeDefaultState();
  197. m_DefaultStack = CreateStack();
  198. stack = m_DefaultStack;
  199. isInitialized = true;
  200. }
  201. /// <summary>
  202. /// Deinitialize VolumeManager. Should be called from <see cref="RenderPipeline.Dispose()"/>.
  203. /// </summary>
  204. public void Deinitialize()
  205. {
  206. Debug.Assert(isInitialized);
  207. DestroyStack(m_DefaultStack);
  208. m_DefaultStack = null;
  209. foreach (var s in m_CreatedVolumeStacks)
  210. s.Dispose();
  211. m_CreatedVolumeStacks.Clear();
  212. baseComponentTypeArray = null;
  213. globalDefaultProfile = null;
  214. qualityDefaultProfile = null;
  215. customDefaultProfiles = null;
  216. isInitialized = false;
  217. }
  218. /// <summary>
  219. /// Assign the given VolumeProfile as the global default profile and update the default component state.
  220. /// </summary>
  221. /// <param name="profile">The VolumeProfile to use as the global default profile.</param>
  222. public void SetGlobalDefaultProfile(VolumeProfile profile)
  223. {
  224. globalDefaultProfile = profile;
  225. EvaluateVolumeDefaultState();
  226. }
  227. /// <summary>
  228. /// Assign the given VolumeProfile as the quality default profile and update the default component state.
  229. /// </summary>
  230. /// <param name="profile">The VolumeProfile to use as the quality level default profile.</param>
  231. public void SetQualityDefaultProfile(VolumeProfile profile)
  232. {
  233. qualityDefaultProfile = profile;
  234. EvaluateVolumeDefaultState();
  235. }
  236. /// <summary>
  237. /// Assign the given VolumeProfiles as custom default profiles and update the default component state.
  238. /// </summary>
  239. /// <param name="profiles">List of VolumeProfiles to set as default profiles, or null to clear them.</param>
  240. public void SetCustomDefaultProfiles(List<VolumeProfile> profiles)
  241. {
  242. var validProfiles = profiles ?? new List<VolumeProfile>();
  243. validProfiles.RemoveAll(x => x == null);
  244. customDefaultProfiles = new ReadOnlyCollection<VolumeProfile>(validProfiles);
  245. EvaluateVolumeDefaultState();
  246. }
  247. /// <summary>
  248. /// Call when a VolumeProfile is modified to trigger default state update if necessary.
  249. /// </summary>
  250. /// <param name="profile">VolumeProfile that has changed.</param>
  251. public void OnVolumeProfileChanged(VolumeProfile profile)
  252. {
  253. if (!isInitialized)
  254. return;
  255. if (globalDefaultProfile == profile ||
  256. qualityDefaultProfile == profile ||
  257. (customDefaultProfiles != null && customDefaultProfiles.Contains(profile)))
  258. EvaluateVolumeDefaultState();
  259. }
  260. /// <summary>
  261. /// Call when a VolumeComponent is modified to trigger default state update if necessary.
  262. /// </summary>
  263. /// <param name="component">VolumeComponent that has changed.</param>
  264. public void OnVolumeComponentChanged(VolumeComponent component)
  265. {
  266. var defaultProfiles = new List<VolumeProfile> { globalDefaultProfile, globalDefaultProfile };
  267. if (customDefaultProfiles != null)
  268. defaultProfiles.AddRange(customDefaultProfiles);
  269. foreach (var defaultProfile in defaultProfiles)
  270. {
  271. if (defaultProfile.components.Contains(component))
  272. {
  273. EvaluateVolumeDefaultState();
  274. return;
  275. }
  276. }
  277. }
  278. /// <summary>
  279. /// Creates and returns a new <see cref="VolumeStack"/> to use when you need to store
  280. /// the result of the Volume blending pass in a separate stack.
  281. /// </summary>
  282. /// <returns>A new <see cref="VolumeStack"/> instance with freshly loaded components.</returns>
  283. /// <seealso cref="VolumeStack"/>
  284. /// <seealso cref="Update(VolumeStack,Transform,LayerMask)"/>
  285. public VolumeStack CreateStack()
  286. {
  287. var stack = new VolumeStack();
  288. stack.Reload(baseComponentTypeArray);
  289. m_CreatedVolumeStacks.Add(stack);
  290. return stack;
  291. }
  292. /// <summary>
  293. /// Resets the main stack to be the default one.
  294. /// Call this function if you've assigned the main stack to something other than the default one.
  295. /// </summary>
  296. public void ResetMainStack()
  297. {
  298. stack = m_DefaultStack;
  299. }
  300. /// <summary>
  301. /// Destroy a Volume Stack
  302. /// </summary>
  303. /// <param name="stack">Volume Stack that needs to be destroyed.</param>
  304. public void DestroyStack(VolumeStack stack)
  305. {
  306. m_CreatedVolumeStacks.Remove(stack);
  307. stack.Dispose();
  308. }
  309. // For now, if a user is having a VolumeComponent with the old attribute for filtering support.
  310. // We are adding it to the supported volume components, but we are showing a warning.
  311. bool IsSupportedByObsoleteVolumeComponentMenuForRenderPipeline(Type t, Type pipelineAssetType)
  312. {
  313. var legacySupported = false;
  314. #pragma warning disable CS0618
  315. var legacyPipelineAttribute = t.GetCustomAttribute<VolumeComponentMenuForRenderPipeline>();
  316. if (legacyPipelineAttribute != null)
  317. {
  318. Debug.LogWarning($"{nameof(VolumeComponentMenuForRenderPipeline)} is deprecated, use {nameof(SupportedOnRenderPipelineAttribute)} and {nameof(VolumeComponentMenu)} with {t} instead. #from(2023.1)");
  319. #if UNITY_EDITOR
  320. var renderPipelineTypeFromAsset = RenderPipelineEditorUtility.GetPipelineTypeFromPipelineAssetType(pipelineAssetType);
  321. for (int i = 0; i < legacyPipelineAttribute.pipelineTypes.Length; ++i)
  322. {
  323. if (legacyPipelineAttribute.pipelineTypes[i] == renderPipelineTypeFromAsset)
  324. {
  325. legacySupported = true;
  326. break;
  327. }
  328. }
  329. #endif
  330. }
  331. #pragma warning restore CS0618
  332. return legacySupported;
  333. }
  334. // This will be called only once at runtime and on domain reload / pipeline switch in the editor
  335. // as we need to keep track of any compatible component in the project
  336. internal void LoadBaseTypes(Type pipelineAssetType)
  337. {
  338. // Grab all the component types we can find that are compatible with current pipeline
  339. using (ListPool<Type>.Get(out var list))
  340. {
  341. foreach (var t in CoreUtils.GetAllTypesDerivedFrom<VolumeComponent>())
  342. {
  343. if (t.IsAbstract)
  344. continue;
  345. var isSupported = SupportedOnRenderPipelineAttribute.IsTypeSupportedOnRenderPipeline(t, pipelineAssetType) ||
  346. IsSupportedByObsoleteVolumeComponentMenuForRenderPipeline(t, pipelineAssetType);
  347. if (isSupported)
  348. list.Add(t);
  349. }
  350. baseComponentTypeArray = list.ToArray();
  351. }
  352. }
  353. internal void InitializeVolumeComponents()
  354. {
  355. // Call custom static Init method if present
  356. var flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
  357. foreach (var type in baseComponentTypeArray)
  358. {
  359. var initMethod = type.GetMethod("Init", flags);
  360. if (initMethod != null)
  361. {
  362. initMethod.Invoke(null, null);
  363. }
  364. }
  365. }
  366. // Evaluate static default values for VolumeComponents, which is the baseline to reset the values to at the start of Update.
  367. internal void EvaluateVolumeDefaultState()
  368. {
  369. if (baseComponentTypeArray == null || baseComponentTypeArray.Length == 0)
  370. return;
  371. using var profilerScope = k_ProfilerMarkerEvaluateVolumeDefaultState.Auto();
  372. // TODO consider if the "component default values" array should be kept in memory separately. Creating the
  373. // instances is likely the slowest operation here, so doing that would mean it can only be done once in
  374. // Initialize() and the default state can be updated a lot quicker.
  375. // First, default-construct all VolumeComponents
  376. List<VolumeComponent> componentsDefaultStateList = new();
  377. foreach (var type in baseComponentTypeArray)
  378. {
  379. componentsDefaultStateList.Add((VolumeComponent) ScriptableObject.CreateInstance(type));
  380. }
  381. void ApplyDefaultProfile(VolumeProfile profile)
  382. {
  383. if (profile == null)
  384. return;
  385. for (int i = 0; i < profile.components.Count; i++)
  386. {
  387. var profileComponent = profile.components[i];
  388. var defaultStateComponent = componentsDefaultStateList.FirstOrDefault(
  389. x => x.GetType() == profileComponent.GetType());
  390. if (defaultStateComponent != null && profileComponent.active)
  391. {
  392. // Ideally we would just call SetValue here. However, there are custom non-trivial
  393. // implementations of VolumeParameter.Interp() (such as DiffusionProfileList) that make it
  394. // necessary for us to call the it. This ensures the new DefaultProfile behavior works
  395. // consistently with the old HDRP implementation where the Default Profile was implemented as
  396. // a regular global volume inside the scene.
  397. profileComponent.Override(defaultStateComponent, 1.0f);
  398. }
  399. }
  400. }
  401. ApplyDefaultProfile(globalDefaultProfile); // Apply global default profile first
  402. ApplyDefaultProfile(qualityDefaultProfile); // Apply quality default profile second
  403. if (customDefaultProfiles != null) // Finally, apply custom default profiles in order
  404. foreach (var profile in customDefaultProfiles)
  405. ApplyDefaultProfile(profile);
  406. // Build the flat parametersDefaultState list for fast per-frame resets
  407. var parametersDefaultStateList = new List<VolumeParameter>();
  408. foreach (var component in componentsDefaultStateList)
  409. {
  410. parametersDefaultStateList.AddRange(component.parameters);
  411. }
  412. m_ComponentsDefaultState = componentsDefaultStateList.ToArray();
  413. m_ParametersDefaultState = parametersDefaultStateList.ToArray();
  414. // All properties in stacks must be reset because the default state has changed
  415. foreach (var s in m_CreatedVolumeStacks)
  416. {
  417. s.requiresReset = true;
  418. s.requiresResetForAllProperties = true;
  419. }
  420. }
  421. /// <summary>
  422. /// Registers a new Volume in the manager. Unity does this automatically when a new Volume is
  423. /// enabled, or its layer changes, but you can use this function to force-register a Volume
  424. /// that is currently disabled.
  425. /// </summary>
  426. /// <param name="volume">The volume to register.</param>
  427. /// <param name="layer">The LayerMask that this volume is in.</param>
  428. /// <seealso cref="Unregister"/>
  429. public void Register(Volume volume, int layer)
  430. {
  431. m_Volumes.Add(volume);
  432. // Look for existing cached layer masks and add it there if needed
  433. foreach (var kvp in m_SortedVolumes)
  434. {
  435. // We add the volume to sorted lists only if the layer match and if it doesn't contain the volume already.
  436. if ((kvp.Key & (1 << layer)) != 0 && !kvp.Value.Contains(volume))
  437. kvp.Value.Add(volume);
  438. }
  439. SetLayerDirty(layer);
  440. }
  441. /// <summary>
  442. /// Unregisters a Volume from the manager. Unity does this automatically when a Volume is
  443. /// disabled or goes out of scope, but you can use this function to force-unregister a Volume
  444. /// that you added manually while it was disabled.
  445. /// </summary>
  446. /// <param name="volume">The Volume to unregister.</param>
  447. /// <param name="layer">The LayerMask that this Volume is in.</param>
  448. /// <seealso cref="Register"/>
  449. public void Unregister(Volume volume, int layer)
  450. {
  451. m_Volumes.Remove(volume);
  452. foreach (var kvp in m_SortedVolumes)
  453. {
  454. // Skip layer masks this volume doesn't belong to
  455. if ((kvp.Key & (1 << layer)) == 0)
  456. continue;
  457. kvp.Value.Remove(volume);
  458. }
  459. }
  460. /// <summary>
  461. /// Checks if a <see cref="VolumeComponent"/> is active in a given LayerMask.
  462. /// </summary>
  463. /// <typeparam name="T">A type derived from <see cref="VolumeComponent"/></typeparam>
  464. /// <param name="layerMask">The LayerMask to check against</param>
  465. /// <returns><c>true</c> if the component is active in the LayerMask, <c>false</c>
  466. /// otherwise.</returns>
  467. public bool IsComponentActiveInMask<T>(LayerMask layerMask)
  468. where T : VolumeComponent
  469. {
  470. int mask = layerMask.value;
  471. foreach (var kvp in m_SortedVolumes)
  472. {
  473. if (kvp.Key != mask)
  474. continue;
  475. foreach (var volume in kvp.Value)
  476. {
  477. if (!volume.enabled || volume.profileRef == null)
  478. continue;
  479. if (volume.profileRef.TryGet(out T component) && component.active)
  480. return true;
  481. }
  482. }
  483. return false;
  484. }
  485. internal void SetLayerDirty(int layer)
  486. {
  487. Assert.IsTrue(layer >= 0 && layer <= k_MaxLayerCount, "Invalid layer bit");
  488. foreach (var kvp in m_SortedVolumes)
  489. {
  490. var mask = kvp.Key;
  491. if ((mask & (1 << layer)) != 0)
  492. m_SortNeeded[mask] = true;
  493. }
  494. }
  495. internal void UpdateVolumeLayer(Volume volume, int prevLayer, int newLayer)
  496. {
  497. Assert.IsTrue(prevLayer >= 0 && prevLayer <= k_MaxLayerCount, "Invalid layer bit");
  498. Unregister(volume, prevLayer);
  499. Register(volume, newLayer);
  500. }
  501. // Go through all listed components and lerp overridden values in the global state
  502. void OverrideData(VolumeStack stack, List<VolumeComponent> components, float interpFactor)
  503. {
  504. var numComponents = components.Count;
  505. for (int i = 0; i < numComponents; i++)
  506. {
  507. var component = components[i];
  508. if (!component.active)
  509. continue;
  510. var state = stack.GetComponent(component.GetType());
  511. if (state != null)
  512. {
  513. component.Override(state, interpFactor);
  514. }
  515. }
  516. }
  517. // Faster version of OverrideData to force replace values in the global state.
  518. // NOTE: As an optimization, only the VolumeParameters with overrideState=true are reset. All other parameters
  519. // are assumed to be in their correct default state so no reset is necessary.
  520. internal void ReplaceData(VolumeStack stack)
  521. {
  522. using var profilerScope = k_ProfilerMarkerReplaceData.Auto();
  523. var stackParams = stack.parameters;
  524. bool resetAllParameters = stack.requiresResetForAllProperties;
  525. int count = stackParams.Length;
  526. Debug.Assert(count == m_ParametersDefaultState.Length);
  527. for (int i = 0; i < count; i++)
  528. {
  529. var stackParam = stackParams[i];
  530. if (stackParam.overrideState || resetAllParameters) // Only reset the parameters that have been overriden by a scene volume
  531. {
  532. stackParam.overrideState = false;
  533. stackParam.SetValue(m_ParametersDefaultState[i]);
  534. }
  535. }
  536. stack.requiresResetForAllProperties = false;
  537. }
  538. /// <summary>
  539. /// Checks component default state. This is only used in the editor to handle entering and exiting play mode
  540. /// because the instances created during playmode are automatically destroyed.
  541. /// </summary>
  542. [Conditional("UNITY_EDITOR")]
  543. public void CheckDefaultVolumeState()
  544. {
  545. if (m_ComponentsDefaultState == null || (m_ComponentsDefaultState.Length > 0 && m_ComponentsDefaultState[0] == null))
  546. {
  547. EvaluateVolumeDefaultState();
  548. }
  549. }
  550. /// <summary>
  551. /// Checks the state of a given stack. This is only used in the editor to handle entering and exiting play mode
  552. /// because the instances created during playmode are automatically destroyed.
  553. /// </summary>
  554. /// <param name="stack">The stack to check.</param>
  555. [Conditional("UNITY_EDITOR")]
  556. public void CheckStack(VolumeStack stack)
  557. {
  558. if (stack.components == null)
  559. {
  560. stack.Reload(baseComponentTypeArray);
  561. return;
  562. }
  563. foreach (var kvp in stack.components)
  564. {
  565. if (kvp.Key == null || kvp.Value == null)
  566. {
  567. stack.Reload(baseComponentTypeArray);
  568. return;
  569. }
  570. }
  571. }
  572. // Returns true if must execute Update() in full, and false if we can early exit.
  573. bool CheckUpdateRequired(VolumeStack stack)
  574. {
  575. if (m_Volumes.Count == 0)
  576. {
  577. if (stack.requiresReset)
  578. {
  579. // Update the stack one more time in case there was a volume that just ceased to exist. This ensures
  580. // the stack will return to default values correctly.
  581. stack.requiresReset = false;
  582. return true;
  583. }
  584. // There were no volumes last frame either, and stack has been returned to defaults, so no update is
  585. // needed and we can early exit from Update().
  586. return false;
  587. }
  588. stack.requiresReset = true; // Stack must be reset every frame whenever there are volumes present
  589. return true;
  590. }
  591. /// <summary>
  592. /// Updates the global state of the Volume manager. Unity usually calls this once per Camera
  593. /// in the Update loop before rendering happens.
  594. /// </summary>
  595. /// <param name="trigger">A reference Transform to consider for positional Volume blending
  596. /// </param>
  597. /// <param name="layerMask">The LayerMask that the Volume manager uses to filter Volumes that it should consider
  598. /// for blending.</param>
  599. public void Update(Transform trigger, LayerMask layerMask)
  600. {
  601. Update(stack, trigger, layerMask);
  602. }
  603. /// <summary>
  604. /// Updates the Volume manager and stores the result in a custom <see cref="VolumeStack"/>.
  605. /// </summary>
  606. /// <param name="stack">The stack to store the blending result into.</param>
  607. /// <param name="trigger">A reference Transform to consider for positional Volume blending.
  608. /// </param>
  609. /// <param name="layerMask">The LayerMask that Unity uses to filter Volumes that it should consider
  610. /// for blending.</param>
  611. /// <seealso cref="VolumeStack"/>
  612. public void Update(VolumeStack stack, Transform trigger, LayerMask layerMask)
  613. {
  614. using var profilerScope = k_ProfilerMarkerUpdate.Auto();
  615. if (!isInitialized)
  616. return;
  617. Assert.IsNotNull(stack);
  618. CheckDefaultVolumeState();
  619. CheckStack(stack);
  620. if (!CheckUpdateRequired(stack))
  621. return;
  622. // Start by resetting the global state to default values.
  623. ReplaceData(stack);
  624. bool onlyGlobal = trigger == null;
  625. var triggerPos = onlyGlobal ? Vector3.zero : trigger.position;
  626. // Sort the cached volume list(s) for the given layer mask if needed and return it
  627. var volumes = GrabVolumes(layerMask);
  628. Camera camera = null;
  629. // Behavior should be fine even if camera is null
  630. if (!onlyGlobal)
  631. trigger.TryGetComponent<Camera>(out camera);
  632. // Traverse all volumes
  633. int numVolumes = volumes.Count;
  634. for (int i = 0; i < numVolumes; i++)
  635. {
  636. Volume volume = volumes[i];
  637. if (volume == null)
  638. continue;
  639. #if UNITY_EDITOR
  640. // Skip volumes that aren't in the scene currently displayed in the scene view
  641. if (!IsVolumeRenderedByCamera(volume, camera))
  642. continue;
  643. #endif
  644. // Skip disabled volumes and volumes without any data or weight
  645. if (!volume.enabled || volume.profileRef == null || volume.weight <= 0f)
  646. continue;
  647. // Global volumes always have influence
  648. if (volume.isGlobal)
  649. {
  650. OverrideData(stack, volume.profileRef.components, Mathf.Clamp01(volume.weight));
  651. continue;
  652. }
  653. if (onlyGlobal)
  654. continue;
  655. // If volume isn't global and has no collider, skip it as it's useless
  656. var colliders = m_TempColliders;
  657. volume.GetComponents(colliders);
  658. if (colliders.Count == 0)
  659. continue;
  660. // Find closest distance to volume, 0 means it's inside it
  661. float closestDistanceSqr = float.PositiveInfinity;
  662. int numColliders = colliders.Count;
  663. for (int c = 0; c < numColliders; c++)
  664. {
  665. var collider = colliders[c];
  666. if (!collider.enabled)
  667. continue;
  668. var closestPoint = collider.ClosestPoint(triggerPos);
  669. var d = (closestPoint - triggerPos).sqrMagnitude;
  670. if (d < closestDistanceSqr)
  671. closestDistanceSqr = d;
  672. }
  673. colliders.Clear();
  674. float blendDistSqr = volume.blendDistance * volume.blendDistance;
  675. // Volume has no influence, ignore it
  676. // Note: Volume doesn't do anything when `closestDistanceSqr = blendDistSqr` but we
  677. // can't use a >= comparison as blendDistSqr could be set to 0 in which case
  678. // volume would have total influence
  679. if (closestDistanceSqr > blendDistSqr)
  680. continue;
  681. // Volume has influence
  682. float interpFactor = 1f;
  683. if (blendDistSqr > 0f)
  684. interpFactor = 1f - (closestDistanceSqr / blendDistSqr);
  685. // No need to clamp01 the interpolation factor as it'll always be in [0;1[ range
  686. OverrideData(stack, volume.profileRef.components, interpFactor * Mathf.Clamp01(volume.weight));
  687. }
  688. }
  689. /// <summary>
  690. /// Get all volumes on a given layer mask sorted by influence.
  691. /// </summary>
  692. /// <param name="layerMask">The LayerMask that Unity uses to filter Volumes that it should consider.</param>
  693. /// <returns>An array of volume.</returns>
  694. public Volume[] GetVolumes(LayerMask layerMask)
  695. {
  696. var volumes = GrabVolumes(layerMask);
  697. volumes.RemoveAll(v => v == null);
  698. return volumes.ToArray();
  699. }
  700. List<Volume> GrabVolumes(LayerMask mask)
  701. {
  702. List<Volume> list;
  703. if (!m_SortedVolumes.TryGetValue(mask, out list))
  704. {
  705. // New layer mask detected, create a new list and cache all the volumes that belong
  706. // to this mask in it
  707. list = new List<Volume>();
  708. var numVolumes = m_Volumes.Count;
  709. for (int i = 0; i < numVolumes; i++)
  710. {
  711. var volume = m_Volumes[i];
  712. if ((mask & (1 << volume.gameObject.layer)) == 0)
  713. continue;
  714. list.Add(volume);
  715. m_SortNeeded[mask] = true;
  716. }
  717. m_SortedVolumes.Add(mask, list);
  718. }
  719. // Check sorting state
  720. bool sortNeeded;
  721. if (m_SortNeeded.TryGetValue(mask, out sortNeeded) && sortNeeded)
  722. {
  723. m_SortNeeded[mask] = false;
  724. SortByPriority(list);
  725. }
  726. return list;
  727. }
  728. // Stable insertion sort. Faster than List<T>.Sort() for our needs.
  729. static void SortByPriority(List<Volume> volumes)
  730. {
  731. Assert.IsNotNull(volumes, "Trying to sort volumes of non-initialized layer");
  732. for (int i = 1; i < volumes.Count; i++)
  733. {
  734. var temp = volumes[i];
  735. int j = i - 1;
  736. // Sort order is ascending
  737. while (j >= 0 && volumes[j].priority > temp.priority)
  738. {
  739. volumes[j + 1] = volumes[j];
  740. j--;
  741. }
  742. volumes[j + 1] = temp;
  743. }
  744. }
  745. static bool IsVolumeRenderedByCamera(Volume volume, Camera camera)
  746. {
  747. #if UNITY_2018_3_OR_NEWER && UNITY_EDITOR
  748. // GameObject for default global volume may not belong to any scene, following check prevents it from being culled
  749. if (!volume.gameObject.scene.IsValid())
  750. return true;
  751. // IsGameObjectRenderedByCamera does not behave correctly when camera is null so we have to catch it here.
  752. return camera == null ? true : UnityEditor.SceneManagement.StageUtility.IsGameObjectRenderedByCamera(volume.gameObject, camera);
  753. #else
  754. return true;
  755. #endif
  756. }
  757. }
  758. /// <summary>
  759. /// A scope in which a Camera filters a Volume.
  760. /// </summary>
  761. [Obsolete("VolumeIsolationScope is deprecated, it does not have any effect anymore.")]
  762. public struct VolumeIsolationScope : IDisposable
  763. {
  764. /// <summary>
  765. /// Constructs a scope in which a Camera filters a Volume.
  766. /// </summary>
  767. /// <param name="unused">Unused parameter.</param>
  768. public VolumeIsolationScope(bool unused) { }
  769. /// <summary>
  770. /// Stops the Camera from filtering a Volume.
  771. /// </summary>
  772. void IDisposable.Dispose() { }
  773. }
  774. }