This commit is contained in:
2026-11-24 15:51:02 +01:00
parent cca4d73e41
commit f4aa17114a
22092 changed files with 5042406 additions and 0 deletions
@@ -0,0 +1,313 @@
using System.Diagnostics.CodeAnalysis;
using Unity.Collections;
using UnityEngine.Assertions;
namespace UnityEngine.Rendering
{
/// <summary>
/// A helper function for interpolating AnimationCurves together. In general, curves can not be directly blended
/// because they will have keypoints at different places. InterpAnimationCurve traverses through the keypoints.
/// If both curves have a keypoint at the same time, they keypoints are trivially lerped together. However
/// if one curve has a keypoint at a time that is missing in the other curve (which is the most common case),
/// InterpAnimationCurve calculates a synthetic keypoint at that time based on value and derivative, and interpolates
/// the resulting keys.
/// Note that this function should only be called by internal rendering code. It creates a small pool of animation
/// curves and reuses them to avoid creating garbage. The number of curves needed is quite small, since curves only need
/// to be used when interpolating multiple volumes together with different curve parameters. The underlying interp
/// function isn't allowed to fail, so in the case where we run out of memory we fall back to returning a single keyframe.
/// </summary>
///
/// <example>
/// <code>
/// {
/// AnimationCurve curve0 = new AnimationCurve();
/// curve0.AddKey(new Keyframe(0.0f, 3.0f));
/// curve0.AddKey(new Keyframe(4.0f, 2.0f));
///
/// AnimationCurve curve1 = new AnimationCurve();
/// curve1.AddKey(new Keyframe(0.0f, 0.0f));
/// curve1.AddKey(new Keyframe(2.0f, 1.0f));
/// curve1.AddKey(new Keyframe(4.0f, 4.0f));
///
/// float t = 0.5f;
/// KeyframeUtility.InterpAnimationCurve(curve0, curve1, t);
///
/// // curve0 now stores the resulting interpolated curve
/// }
/// </code>
/// </example>
public class KeyframeUtility
{
/// <summary>
/// Helper function to remove all control points for an animation curve. Since animation curves are reused in a pool,
/// this function clears existing keys so the curve is ready for reuse.
/// </summary>
/// <param name="curve">The curve to reset.</param>
static public void ResetAnimationCurve(AnimationCurve curve)
{
curve.ClearKeys();
}
static private Keyframe LerpSingleKeyframe(Keyframe lhs, Keyframe rhs, float t)
{
var ret = new Keyframe();
ret.time = Mathf.Lerp(lhs.time, rhs.time, t);
ret.value = Mathf.Lerp(lhs.value, rhs.value, t);
ret.inTangent = Mathf.Lerp(lhs.inTangent, rhs.inTangent, t);
ret.outTangent = Mathf.Lerp(lhs.outTangent, rhs.outTangent, t);
ret.inWeight = Mathf.Lerp(lhs.inWeight, rhs.inWeight, t);
ret.outWeight = Mathf.Lerp(lhs.outWeight, rhs.outWeight, t);
// it's not possible to lerp the weightedMode, so use the lhs mode.
ret.weightedMode = lhs.weightedMode;
// Note: ret.tangentMode is deprecated, so we will use the value from the constructor
return ret;
}
/// In an animation curve, the inTangent and outTangent don't match the edge of the curve. For example,
/// the first key might have inTangent=3.0f but the actual incoming tangent is 0.0 because the curve is
/// clamped outside the time domain. So this helper fetches a key, but zeroes out the inTangent of the first
/// key and the outTangent of the last key.
static private Keyframe GetKeyframeAndClampEdge([DisallowNull] NativeArray<Keyframe> keys, int index)
{
var lastKeyIndex = keys.Length - 1;
if (index < 0 || index > lastKeyIndex)
{
Debug.LogWarning("Invalid index in GetKeyframeAndClampEdge. This is likely a bug.");
return new Keyframe();
}
var currKey = keys[index];
if (index == 0)
{
currKey.inTangent = 0.0f;
}
if (index == lastKeyIndex)
{
currKey.outTangent = 0.0f;
}
return currKey;
}
/// Fetch a key from the keys list. If index<0, then expand the first key backwards to startTime. If index>=keys.length,
/// then extend the last key to endTime. Keys must be a valid array with at least one element.
static private Keyframe FetchKeyFromIndexClampEdge([DisallowNull] NativeArray<Keyframe> keys, int index, float segmentStartTime, float segmentEndTime)
{
float startTime = Mathf.Min(segmentStartTime, keys[0].time);
float endTime = Mathf.Max(segmentEndTime, keys[keys.Length - 1].time);
float startValue = keys[0].value;
float endValue = keys[keys.Length - 1].value;
// In practice, we are lerping animcurves for post processing curves that are always clamping at the begining and the end,
// so we are not implementing the other wrap modes like Loop, PingPong, etc.
Keyframe ret;
if (index < 0)
{
// when you are at a time either before the curve start time the value is clamped to the start time and the input tangent is ignored.
ret = new Keyframe(startTime, startValue, 0.0f, 0.0f);
}
else if (index >= keys.Length)
{
// if we are after the end of the curve, there slope is always zero just like before the start of a curve
var lastKey = keys[keys.Length - 1];
ret = new Keyframe(endTime, endValue, 0.0f, 0.0f);
}
else
{
// only remaining case is that we have a proper index
ret = GetKeyframeAndClampEdge(keys, index);
}
return ret;
}
/// Given a desiredTime, interpoloate between two keys to find the value and derivative. This function assumes that lhsKey.time <= desiredTime <= rhsKey.time,
/// but will return a reasonable float value if that's not the case.
static private void EvalCurveSegmentAndDeriv(out float dstValue, out float dstDeriv, Keyframe lhsKey, Keyframe rhsKey, float desiredTime)
{
// This is the same epsilon used internally
const float epsilon = 0.0001f;
float currTime = Mathf.Clamp(desiredTime, lhsKey.time, rhsKey.time);
// (lhsKey.time <= rhsKey.time) should always be true. But theoretically, if garbage values get passed in, the value would
// be clamped here to epsilon, and we would still end up with a reasonable value for dx.
float dx = Mathf.Max(rhsKey.time - lhsKey.time, epsilon);
float dy = rhsKey.value - lhsKey.value;
float length = 1.0f / dx;
float lengthSqr = length * length;
float m1 = lhsKey.outTangent;
float m2 = rhsKey.inTangent;
float d1 = m1 * dx;
float d2 = m2 * dx;
// Note: The coeffecients are calculated to match what the editor does internally. These coeffeceients expect a
// t in the range of [0,dx]. We could change the function to accept a range between [0,1], but then this logic would
// be different from internal editor logic which could cause subtle bugs later.
float c0 = (d1 + d2 - dy - dy) * lengthSqr * length;
float c1 = (dy + dy + dy - d1 - d1 - d2) * lengthSqr;
float c2 = m1;
float c3 = lhsKey.value;
float t = Mathf.Clamp(currTime - lhsKey.time, 0.0f, dx);
dstValue = (t * (t * (t * c0 + c1) + c2)) + c3;
dstDeriv = (t * (3.0f * t * c0 + 2.0f * c1)) + c2;
}
/// lhsIndex and rhsIndex are the indices in the keys array. The lhsIndex/rhsIndex may be -1, in which it creates a synthetic first key
/// at startTime, or beyond the length of the array, in which case it creates a synthetic key at endTime.
static private Keyframe EvalKeyAtTime([DisallowNull] NativeArray<Keyframe> keys, int lhsIndex, int rhsIndex, float startTime, float endTime, float currTime)
{
var lhsKey = KeyframeUtility.FetchKeyFromIndexClampEdge(keys, lhsIndex, startTime, endTime);
var rhsKey = KeyframeUtility.FetchKeyFromIndexClampEdge(keys, rhsIndex, startTime, endTime);
float currValue;
float currDeriv;
KeyframeUtility.EvalCurveSegmentAndDeriv(out currValue, out currDeriv, lhsKey, rhsKey, currTime);
return new Keyframe(currTime, currValue, currDeriv, currDeriv);
}
/// <summary>
/// Interpolates two AnimationCurves. Since both curves likely have control points at different places
/// in the curve, this method will create a new curve from the union of times between both curves. However, to avoid creating
/// garbage, this function will always replace the keys of lhsAndResultCurve with the final result, and return lhsAndResultCurve.
/// </summary>
/// <param name="lhsAndResultCurve">The start value. Additionaly, this instance will be reused and returned as the result.</param>
/// <param name="rhsCurve">The end value.</param>
/// <param name="t">The interpolation factor in range [0,1].</param>
static public void InterpAnimationCurve(ref AnimationCurve lhsAndResultCurve, [DisallowNull] AnimationCurve rhsCurve, float t)
{
if (t <= 0.0f || rhsCurve.length == 0)
{
// no op. lhsAndResultCurve is already the result
}
else if (t >= 1.0f || lhsAndResultCurve.length == 0)
{
// In this case the obvious solution would be to return the rhsCurve. BUT (!) the lhsCurve and rhsCurve are different. This function is
// called by:
// stateParam.Interp(stateParam, toParam, interpFactor);
//
// stateParam (lhsCurve) is a temporary in/out parameter, but toParam (rhsCurve) might point to the original component, so it's unsafe to
// change that data. Thus, we need to copy the keys from the rhsCurve to the lhsCurve instead of returning rhsCurve.
lhsAndResultCurve.CopyFrom(rhsCurve);
}
else
{
// Note: If we reached this code, we are guaranteed that both lhsCurve and rhsCurve are valid with at least 1 key
// create a native array for the temp keys to avoid GC
var lhsCurveKeys = new NativeArray<Keyframe>(lhsAndResultCurve.length, Allocator.Temp);
var rhsCurveKeys = new NativeArray<Keyframe>(rhsCurve.length, Allocator.Temp);
for (int i = 0; i < lhsAndResultCurve.length; i++)
{
lhsCurveKeys[i] = lhsAndResultCurve[i];
}
for (int i = 0; i < rhsCurve.length; i++)
{
rhsCurveKeys[i] = rhsCurve[i];
}
float startTime = Mathf.Min(lhsCurveKeys[0].time, rhsCurveKeys[0].time);
float endTime = Mathf.Max(lhsCurveKeys[lhsAndResultCurve.length - 1].time, rhsCurveKeys[rhsCurve.length - 1].time);
// we don't know how many keys the resulting curve will have (because we will compact keys that are at the exact
// same time), but in most cases we will need the worst case number of keys. So allocate the worst case.
int maxNumKeys = lhsAndResultCurve.length + rhsCurve.length;
int currNumKeys = 0;
var dstKeys = new NativeArray<Keyframe>(maxNumKeys, Allocator.Temp);
int lhsKeyCurr = 0;
int rhsKeyCurr = 0;
while (lhsKeyCurr < lhsCurveKeys.Length || rhsKeyCurr < rhsCurveKeys.Length)
{
// the index is considered invalid once it goes off the end of the array
bool lhsValid = lhsKeyCurr < lhsCurveKeys.Length;
bool rhsValid = rhsKeyCurr < rhsCurveKeys.Length;
// it's actually impossible for lhsKey/rhsKey to be uninitialized, but have to
// add initialize here to prevent compiler erros
var lhsKey = new Keyframe();
var rhsKey = new Keyframe();
if (lhsValid && rhsValid)
{
lhsKey = GetKeyframeAndClampEdge(lhsCurveKeys, lhsKeyCurr);
rhsKey = GetKeyframeAndClampEdge(rhsCurveKeys, rhsKeyCurr);
if (lhsKey.time == rhsKey.time)
{
lhsKeyCurr++;
rhsKeyCurr++;
}
else if (lhsKey.time < rhsKey.time)
{
// in this case:
// rhsKey[curr-1].time <= lhsKey.time <= rhsKey[curr].time
// so interpolate rhsKey at the lhsKey.time.
rhsKey = KeyframeUtility.EvalKeyAtTime(rhsCurveKeys, rhsKeyCurr - 1, rhsKeyCurr, startTime, endTime, lhsKey.time);
lhsKeyCurr++;
}
else
{
// only case left is (lhsKey.time > rhsKey.time)
Assert.IsTrue(lhsKey.time > rhsKey.time);
// this is the reverse of the lhs key case
// lhsKey[curr-1].time <= rhsKey.time <= lhsKey[curr].time
// so interpolate lhsKey at the rhsKey.time.
lhsKey = KeyframeUtility.EvalKeyAtTime(lhsCurveKeys, lhsKeyCurr - 1, lhsKeyCurr, startTime, endTime, rhsKey.time);
rhsKeyCurr++;
}
}
else if (lhsValid)
{
// we are still processing lhsKeys, but we are out of rhsKeys, so increment lhs and evaluate rhs
lhsKey = GetKeyframeAndClampEdge(lhsCurveKeys, lhsKeyCurr);
// rhs will be evaluated between the last rhs key and the extrapolated rhs key at the end time
rhsKey = KeyframeUtility.EvalKeyAtTime(rhsCurveKeys, rhsKeyCurr - 1, rhsKeyCurr, startTime, endTime, lhsKey.time);
lhsKeyCurr++;
}
else
{
// either lhsValid is True, rhsValid is True, or they are both True. So to miss the first two cases,
// right here rhsValid must be true.
Assert.IsTrue(rhsValid);
// we still have rhsKeys to lerp, but we are out of lhsKeys, to increment rhs and evaluate lhs
rhsKey = GetKeyframeAndClampEdge(rhsCurveKeys, rhsKeyCurr);
// lhs will be evaluated between the last lhs key and the extrapolated lhs key at the end time
lhsKey = KeyframeUtility.EvalKeyAtTime(lhsCurveKeys, lhsKeyCurr - 1, lhsKeyCurr, startTime, endTime, rhsKey.time);
rhsKeyCurr++;
}
var dstKey = KeyframeUtility.LerpSingleKeyframe(lhsKey, rhsKey, t);
dstKeys[currNumKeys] = dstKey;
currNumKeys++;
}
// Replace the keys in lhsAndResultCurve with our interpolated curve.
KeyframeUtility.ResetAnimationCurve(lhsAndResultCurve);
for (int i = 0; i < currNumKeys; i++)
{
lhsAndResultCurve.AddKey(dstKeys[i]);
}
dstKeys.Dispose();
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 1e28576c73484c844b4b56a5352abe6f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,200 @@
using System;
using System.Collections.Generic;
using UnityEngine.Serialization;
namespace UnityEngine.Rendering
{
/// <summary>
/// A generic Volume component holding a <see cref="VolumeProfile"/>.
/// </summary>
[PipelineHelpURL("HDRenderPipelineAsset","understand-volumes")]
[PipelineHelpURL("UniversalRenderPipelineAsset", "urp/Volumes")]
[ExecuteAlways]
[AddComponentMenu("Miscellaneous/Volume")]
[Icon("Packages/com.unity.render-pipelines.core/Editor/Icons/Processed/Volume Icon.asset")]
public class Volume : MonoBehaviour
{
[SerializeField, FormerlySerializedAs("isGlobal")]
bool m_IsGlobal = true;
/// <summary>
/// Specifies whether to apply the Volume to the entire Scene or not.
/// </summary>
public bool isGlobal
{
get => m_IsGlobal;
set
{
m_IsGlobal = value;
if (!m_IsGlobal)
UpdateColliders();
}
}
/// <summary>
/// A value which determines which Volume is being used when Volumes have an equal amount of influence on the Scene. Volumes with a higher priority will override lower ones.
/// </summary>
[Delayed, FormerlySerializedAs("m_Priority")]
public float priority = 0f;
/// <summary>
/// The outer distance to start blending from. A value of 0 means no blending and Unity applies
/// the Volume overrides immediately upon entry.
/// </summary>
[FormerlySerializedAs("m_BlendDistance")]
public float blendDistance = 0f;
/// <summary>
/// The total weight of this volume in the Scene. 0 means no effect and 1 means full effect.
/// </summary>
[Range(0f, 1f), FormerlySerializedAs("m_Weight")]
public float weight = 1f;
/// <summary>
/// The shared Profile that this Volume uses.
/// Modifying <c>sharedProfile</c> changes every Volumes that uses this Profile and also changes
/// the Profile settings stored in the Project.
/// </summary>
/// <remarks>
/// You should not modify Profiles that <c>sharedProfile</c> returns. If you want
/// to modify the Profile of a Volume, use <see cref="profile"/> instead.
/// </remarks>
/// <seealso cref="profile"/>
public VolumeProfile sharedProfile = null;
/// <summary>
/// Gets the first instantiated <see cref="VolumeProfile"/> assigned to the Volume.
/// Modifying <c>profile</c> changes the Profile for this Volume only. If another Volume
/// uses the same Profile, this clones the shared Profile and starts using it from now on.
/// </summary>
/// <remarks>
/// This property automatically instantiates the Profile and make it unique to this Volume
/// so you can safely edit it via scripting at runtime without changing the original Asset
/// in the Project.
/// Note that if you pass your own Profile, you must destroy it when you finish using it.
/// </remarks>
/// <seealso cref="sharedProfile"/>
public VolumeProfile profile
{
get
{
if (m_InternalProfile == null)
{
m_InternalProfile = ScriptableObject.CreateInstance<VolumeProfile>();
if (sharedProfile != null)
{
m_InternalProfile.name = sharedProfile.name;
foreach (var item in sharedProfile.components)
{
var itemCopy = Instantiate(item);
m_InternalProfile.components.Add(itemCopy);
}
}
}
return m_InternalProfile;
}
set => m_InternalProfile = value;
}
#if ENABLE_PHYSICS_MODULE
readonly List<Collider> m_Colliders = new List<Collider>();
/// <summary>
/// The colliders of the volume if <see cref="isGlobal"/> is false
/// </summary>
public List<Collider> colliders => m_Colliders;
#endif
GameObject m_CachedGameObject;
internal GameObject cachedGameObject => m_CachedGameObject;
internal VolumeProfile profileRef => m_InternalProfile == null ? sharedProfile : m_InternalProfile;
/// <summary>
/// Checks if the Volume has an instantiated Profile or if it uses a shared Profile.
/// </summary>
/// <returns><c>true</c> if the profile has been instantiated.</returns>
/// <seealso cref="profile"/>
/// <seealso cref="sharedProfile"/>
public bool HasInstantiatedProfile() => m_InternalProfile != null;
// Needed for state tracking (see the comments in Update)
int m_PreviousLayer;
float m_PreviousPriority;
VolumeProfile m_InternalProfile;
void OnEnable()
{
m_CachedGameObject = gameObject;
m_PreviousLayer = cachedGameObject.layer;
VolumeManager.instance.Register(this);
UpdateColliders();
}
void OnDisable()
{
VolumeManager.instance.Unregister(this);
}
void Update()
{
UpdateLayer();
UpdatePriority();
#if UNITY_EDITOR
// In the editor, we refresh the list of colliders at every frame because it's frequent to add/remove them
UpdateColliders();
#endif
}
/// <summary>
/// Updates the cached list of colliders stored in the Volume.
/// </summary>
/// <remarks>
/// The Volume class caches a list of colliders for performance and quick access.
/// If you add or remove colliders at runtime, call this method to refresh the cached collider list.
/// </remarks>
public void UpdateColliders()
{
#if ENABLE_PHYSICS_MODULE
GetComponents(m_Colliders);
#endif
}
internal void UpdateLayer()
{
// Unfortunately we need to track the current layer to update the volume manager in
// real-time as the user could change it at any time in the editor or at runtime.
// Because no event is raised when the layer changes, we have to track it on every
// frame :/
int layer = cachedGameObject.layer;
if (layer == m_PreviousLayer)
return;
VolumeManager.instance.UpdateVolumeLayer(this, m_PreviousLayer, layer);
m_PreviousLayer = layer;
}
internal void UpdatePriority()
{
if (!(Mathf.Abs(priority - m_PreviousPriority) > Mathf.Epsilon))
return;
// Same for priority. We could use a property instead, but it doesn't play nice with the
// serialization system. Using a custom Attribute/PropertyDrawer for a property is
// possible but it doesn't work with Undo/Redo in the editor, which makes it useless for
// our case.
VolumeManager.instance.SetLayerDirty(cachedGameObject.layer);
m_PreviousPriority = priority;
}
void OnValidate()
{
blendDistance = Mathf.Max(blendDistance, 0f);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 172515602e62fb746b5d573b38a5fe58
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {fileID: 2800000, guid: 177b2538515c71b4a86aa1cad939807a, type: 2}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,166 @@
using System;
using System.Collections.Generic;
using UnityEngine.Assertions;
namespace UnityEngine.Rendering
{
internal class VolumeCollection
{
// Max amount of layers available in Unity
internal const int k_MaxLayerCount = 32;
// Cached lists of all volumes (sorted by priority) by layer mask
readonly Dictionary<int, List<Volume>> m_SortedVolumes = new();
// Holds all the registered volumes
readonly List<Volume> m_Volumes = new();
// Keep track of sorting states for layer masks
readonly Dictionary<int, bool> m_SortNeeded = new();
public int count => m_Volumes.Count;
public bool Register(Volume volume, int layer)
{
if (volume == null)
throw new ArgumentNullException(nameof(volume), "The volume to register is null");
if (m_Volumes.Contains(volume))
return false;
m_Volumes.Add(volume);
// Look for existing cached layer masks and add it there if needed
foreach (var kvp in m_SortedVolumes)
{
// We add the volume to sorted lists only if the layer match and if it doesn't contain the volume already.
if ((kvp.Key & (1 << layer)) != 0 && !kvp.Value.Contains(volume))
kvp.Value.Add(volume);
}
SetLayerIndexDirty(layer);
return true;
}
public bool Unregister(Volume volume, int layer)
{
if (volume == null)
throw new ArgumentNullException(nameof(volume), "The volume to unregister is null");
m_Volumes.Remove(volume);
foreach (var kvp in m_SortedVolumes)
{
// Skip layer masks this volume doesn't belong to
if ((kvp.Key & (1 << layer)) == 0)
continue;
kvp.Value.Remove(volume);
}
SetLayerIndexDirty(layer);
return true;
}
public bool ChangeLayer(Volume volume, int previousLayerIndex, int currentLayerIndex)
{
if (volume == null)
throw new ArgumentNullException(nameof(volume), "The volume to change layer is null");
Assert.IsTrue(previousLayerIndex >= 0 && previousLayerIndex <= k_MaxLayerCount, "Invalid layer bit");
Unregister(volume, previousLayerIndex);
return Register(volume, currentLayerIndex);
}
// Stable insertion sort. Faster than List<T>.Sort() for our needs.
internal static void SortByPriority(List<Volume> volumes)
{
for (int i = 1; i < volumes.Count; i++)
{
var temp = volumes[i];
int j = i - 1;
// Sort order is ascending
while (j >= 0 && volumes[j].priority > temp.priority)
{
volumes[j + 1] = volumes[j];
j--;
}
volumes[j + 1] = temp;
}
}
public List<Volume> GrabVolumes(LayerMask mask)
{
List<Volume> list;
if (!m_SortedVolumes.TryGetValue(mask, out list))
{
// New layer mask detected, create a new list and cache all the volumes that belong
// to this mask in it
list = new List<Volume>();
var numVolumes = m_Volumes.Count;
for (int i = 0; i < numVolumes; i++)
{
var volume = m_Volumes[i];
if ((mask & (1 << volume.gameObject.layer)) == 0)
continue;
list.Add(volume);
m_SortNeeded[mask] = true;
}
m_SortedVolumes.Add(mask, list);
}
// Check sorting state
if (m_SortNeeded.TryGetValue(mask, out var sortNeeded) && sortNeeded)
{
m_SortNeeded[mask] = false;
SortByPriority(list);
}
return list;
}
public void SetLayerIndexDirty(int layerIndex)
{
Assert.IsTrue(layerIndex >= 0 && layerIndex <= k_MaxLayerCount, "Invalid layer bit");
foreach (var kvp in m_SortedVolumes)
{
var mask = kvp.Key;
if ((mask & (1 << layerIndex)) != 0)
m_SortNeeded[mask] = true;
}
}
public bool IsComponentActiveInMask<T>(LayerMask layerMask)
where T : VolumeComponent
{
int mask = layerMask.value;
foreach (var kvp in m_SortedVolumes)
{
if (kvp.Key != mask)
continue;
foreach (var volume in kvp.Value)
{
if (!volume.enabled || volume.profileRef == null)
continue;
if (volume.profileRef.TryGet(out T component) && component.active)
return true;
}
}
return false;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 993a8382d5f766441859ffb0146774d1
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,54 @@
#if UNITY_EDITOR
using System;
using UnityEditor;
namespace UnityEngine.Rendering
{
public partial class VolumeComponent : IApplyRevertPropertyContextMenuItemProvider
{
public bool TryGetRevertMethodForFieldName(SerializedProperty property, out Action<SerializedProperty> revertMethod)
{
revertMethod = property =>
{
var targetObject = property.serializedObject.targetObject;
var type = targetObject.GetType();
var defaultVolumeComponent = (VolumeComponent) CreateInstance(type);
Undo.RecordObject(targetObject, $"Revert property {property.propertyPath} from {property.serializedObject}");
SerializedObject serializedObject = new SerializedObject(defaultVolumeComponent);
if (property.propertyType == SerializedPropertyType.ObjectReference)
{
property.objectReferenceValue = null;
}
else
{
var serializedProperty = serializedObject.FindProperty(property.propertyPath);
property.serializedObject.CopyFromSerializedProperty(serializedProperty);
VolumeManager.instance.OnVolumeComponentChanged(targetObject as VolumeComponent);
}
property.serializedObject.ApplyModifiedProperties();
};
return true;
}
public string GetSourceTerm()
{
return "Property";
}
public bool TryGetApplyMethodForFieldName(SerializedProperty property, out Action<SerializedProperty> applyMethod)
{
applyMethod = null;
return false;
}
public string GetSourceName(Component comp)
{
return string.Empty;
}
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 9c62ee15c68690246a39d8c29726cb19
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,385 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
namespace UnityEngine.Rendering
{
/// <summary>
/// This attribute is used to set up a path in the <b>Add Override</b> popup menu in Unity's Volume system.
/// It allows you to organize and categorize your Volume components into submenus for easier access and management within the editor.
/// </summary>
/// <remarks>Specify the name of the menu entry, and use slashes ("/") to create hierarchical submenus in the popup. This is useful for organizing large or complex sets of Volume components.
/// To further filter the menu entries based on the active Render Pipeline, you can combine this attribute with the <see cref="SupportedOnRenderPipeline"/> attribute.
/// This enables conditional display of Volume components depending on the Render Pipeline being used in the project.
/// </remarks>
/// <example>
/// <code>
/// [VolumeComponentMenu("MyVolumeCategory/LightingEffects")]
/// public class CustomLightingVolume : VolumeComponent { ... }
/// </code>
/// </example>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class VolumeComponentMenu : Attribute
{
/// <summary>
/// The name of the entry in the override list. You can use slashes to create sub-menus.
/// </summary>
public readonly string menu;
// TODO: Add support for component icons
/// <summary>
/// Creates a new <see cref="VolumeComponentMenu"/> instance.
/// </summary>
/// <param name="menu">The name of the entry in the override list. You can use slashes to
/// create sub-menus.</param>
public VolumeComponentMenu(string menu)
{
this.menu = menu;
}
}
/// <summary>
/// This attribute allows you to add commands to the <b>Add Override</b> popup menu on Volumes,
/// while also specifying the render pipeline(s) for which the command will be supported.
/// </summary>
[Obsolete(@"VolumeComponentMenuForRenderPipelineAttribute is deprecated. Use VolumeComponentMenu with SupportedOnRenderPipeline instead. #from(2023.1)", true)]
public class VolumeComponentMenuForRenderPipeline : VolumeComponentMenu
{
/// <summary>
/// The list of pipeline types that the target class supports.
/// </summary>
public Type[] pipelineTypes { get; }
/// <summary>
/// Creates a new <see cref="VolumeComponentMenuForRenderPipeline"/> instance.
/// </summary>
/// <param name="menu">The name of the entry in the override list. You can use slashes to
/// create sub-menus.</param>
/// <param name="pipelineTypes">The list of pipeline types that the target class supports.</param>
/// <exception cref="Exception">Thrown when the pipelineTypes is null or the types do not inherit from <see cref="RenderPipeline"/>.</exception>
public VolumeComponentMenuForRenderPipeline(string menu, params Type[] pipelineTypes)
: base(menu)
{
if (pipelineTypes == null)
throw new Exception("Specify a list of supported pipeline.");
// Ensure that we only allow class types that inherit from RenderPipeline
foreach (var t in pipelineTypes)
{
if (!typeof(RenderPipeline).IsAssignableFrom(t))
throw new Exception(
$"You can only specify types that inherit from {typeof(RenderPipeline)}, please check {t}");
}
this.pipelineTypes = pipelineTypes;
}
}
/// <summary>
/// This attribute prevents the component from being included in the list of available
/// overrides in the Volume Inspector via the <b>Add Override</b> button.
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
[Obsolete("VolumeComponentDeprecated has been deprecated. #from(2023.1) (UnityUpgradable) -> [UnityEngine] UnityEngine.HideInInspector")]
public sealed class VolumeComponentDeprecated : Attribute
{
}
/// <summary>
/// The base class for all components that can be part of a <see cref="VolumeProfile"/>.
/// This class serves as the foundation for creating and managing volume components in Unity's
/// volume system, enabling the handling of various <see cref="VolumeParameter"/> types in a unified way.
/// </summary>
/// <remarks>The <see cref="VolumeComponent"/> class is automatically integrated into the volume framework,
/// which handles interpolation and blending of <see cref="VolumeParameter"/> members at runtime.
/// It ensures that parameter values can be adjusted and smoothly transitioned based on different factors,
/// such as render pipeline settings, quality settings, or user-defined parameters.
///
/// Due to the need to store multiple <see cref="VolumeParameter{T}"/> types in a single collection,
/// this base class provides a mechanism to handle them generically. It allows for easy management and
/// manipulation of parameters of varying types, ensuring consistency across different volume components.
///
/// - Stores and manages a collection of <see cref="VolumeParameter"/> objects..
/// - Integrates seamlessly into <see cref="VolumeProfile"/> for enhanced control over rendering and post-processing effects.
/// </remarks>
/// <example>
/// <para>
/// You can create a custom volume component by inheriting from this base class and defining your own.
/// <see cref="VolumeParameter"/> fields. The <see cref="VolumeManager"/> will handle the interpolation and blending for you.
/// </para>
/// <code>
/// using UnityEngine.Rendering;
///
/// [Serializable, VolumeComponentMenuForRenderPipeline("Custom/Example Component")]
/// public class ExampleComponent : VolumeComponent
/// {
/// public ClampedFloatParameter intensity = new ClampedFloatParameter(0f, 0f, 1f);
/// }
/// </code>
///
/// <para>
/// In the example above, the custom component `ExampleComponent` extends `VolumeComponent` and defines a parameter
/// (`intensity`) that can be manipulated within the volume framework. The `ClampedFloatParameter` is a type of
/// <see cref="VolumeParameter{T}"/> that ensures the value remains within a specified range.
/// </para>
/// </example>
[Serializable]
public partial class VolumeComponent : ScriptableObject
{
/// <summary>
/// Local attribute for VolumeComponent fields only.
/// It handles relative indentation of a property for inspector.
/// </summary>
public sealed class Indent : PropertyAttribute
{
/// <summary> Relative indent amount registered in this attribute </summary>
public readonly int relativeAmount;
/// <summary> Constructor </summary>
/// <param name="relativeAmount">Relative indent change to use</param>
public Indent(int relativeAmount = 1)
=> this.relativeAmount = relativeAmount;
}
/// <summary>
/// The active state of the set of parameters defined in this class. You can use this to
/// quickly turn on or off all the overrides at once.
/// </summary>
public bool active = true;
/// <summary>
/// The name displayed in the component header. If you do not set a name, Unity generates one from
/// the class name automatically.
/// </summary>
[Obsolete("Use DisplayInfo attribute to define a display name instead. #from(6000.3)", false)]
public string displayName { get; protected set; }
/// <summary>
/// The backing storage of <see cref="parameters"/>. Use this for performance-critical work.
/// </summary>
internal VolumeParameter[] parameterList;
ReadOnlyCollection<VolumeParameter> m_ParameterReadOnlyCollection;
/// <summary>
/// A read-only collection of all the <see cref="VolumeParameter"/>s defined in this class.
/// </summary>
public ReadOnlyCollection<VolumeParameter> parameters => m_ParameterReadOnlyCollection ??= new ReadOnlyCollection<VolumeParameter>(parameterList);
/// <summary>
/// Extracts all the <see cref="VolumeParameter"/>s defined in this class and nested classes.
/// </summary>
/// <param name="o">The object to find the parameters</param>
/// <param name="parameters">The list filled with the parameters.</param>
/// <param name="filter">If you want to filter the parameters</param>
internal static void FindParameters(object o, List<VolumeParameter> parameters, Func<FieldInfo, bool> filter = null)
{
if (o == null)
return;
var fields = o.GetType()
.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.OrderBy(t => t.MetadataToken); // Guaranteed order
foreach (var field in fields)
{
var fieldType = field.FieldType;
if (fieldType.IsSubclassOf(typeof(VolumeParameter)))
{
if (filter?.Invoke(field) ?? true)
{
VolumeParameter volumeParameter = (VolumeParameter)field.GetValue(o);
#if UNITY_ENABLE_CHECKS
VolumeDebugData.AddVolumeParameterDebugId(volumeParameter, field);
#endif
parameters.Add(volumeParameter);
}
}
else if (!fieldType.IsArray && fieldType.IsClass)
FindParameters(field.GetValue(o), parameters, filter);
}
}
/// <summary>
/// Unity calls this method when it loads the class.
/// </summary>
/// <remarks>
/// If you want to override this method, you must call <c>base.OnEnable()</c>.
/// </remarks>
protected virtual void OnEnable()
{
// Automatically grab all fields of type VolumeParameter for this instance
ListPool<VolumeParameter>.Get(out var tempList);
FindParameters(this, tempList);
parameterList = tempList.ToArray();
ListPool<VolumeParameter>.Release(tempList);
foreach (var parameter in parameterList)
{
if (parameter != null)
parameter.OnEnable();
else
Debug.LogWarning("Volume Component " + GetType().Name + " contains a null parameter; please make sure all parameters are initialized to a default value. Until this is fixed the null parameters will not be considered by the system.");
}
}
/// <summary>
/// Unity calls this method when the object goes out of scope.
/// </summary>
protected virtual void OnDisable()
{
foreach (var parameter in parameterList)
{
if (parameter != null)
parameter.OnDisable();
}
}
/// <summary>
/// Interpolates a <see cref="VolumeComponent"/> with this component by an interpolation
/// factor and puts the result back into the given <see cref="VolumeComponent"/>.
/// </summary>
/// <remarks>
/// You can override this method to do your own blending. Either loop through the
/// <see cref="parameters"/> list or reference direct fields. You should only use
/// <see cref="VolumeParameter.SetValue"/> to set parameter values and not assign
/// directly to the state object. you should also manually check
/// <see cref="VolumeParameter.overrideState"/> before you set any values.
/// </remarks>
/// <param name="state">The internal component to interpolate from. You must store
/// the result of the interpolation in this same component.</param>
/// <param name="interpFactor">The interpolation factor in range [0,1].</param>
/// <example>
/// <para> Below is the default implementation for blending:</para>
/// <code>
/// public virtual void Override(VolumeComponent state, float interpFactor)
/// {
/// int count = parameters.Count;
///
/// for (int i = 0; i &lt; count; i++)
/// {
/// var stateParam = state.parameters[i];
/// var toParam = parameters[i];
///
/// if (toParam.overrideState)
/// {
/// // Keep track of the override state to ensure that state will be reset on next frame (and for debugging purpose)
/// stateParam.overrideState = toParam.overrideState;
/// stateParam.Interp(stateParam, toParam, interpFactor);
/// }
/// }
/// }
/// </code>
/// </example>
public virtual void Override(VolumeComponent state, float interpFactor)
{
int count = parameterList.Length;
for (int i = 0; i < count; i++)
{
var stateParam = state.parameterList[i];
var toParam = parameterList[i];
if (toParam.overrideState)
{
// Keep track of the override state to ensure that state will be reset on next frame (and for debugging purpose)
stateParam.overrideState = toParam.overrideState;
stateParam.Interp(stateParam, toParam, interpFactor);
}
}
}
/// <summary>
/// Sets the state of all the overrides on this component to a given value.
/// </summary>
/// <param name="state">The value to set the state of the overrides to.</param>
public void SetAllOverridesTo(bool state)
{
SetOverridesTo(parameterList, state);
}
/// <summary>
/// Sets the override state of the given parameters on this component to a given value.
/// </summary>
/// <param name="state">The value to set the state of the overrides to.</param>
internal void SetOverridesTo(IEnumerable<VolumeParameter> enumerable, bool state)
{
foreach (var prop in enumerable)
{
prop.overrideState = state;
var t = prop.GetType();
if (VolumeParameter.IsObjectParameter(t))
{
// This method won't be called a lot but this is sub-optimal, fix me
var innerParams = (ReadOnlyCollection<VolumeParameter>)
t.GetProperty("parameters", BindingFlags.NonPublic | BindingFlags.Instance)
.GetValue(prop, null);
if (innerParams != null)
SetOverridesTo(innerParams, state);
}
}
}
/// <summary>
/// Returns true if any of the volume properites has been overridden.
/// </summary>
/// <returns>True if any of the volume properites has been overridden.</returns>
public bool AnyPropertiesIsOverridden()
{
for (int i = 0; i < parameterList.Length; ++i)
{
if (parameterList[i].overrideState)
return true;
}
return false;
}
/// <summary>
/// Computes a hash of the current state of every parameter on this component
/// (values and override flags). Intended for change detection — for example,
/// invalidating a cached render target when any parameter changes.
/// </summary>
/// <remarks>
/// This value mutates as parameters change, so it must not be used as a key in
/// a <see cref="System.Collections.Generic.Dictionary{TKey,TValue}"/>,
/// <see cref="System.Collections.Generic.HashSet{T}"/>, or any other structure
/// that assumes a stable hash. Use <see cref="object.GetHashCode"/> for that.
/// </remarks>
/// <returns>A hash that changes whenever any parameter's value or override state changes.</returns>
public int GetStateHash()
{
var hash = HashFNV1A32.Create();
for (int i = 0; i < parameterList.Length; i++)
hash.Append(parameterList[i].GetHashCode());
return hash.value;
}
/// <summary>
/// Unity calls this method before the object is destroyed.
/// </summary>
protected virtual void OnDestroy() => Release();
/// <summary>
/// Releases all the allocated resources.
/// </summary>
public void Release()
{
if (parameterList == null)
return;
for (int i = 0; i < parameterList.Length; i++)
{
if (parameterList[i] != null)
parameterList[i].Release();
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 556096baecf4aeb4e9f0d3efce77e08f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using Unity.Scripting.LifecycleManagement;
namespace UnityEngine.Rendering
{
#if UNITY_ENABLE_CHECKS
internal static class VolumeDebugData
{
[NoAutoStaticsCleanup] // Cache for reflection data, no need to reset
static Lazy<Dictionary<int, string>> debugIds = new(() => new Dictionary<int, string>());
internal static string GetVolumeParameterDebugId(VolumeParameter parameter)
{
return debugIds.Value.TryGetValue(parameter.fieldHash, out var debugId) ? debugId : string.Empty;
}
internal static void AddVolumeParameterDebugId(VolumeParameter parameter, FieldInfo field)
{
var fieldHash = field.GetHashCode();
parameter.fieldHash = fieldHash;
if (debugIds.Value.ContainsKey(fieldHash))
return;
var displayInfo = field.GetCustomAttribute<DisplayInfoAttribute>(true);
var debugId = displayInfo != null ? displayInfo.name : field.Name;
#if UNITY_EDITOR
debugId = UnityEditor.ObjectNames.NicifyVariableName(debugId); // In the editor, make the name more readable
#endif
debugIds.Value.Add(fieldHash, debugId);
}
}
#endif
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: a359de1dc98b4f1db3fffb9601eb785b
timeCreated: 1743511791
@@ -0,0 +1,935 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using Unity.Profiling;
using UnityEngine.Assertions;
#if UNITY_EDITOR
using UnityEditor;
using UnityEditor.Rendering;
#endif
namespace UnityEngine.Rendering
{
/// <summary>
/// The <see cref="VolumeManager"/> is a global manager responsible for tracking and managing all Volume settings across the currently loaded Scenes.
/// It handles interpolation and blending of Volume settings at runtime, ensuring smooth transitions between different states of the volumes.
/// This includes managing post-processing effects, lighting settings, and other environmental effects based on volume profiles.
/// </summary>
/// <remarks>
///
/// The <see cref="VolumeManager"/> is initialized with two VolumeProfiles:
/// 1. The default VolumeProfile defined in the Graphics Settings.
/// 2. The default VolumeProfile defined in the Quality Settings.
///
/// These profiles represent the baseline state of all volume parameters, and the VolumeManager interpolates values between them to create a final blended VolumeStack for each camera.
/// Every frame, the VolumeManager updates the parameters of local and global VolumeComponents attached to game objects and ensures that the correct interpolation is applied across different volumes.
/// The VolumeManager acts as the central "point of truth" for all VolumeComponent parameters in a scene.
/// It provides default states for volume settings and dynamically interpolates between different VolumeProfiles to manage changes during runtime. This system is used to handle dynamic environmental and post-processing effects in Unity, ensuring smooth transitions across scene changes and camera views.
///
/// The VolumeManager integrates seamlessly with Unity's Scriptable Render Pipelines, applying the appropriate settings for rendering effects such as lighting, bloom, exposure, etc., in real time.
/// </remarks>
/// <seealso cref="Volume"/>
/// <seealso cref="VolumeProfile"/>
/// <seealso cref="VolumeStack"/>
/// <seealso cref="VolumeComponent"/>
/// <seealso cref="VolumeParameter"/>
/// <seealso cref="QualitySettings"/>
/// <seealso cref="GraphicsSettings"/>
public sealed partial class VolumeManager
{
static readonly ProfilerMarker k_ProfilerMarkerInitialize = new ("VolumeManager.Initialize");
static readonly ProfilerMarker k_ProfilerMarkerInitializeBaseTypesArray = new ("VolumeManager.InitializeBaseTypesArray");
static readonly ProfilerMarker k_ProfilerMarkerUpdate = new ("VolumeManager.Update");
static readonly ProfilerMarker k_ProfilerMarkerReplaceData = new ("VolumeManager.ReplaceData");
static readonly ProfilerMarker k_ProfilerMarkerEvaluateVolumeDefaultState = new ("VolumeManager.EvaluateVolumeDefaultState");
static readonly Lazy<VolumeManager> s_Instance = new Lazy<VolumeManager>(() => new VolumeManager());
/// <summary>
/// The current singleton instance of <see cref="VolumeManager"/>.
/// </summary>
public static VolumeManager instance => s_Instance.Value;
/// <summary>
/// A reference to the main <see cref="VolumeStack"/>.
/// </summary>
/// <seealso cref="VolumeStack"/>
public VolumeStack stack { get; set; }
/// <summary>
/// The current list of all available types that derive from <see cref="VolumeComponent"/>.
/// </summary>
[Obsolete("Please use baseComponentTypeArray instead. #from(2021.2)")]
public IEnumerable<Type> baseComponentTypes => baseComponentTypeArray;
static readonly Dictionary<Type, List<(string, Type)>> s_SupportedVolumeComponentsForRenderPipeline = new();
internal List<(string, Type)> GetVolumeComponentsForDisplay(Type currentPipelineAssetType)
{
if (currentPipelineAssetType == null)
return new List<(string, Type)>();
if (!currentPipelineAssetType.IsSubclassOf(typeof(RenderPipelineAsset)))
throw new ArgumentException(nameof(currentPipelineAssetType));
if (s_SupportedVolumeComponentsForRenderPipeline.TryGetValue(currentPipelineAssetType, out var supportedVolumeComponents))
return supportedVolumeComponents;
if (baseComponentTypeArray == null)
InitializeBaseTypesArray();
supportedVolumeComponents = BuildVolumeComponentDisplayList(baseComponentTypeArray);
s_SupportedVolumeComponentsForRenderPipeline[currentPipelineAssetType] = supportedVolumeComponents;
return supportedVolumeComponents;
}
internal bool TryGetVolumePathAndType(Type type, out (string path, Type t) result)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
string path = string.Empty;
bool skipComponent = false;
// Look for the attributes of this volume component and decide how is added and if it needs to be skipped
var attrs = type.GetCustomAttributes(false);
foreach (var attr in attrs)
{
switch (attr)
{
case VolumeComponentMenu attrMenu:
{
path = attrMenu.menu;
break;
}
case HideInInspector:
case ObsoleteAttribute:
skipComponent = true;
break;
}
}
if (skipComponent)
{
result = (string.Empty, type);
return false;
}
// If no attribute or in case something went wrong when grabbing it, fallback to a
// beautified class name
if (string.IsNullOrEmpty(path))
{
#if UNITY_EDITOR
path = ObjectNames.NicifyVariableName(type.Name);
#else
path = type.Name;
#endif
}
result = (path, type);
return true;
}
List<(string, Type)> BuildVolumeComponentDisplayList(Type[] types)
{
if (types == null)
throw new ArgumentNullException(nameof(types));
var volumes = new List<(string, Type)>();
foreach (var t in types)
{
if (TryGetVolumePathAndType(t, out var result))
volumes.Add(result);
}
volumes.Sort((a, b) => string.Compare(a.Item1, b.Item1));
return volumes;
}
Type[] m_BaseComponentTypeArray;
/// <summary>
/// The current list of all available types that derive from <see cref="VolumeComponent"/>.
/// </summary>
public Type[] baseComponentTypeArray
{
get
{
if (isInitialized)
return m_BaseComponentTypeArray;
throw new InvalidOperationException($"{nameof(VolumeManager)}.{nameof(instance)}.{nameof(baseComponentTypeArray)} cannot be called before the {nameof(VolumeManager)} is initialized. (See {nameof(VolumeManager)}.{nameof(instance)}.{nameof(isInitialized)} and {nameof(RenderPipelineManager)} for creation callback).");
}
internal set => m_BaseComponentTypeArray = value; // internal only for tests
}
/// <summary>
/// Global default profile that provides default values for volume components. VolumeManager applies
/// this profile to its internal component default state first, before <see cref="qualityDefaultProfile"/>
/// and <see cref="customDefaultProfiles"/>.
/// </summary>
public VolumeProfile globalDefaultProfile { get; private set; }
/// <summary>
/// Quality level specific volume profile that is applied to the default state after
/// <see cref="globalDefaultProfile"/> and before <see cref="customDefaultProfiles"/>.
/// </summary>
public VolumeProfile qualityDefaultProfile { get; private set; }
/// <summary>
/// Collection of additional default profiles that can be used to override default values for volume components
/// in a way that doesn't cause any overhead at runtime. Unity applies these Volume Profiles to its internal
/// component default state after <see cref="globalDefaultProfile"/> and <see cref="qualityDefaultProfile"/>.
/// The custom profiles are applied in the order that they appear in the collection.
/// </summary>
public ReadOnlyCollection<VolumeProfile> customDefaultProfiles { get; private set; }
private readonly VolumeCollection m_VolumeCollection = new VolumeCollection();
// Internal list of default state for each component type - this is used to reset component
// states on update instead of having to implement a Reset method on all components (which
// would be error-prone)
// The "Default State" is evaluated as follows:
// Default-constructed VolumeComponents (VolumeParameter values coming from code)
// + Values from globalDefaultProfile
// + Values from qualityDefaultProfile
// + Values from customDefaultProfiles
// = Default State.
VolumeComponent[] m_ComponentsDefaultState;
// Flat list of every volume parameter in default state for faster per-frame stack reset.
internal VolumeParameter[] m_ParametersDefaultState;
/// <summary>
/// Retrieve the default state for a given VolumeComponent type. Default state is defined as
/// "default-constructed VolumeComponent + Default Profiles evaluated in order".
/// </summary>
/// <remarks>
/// If you want just the VolumeComponent with default-constructed values without overrides from
/// Default Profiles, use <see cref="ScriptableObject.CreateInstance(Type)"/>.
/// </remarks>
/// <param name="volumeComponentType">Type of VolumeComponent</param>
/// <returns>VolumeComponent in default state, or null if the type is not found</returns>
public VolumeComponent GetVolumeComponentDefaultState(Type volumeComponentType)
{
if (!typeof(VolumeComponent).IsAssignableFrom(volumeComponentType))
return null;
foreach (VolumeComponent component in m_ComponentsDefaultState)
{
if (component.GetType() == volumeComponentType)
return component;
}
return null;
}
// The default stack the volume manager uses.
// We cache this as users able to change the stack through code and
// we want to be able to switch to the default one through the ResetMainStack() function.
VolumeStack m_DefaultStack;
// List of stacks created through VolumeManager.
readonly List<VolumeStack> m_CreatedVolumeStacks = new();
// Internal for tests
internal VolumeManager()
{
}
// Note: The "isInitialized" state and explicit Initialize/Deinitialize are only required because VolumeManger
// is a singleton whose lifetime exceeds that of RenderPipelines. Thus it must be initialized & deinitialized
// explicitly by the RP to handle pipeline switch gracefully. It would be better to get rid of singletons and
// have the RP own the class instance instead.
/// <summary>
/// Returns whether <see cref="VolumeManager.Initialize(VolumeProfile,VolumeProfile)"/> has been called, and the
/// class is in valid state. It is not valid to use VolumeManager before this returns true.
/// </summary>
public bool isInitialized { get; private set; }
/// <summary>
/// Initialize VolumeManager with specified global and quality default volume profiles that are used to evaluate
/// the default state of all VolumeComponents. Should be called from <see cref="RenderPipeline"/> constructor.
/// </summary>
/// <param name="globalDefaultVolumeProfile">Global default volume profile.</param>
/// <param name="qualityDefaultVolumeProfile">Quality default volume profile.</param>
public void Initialize(VolumeProfile globalDefaultVolumeProfile = null, VolumeProfile qualityDefaultVolumeProfile = null)
{
using var profilerScope = k_ProfilerMarkerInitialize.Auto();
Debug.Assert(!isInitialized);
Debug.Assert(m_CreatedVolumeStacks.Count == 0);
InitializeBaseTypesArray(globalDefaultVolumeProfile);
InitializeInternal(globalDefaultVolumeProfile, qualityDefaultVolumeProfile);
}
void InitializeBaseTypesArray(VolumeProfile globalDefaultVolumeProfile = null)
{
using var profilerScope = k_ProfilerMarkerInitializeBaseTypesArray.Auto();
#if !UNITY_EDITOR
if (globalDefaultVolumeProfile == null)
{
var defaultVolumeProfileSettings = GraphicsSettings.GetRenderPipelineSettings<IDefaultVolumeProfileAsset>();
globalDefaultVolumeProfile = defaultVolumeProfileSettings?.defaultVolumeProfile;
}
#endif
m_BaseComponentTypeArray = GetBaseComponentTypesForPipeline(GraphicsSettings.currentRenderPipelineAssetType, globalDefaultVolumeProfile);
}
//This is called by test where the basetypes are tuned for the purpose of the test.
internal void InitializeInternal(VolumeProfile globalDefaultVolumeProfile = null, VolumeProfile qualityDefaultVolumeProfile = null)
{
InitializeVolumeComponents();
globalDefaultProfile = globalDefaultVolumeProfile;
qualityDefaultProfile = qualityDefaultVolumeProfile;
EvaluateVolumeDefaultState();
m_DefaultStack = CreateStackInternal();
stack = m_DefaultStack;
isInitialized = true;
}
/// <summary>
/// Deinitialize VolumeManager. Should be called from <see cref="RenderPipeline.Dispose()"/>.
/// </summary>
public void Deinitialize()
{
Debug.Assert(isInitialized);
DestroyStack(m_DefaultStack);
m_DefaultStack = null;
foreach (var s in m_CreatedVolumeStacks)
s.Dispose();
m_CreatedVolumeStacks.Clear();
baseComponentTypeArray = null;
globalDefaultProfile = null;
qualityDefaultProfile = null;
customDefaultProfiles = null;
isInitialized = false;
}
/// <summary>
/// Assign the given VolumeProfile as the global default profile and update the default component state.
/// </summary>
/// <param name="profile">The VolumeProfile to use as the global default profile.</param>
public void SetGlobalDefaultProfile(VolumeProfile profile)
{
m_BaseComponentTypeArray = GetBaseComponentTypesForPipeline(GraphicsSettings.currentRenderPipelineAssetType, profile);
globalDefaultProfile = profile;
EvaluateVolumeDefaultState();
}
/// <summary>
/// Assign the given VolumeProfile as the quality default profile and update the default component state.
/// </summary>
/// <param name="profile">The VolumeProfile to use as the quality level default profile.</param>
public void SetQualityDefaultProfile(VolumeProfile profile)
{
qualityDefaultProfile = profile;
EvaluateVolumeDefaultState();
}
/// <summary>
/// Assign the given VolumeProfiles as custom default profiles and update the default component state.
/// </summary>
/// <param name="profiles">List of VolumeProfiles to set as default profiles, or null to clear them.</param>
public void SetCustomDefaultProfiles(List<VolumeProfile> profiles)
{
var validProfiles = profiles ?? new List<VolumeProfile>();
validProfiles.RemoveAll(x => x == null);
if (globalDefaultProfile == null && validProfiles.Count > 0)
globalDefaultProfile = validProfiles[0];
customDefaultProfiles = new ReadOnlyCollection<VolumeProfile>(validProfiles);
EvaluateVolumeDefaultState();
}
/// <summary>
/// Call when a VolumeProfile is modified to trigger default state update if necessary.
/// </summary>
/// <param name="profile">VolumeProfile that has changed.</param>
public void OnVolumeProfileChanged(VolumeProfile profile)
{
if (!isInitialized)
return;
if (globalDefaultProfile == profile ||
qualityDefaultProfile == profile ||
(customDefaultProfiles != null && customDefaultProfiles.Contains(profile)))
EvaluateVolumeDefaultState();
}
/// <summary>
/// Call when a VolumeComponent is modified to trigger default state update if necessary.
/// </summary>
/// <param name="component">VolumeComponent that has changed.</param>
public void OnVolumeComponentChanged(VolumeComponent component)
{
var defaultProfiles = new List<VolumeProfile> { globalDefaultProfile, globalDefaultProfile };
if (customDefaultProfiles != null)
defaultProfiles.AddRange(customDefaultProfiles);
foreach (var defaultProfile in defaultProfiles)
{
if (defaultProfile.components.Contains(component))
{
EvaluateVolumeDefaultState();
return;
}
}
}
/// <summary>
/// Creates and returns a new <see cref="VolumeStack"/> to use when you need to store
/// the result of the Volume blending pass in a separate stack.
/// </summary>
/// <returns>A new <see cref="VolumeStack"/> instance with freshly loaded components.</returns>
/// <seealso cref="VolumeStack"/>
/// <seealso cref="Update(VolumeStack,Transform,LayerMask)"/>
public VolumeStack CreateStack()
{
if (!isInitialized)
throw new InvalidOperationException($"{nameof(VolumeManager)}.{nameof(instance)}.{nameof(CreateStack)}() cannot be called before the {nameof(VolumeManager)} is initialized. (See {nameof(VolumeManager)}.{nameof(instance)}.{nameof(isInitialized)} and {nameof(RenderPipelineManager)} for creation callback).");
return CreateStackInternal();
}
VolumeStack CreateStackInternal()
{
var stack = new VolumeStack();
stack.Reload(m_BaseComponentTypeArray);
m_CreatedVolumeStacks.Add(stack);
return stack;
}
/// <summary>
/// Resets the main stack to be the default one.
/// Call this function if you've assigned the main stack to something other than the default one.
/// </summary>
public void ResetMainStack()
{
stack = m_DefaultStack;
}
/// <summary>
/// Destroy a Volume Stack
/// </summary>
/// <param name="stack">Volume Stack that needs to be destroyed.</param>
public void DestroyStack(VolumeStack stack)
{
m_CreatedVolumeStacks.Remove(stack);
stack.Dispose();
}
/// <summary>
/// Returns the VolumeComponent types compatible with the given pipeline asset type. Pure lookup — does
/// not touch VolumeManager state, safe to call for a pipeline that is not currently active.
/// In the editor, scans every VolumeComponent in the project via reflection so newly added types are
/// picked up. In a player, uses the components stored in the provided default volume profile.
/// </summary>
/// <param name="pipelineAssetType">The Pipeline Asset Type used to check if each VolumeComponent is supported.</param>
/// <param name="globalDefaultVolumeProfile">In a player build, the source of components to consider. Ignored in the editor.</param>
internal static Type[] GetBaseComponentTypesForPipeline(Type pipelineAssetType, VolumeProfile globalDefaultVolumeProfile = null)
{
#if UNITY_EDITOR
return GetBaseComponentTypesByReflection(pipelineAssetType);
#else
return GetBaseComponentTypesFromProfile(pipelineAssetType, globalDefaultVolumeProfile);
#endif
}
#if UNITY_EDITOR
// Editor-only: scan every VolumeComponent type in the project via reflection. Slow, used during
// initialization, on domain reload, or whenever we need an authoritative list independent of any profile.
static Type[] GetBaseComponentTypesByReflection(Type pipelineAssetType)
{
using (ListPool<Type>.Get(out var list))
{
foreach (var t in CoreUtils.GetAllTypesDerivedFrom<VolumeComponent>())
{
if (t.IsAbstract)
continue;
if (!SupportedOnRenderPipelineAttribute.IsTypeSupportedOnRenderPipeline(t, pipelineAssetType))
continue;
if (t.GetCustomAttribute<ObsoleteAttribute>() != null)
continue;
list.Add(t);
}
return list.ToArray();
}
}
#else
// Player builds can't use reflection here, so we read the supported types from the components already
// present in the global default volume profile shipped with the build.
static Type[] GetBaseComponentTypesFromProfile(Type pipelineAssetType, VolumeProfile globalDefaultVolumeProfile)
{
if (globalDefaultVolumeProfile == null)
return Array.Empty<Type>();
using (ListPool<Type>.Get(out var list))
{
foreach (var comp in globalDefaultVolumeProfile.components)
{
if (comp == null)
continue;
var componentType = comp.GetType();
if (!SupportedOnRenderPipelineAttribute.IsTypeSupportedOnRenderPipeline(componentType, pipelineAssetType))
continue;
list.Add(componentType);
}
return list.ToArray();
}
}
#endif
internal void InitializeVolumeComponents()
{
if (m_BaseComponentTypeArray == null || m_BaseComponentTypeArray.Length == 0)
return;
// Call deprecated static Init method if present
var flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
foreach (var type in m_BaseComponentTypeArray)
{
var initMethod = type.GetMethod("Init", flags);
if (initMethod != null)
{
initMethod.Invoke(null, null);
}
}
}
// Evaluate static default values for VolumeComponents, which is the baseline to reset the values to at the start of Update.
void EvaluateVolumeDefaultState()
{
if (m_BaseComponentTypeArray == null || m_BaseComponentTypeArray.Length == 0)
{
m_ComponentsDefaultState = Array.Empty<VolumeComponent>();
m_ParametersDefaultState = Array.Empty<VolumeParameter>();
return;
}
using var profilerScope = k_ProfilerMarkerEvaluateVolumeDefaultState.Auto();
// TODO consider if the "component default values" array should be kept in memory separately. Creating the
// instances is likely the slowest operation here, so doing that would mean it can only be done once in
// Initialize() and the default state can be updated a lot quicker.
// First, default-construct all VolumeComponents
using var _ = ListPool<VolumeComponent>.Get(out var componentsDefaultStateList);
foreach (var type in m_BaseComponentTypeArray)
{
componentsDefaultStateList.Add((VolumeComponent) ScriptableObject.CreateInstance(type));
}
void ApplyDefaultProfile(VolumeProfile profile)
{
if (profile == null)
return;
for (int i = 0; i < profile.components.Count; i++)
{
var profileComponent = profile.components[i];
var defaultStateComponent = componentsDefaultStateList.FirstOrDefault(
x => x.GetType() == profileComponent.GetType());
if (defaultStateComponent != null && profileComponent.active)
{
// Ideally we would just call SetValue here. However, there are custom non-trivial
// implementations of VolumeParameter.Interp() (such as DiffusionProfileList) that make it
// necessary for us to call the it. This ensures the new DefaultProfile behavior works
// consistently with the old HDRP implementation where the Default Profile was implemented as
// a regular global volume inside the scene.
profileComponent.Override(defaultStateComponent, 1.0f);
}
}
}
ApplyDefaultProfile(globalDefaultProfile); // Apply global default profile first
ApplyDefaultProfile(qualityDefaultProfile); // Apply quality default profile second
if (customDefaultProfiles != null) // Finally, apply custom default profiles in order
foreach (var profile in customDefaultProfiles)
ApplyDefaultProfile(profile);
// Build the flat parametersDefaultState list for fast per-frame resets
var parametersDefaultStateList = new List<VolumeParameter>();
foreach (var component in componentsDefaultStateList)
{
parametersDefaultStateList.AddRange(component.parameters);
}
m_ComponentsDefaultState = componentsDefaultStateList.ToArray();
m_ParametersDefaultState = parametersDefaultStateList.ToArray();
// All properties in stacks must be reset because the default state has changed
foreach (var s in m_CreatedVolumeStacks)
{
s.requiresReset = true;
s.requiresResetForAllProperties = true;
}
}
/// <summary>
/// Registers a new Volume in the manager. Unity does this automatically when a new Volume is
/// enabled, or its layer changes, but you can use this function to force-register a Volume
/// that is currently disabled.
/// </summary>
/// <param name="volume">The volume to register.</param>
/// <seealso cref="Unregister"/>
public void Register(Volume volume)
{
m_VolumeCollection.Register(volume, volume.gameObject.layer);
}
/// <summary>
/// Unregisters a Volume from the manager. Unity does this automatically when a Volume is
/// disabled or goes out of scope, but you can use this function to force-unregister a Volume
/// that you added manually while it was disabled.
/// </summary>
/// <param name="volume">The Volume to unregister.</param>
/// <seealso cref="Register"/>
public void Unregister(Volume volume)
{
m_VolumeCollection.Unregister(volume, volume.gameObject.layer);
}
/// <summary>
/// Checks if a <see cref="VolumeComponent"/> is active in a given LayerMask.
/// </summary>
/// <typeparam name="T">A type derived from <see cref="VolumeComponent"/></typeparam>
/// <param name="layerMask">The LayerMask to check against</param>
/// <returns><c>true</c> if the component is active in the LayerMask, <c>false</c>
/// otherwise.</returns>
public bool IsComponentActiveInMask<T>(LayerMask layerMask)
where T : VolumeComponent
{
return m_VolumeCollection.IsComponentActiveInMask<T>(layerMask);
}
internal void SetLayerDirty(int layer)
{
m_VolumeCollection.SetLayerIndexDirty(layer);
}
internal void UpdateVolumeLayer(Volume volume, int prevLayer, int newLayer)
{
m_VolumeCollection.ChangeLayer(volume, prevLayer, newLayer);
}
#if UNITY_ENABLE_CHECKS
internal bool renderingDebuggerAttached { get; set; }
internal event Action<VolumeStack, Camera> beginVolumeStackUpdate;
internal event Action<VolumeStack, Camera> endVolumeStackUpdate;
internal event Action<VolumeStack, Volume, float> overrideVolumeStackData;
#endif
// Go through all listed components and lerp overridden values in the global state
void OverrideData(VolumeStack stack, Volume volume, float interpFactor)
{
var components = volume.profileRef.components;
var numComponents = components.Count;
for (int i = 0; i < numComponents; i++)
{
var component = components[i];
if (!component.active)
continue;
var state = stack.GetComponent(component.GetType());
if (state != null)
{
component.Override(state, interpFactor);
}
}
#if UNITY_ENABLE_CHECKS
if (renderingDebuggerAttached)
overrideVolumeStackData?.Invoke(stack, volume, interpFactor);
#endif
}
// Faster version of OverrideData to force replace values in the global state.
// NOTE: As an optimization, only the VolumeParameters with overrideState=true are reset. All other parameters
// are assumed to be in their correct default state so no reset is necessary.
internal void ReplaceData(VolumeStack stack)
{
using var profilerScope = k_ProfilerMarkerReplaceData.Auto();
var stackParams = stack.parameters;
bool resetAllParameters = stack.requiresResetForAllProperties;
int count = stackParams.Length;
Debug.Assert(count == m_ParametersDefaultState.Length);
for (int i = 0; i < count; i++)
{
var stackParam = stackParams[i];
if (stackParam.overrideState || resetAllParameters) // Only reset the parameters that have been overriden by a scene volume
{
stackParam.overrideState = false;
stackParam.SetValue(m_ParametersDefaultState[i]);
}
}
stack.requiresResetForAllProperties = false;
}
/// <summary>
/// Checks component default state. This is only used in the editor to handle entering and exiting play mode
/// because the instances created during playmode are automatically destroyed.
/// </summary>
[Conditional("UNITY_EDITOR")]
public void CheckDefaultVolumeState()
{
if (m_ComponentsDefaultState == null || (m_ComponentsDefaultState.Length > 0 && m_ComponentsDefaultState[0] == null))
{
EvaluateVolumeDefaultState();
}
}
/// <summary>
/// Checks the state of a given stack. This is only used in the editor to handle entering and exiting play mode
/// because the instances created during playmode are automatically destroyed.
/// </summary>
/// <param name="stack">The stack to check.</param>
[Conditional("UNITY_EDITOR")]
public void CheckStack(VolumeStack stack)
{
if (stack.components == null)
{
stack.Reload(baseComponentTypeArray);
return;
}
foreach (var kvp in stack.components)
{
if (kvp.Key == null || kvp.Value == null)
{
stack.Reload(baseComponentTypeArray);
return;
}
}
}
// Returns true if must execute Update() in full, and false if we can early exit.
bool CheckUpdateRequired(VolumeStack stack)
{
if (m_VolumeCollection.count == 0)
{
if (stack.requiresReset)
{
// Update the stack one more time in case there was a volume that just ceased to exist. This ensures
// the stack will return to default values correctly.
stack.requiresReset = false;
return true;
}
// There were no volumes last frame either, and stack has been returned to defaults, so no update is
// needed and we can early exit from Update().
return false;
}
stack.requiresReset = true; // Stack must be reset every frame whenever there are volumes present
return true;
}
/// <summary>
/// Updates the global state of the Volume manager. Unity usually calls this once per Camera
/// in the Update loop before rendering happens.
/// </summary>
/// <param name="trigger">A reference Transform to consider for positional Volume blending
/// </param>
/// <param name="layerMask">The LayerMask that the Volume manager uses to filter Volumes that it should consider
/// for blending.</param>
public void Update(Transform trigger, LayerMask layerMask)
{
Update(stack, trigger, layerMask);
}
/// <summary>
/// Updates the Volume manager and stores the result in a custom <see cref="VolumeStack"/>.
/// </summary>
/// <param name="stack">The stack to store the blending result into.</param>
/// <param name="trigger">A reference Transform to consider for positional Volume blending.
/// </param>
/// <param name="layerMask">The LayerMask that Unity uses to filter Volumes that it should consider
/// for blending.</param>
/// <seealso cref="VolumeStack"/>
public void Update(VolumeStack stack, Transform trigger, LayerMask layerMask)
{
using var profilerScope = k_ProfilerMarkerUpdate.Auto();
if (!isInitialized)
return;
Assert.IsNotNull(stack);
CheckDefaultVolumeState();
CheckStack(stack);
if (!CheckUpdateRequired(stack))
return;
// Start by resetting the global state to default values.
ReplaceData(stack);
bool onlyGlobal = trigger == null;
var triggerPos = onlyGlobal ? Vector3.zero : trigger.position;
// Sort the cached volume list(s) for the given layer mask if needed and return it
var volumes = GrabVolumes(layerMask);
Camera camera = null;
// Behavior should be fine even if camera is null
if (!onlyGlobal)
trigger.TryGetComponent<Camera>(out camera);
#if UNITY_ENABLE_CHECKS
if (renderingDebuggerAttached)
beginVolumeStackUpdate?.Invoke(stack, camera);
#endif
#if ENABLE_PHYSICS_MODULE
bool physicsBackendIsNone = Physics.GetCurrentIntegrationInfo().isFallback;
#endif
// Traverse all volumes
int numVolumes = volumes.Count;
for (int i = 0; i < numVolumes; i++)
{
Volume volume = volumes[i];
if (volume == null)
continue;
#if UNITY_EDITOR
// Skip volumes that aren't in the scene currently displayed in the scene view
if (!IsVolumeRenderedByCamera(volume, camera))
continue;
#endif
// Skip disabled volumes and volumes without any data or weight
if (!volume.enabled || volume.profileRef == null || volume.weight <= 0f)
continue;
// Global volumes always have influence
if (volume.isGlobal)
{
OverrideData(stack, volume, Mathf.Clamp01(volume.weight));
continue;
}
if (onlyGlobal)
continue;
// NOTE: Local volumes require physics module to be enabled
#if ENABLE_PHYSICS_MODULE
if (physicsBackendIsNone)
continue;
// If volume isn't global and has no collider, skip it as it's useless
var colliders = volume.colliders;
int numColliders = colliders.Count;
if (numColliders == 0)
continue;
// Find closest distance to volume, 0 means it's inside it
float closestDistanceSqr = float.PositiveInfinity;
for (int c = 0; c < numColliders; c++)
{
var collider = colliders[c];
if (!collider.enabled)
continue;
var closestPoint = collider.ClosestPoint(triggerPos);
var d = (closestPoint - triggerPos).sqrMagnitude;
if (d < closestDistanceSqr)
closestDistanceSqr = d;
}
float blendDistSqr = volume.blendDistance * volume.blendDistance;
// Volume has no influence, ignore it
// Note: Volume doesn't do anything when `closestDistanceSqr = blendDistSqr` but we
// can't use a >= comparison as blendDistSqr could be set to 0 in which case
// volume would have total influence
if (closestDistanceSqr > blendDistSqr)
continue;
// Volume has influence
float interpFactor = 1f;
if (blendDistSqr > 0f)
interpFactor = 1f - (closestDistanceSqr / blendDistSqr);
// No need to clamp01 the interpolation factor or weight as both are always in [0;1[ range
OverrideData(stack, volume, interpFactor * Mathf.Clamp01(volume.weight));
#endif
}
#if UNITY_ENABLE_CHECKS
if (renderingDebuggerAttached)
endVolumeStackUpdate?.Invoke(stack, camera);
#endif
}
/// <summary>
/// Get all volumes on a given layer mask sorted by influence.
/// </summary>
/// <param name="layerMask">The LayerMask that Unity uses to filter Volumes that it should consider.</param>
/// <returns>An array of volume.</returns>
public Volume[] GetVolumes(LayerMask layerMask)
{
var volumes = GrabVolumes(layerMask);
volumes.RemoveAll(v => v == null);
return volumes.ToArray();
}
List<Volume> GrabVolumes(LayerMask mask)
{
return m_VolumeCollection.GrabVolumes(mask);
}
static bool IsVolumeRenderedByCamera(Volume volume, Camera camera)
{
#if UNITY_EDITOR
// GameObject for default global volume may not belong to any scene, following check prevents it from being culled
if (!volume.cachedGameObject.scene.IsValid())
return true;
// IsGameObjectRenderedByCamera does not behave correctly when camera is null so we have to catch it here.
return camera == null || UnityEditor.SceneManagement.StageUtility.IsGameObjectRenderedByCamera(volume.cachedGameObject, camera);
#else
return true;
#endif
}
}
/// <summary>
/// A scope in which a Camera filters a Volume.
/// </summary>
[Obsolete("VolumeIsolationScope is deprecated, it does not have any effect anymore. #from(2021.1)")]
public struct VolumeIsolationScope : IDisposable
{
/// <summary>
/// Constructs a scope in which a Camera filters a Volume.
/// </summary>
/// <param name="unused">Unused parameter.</param>
public VolumeIsolationScope(bool unused) { }
/// <summary>
/// Stops the Camera from filtering a Volume.
/// </summary>
void IDisposable.Dispose() { }
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: f709aacbf8d0b0048889f52315d67d58
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: d53242bc2649d524aa42f2a84eb077b2
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,391 @@
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine.Assertions;
namespace UnityEngine.Rendering
{
/// <summary>
/// An Asset which holds a set of settings to use with a <see cref="Volume"/>.
/// </summary>
[PipelineHelpURL("UniversalRenderPipelineAsset","urp/Volume-Profile")]
[PipelineHelpURL("HDRenderPipelineAsset","create-a-volume-profile")]
[Icon("Packages/com.unity.render-pipelines.core/Editor/Icons/Processed/VolumeProfile Icon.asset")]
public sealed class VolumeProfile : ScriptableObject
{
/// <summary>
/// A list of every setting that this Volume Profile stores.
/// </summary>
public List<VolumeComponent> components = new List<VolumeComponent>();
/// <summary>
/// **Note**: For Internal Use Only<br/>
/// A dirty check used to redraw the profile inspector when something has changed. This is
/// currently only used in the editor.
/// </summary>
[Obsolete("This field was only public for editor access. #from(6000.0)")]
public bool isDirty
{
get => dirtyState != DirtyState.None;
set
{
if (value)
dirtyState |= DirtyState.Other;
else
dirtyState &= ~DirtyState.Other;
}
}
[Flags] internal enum DirtyState
{
None = 0,
DirtyByComponentChange = 1,
DirtyByProfileReset = 2,
Other = 4
}
internal DirtyState dirtyState;
void OnEnable()
{
// Make sure every setting is valid. If a profile holds a script that doesn't exist
// anymore, nuke it to keep the volume clean. Note that if you delete a script that is
// currently in use in a volume you'll still get a one-time error in the console, it's
// harmless and happens because Unity does a redraw of the editor (and thus the current
// frame) before the recompilation step.
components.RemoveAll(x => x == null);
}
// The lifetime of ScriptableObjects is different from MonoBehaviours. When the last reference to a
// VolumeProfile goes out of scope (e.g. when a scene containing Volume components is unloaded), Unity will call
// OnDisable() on the VolumeProfile. We need to release the internal resources in this case to avoid leaks.
internal void OnDisable()
{
if (components == null)
return;
for (int i = 0; i < components.Count; i++)
{
if (components[i] != null)
components[i].Release();
}
}
/// <summary>
/// Resets the dirty state of the Volume Profile. Unity uses this to force-refresh and redraw the
/// Volume Profile editor when you modify the Asset via script instead of the Inspector.
/// </summary>
public void Reset()
=> dirtyState |= DirtyState.DirtyByProfileReset;
/// <summary>
/// Adds a <see cref="VolumeComponent"/> to this Volume Profile.
/// </summary>
/// <remarks>
/// You can only have a single component of the same type per Volume Profile.
/// </remarks>
/// <typeparam name="T">A type of <see cref="VolumeComponent"/>.</typeparam>
/// <param name="overrides">Specifies whether Unity should automatically override all the settings when
/// you add a <see cref="VolumeComponent"/> to the Volume Profile.</param>
/// <returns>The instance for the given type that you added to the Volume Profile</returns>
/// <seealso cref="Add"/>
public T Add<T>(bool overrides = false)
where T : VolumeComponent
{
return (T)Add(typeof(T), overrides);
}
/// <summary>
/// Adds a <see cref="VolumeComponent"/> to this Volume Profile.
/// </summary>
/// <remarks>
/// You can only have a single component of the same type per Volume Profile.
/// </remarks>
/// <param name="type">A type that inherits from <see cref="VolumeComponent"/>.</param>
/// <param name="overrides">Specifies whether Unity should automatically override all the settings when
/// you add a <see cref="VolumeComponent"/> to the Volume Profile.</param>
/// <returns>The instance created for the given type that has been added to the profile</returns>
/// <seealso cref="Add{T}"/>
public VolumeComponent Add(Type type, bool overrides = false)
{
if (Has(type))
throw new InvalidOperationException("Component already exists in the volume");
var component = (VolumeComponent)CreateInstance(type);
#if UNITY_EDITOR
component.hideFlags = HideFlags.HideInInspector | HideFlags.HideInHierarchy;
component.name = type.Name;
#endif
component.SetAllOverridesTo(overrides);
components.Add(component);
dirtyState |= DirtyState.DirtyByComponentChange;
return component;
}
/// <summary>
/// Removes a <see cref="VolumeComponent"/> from this Volume Profile.
/// </summary>
/// <remarks>
/// This method does nothing if the type does not exist in the Volume Profile.
/// </remarks>
/// <typeparam name="T">A type of <see cref="VolumeComponent"/>.</typeparam>
/// <seealso cref="Remove"/>
public void Remove<T>()
where T : VolumeComponent
{
Remove(typeof(T));
}
/// <summary>
/// Removes a <see cref="VolumeComponent"/> from this Volume Profile.
/// </summary>
/// <remarks>
/// This method does nothing if the type does not exist in the Volume Profile.
/// </remarks>
/// <param name="type">A type that inherits from <see cref="VolumeComponent"/>.</param>
/// <seealso cref="Remove{T}"/>
public void Remove(Type type)
{
int toRemove = -1;
for (int i = 0; i < components.Count; i++)
{
if (components[i].GetType() == type)
{
toRemove = i;
break;
}
}
if (toRemove >= 0)
{
components.RemoveAt(toRemove);
dirtyState |= DirtyState.DirtyByComponentChange;
}
}
/// <summary>
/// Checks if this Volume Profile contains the <see cref="VolumeComponent"/> you pass in.
/// </summary>
/// <typeparam name="T">A type of <see cref="VolumeComponent"/>.</typeparam>
/// <returns><c>true</c> if the <see cref="VolumeComponent"/> exists in the Volume Profile,
/// <c>false</c> otherwise.</returns>
/// <seealso cref="Has"/>
/// <seealso cref="HasSubclassOf"/>
public bool Has<T>()
where T : VolumeComponent
{
return Has(typeof(T));
}
/// <summary>
/// Checks if this Volume Profile contains the <see cref="VolumeComponent"/> you pass in.
/// </summary>
/// <param name="type">A type that inherits from <see cref="VolumeComponent"/>.</param>
/// <returns><c>true</c> if the <see cref="VolumeComponent"/> exists in the Volume Profile,
/// <c>false</c> otherwise.</returns>
/// <seealso cref="Has{T}"/>
/// <seealso cref="HasSubclassOf"/>
public bool Has(Type type)
{
foreach (var component in components)
{
if (component.GetType() == type)
return true;
}
return false;
}
/// <summary>
/// Checks if this Volume Profile contains the <see cref="VolumeComponent"/>, which is a subclass of <paramref name="type"/>,
/// that you pass in.
/// </summary>
/// <param name="type">A type that inherits from <see cref="VolumeComponent"/>.</param>
/// <returns><c>true</c> if the <see cref="VolumeComponent"/> exists in the Volume Profile,
/// <c>false</c> otherwise.</returns>
/// <seealso cref="Has"/>
/// <seealso cref="Has{T}"/>
public bool HasSubclassOf(Type type)
{
foreach (var component in components)
{
if (component.GetType().IsSubclassOf(type))
return true;
}
return false;
}
/// <summary>
/// Gets the <see cref="VolumeComponent"/> of the specified type, if it exists.
/// </summary>
/// <typeparam name="T">A type of <see cref="VolumeComponent"/>.</typeparam>
/// <param name="component">The output argument that contains the <see cref="VolumeComponent"/>
/// or <c>null</c>.</param>
/// <returns><c>true</c> if the <see cref="VolumeComponent"/> is in the Volume Profile,
/// <c>false</c> otherwise.</returns>
/// <seealso cref="TryGet{T}(Type, out T)"/>
/// <seealso cref="TryGetSubclassOf{T}"/>
/// <seealso cref="TryGetAllSubclassOf{T}"/>
public bool TryGet<T>(out T component)
where T : VolumeComponent
{
return TryGet(typeof(T), out component);
}
/// <summary>
/// Gets the <see cref="VolumeComponent"/> of the specified type, if it exists.
/// </summary>
/// <typeparam name="T">A type of <see cref="VolumeComponent"/></typeparam>
/// <param name="type">A type that inherits from <see cref="VolumeComponent"/>.</param>
/// <param name="component">The output argument that contains the <see cref="VolumeComponent"/>
/// or <c>null</c>.</param>
/// <returns><c>true</c> if the <see cref="VolumeComponent"/> is in the Volume Profile,
/// <c>false</c> otherwise.</returns>
/// <seealso cref="TryGet{T}(out T)"/>
/// <seealso cref="TryGetSubclassOf{T}"/>
/// <seealso cref="TryGetAllSubclassOf{T}"/>
public bool TryGet<T>(Type type, out T component)
where T : VolumeComponent
{
component = null;
foreach (var comp in components)
{
if (comp.GetType() == type)
{
component = (T)comp;
return true;
}
}
return false;
}
/// <summary>
/// Gets the <see cref="VolumeComponent"/>, which is a subclass of <paramref name="type"/>, if
/// it exists.
/// </summary>
/// <typeparam name="T">A type of <see cref="VolumeComponent"/>.</typeparam>
/// <param name="type">A type that inherits from <see cref="VolumeComponent"/>.</param>
/// <param name="component">The output argument that contains the <see cref="VolumeComponent"/>
/// or <c>null</c>.</param>
/// <returns><c>true</c> if the <see cref="VolumeComponent"/> is in the Volume Profile,
/// <c>false</c> otherwise.</returns>
/// <seealso cref="TryGet{T}(Type, out T)"/>
/// <seealso cref="TryGet{T}(out T)"/>
/// <seealso cref="TryGetAllSubclassOf{T}"/>
public bool TryGetSubclassOf<T>(Type type, out T component)
where T : VolumeComponent
{
component = null;
foreach (var comp in components)
{
if (comp.GetType().IsSubclassOf(type))
{
component = (T)comp;
return true;
}
}
return false;
}
/// <summary>
/// Gets all the <see cref="VolumeComponent"/> that are subclasses of the specified type,
/// if there are any.
/// </summary>
/// <typeparam name="T">A type of <see cref="VolumeComponent"/>.</typeparam>
/// <param name="type">A type that inherits from <see cref="VolumeComponent"/>.</param>
/// <param name="result">The output list that contains all the <see cref="VolumeComponent"/>
/// if any. Note that Unity does not clear this list.</param>
/// <returns><c>true</c> if any <see cref="VolumeComponent"/> have been found in the profile,
/// <c>false</c> otherwise.</returns>
/// <seealso cref="TryGet{T}(Type, out T)"/>
/// <seealso cref="TryGet{T}(out T)"/>
/// <seealso cref="TryGetSubclassOf{T}"/>
public bool TryGetAllSubclassOf<T>(Type type, List<T> result)
where T : VolumeComponent
{
Assert.IsNotNull(components);
int count = result.Count;
foreach (var comp in components)
{
if (comp.GetType().IsSubclassOf(type))
result.Add((T)comp);
}
return count != result.Count;
}
internal int GetComponentListHashCode()
{
unchecked
{
var hashCode = HashFNV1A32.Create();
for (int i = 0; i < components.Count; i++)
hashCode.Append(components[i].GetType().GetHashCode());
return hashCode.value;
}
}
/// <summary>
/// Computes a hash of the current state of every component on this profile
/// (the values and override flags of all their parameters).
/// Intended for change detection — for example, detecting that a Volume Profile
/// asset has been edited and a dependent cached resource must be rebuilt.
/// </summary>
/// <remarks>
/// This value mutates as parameters change, so it must not be used as a key in
/// a <see cref="System.Collections.Generic.Dictionary{TKey,TValue}"/>,
/// <see cref="System.Collections.Generic.HashSet{T}"/>, or any other structure
/// that assumes a stable hash. Use <see cref="object.GetHashCode"/> for that.
///
/// This hash covers parameter state only. To detect changes to the *set* of
/// components on the profile (additions/removals), use
/// <see cref="GetComponentListHashCode"/>.
/// </remarks>
/// <returns>A hash that changes whenever any component's state changes.</returns>
public int GetStateHash()
{
var hash = HashFNV1A32.Create();
for (int i = 0; i < components.Count; i++)
{
var comp = components[i];
if (comp == null)
continue;
hash.Append(comp.GetStateHash());
}
return hash.value;
}
/// <summary>
/// Removes any components that were destroyed externally from the iternal list of components
/// </summary>
internal void Sanitize()
{
for (int i = components.Count - 1; i >= 0; i--)
if (components[i] == null)
components.RemoveAt(i);
}
#if UNITY_EDITOR
void OnValidate()
{
// Delay the callback because when undoing the deletion of a VolumeComponent from a profile,
// it's possible VolumeComponent.OnEnable() has not yet been called, resulting in a crash when trying to
// update the default state.
EditorApplication.delayCall += () =>
{
if (VolumeManager.instance.isInitialized)
VolumeManager.instance.OnVolumeProfileChanged(this);
};
}
#endif
}
}
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: d7fd9488000d3734a9e00ee676215985
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,124 @@
using System;
using System.Collections.Generic;
namespace UnityEngine.Rendering
{
/// <summary>
/// Represents the state of a Volume blending update within the Volume system.
/// </summary>
/// <remarks>
///
/// This class is responsible for storing the blending of Volume components across multiple scenes and cameras,
/// By default, a global volume stack is provided by the <see cref="VolumeManager"/> to handle the blending of Volume data across your project.
/// This global stack simplifies managing and blending volume data at a project-wide level. However, if you require more granular control over
/// the blending process or want to store and manage the blending results separately (e.g., per camera or scene), you can create custom volume
/// stacks using <see cref="VolumeManager.CreateStack"/>.
/// The blending of volumes is based on a combination of several factors:
/// - **Volume Weight:** Determines how strongly a particular volume influences the final result.
/// - **Volume Parameters:** These can be visual settings such as post-processing effects, lighting adjustments, or other specialized effects defined
/// in the Volume components.
/// - **Camera Volume Stack:** Volume blending can vary per camera, allowing different volumes to be blended for different camera views or scenes.
///
/// While the default global volume stack works for most use cases, custom stacks provide greater flexibility and control, allowing developers
/// to manage and store volume blending results at a per-scene or per-camera level. This can be particularly useful in complex rendering setups
/// or when you want to apply different volume blends for different gameplay contexts or visual effects.
///
/// Keep in mind that frequent updates to the volume blending process (e.g., every frame) may have an impact on performance, especially when
/// dealing with large numbers of volumes or complex blending operations.
/// </remarks>
/// <seealso cref="Volume"/>
/// <seealso cref="VolumeProfile"/>
/// <seealso cref="VolumeComponent"/>
/// <seealso cref="VolumeParameter"/>
public sealed class VolumeStack : IDisposable
{
// Holds the state of _all_ component types you can possibly add on volumes
internal readonly Dictionary<Type, VolumeComponent> components = new();
// Flat list of every volume parameter for faster per-frame stack reset.
internal VolumeParameter[] parameters;
// Flag indicating that some properties have received overrides, therefore they must be reset in the next update.
internal bool requiresReset = true;
// Flag indicating that default state has changed, therefore all properties in the stack must be reset in the next update.
internal bool requiresResetForAllProperties = true;
internal VolumeStack()
{
}
internal void Clear()
{
foreach (var component in components)
CoreUtils.Destroy(component.Value);
components.Clear();
parameters = null;
}
internal void Reload(Type[] componentTypes)
{
Clear();
requiresReset = true;
requiresResetForAllProperties = true;
List<VolumeParameter> parametersList = new();
foreach (var type in componentTypes)
{
var component = (VolumeComponent)ScriptableObject.CreateInstance(type);
components.Add(type, component);
parametersList.AddRange(component.parameters);
}
parameters = parametersList.ToArray();
isValid = true;
}
/// <summary>
/// Gets the current state of the <see cref="VolumeComponent"/> of type <typeparamref name="T"/>
/// in the stack.
/// </summary>
/// <typeparam name="T">A type of <see cref="VolumeComponent"/>.</typeparam>
/// <returns>The current state of the <see cref="VolumeComponent"/> of type <typeparamref name="T"/>
/// in the stack.</returns>
public T GetComponent<T>()
where T : VolumeComponent
{
var comp = GetComponent(typeof(T));
return (T)comp;
}
/// <summary>
/// Gets the current state of the <see cref="VolumeComponent"/> of the specified type in the
/// stack.
/// </summary>
/// <param name="type">The type of <see cref="VolumeComponent"/> to look for.</param>
/// <returns>The current state of the <see cref="VolumeComponent"/> of the specified type,
/// or <c>null</c> if the type is invalid.</returns>
public VolumeComponent GetComponent(Type type)
{
components.TryGetValue(type, out var comp);
return comp;
}
/// <summary>
/// Cleans up the content of this stack. Once a <c>VolumeStack</c> is disposed, it shouldn't
/// be used anymore.
/// </summary>
public void Dispose()
{
Clear();
isValid = false;
}
/// <summary>
/// Check if the stack is in valid state and can be used.
/// </summary>
public bool isValid { get; private set; }
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 7af226ce5122db0409963decbabf9d9b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: