浏览代码

Merge branch 'master' into stacklit

/main
Stephane Laroche 7 年前
当前提交
e0b3d217
共有 75 个文件被更改,包括 1076 次插入851 次删除
  1. 1
      ScriptableRenderPipeline/Core/CoreRP/Editor/CoreEditorDrawers.cs
  2. 2
      ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/GeometricTools.hlsl
  3. 28
      ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/VolumeRendering.hlsl
  4. 2
      ScriptableRenderPipeline/Core/CoreRP/Shadow/Shadow.cs
  5. 4
      ScriptableRenderPipeline/Core/CoreRP/Textures/RTHandleSystem.RTHandle.cs
  6. 31
      ScriptableRenderPipeline/Core/CoreRP/Textures/RTHandleSystem.cs
  7. 128
      ScriptableRenderPipeline/Core/CoreRP/Textures/RTHandles.cs
  8. 2
      ScriptableRenderPipeline/Core/CoreRP/Textures/TextureCache.cs
  9. 25
      ScriptableRenderPipeline/Core/CoreRP/Utilities/CoreUtils.cs
  10. 13
      ScriptableRenderPipeline/HDRenderPipeline/CHANGELOG.md
  11. 78
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Camera/HDCamera.cs
  12. 6
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Camera/HDCameraFrameHistoryType.cs
  13. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugViewMaterialGBuffer.shader
  14. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugViewTiles.shader
  15. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Camera/HDCameraEditor.Handlers.cs
  16. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Camera/HDCameraEditor.cs
  17. 3
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/HDLightEditor.Styles.cs
  18. 5
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/HDLightEditor.cs
  19. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/Reflection/HDReflectionProbeUI.Drawers.cs
  20. 1
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/RenderLoopSettings/RenderPipelineSettingsUI.cs
  21. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/RenderLoopSettings/SerializedRenderPipelineSettings.cs
  22. 6
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Sky/AtmosphericScattering/VolumetricFogEditor.cs
  23. 260
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDRenderPipeline.cs
  24. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDRenderPipelineAsset.cs
  25. 6
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDStringConstants.cs
  26. 18
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDUtils.cs
  27. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Deferred.shader
  28. 8
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/DeferredDirectionalShadow.compute
  29. 3
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Light/HDAdditionalLightData.cs
  30. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightDefinition.cs
  31. 10
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightDefinition.cs.hlsl
  32. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/Deferred.compute
  33. 63
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/GlobalLightLoopSettings.cs
  34. 15
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoop.cs
  35. 27
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoopDef.hlsl
  36. 1
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Lighting.hlsl
  37. 6
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Reflection/PlanarReflectionProbeCache.cs
  38. 6
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Reflection/ReflectionProbeCache.cs
  39. 43
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Reflection/ReflectionSystemInternal.cs
  40. 8
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/SphericalHarmonics.cs
  41. 3
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Volumetrics/DensityVolumeManager.cs
  42. 27
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Volumetrics/VBuffer.hlsl
  43. 42
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Volumetrics/VolumetricLighting.compute
  44. 485
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Volumetrics/VolumetricLighting.cs
  45. 52
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Volumetrics/VolumetricLightingController.cs
  46. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/DBufferManager.cs
  47. 14
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/GGXConvolution/RuntimeFilterIBL.cs
  48. 56
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/Lit.hlsl
  49. 23
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/ShaderPass/LitDepthPass.hlsl
  50. 39
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/ShaderPass/LitDistortionPass.hlsl
  51. 23
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/ShaderPass/LitVelocityPass.hlsl
  52. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/PreIntegratedFGD/PreIntegratedFGD.cs
  53. 117
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/StackLit.hlsl
  54. 16
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/StackLitData.hlsl
  55. 23
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/SubsurfaceScattering/SubsurfaceScattering.compute
  56. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/SubsurfaceScattering/SubsurfaceScattering.shader
  57. 12
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs
  58. 7
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipeline/FrameSettings.cs
  59. 1
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipeline/RenderPipelineSettings.cs
  60. 6
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/CameraMotionVectors.shader
  61. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderPass/ShaderPassDBuffer.hlsl
  62. 7
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderPass/ShaderPassLightTransport.hlsl
  63. 16
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderVariables.hlsl
  64. 14
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderVariablesFunctions.hlsl
  65. 8
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/AtmosphericScattering/AtmosphericScattering.cs
  66. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/AtmosphericScattering/AtmosphericScattering.hlsl
  67. 6
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/AtmosphericScattering/ExponentialFog.cs
  68. 6
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/AtmosphericScattering/LinearFog.cs
  69. 18
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/AtmosphericScattering/VolumetricFog.cs
  70. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/OpaqueAtmosphericScattering.shader
  71. 10
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/VisualEnvironment.cs
  72. 1
      ScriptableRenderPipeline/LightweightPipeline/LWRP/LightweightPipeline.cs
  73. 1
      Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/011_UnlitSprites/Scripts/Oscilate.cs
  74. 32
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightUtilities.hlsl
  75. 9
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightUtilities.hlsl.meta

1
ScriptableRenderPipeline/Core/CoreRP/Editor/CoreEditorDrawers.cs


AnimBoolGetter m_IsExpanded;
string m_Title;
FoldoutOption m_Options;
bool m_Animate;
bool animate { get { return (m_Options & FoldoutOption.Animate) != 0; } }
bool indent { get { return (m_Options & FoldoutOption.Indent) != 0; } }

2
ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/GeometricTools.hlsl


// This simplified version assume that we care about the result only when we are inside the box
float IntersectRayAABBSimple(float3 start, float3 dir, float3 boxMin, float3 boxMax)
{
float3 invDir = 1.0 / dir;
float3 invDir = rcp(dir);
// Find the ray intersection with box plane
float3 rbmin = (boxMin - start) * invDir;

28
ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/VolumeRendering.hlsl


return INV_FOUR_PI;
}
real HenyeyGreensteinPhasePartConstant(real asymmetry)
real HenyeyGreensteinPhasePartConstant(real anisotropy)
real g = asymmetry;
real g = anisotropy;
real HenyeyGreensteinPhasePartVarying(real asymmetry, real cosTheta)
real HenyeyGreensteinPhasePartVarying(real anisotropy, real cosTheta)
real g = asymmetry;
real g = anisotropy;
real HenyeyGreensteinPhaseFunction(real asymmetry, real cosTheta)
real HenyeyGreensteinPhaseFunction(real anisotropy, real cosTheta)
return HenyeyGreensteinPhasePartConstant(asymmetry) *
HenyeyGreensteinPhasePartVarying(asymmetry, cosTheta);
return HenyeyGreensteinPhasePartConstant(anisotropy) *
HenyeyGreensteinPhasePartVarying(anisotropy, cosTheta);
real CornetteShanksPhasePartConstant(real asymmetry)
real CornetteShanksPhasePartConstant(real anisotropy)
real g = asymmetry;
real g = anisotropy;
real CornetteShanksPhasePartVarying(real asymmetry, real cosTheta)
real CornetteShanksPhasePartVarying(real anisotropy, real cosTheta)
real g = asymmetry;
real g = anisotropy;
real f = rsqrt(1 + g * g - 2 * g * cosTheta); // x^(-1/2)
real h = (1 + cosTheta * cosTheta);

// A better approximation of the Mie phase function.
// Ref: Henyey–Greenstein and Mie phase functions in Monte Carlo radiative transfer computations
real CornetteShanksPhaseFunction(real asymmetry, real cosTheta)
real CornetteShanksPhaseFunction(real anisotropy, real cosTheta)
return CornetteShanksPhasePartConstant(asymmetry) *
CornetteShanksPhasePartVarying(asymmetry, cosTheta);
return CornetteShanksPhasePartConstant(anisotropy) *
CornetteShanksPhasePartVarying(anisotropy, cosTheta);
}
// Samples the interval of homogeneous participating medium using the closed-form tracking approach

2
ScriptableRenderPipeline/Core/CoreRP/Shadow/Shadow.cs


m_Shadowmap.hideFlags = HideFlags.DontSaveInEditor | HideFlags.DontSaveInBuild;
m_Shadowmap.dimension = TextureDimension.Tex2DArray;
m_Shadowmap.volumeDepth = (int) m_Slices;
m_Shadowmap.name = CoreUtils.GetRenderTargetAutoName(shadowmap.width, shadowmap.height, shadowmap.format, "Shadow", mips : shadowmap.useMipMap);
m_Shadowmap.name = CoreUtils.GetRenderTargetAutoName(shadowmap.width, shadowmap.height, 1, shadowmap.format, "Shadow", mips : shadowmap.useMipMap);
m_ShadowmapId = new RenderTargetIdentifier( m_Shadowmap );
}

4
ScriptableRenderPipeline/Core/CoreRP/Textures/RTHandleSystem.RTHandle.cs


{
get
{
if(!useScaling)
if (!useScaling)
{
return m_EnableMSAA ? m_RTs[(int)RTCategory.MSAA] : m_RTs[(int)RTCategory.Regular];
}

useDynamicScale = refRT.useDynamicScale,
vrUsage = refRT.vrUsage,
memorylessMode = refRT.memorylessMode,
name = CoreUtils.GetRenderTargetAutoName(refRT.width, refRT.height, refRT.format, m_Name, mips : refRT.useMipMap)
name = CoreUtils.GetRenderTargetAutoName(refRT.width, refRT.height, refRT.volumeDepth, refRT.format, m_Name, mips : refRT.useMipMap)
};
newRT.Create();

31
ScriptableRenderPipeline/Core/CoreRP/Textures/RTHandleSystem.cs


public void DemandResize(RTHandle rth)
{
Assert.IsTrue(m_ResizeOnDemandRTs.Contains(rth), string.Format("The RTHandle {0} is not an resize on demand handle in this RTHandleSystem. Please call SwitchToResizeOnDemand(rth, true) before resizing on demand.", rth));
for (int i = 0, c = (int)RTCategory.Count; i < c; ++i)
{
if (rth.m_RTs[i] == null)

rt.height = scaledSize.y;
rt.name = CoreUtils.GetRenderTargetAutoName(
rt.width,
rt.height,
rt.format,
rth.m_Name,
mips: rt.useMipMap,
enableMSAA : enableMSAA,
rt.width,
rt.height,
rt.volumeDepth,
rt.format,
rth.m_Name,
mips: rt.useMipMap,
enableMSAA : enableMSAA,
msaaSamples: m_ScaledRTCurrentMSAASamples
);
rt.Create();

{
var rth = m_AutoSizedRTsArray[i];
rth.referenceSize = maxSize;
var rt = rth.m_RTs[(int)category];
// This can happen if you create a RTH for MSAA. By default we only create the MSAA version of the target.

if (category == RTCategory.MSAA)
rt.antiAliasing = (int)m_ScaledRTCurrentMSAASamples;
rt.name = CoreUtils.GetRenderTargetAutoName(rt.width, rt.height, rt.format, rth.m_Name, mips: rt.useMipMap, enableMSAA : category == RTCategory.MSAA, msaaSamples: m_ScaledRTCurrentMSAASamples);
rt.name = CoreUtils.GetRenderTargetAutoName(rt.width, rt.height, rt.volumeDepth, rt.format, rth.m_Name, mips: rt.useMipMap, enableMSAA : category == RTCategory.MSAA, msaaSamples: m_ScaledRTCurrentMSAASamples);
rt.Create();
}
}

useDynamicScale = useDynamicScale,
vrUsage = vrUsage,
memorylessMode = memoryless,
name = CoreUtils.GetRenderTargetAutoName(width, height, colorFormat, name, mips: useMipMap, enableMSAA: enableMSAA, msaaSamples: msaaSamples)
name = CoreUtils.GetRenderTargetAutoName(width, height, slices, colorFormat, name, mips: useMipMap, enableMSAA: enableMSAA, msaaSamples: msaaSamples)
};
rt.Create();

newRT.m_Name = name;
newRT.referenceSize = new Vector2Int(width, height);
return newRT;
}

// Since MSAA cannot be changed on the fly for a given RenderTexture, a separate instance will be created if the user requires it. This instance will be the one used after the next call of SetReferenceSize if MSAA is required.
public RTHandle Alloc(
Vector2 scaleFactor,
int slices = 1,
DepthBits depthBufferBits = DepthBits.None,
RenderTextureFormat colorFormat = RenderTextureFormat.Default,
FilterMode filterMode = FilterMode.Point,

var rth = AllocAutoSizedRenderTexture(width,
height,
1,
slices,
depthBufferBits,
colorFormat,
filterMode,

//
public RTHandle Alloc(
ScaleFunc scaleFunc,
int slices = 1,
DepthBits depthBufferBits = DepthBits.None,
RenderTextureFormat colorFormat = RenderTextureFormat.Default,
FilterMode filterMode = FilterMode.Point,

var rth = AllocAutoSizedRenderTexture(width,
height,
1,
slices,
depthBufferBits,
colorFormat,
filterMode,

useDynamicScale = useDynamicScale,
vrUsage = vrUsage,
memorylessMode = memoryless,
name = CoreUtils.GetRenderTargetAutoName(width, height, colorFormat, name, mips : useMipMap, enableMSAA: allocForMSAA, msaaSamples : m_ScaledRTCurrentMSAASamples)
name = CoreUtils.GetRenderTargetAutoName(width, height, slices, colorFormat, name, mips : useMipMap, enableMSAA: allocForMSAA, msaaSamples : m_ScaledRTCurrentMSAASamples)
};
rt.Create();

128
ScriptableRenderPipeline/Core/CoreRP/Textures/RTHandles.cs


using System.Collections.Generic;
using System.Collections.Generic;
using UnityEngine.Rendering;
namespace UnityEngine.Experimental.Rendering

public static int maxHeight { get { return s_DefaultInstance.maxHeight; } }
public static RTHandleSystem.RTHandle Alloc(
int width,
int height,
int slices = 1,
DepthBits depthBufferBits = DepthBits.None,
RenderTextureFormat colorFormat = RenderTextureFormat.Default,
FilterMode filterMode = FilterMode.Point,
TextureWrapMode wrapMode = TextureWrapMode.Repeat,
TextureDimension dimension = TextureDimension.Tex2D,
bool sRGB = true,
bool enableRandomWrite = false,
bool useMipMap = false,
bool autoGenerateMips = true,
int anisoLevel = 1,
float mipMapBias = 0,
MSAASamples msaaSamples = MSAASamples.None,
bool bindTextureMS = false,
bool useDynamicScale = false,
VRTextureUsage vrUsage = VRTextureUsage.None,
RenderTextureMemoryless memoryless = RenderTextureMemoryless.None,
int width,
int height,
int slices = 1,
DepthBits depthBufferBits = DepthBits.None,
RenderTextureFormat colorFormat = RenderTextureFormat.Default,
FilterMode filterMode = FilterMode.Point,
TextureWrapMode wrapMode = TextureWrapMode.Repeat,
TextureDimension dimension = TextureDimension.Tex2D,
bool sRGB = true,
bool enableRandomWrite = false,
bool useMipMap = false,
bool autoGenerateMips = true,
int anisoLevel = 1,
float mipMapBias = 0,
MSAASamples msaaSamples = MSAASamples.None,
bool bindTextureMS = false,
bool useDynamicScale = false,
VRTextureUsage vrUsage = VRTextureUsage.None,
RenderTextureMemoryless memoryless = RenderTextureMemoryless.None,
string name = ""
)
{

}
public static RTHandleSystem.RTHandle Alloc(
Vector2 scaleFactor,
DepthBits depthBufferBits = DepthBits.None,
RenderTextureFormat colorFormat = RenderTextureFormat.Default,
FilterMode filterMode = FilterMode.Point,
TextureWrapMode wrapMode = TextureWrapMode.Repeat,
TextureDimension dimension = TextureDimension.Tex2D,
bool sRGB = true,
bool enableRandomWrite = false,
bool useMipMap = false,
bool autoGenerateMips = true,
int anisoLevel = 1,
float mipMapBias = 0,
bool enableMSAA = false,
bool bindTextureMS = false,
bool useDynamicScale = false,
VRTextureUsage vrUsage = VRTextureUsage.None,
RenderTextureMemoryless memoryless = RenderTextureMemoryless.None,
Vector2 scaleFactor,
int slices = 1,
DepthBits depthBufferBits = DepthBits.None,
RenderTextureFormat colorFormat = RenderTextureFormat.Default,
FilterMode filterMode = FilterMode.Point,
TextureWrapMode wrapMode = TextureWrapMode.Repeat,
TextureDimension dimension = TextureDimension.Tex2D,
bool sRGB = true,
bool enableRandomWrite = false,
bool useMipMap = false,
bool autoGenerateMips = true,
int anisoLevel = 1,
float mipMapBias = 0,
bool enableMSAA = false,
bool bindTextureMS = false,
bool useDynamicScale = false,
VRTextureUsage vrUsage = VRTextureUsage.None,
RenderTextureMemoryless memoryless = RenderTextureMemoryless.None,
slices,
depthBufferBits,
colorFormat,
filterMode,

}
public static RTHandleSystem.RTHandle Alloc(
ScaleFunc scaleFunc,
DepthBits depthBufferBits = DepthBits.None,
RenderTextureFormat colorFormat = RenderTextureFormat.Default,
FilterMode filterMode = FilterMode.Point,
TextureWrapMode wrapMode = TextureWrapMode.Repeat,
TextureDimension dimension = TextureDimension.Tex2D,
bool sRGB = true,
bool enableRandomWrite = false,
ScaleFunc scaleFunc,
int slices = 1,
DepthBits depthBufferBits = DepthBits.None,
RenderTextureFormat colorFormat = RenderTextureFormat.Default,
FilterMode filterMode = FilterMode.Point,
TextureWrapMode wrapMode = TextureWrapMode.Repeat,
TextureDimension dimension = TextureDimension.Tex2D,
bool sRGB = true,
bool enableRandomWrite = false,
bool autoGenerateMips = true,
int anisoLevel = 1,
float mipMapBias = 0,
bool enableMSAA = false,
bool bindTextureMS = false,
bool useDynamicScale = false,
VRTextureUsage vrUsage = VRTextureUsage.None,
RenderTextureMemoryless memoryless = RenderTextureMemoryless.None,
bool autoGenerateMips = true,
int anisoLevel = 1,
float mipMapBias = 0,
bool enableMSAA = false,
bool bindTextureMS = false,
bool useDynamicScale = false,
VRTextureUsage vrUsage = VRTextureUsage.None,
RenderTextureMemoryless memoryless = RenderTextureMemoryless.None,
slices,
depthBufferBits,
colorFormat,
filterMode,

}
public static void Initialize(
int width,
int height,
bool scaledRTsupportsMSAA,
int width,
int height,
bool scaledRTsupportsMSAA,
MSAASamples scaledRTMSAASamples
)
{

}
public static void ResetReferenceSize(
int width,
int height,
bool msaa,
int width,
int height,
bool msaa,
MSAASamples msaaSamples
)
{

}
public static void SetReferenceSize(
int width,
int height,
bool msaa,
int width,
int height,
bool msaa,
MSAASamples msaaSamples
)
{

2
ScriptableRenderPipeline/Core/CoreRP/Textures/TextureCache.cs


for (int m = 0; m < m_NumPanoMipLevels; m++)
{
m_StagingRTs[m] = new RenderTexture(Mathf.Max(1, panoWidthTop >> m), Mathf.Max(1, panoHeightTop >> m), 0, RenderTextureFormat.ARGBHalf) { hideFlags = HideFlags.HideAndDontSave };
m_StagingRTs[m].name = CoreUtils.GetRenderTargetAutoName(Mathf.Max(1, panoWidthTop >> m), Mathf.Max(1, panoHeightTop >> m), RenderTextureFormat.ARGBHalf, String.Format("PanaCache{0}", m));
m_StagingRTs[m].name = CoreUtils.GetRenderTargetAutoName(Mathf.Max(1, panoWidthTop >> m), Mathf.Max(1, panoHeightTop >> m), 1, RenderTextureFormat.ARGBHalf, String.Format("PanaCache{0}", m));
}
if (m_CubeBlitMaterial)

25
ScriptableRenderPipeline/Core/CoreRP/Utilities/CoreUtils.cs


ClearRenderTarget(cmd, clearFlag, clearColor);
}
public static string GetRenderTargetAutoName(int width, int height, RenderTextureFormat format, string name = "", bool mips = false, bool enableMSAA = false, MSAASamples msaaSamples = MSAASamples.None)
public static string GetRenderTargetAutoName(int width, int height, int depth, RenderTextureFormat format, string name, bool mips = false, bool enableMSAA = false, MSAASamples msaaSamples = MSAASamples.None)
string temp;
string result = string.Format("{0}_{1}x{2}", name, width, height);
if (depth > 1)
result = string.Format("{0}x{1}", result, depth);
if (mips)
result = string.Format("{0}_{1}", result, "Mips");
result = string.Format("{0}_{1}", result, format);
temp = string.Format("{0}x{1}_{2}{3}_{4}", width, height, format, mips ? "_Mips" : "", msaaSamples.ToString());
else
temp = string.Format("{0}x{1}_{2}{3}", width, height, format, mips ? "_Mips" : "");
temp = String.Format("{0}_{1}", name == "" ? "RenderTarget" : name, temp);
result = string.Format("{0}_{1}", result, msaaSamples.ToString());
return temp;
return result;
}
public static string GetTextureAutoName(int width, int height, TextureFormat format, TextureDimension dim = TextureDimension.None, string name = "", bool mips = false, int depth = 0)

temp = string.Format("{0}x{1}_{2}{3}", width, height, format, mips ? "_Mips" : "");
temp = string.Format("{0}x{1}{2}_{3}", width, height, mips ? "_Mips" : "", format);
temp = string.Format("{0}x{1}x{2}_{3}{4}", width, height, depth, format, mips ? "_Mips" : "");
temp = string.Format("{0}x{1}x{2}{3}_{4}", width, height, depth, mips ? "_Mips" : "", format);
temp = String.Format("{0}_{1}_{2}", name == "" ? "Texture" : name, (dim == TextureDimension.None) ? "" : dim.ToString(), temp);
return temp;

13
ScriptableRenderPipeline/HDRenderPipeline/CHANGELOG.md


## [2018.1 undecided]
### Improvements
- Configure the volumetric lighting code path to be on by default
- Configure the VolumetricLightingSystem code path to be on by default
- Add 3D texture support for DensityVolumes
- Add a better mapping of roughness to mipmap for planar reflection
- The VolumetricLightingSystem now uses RTHandles, which allows to save memory by sharing buffers between different cameras (history buffers are not shared), and reduce reallocation frequency by reallocating buffers only if the rendering resolution increases (and suballocating within existing buffers if the rendering resolution decreases)
- Add a Volumetric Dimmer slider to lights to control the intensity of the scattered volumetric lighting
- Rename _MainDepthTexture to _CameraDepthTexture
- The VolumetricLightingController has been moved to the Interpolation Volume framework and now functions similarly to the VolumetricFog settings
- Update of UI of cookie, CubeCookie, Reflection probe and planar reflection probe to combo box
- Fix the bug preventing decals from coexisting with density volumes
- Fix the bug preventing decals from coexisting with density volumes
- Fix issue with alpha tested geometry using planar/triplanar mapping not render correctly or flickering (due to being wrongly alpha tested in depth prepass)
- Fix meta pass with triplanar (was not handling correctly the normal)
## [2018.1.0f2]

78
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Camera/HDCamera.cs


public Vector4 projectionParams;
public Vector4 screenParams;
public VolumetricLightingSystem.VBufferParameters[] vBufferParams; // Double-buffered
public PostProcessRenderContext postprocessRenderContext;
public Matrix4x4[] viewMatrixStereo;

// This is the size actually used for this camera (as it can be altered by VR for example)
int m_ActualWidth;
int m_ActualHeight;
// This is the scale and bias of the camera viewport compared to the reference size of our Render Targets (RHandle.maxSize)
Vector2 m_CameraScaleBias;
// This is the scale of the camera viewport compared to the reference size of our Render Targets (RTHandle.maxSize)
Vector2 m_ViewportScaleCurrentFrame;
Vector2 m_ViewportScalePreviousFrame;
FrameSettings m_frameSettings;
public Vector2 scaleBias { get { return m_CameraScaleBias; } }
public Vector2 viewportScale { get { return m_ViewportScaleCurrentFrame; } }
public Vector4 doubleBufferedViewportScale { get { return new Vector4(m_ViewportScaleCurrentFrame.x, m_ViewportScaleCurrentFrame.y, m_ViewportScalePreviousFrame.x, m_ViewportScalePreviousFrame.y); } }
public FrameSettings frameSettings { get { return m_frameSettings; } }
public Matrix4x4 viewProjMatrix
{

projMatrixStereo = new Matrix4x4[2];
postprocessRenderContext = new PostProcessRenderContext();
public void Update(PostProcessLayer postProcessLayer, FrameSettings frameSettings)
// Pass all the systems that may want to update per-camera data here.
// That way you will never update an HDCamera and forget to update the dependent system.
public void Update(FrameSettings currentFrameSettings, PostProcessLayer postProcessLayer, VolumetricLightingSystem vlSys)
m_frameSettings = currentFrameSettings;
frameSettings.enablePostprocess;
m_frameSettings.enablePostprocess;
var nonJitteredCameraProj = camera.projectionMatrix;
var cameraProj = taaEnabled

var screenWidth = m_ActualWidth;
var screenHeight = m_ActualHeight;
#if !UNITY_SWITCH
if (frameSettings.enableStereo)
if (m_frameSettings.enableStereo)
{
screenWidth = XRSettings.eyeTextureWidth;
screenHeight = XRSettings.eyeTextureHeight;

// Unfortunately sometime (like in the HDCameraEditor) HDUtils.hdrpSettings can be null because of scripts that change the current pipeline...
m_msaaSamples = HDUtils.hdrpSettings != null ? HDUtils.hdrpSettings.msaaSampleCount : MSAASamples.None;
RTHandles.SetReferenceSize(m_ActualWidth, m_ActualHeight, frameSettings.enableMSAA, m_msaaSamples);
m_HistoryRTSystem.SetReferenceSize(m_ActualWidth, m_ActualHeight, frameSettings.enableMSAA, m_msaaSamples);
RTHandles.SetReferenceSize(m_ActualWidth, m_ActualHeight, m_frameSettings.enableMSAA, m_msaaSamples);
m_HistoryRTSystem.SetReferenceSize(m_ActualWidth, m_ActualHeight, m_frameSettings.enableMSAA, m_msaaSamples);
m_CameraScaleBias.x = (float)m_ActualWidth / maxWidth;
m_CameraScaleBias.y = (float)m_ActualHeight / maxHeight;
m_ViewportScalePreviousFrame = m_ViewportScaleCurrentFrame; // Double-buffer
m_ViewportScaleCurrentFrame.x = (float)m_ActualWidth / maxWidth;
m_ViewportScaleCurrentFrame.y = (float)m_ActualHeight / maxHeight;
if (vlSys != null)
{
vlSys.UpdatePerCameraData(this);
}
public void UpdateStereoDependentState(FrameSettings frameSettings, ref ScriptableCullingParameters cullingParams)
public void UpdateStereoDependentState(ref ScriptableCullingParameters cullingParams)
if (!frameSettings.enableStereo)
if (!m_frameSettings.enableStereo)
return;
// What constants in UnityPerPass need updating for stereo considerations?

isFirstFrame = true;
}
// Grab the HDCamera tied to a given Camera and update it.
public static HDCamera Get(Camera camera, PostProcessLayer postProcessLayer, FrameSettings frameSettings)
// Will return NULL if the camera does not exist.
public static HDCamera Get(Camera camera)
{
HDCamera hdCamera;
if (!s_Cameras.TryGetValue(camera, out hdCamera))
{
hdCamera = null;
}
return hdCamera;
}
// Pass all the systems that may want to initialize per-camera data here.
// That way you will never create an HDCamera and forget to initialize the data.
public static HDCamera Create(Camera camera, VolumetricLightingSystem vlSys)
HDCamera hdcam;
HDCamera hdCamera = new HDCamera(camera);
s_Cameras.Add(camera, hdCamera);
if (!s_Cameras.TryGetValue(camera, out hdcam))
if (vlSys != null)
hdcam = new HDCamera(camera);
s_Cameras.Add(camera, hdcam);
// Have to perform a NULL check here because the Reflection System internally allocates HDCameras.
vlSys.InitializePerCameraData(hdCamera);
hdcam.Update(postProcessLayer, frameSettings);
return hdcam;
return hdCamera;
}
public static void ClearAll()

cmd.SetGlobalVector(HDShaderIDs._WorldSpaceCameraPos, worldSpaceCameraPos);
cmd.SetGlobalFloat( HDShaderIDs._DetViewMatrix, detViewMatrix);
cmd.SetGlobalVector(HDShaderIDs._ScreenSize, screenSize);
cmd.SetGlobalVector(HDShaderIDs._ScreenToTargetScale, scaleBias);
cmd.SetGlobalVector(HDShaderIDs._ScreenToTargetScale, doubleBufferedViewportScale);
cmd.SetGlobalVector(HDShaderIDs._ZBufferParams, zBufferParams);
cmd.SetGlobalVector(HDShaderIDs._ProjectionParams, projectionParams);
cmd.SetGlobalVector(HDShaderIDs.unity_OrthoParams, unity_OrthoParams);

// Allocate buffers frames and return current frame
public RTHandleSystem.RTHandle AllocHistoryFrameRT(int id, Func<string, int, RTHandleSystem, RTHandleSystem.RTHandle> allocator)
{
m_HistoryRTSystem.AllocBuffer(id, (rts, i) => allocator(camera.name, i, rts), 2);
const int bufferCount = 2; // Hard-coded for now. Will have to see if this is enough...
m_HistoryRTSystem.AllocBuffer(id, (rts, i) => allocator(camera.name, i, rts), bufferCount);
return m_HistoryRTSystem.GetFrameRT(id, 0);
}

6
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Camera/HDCameraFrameHistoryType.cs


{
public enum HDCameraFrameHistoryType
{
DepthPyramid,
ColorPyramid
DepthPyramid = 0,
ColorPyramid = 1,
VolumetricLighting = 2,
Count = 3 // Keep this last
}
}

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugViewMaterialGBuffer.shader


float4 Frag(Varyings input) : SV_Target
{
// input.positionCS is SV_Position
float depth = LOAD_TEXTURE2D(_MainDepthTexture, input.positionCS.xy).x;
float depth = LOAD_TEXTURE2D(_CameraDepthTexture, input.positionCS.xy).x;
PositionInputs posInput = GetPositionInput(input.positionCS.xy, _ScreenSize.zw, depth, UNITY_MATRIX_I_VP, UNITY_MATRIX_V);
BSDFData bsdfData;

4
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugViewTiles.shader


float4 Frag(Varyings input) : SV_Target
{
// positionCS is SV_Position
float depth = LOAD_TEXTURE2D(_MainDepthTexture, input.positionCS.xy).x;
float depth = LOAD_TEXTURE2D(_CameraDepthTexture, input.positionCS.xy).x;
PositionInputs posInput = GetPositionInput(input.positionCS.xy, _ScreenSize.zw, depth, UNITY_MATRIX_I_VP, UNITY_MATRIX_V, uint2(input.positionCS.xy) / GetTileSize());
int2 pixelCoord = posInput.positionSS.xy;

int maxLights = 32;
if (tileCoord.y < LIGHTCATEGORY_COUNT && tileCoord.x < maxLights + 3)
{
float depthMouse = LOAD_TEXTURE2D(_MainDepthTexture, _MousePixelCoord.xy).x;
float depthMouse = LOAD_TEXTURE2D(_CameraDepthTexture, _MousePixelCoord.xy).x;
PositionInputs mousePosInput = GetPositionInput(_MousePixelCoord.xy, _ScreenSize.zw, depthMouse, UNITY_MATRIX_I_VP, UNITY_MATRIX_V, mouseTileCoord);
uint category = (LIGHTCATEGORY_COUNT - 1) - tileCoord.y;

4
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Camera/HDCameraEditor.Handlers.cs


using System;
using System;
using System.Reflection;
using UnityEngine;
using UnityEngine.Experimental.Rendering;

// And then to copy the runtime frame settings
// So this includes the runtime frame settings properly
cameraData.GetFrameSettings().CopyTo(m_PreviewAdditionalCameraData.GetFrameSettings());
m_PreviewHDCamera.Update(m_PreviewPostProcessLayer, m_PreviewAdditionalCameraData.GetFrameSettings());
m_PreviewHDCamera.Update(m_PreviewAdditionalCameraData.GetFrameSettings(), m_PreviewPostProcessLayer, null);
var previewTexture = GetPreviewTextureWithSize((int)previewSize.x, (int)previewSize.y);
m_PreviewCamera.targetTexture = previewTexture;

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Camera/HDCameraEditor.cs


m_PreviewAdditionalCameraData = m_PreviewCamera.gameObject.AddComponent<HDAdditionalCameraData>();
m_PreviewPostProcessLayer = m_PreviewCamera.gameObject.AddComponent<PostProcessLayer>();
m_PreviewHDCamera = new HDCamera(m_PreviewCamera);
m_PreviewHDCamera.Update(m_PreviewPostProcessLayer, m_PreviewAdditionalCameraData.GetFrameSettings());
m_PreviewHDCamera.Update(m_PreviewAdditionalCameraData.GetFrameSettings(), m_PreviewPostProcessLayer, null);
}
void OnDisable()

3
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/HDLightEditor.Styles.cs


using System;
using System;
using System.Linq;
using UnityEngine;

public readonly GUIContent affectDiffuse = new GUIContent("Affect Diffuse", "This will disable diffuse lighting for this light. Doesn't save performance, diffuse lighting is still computed.");
public readonly GUIContent affectSpecular = new GUIContent("Affect Specular", "This will disable specular lighting for this light. Doesn't save performance, specular lighting is still computed.");
public readonly GUIContent lightDimmer = new GUIContent("Dimmer", "Aim to be used with script, timeline or animation. It allows dimming one or multiple lights of heterogeneous intensity easily (without needing to know the intensity of each light).");
public readonly GUIContent volumetricDimmer = new GUIContent("Volumetric Dimmer", "Allows to reduce the intensity of the scattered volumetric lighting.");
public readonly GUIContent fadeDistance = new GUIContent("Fade Distance", "The distance at which the light will smoothly fade before being culled to minimize popping.");
public readonly GUIContent spotInnerPercent = new GUIContent("Inner Percent", "Controls size of the angular attenuation in percent of the base angle of the Spot light's cone.");
public readonly GUIContent spotLightShape = new GUIContent("Shape", "The shape use for the spotlight. Has an impact on the cookie transformation and light angular attenuation.");

5
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/HDLightEditor.cs


public SerializedProperty shapeRadius;
public SerializedProperty maxSmoothness;
public SerializedProperty applyRangeAttenuation;
public SerializedProperty volumetricDimmer;
// Editor stuff
public SerializedProperty useOldInspector;

enableSpotReflector = o.Find(x => x.enableSpotReflector),
spotInnerPercent = o.Find(x => x.m_InnerSpotPercent),
lightDimmer = o.Find(x => x.lightDimmer),
volumetricDimmer = o.Find(x => x.volumetricDimmer),
spotLightShape = o.Find(x => x.spotLightShape),
spotLightShape = o.Find(x => x.spotLightShape),
shapeWidth = o.Find(x => x.shapeWidth),
shapeHeight = o.Find(x => x.shapeHeight),
aspectRatio = o.Find(x => x.aspectRatio),

EditorGUILayout.PropertyField(m_AdditionalLightData.affectSpecular, s_Styles.affectSpecular);
EditorGUILayout.PropertyField(m_AdditionalLightData.fadeDistance, s_Styles.fadeDistance);
EditorGUILayout.PropertyField(m_AdditionalLightData.lightDimmer, s_Styles.lightDimmer);
EditorGUILayout.PropertyField(m_AdditionalLightData.volumetricDimmer, s_Styles.volumetricDimmer);
EditorGUILayout.PropertyField(m_AdditionalLightData.applyRangeAttenuation, s_Styles.applyRangeAttenuation);
EditorGUI.indentLevel--;
}

4
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/Reflection/HDReflectionProbeUI.Drawers.cs


public static readonly CED.IDrawer[] Inspector;
public static readonly CED.IDrawer SectionPrimarySettings = CED.Group(
CED.Action(Drawer_ReflectionProbeMode),
CED.FadeGroup((s, p, o, i) => s.IsSectionExpandedMode((ReflectionProbeMode)i),
FadeOption.Indent,

static void Drawer_CaptureSettings(HDReflectionProbeUI s, SerializedHDReflectionProbe p, Editor owner)
{
var renderPipelineAsset = (HDRenderPipelineAsset)GraphicsSettings.renderPipelineAsset;
p.resolution.intValue = renderPipelineAsset.GetRenderPipelineSettings().lightLoopSettings.reflectionCubemapSize;
p.resolution.intValue = (int)renderPipelineAsset.GetRenderPipelineSettings().lightLoopSettings.reflectionCubemapSize;
EditorGUILayout.LabelField(CoreEditorUtils.GetContent("Resolution"), CoreEditorUtils.GetContent(p.resolution.intValue.ToString()));
EditorGUILayout.PropertyField(p.shadowDistance, CoreEditorUtils.GetContent("Shadow Distance"));

1
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/RenderLoopSettings/RenderPipelineSettingsUI.cs


EditorGUILayout.PropertyField(d.supportMotionVectors, _.GetContent("Support Motion Vectors"));
EditorGUILayout.PropertyField(d.supportStereo, _.GetContent("Support Stereo Rendering"));
EditorGUILayout.PropertyField(d.enableUltraQualitySSS, _.GetContent("Increase SSS Sample Count"));
EditorGUILayout.PropertyField(d.supportVolumetric, _.GetContent("Support volumetric"));
--EditorGUI.indentLevel;
}
}

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/RenderLoopSettings/SerializedRenderPipelineSettings.cs


public SerializedProperty supportMotionVectors;
public SerializedProperty supportStereo;
public SerializedProperty enableUltraQualitySSS;
public SerializedProperty supportVolumetric;
public SerializedGlobalLightLoopSettings lightLoopSettings;
public SerializedShadowInitParameters shadowInitParams;

supportMotionVectors = root.Find((RenderPipelineSettings s) => s.supportMotionVectors);
supportStereo = root.Find((RenderPipelineSettings s) => s.supportStereo);
enableUltraQualitySSS = root.Find((RenderPipelineSettings s) => s.enableUltraQualitySSS);
supportVolumetric = root.Find((RenderPipelineSettings s) => s.supportVolumetric);
lightLoopSettings = new SerializedGlobalLightLoopSettings(root.Find((RenderPipelineSettings s) => s.lightLoopSettings));
shadowInitParams = new SerializedShadowInitParameters(root.Find((RenderPipelineSettings s) => s.shadowInitParams));

6
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Sky/AtmosphericScattering/VolumetricFogEditor.cs


{
private SerializedDataParameter m_Albedo;
private SerializedDataParameter m_MeanFreePath;
private SerializedDataParameter m_Asymmetry;
private SerializedDataParameter m_Anisotropy;
public override void OnEnable()
{

m_Albedo = Unpack(o.Find(x => x.albedo));
m_MeanFreePath = Unpack(o.Find(x => x.meanFreePath));
m_Asymmetry = Unpack(o.Find(x => x.asymmetry));
m_Anisotropy = Unpack(o.Find(x => x.anisotropy));
}
public override void OnInspectorGUI()

PropertyField(m_Asymmetry);
PropertyField(m_Anisotropy);
}
}
}

260
ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDRenderPipeline.cs


public Material GetBlitMaterial() { return m_Blit; }
FrameSettings m_FrameSettings; // Init every frame
ComputeBuffer m_DebugScreenSpaceTracingData = null;
ScreenSpaceTracingDebug[] m_DebugScreenSpaceTracingDataArray = new ScreenSpaceTracingDebug[1];

}
m_Asset = asset;
// Initial state of the RTHandle system.
// Tells the system that we will require MSAA or not so that we can avoid wasteful render texture allocation.
// TODO: Might want to initialize to at least the window resolution to avoid un-necessary re-alloc in the player
RTHandles.Initialize(1, 1, m_Asset.renderPipelineSettings.supportMSAA, m_Asset.renderPipelineSettings.msaaSampleCount);
var bufferPyramidProcessor = new BufferPyramidProcessor(
asset.renderPipelineResources.colorPyramidCS,
asset.renderPipelineResources.depthPyramidCS,

void InitializeRenderTextures()
{
// Initial state of the RTHandle system.
// Tells the system that we will require MSAA or not so that we can avoid wasteful render texture allocation.
// TODO: Might want to initialize to at least the window resolution to avoid un-necessary re-alloc in the player
RTHandles.Initialize(1, 1, m_Asset.renderPipelineSettings.supportMSAA, m_Asset.renderPipelineSettings.msaaSampleCount);
if(!m_Asset.renderPipelineSettings.supportForwardOnly)
m_GbufferManager.CreateBuffers();

RTHandles.Release(m_DebugFullScreenTempBuffer);
m_DebugScreenSpaceTracingData.Release();
HDCamera.CleanUnused();
}

m_VolumetricLightingSystem.Cleanup();
m_IBLFilterGGX.Cleanup();
HDCamera.ClearAll();
DestroyRenderTextures();
#if UNITY_EDITOR

if (m_CurrentWidth > 0 && m_CurrentHeight > 0)
m_LightLoop.ReleaseResolutionDependentBuffers();
m_LightLoop.AllocResolutionDependentBuffers((int)hdCamera.screenSize.x, (int)hdCamera.screenSize.y, m_FrameSettings.enableStereo);
m_LightLoop.AllocResolutionDependentBuffers((int)hdCamera.screenSize.x, (int)hdCamera.screenSize.y, hdCamera.frameSettings.enableStereo);
// Warning: (resolutionChanged == false) if you open a new Editor tab of the same size!
m_VolumetricLightingSystem.ResizeVBufferAndUpdateProperties(hdCamera, m_FrameCount);
// update recorded window resolution
m_CurrentWidth = hdCamera.actualWidth;

using (new ProfilingSample(cmd, "Push Global Parameters", CustomSamplerId.PushGlobalParameters.GetSampler()))
{
// Set up UnityPerFrame CBuffer.
m_SSSBufferManager.PushGlobalParams(cmd, sssParameters, m_FrameSettings);
m_SSSBufferManager.PushGlobalParams(hdCamera, cmd, sssParameters);
m_DbufferManager.PushGlobalParams(cmd, m_FrameSettings);
m_DbufferManager.PushGlobalParams(hdCamera, cmd);
m_VolumetricLightingSystem.PushGlobalParams(hdCamera, cmd, m_FrameCount);

// Set up UnityPerView CBuffer.
hdCamera.SetupGlobalParams(cmd, m_Time, m_LastTime);
if (m_FrameSettings.enableStereo) hdCamera.SetupGlobalStereoParams(cmd);
if (hdCamera.frameSettings.enableStereo)
hdCamera.SetupGlobalStereoParams(cmd);
var previousDepthPyramidRT = hdCamera.GetPreviousFrameRT((int)HDCameraFrameHistoryType.DepthPyramid);
if (previousDepthPyramidRT != null)

}
}
public void UpdateShadowSettings()
public void UpdateShadowSettings(HDCamera hdCamera)
{
var shadowSettings = VolumeManager.instance.stack.GetComponent<HDShadowSettings>();

m_ShadowSettings.enabled = m_FrameSettings.enableShadow;
m_ShadowSettings.enabled = hdCamera.frameSettings.enableShadow;
}
public void ConfigureForShadowMask(bool enableBakeShadowMask, CommandBuffer cmd)

{
srcFrameSettings = m_Asset.GetFrameSettings();
}
FrameSettings currentFrameSettings = new FrameSettings();
FrameSettings.InitializeFrameSettings(camera, m_Asset.GetRenderPipelineSettings(), srcFrameSettings, ref m_FrameSettings);
FrameSettings.InitializeFrameSettings(camera, m_Asset.GetRenderPipelineSettings(), srcFrameSettings, ref currentFrameSettings);
// This is the main command buffer used for the frame.
var cmd = CommandBufferPool.Get("");

using (new ProfilingSample(cmd, "HDRenderPipeline::Render", CustomSamplerId.HDRenderPipelineRender.GetSampler()))
{
// Do anything we need to do upon a new frame.
m_LightLoop.NewFrame(m_FrameSettings);
m_LightLoop.NewFrame(currentFrameSettings);
// If we render a reflection view or a preview we should not display any debug information
// This need to be call before ApplyDebugDisplaySettings()

// Disable post process if we enable debug mode or if the post process layer is disabled
if (m_CurrentDebugDisplaySettings.IsDebugDisplayRemovePostprocess() || !CoreUtils.IsPostProcessingActive(postProcessLayer))
{
m_FrameSettings.enablePostprocess = false;
currentFrameSettings.enablePostprocess = false;
var hdCamera = HDCamera.Get(camera, postProcessLayer, m_FrameSettings);
var hdCamera = HDCamera.Get(camera);
if (hdCamera == null)
{
hdCamera = HDCamera.Create(camera, m_VolumetricLightingSystem);
}
// From this point, we should only use frame settings from the camera
hdCamera.Update(currentFrameSettings, postProcessLayer, m_VolumetricLightingSystem);
UpdateShadowSettings();
UpdateShadowSettings(hdCamera);
if (!CullResults.GetCullingParameters(camera, m_FrameSettings.enableStereo, out cullingParams))
if (!CullResults.GetCullingParameters(camera, hdCamera.frameSettings.enableStereo, out cullingParams))
{
renderContext.Submit();
continue;

hdCamera.UpdateStereoDependentState(m_FrameSettings, ref cullingParams);
hdCamera.UpdateStereoDependentState(ref cullingParams);
#if UNITY_EDITOR
// emit scene view UI

}
#endif
if (m_FrameSettings.enableDBuffer)
if (hdCamera.frameSettings.enableDBuffer)
{
// decal system needs to be updated with current camera, it needs it to set up culling and light list generation parameters
DecalSystem.instance.CurrentCamera = camera;

m_DbufferManager.vsibleDecalCount = 0;
using (new ProfilingSample(cmd, "DBufferPrepareDrawData", CustomSamplerId.DBufferPrepareDrawData.GetSampler()))
{
if (m_FrameSettings.enableDBuffer)
if (hdCamera.frameSettings.enableDBuffer)
{
DecalSystem.instance.EndCull();
m_DbufferManager.vsibleDecalCount = DecalSystem.m_DecalsVisibleThisFrame;

}
}
renderContext.SetupCameraProperties(camera, m_FrameSettings.enableStereo);
renderContext.SetupCameraProperties(camera, hdCamera.frameSettings.enableStereo);
PushGlobalParams(hdCamera, cmd, diffusionProfileSettings);

bool enableBakeShadowMask;
using (new ProfilingSample(cmd, "TP_PrepareLightsForGPU", CustomSamplerId.TPPrepareLightsForGPU.GetSampler()))
{
enableBakeShadowMask = m_LightLoop.PrepareLightsForGPU(cmd, camera, m_ShadowSettings, m_CullResults, m_ReflectionProbeCullResults, densityVolumes) && m_FrameSettings.enableShadowMask;
enableBakeShadowMask = m_LightLoop.PrepareLightsForGPU(cmd, camera, m_ShadowSettings, m_CullResults, m_ReflectionProbeCullResults, densityVolumes) && hdCamera.frameSettings.enableShadowMask;
StartStereoRendering(renderContext, hdCamera.camera);
StartStereoRendering(renderContext, hdCamera);
ClearBuffers(hdCamera, cmd);

RenderObjectsVelocity(m_CullResults, hdCamera, renderContext, cmd);
// This will bind the depth buffer if needed for DBuffer)
RenderDBuffer(hdCamera, cmd);
RenderGBuffer(m_CullResults, hdCamera, enableBakeShadowMask, renderContext, cmd);

RenderCameraVelocity(m_CullResults, hdCamera, renderContext, cmd);
// Depth texture is now ready, bind it.
cmd.SetGlobalTexture(HDShaderIDs._MainDepthTexture, GetDepthTexture());
// Depth texture is now ready, bind it (Depth buffer could have been bind before if DBuffer is enable)
cmd.SetGlobalTexture(HDShaderIDs._CameraDepthTexture, GetDepthTexture());
// Caution: We require sun light here as some skies use the sun light to render, it means that UpdateSkyEnvironment must be called after PrepareLightsForGPU.
// TODO: Try to arrange code so we can trigger this call earlier and use async compute here to run sky convolution during other passes (once we move convolution shader to compute).

StopStereoRendering(renderContext, hdCamera.camera);
StopStereoRendering(renderContext, hdCamera);
if (m_CurrentDebugDisplaySettings.IsDebugMaterialDisplayEnabled())
{

}
else
{
StartStereoRendering(renderContext, hdCamera.camera);
StartStereoRendering(renderContext, hdCamera);
using (new ProfilingSample(cmd, "Render SSAO", CustomSamplerId.RenderSSAO.GetSampler()))
{

}
}
StopStereoRendering(renderContext, hdCamera.camera);
StopStereoRendering(renderContext, hdCamera);
if (m_FrameSettings.enableAsyncCompute)
if (hdCamera.frameSettings.enableAsyncCompute)
{
GPUFence startFence = cmd.CreateGPUFence();
renderContext.ExecuteCommandBuffer(cmd);

m_LightLoop.RenderShadows(renderContext, cmd, m_CullResults);
// Overwrite camera properties set during the shadow pass with the original camera properties.
renderContext.SetupCameraProperties(camera, m_FrameSettings.enableStereo);
renderContext.SetupCameraProperties(camera, hdCamera.frameSettings.enableStereo);
if (m_FrameSettings.enableStereo) hdCamera.SetupGlobalStereoParams(cmd);
if (hdCamera.frameSettings.enableStereo)
hdCamera.SetupGlobalStereoParams(cmd);
}
using (new ProfilingSample(cmd, "Deferred directional shadows", CustomSamplerId.RenderDeferredDirectionalShadow.GetSampler()))

}
m_LightLoop.RenderDeferredDirectionalShadow(hdCamera, m_DeferredShadowBuffer, GetDepthTexture(), cmd);
PushFullScreenDebugTexture(cmd, m_DeferredShadowBuffer, hdCamera, FullScreenDebugMode.DeferredShadows);
PushFullScreenDebugTexture(hdCamera, cmd, m_DeferredShadowBuffer, FullScreenDebugMode.DeferredShadows);
if (m_FrameSettings.enableAsyncCompute)
if (hdCamera.frameSettings.enableAsyncCompute)
{
m_LightLoop.BuildGPULightListAsyncEnd(hdCamera, cmd, buildGPULightListsCompleteFence);
}

{
// Set fog parameters for volumetric lighting.
var visualEnv = VolumeManager.instance.stack.GetComponent<VisualEnvironment>();
visualEnv.PushFogShaderParameters(cmd, m_FrameSettings);
visualEnv.PushFogShaderParameters(hdCamera, cmd);
m_VolumetricLightingSystem.VolumeVoxelizationPass(densityVolumes, hdCamera, cmd, m_FrameSettings, m_FrameCount);
m_VolumetricLightingSystem.VolumeVoxelizationPass(hdCamera, cmd, m_FrameCount, densityVolumes);
m_VolumetricLightingSystem.VolumetricLightingPass(hdCamera, cmd, m_FrameSettings, m_FrameCount);
m_VolumetricLightingSystem.VolumetricLightingPass(hdCamera, cmd, m_FrameCount);
StartStereoRendering(renderContext, hdCamera.camera);
StartStereoRendering(renderContext, hdCamera);
m_SSSBufferManager.SubsurfaceScatteringPass(hdCamera, cmd, diffusionProfileSettings, m_FrameSettings,
m_SSSBufferManager.SubsurfaceScatteringPass(hdCamera, cmd, diffusionProfileSettings,
m_CameraColorBuffer, m_CameraSssDiffuseLightingBuffer, m_CameraDepthStencilBuffer, GetDepthTexture());
RenderSky(hdCamera, cmd);

RenderColorPyramid(hdCamera, cmd, renderContext, false);
AccumulateDistortion(m_CullResults, hdCamera, renderContext, cmd);
RenderDistortion(cmd, m_Asset.renderPipelineResources, hdCamera);
RenderDistortion(hdCamera, cmd, m_Asset.renderPipelineResources);
StopStereoRendering(renderContext, hdCamera.camera);
StopStereoRendering(renderContext, hdCamera);
PushFullScreenDebugTexture(cmd, m_CameraColorBuffer, hdCamera, FullScreenDebugMode.NanTracker);
PushColorPickerDebugTexture(cmd, m_CameraColorBuffer, hdCamera);
PushFullScreenDebugTexture(hdCamera, cmd, m_CameraColorBuffer, FullScreenDebugMode.NanTracker);
PushColorPickerDebugTexture(hdCamera, cmd, m_CameraColorBuffer);
StartStereoRendering(renderContext, hdCamera.camera);
StartStereoRendering(renderContext, hdCamera);
if (m_FrameSettings.enablePostprocess)
if (hdCamera.frameSettings.enablePostprocess)
{
RenderPostProcess(hdCamera, cmd, postProcessLayer);
}

}
}
StopStereoRendering(renderContext, hdCamera.camera);
StopStereoRendering(renderContext, hdCamera);
if (m_FrameSettings.enableStereo)
if (hdCamera.frameSettings.enableStereo)
renderContext.StereoEndRender(hdCamera.camera);
}

}
}
#endif
PushFullScreenDebugTexture(cmd, m_CameraColorBuffer, hdCamera, FullScreenDebugMode.ScreenSpaceTracing);
PushFullScreenDebugTexture(hdCamera, cmd, m_CameraColorBuffer, FullScreenDebugMode.ScreenSpaceTracing);
// Caution: RenderDebug need to take into account that we have flip the screen (so anything capture before the flip will be flipped)
RenderDebug(hdCamera, cmd);

}
void RenderOpaqueRenderList(CullResults cull,
Camera camera,
HDCamera hdCamera,
ScriptableRenderContext renderContext,
CommandBuffer cmd,
ShaderPassName passName,

Material overrideMaterial = null)
{
m_SinglePassName[0] = passName;
RenderOpaqueRenderList(cull, camera, renderContext, cmd, m_SinglePassName, rendererConfiguration, inRenderQueueRange, stateBlock, overrideMaterial);
RenderOpaqueRenderList(cull, hdCamera, renderContext, cmd, m_SinglePassName, rendererConfiguration, inRenderQueueRange, stateBlock, overrideMaterial);
Camera camera,
HDCamera hdCamera,
ScriptableRenderContext renderContext,
CommandBuffer cmd,
ShaderPassName[] passNames,

Material overrideMaterial = null)
{
if (!m_FrameSettings.enableOpaqueObjects)
if (!hdCamera.frameSettings.enableOpaqueObjects)
return;
// This is done here because DrawRenderers API lives outside command buffers so we need to make call this before doing any DrawRenders

var drawSettings = new DrawRendererSettings(camera, HDShaderPassNames.s_EmptyName)
var drawSettings = new DrawRendererSettings(hdCamera.camera, HDShaderPassNames.s_EmptyName)
{
rendererConfiguration = rendererConfiguration,
sorting = { flags = SortFlags.CommonOpaque }

}
void RenderTransparentRenderList(CullResults cull,
Camera camera,
HDCamera hdCamera,
ScriptableRenderContext renderContext,
CommandBuffer cmd,
ShaderPassName passName,

Material overrideMaterial = null)
{
m_SinglePassName[0] = passName;
RenderTransparentRenderList(cull, camera, renderContext, cmd, m_SinglePassName,
RenderTransparentRenderList(cull, hdCamera, renderContext, cmd, m_SinglePassName,
Camera camera,
HDCamera hdCamera,
ScriptableRenderContext renderContext,
CommandBuffer cmd,
ShaderPassName[] passNames,

Material overrideMaterial = null
)
{
if (!m_FrameSettings.enableTransparentObjects)
if (!hdCamera.frameSettings.enableTransparentObjects)
return;
// This is done here because DrawRenderers API lives outside command buffers so we need to make call this before doing any DrawRenders

var drawSettings = new DrawRendererSettings(camera, HDShaderPassNames.s_EmptyName)
var drawSettings = new DrawRendererSettings(hdCamera.camera, HDShaderPassNames.s_EmptyName)
{
rendererConfiguration = rendererConfiguration,
sorting = { flags = SortFlags.CommonTransparent }

void AccumulateDistortion(CullResults cullResults, HDCamera hdCamera, ScriptableRenderContext renderContext, CommandBuffer cmd)
{
if (!m_FrameSettings.enableDistortion)
if (!hdCamera.frameSettings.enableDistortion)
return;
using (new ProfilingSample(cmd, "Distortion", CustomSamplerId.Distortion.GetSampler()))

// Only transparent object can render distortion vectors
RenderTransparentRenderList(cullResults, hdCamera.camera, renderContext, cmd, HDShaderPassNames.s_DistortionVectorsName);
RenderTransparentRenderList(cullResults, hdCamera, renderContext, cmd, HDShaderPassNames.s_DistortionVectorsName);
void RenderDistortion(CommandBuffer cmd, RenderPipelineResources resources, HDCamera hdCamera)
void RenderDistortion(HDCamera hdCamera, CommandBuffer cmd, RenderPipelineResources resources)
if (!m_FrameSettings.enableDistortion)
if (!hdCamera.frameSettings.enableDistortion)
return;
using (new ProfilingSample(cmd, "ApplyDistortion", CustomSamplerId.ApplyDistortion.GetSampler()))

// by using the pass "ForwardOnly". In this case the .shader should not have "Forward" but only a "ForwardOnly" pass.
// It must also have a "DepthForwardOnly" and no "DepthOnly" pass as forward material (either deferred or forward only rendering) have always a depth pass.
// If a forward material have no depth prepass, then lighting can be incorrect (deferred sahdowing, SSAO), this may be acceptable depends on usage
bool addFullDepthPrepass = forcePrepass || m_FrameSettings.enableForwardRenderingOnly || m_FrameSettings.enableDepthPrepassWithDeferredRendering;
var camera = hdCamera.camera;
bool addFullDepthPrepass = forcePrepass || hdCamera.frameSettings.enableForwardRenderingOnly || hdCamera.frameSettings.enableDepthPrepassWithDeferredRendering;
using (new ProfilingSample(cmd, !addFullDepthPrepass ? "Depth Prepass alpha test" : "Depth Prepass", CustomSamplerId.DepthPrepass.GetSampler()))
{

// We render first the opaque object as opaque alpha tested are more costly to render and could be reject by early-z (but not Hi-z as it is disable with clip instruction)
// This is handled automatically with the RenderQueue value (OpaqueAlphaTested have a different value and thus are sorted after Opaque)
RenderOpaqueRenderList(cull, camera, renderContext, cmd, m_DepthOnlyAndDepthForwardOnlyPassNames, 0, HDRenderQueue.k_RenderQueue_AllOpaque);
RenderOpaqueRenderList(cull, hdCamera, renderContext, cmd, m_DepthOnlyAndDepthForwardOnlyPassNames, 0, HDRenderQueue.k_RenderQueue_AllOpaque);
RenderOpaqueRenderList(cull, camera, renderContext, cmd, m_DepthForwardOnlyPassNames, 0, HDRenderQueue.k_RenderQueue_AllOpaque);
RenderOpaqueRenderList(cull, hdCamera, renderContext, cmd, m_DepthForwardOnlyPassNames, 0, HDRenderQueue.k_RenderQueue_AllOpaque);
RenderOpaqueRenderList(cull, camera, renderContext, cmd, m_DepthOnlyPassNames, 0, renderQueueRange);
RenderOpaqueRenderList(cull, hdCamera, renderContext, cmd, m_DepthOnlyPassNames, 0, renderQueueRange);
if (m_FrameSettings.enableTransparentPrepass)
if (hdCamera.frameSettings.enableTransparentPrepass)
RenderTransparentRenderList(cull, camera, renderContext, cmd, m_TransparentDepthPrepassNames);
RenderTransparentRenderList(cull, hdCamera, renderContext, cmd, m_TransparentDepthPrepassNames);
}
}
}

void RenderGBuffer(CullResults cull, HDCamera hdCamera, bool enableShadowMask, ScriptableRenderContext renderContext, CommandBuffer cmd)
{
if (m_FrameSettings.enableForwardRenderingOnly)
if (hdCamera.frameSettings.enableForwardRenderingOnly)
var camera = hdCamera.camera;
RenderOpaqueRenderList(cull, camera, renderContext, cmd, HDShaderPassNames.s_GBufferName, m_currentRendererConfigurationBakedLighting, HDRenderQueue.k_RenderQueue_AllOpaque);
RenderOpaqueRenderList(cull, hdCamera, renderContext, cmd, HDShaderPassNames.s_GBufferName, m_currentRendererConfigurationBakedLighting, HDRenderQueue.k_RenderQueue_AllOpaque);
void RenderDBuffer(HDCamera camera, CommandBuffer cmd)
void RenderDBuffer(HDCamera hdCamera, CommandBuffer cmd)
if (!m_FrameSettings.enableDBuffer)
if (!hdCamera.frameSettings.enableDBuffer)
return;
using (new ProfilingSample(cmd, "DBufferRender", CustomSamplerId.DBufferRender.GetSampler()))

// Depth texture is now ready, bind it.
cmd.SetGlobalTexture(HDShaderIDs._MainDepthTexture, GetDepthTexture());
m_DbufferManager.ClearTargets(cmd, camera);
HDUtils.SetRenderTarget(cmd, camera, m_DbufferManager.GetBuffersRTI(), m_CameraDepthStencilBuffer); // do not clear anymore
cmd.SetGlobalTexture(HDShaderIDs._CameraDepthTexture, GetDepthTexture());
m_DbufferManager.ClearTargets(cmd, hdCamera);
HDUtils.SetRenderTarget(cmd, hdCamera, m_DbufferManager.GetBuffersRTI(), m_CameraDepthStencilBuffer); // do not clear anymore
m_DbufferManager.SetHTile(m_DbufferManager.bufferCount, cmd);
DecalSystem.instance.RenderIntoDBuffer(cmd);
m_DbufferManager.UnSetHTile(cmd);

{
using (new ProfilingSample(cmd, "DisplayDebug ViewMaterial", CustomSamplerId.DisplayDebugViewMaterial.GetSampler()))
{
if (m_CurrentDebugDisplaySettings.materialDebugSettings.IsDebugGBufferEnabled() && !m_FrameSettings.enableForwardRenderingOnly)
if (m_CurrentDebugDisplaySettings.materialDebugSettings.IsDebugGBufferEnabled() && !hdCamera.frameSettings.enableForwardRenderingOnly)
{
using (new ProfilingSample(cmd, "DebugViewMaterialGBuffer", CustomSamplerId.DebugViewMaterialGBuffer.GetSampler()))
{

HDUtils.SetRenderTarget(cmd, hdCamera, m_CameraColorBuffer, m_CameraDepthStencilBuffer, ClearFlag.All, CoreUtils.clearColorAllBlack);
// Render Opaque forward
RenderOpaqueRenderList(cull, hdCamera.camera, renderContext, cmd, m_AllForwardOpaquePassNames, m_currentRendererConfigurationBakedLighting, stateBlock: m_DepthStateOpaque);
RenderOpaqueRenderList(cull, hdCamera, renderContext, cmd, m_AllForwardOpaquePassNames, m_currentRendererConfigurationBakedLighting, stateBlock: m_DepthStateOpaque);
RenderTransparentRenderList(cull, hdCamera.camera, renderContext, cmd, m_AllTransparentPassNames, m_currentRendererConfigurationBakedLighting, stateBlock: m_DepthStateOpaque);
RenderTransparentRenderList(cull, hdCamera, renderContext, cmd, m_AllTransparentPassNames, m_currentRendererConfigurationBakedLighting, stateBlock: m_DepthStateOpaque);
}
}

var camera = hdCamera.camera;
// Apply SSAO from PostProcessLayer
if (m_FrameSettings.enableSSAO && postProcessLayer != null && postProcessLayer.enabled)
if (hdCamera.frameSettings.enableSSAO && postProcessLayer != null && postProcessLayer.enabled)
{
var settings = postProcessLayer.GetSettings<AmbientOcclusion>();

cmd.SetGlobalTexture(HDShaderIDs._AmbientOcclusionTexture, m_AmbientOcclusionBuffer);
cmd.SetGlobalVector(HDShaderIDs._AmbientOcclusionParam, new Vector4(settings.color.value.r, settings.color.value.g, settings.color.value.b, settings.directLightingStrength.value));
PushFullScreenDebugTexture(cmd, m_AmbientOcclusionBuffer, hdCamera, FullScreenDebugMode.SSAO);
PushFullScreenDebugTexture(hdCamera, cmd, m_AmbientOcclusionBuffer, FullScreenDebugMode.SSAO);
return;
}
}

void RenderDeferredLighting(HDCamera hdCamera, CommandBuffer cmd)
{
if (m_FrameSettings.enableForwardRenderingOnly)
if (hdCamera.frameSettings.enableForwardRenderingOnly)
return;
m_MRTCache2[0] = m_CameraColorBuffer;

var options = new LightLoop.LightingPassOptions();
if (m_FrameSettings.enableSubsurfaceScattering)
if (hdCamera.frameSettings.enableSubsurfaceScattering)
{
// Output split lighting for materials asking for it (masked in the stencil buffer)
options.outputSplitLighting = true;

if (pass == ForwardPass.Opaque)
{
// In case of forward SSS we will bind all the required target. It is up to the shader to write into it or not.
if (m_FrameSettings.enableSubsurfaceScattering)
if (hdCamera.frameSettings.enableSubsurfaceScattering)
{
RenderTargetIdentifier[] m_MRTWithSSS =
new RenderTargetIdentifier[2 + m_SSSBufferManager.sssBufferCount];

HDShaderPassNames.s_ForwardOnlyName;
m_ForwardAndForwardOnlyPassNames[1] = HDShaderPassNames.s_ForwardName;
var passNames = m_FrameSettings.enableForwardRenderingOnly
var passNames = hdCamera.frameSettings.enableForwardRenderingOnly
? m_ForwardAndForwardOnlyPassNames
: m_ForwardOnlyPassNames;
var debugSSTThisPass = debugScreenSpaceTracing && (m_CurrentDebugDisplaySettings.lightingDebugSettings.debugLightingMode == DebugLightingMode.ScreenSpaceTracingReflection);

cmd.SetRandomWriteTarget(7, m_DebugScreenSpaceTracingData);
}
RenderOpaqueRenderList(cullResults, camera, renderContext, cmd, passNames, m_currentRendererConfigurationBakedLighting);
RenderOpaqueRenderList(cullResults, hdCamera, renderContext, cmd, passNames, m_currentRendererConfigurationBakedLighting);
if (debugSSTThisPass)
cmd.ClearRandomWriteTargets();
}

if ((m_FrameSettings.enableDBuffer) && (DecalSystem.m_DecalsVisibleThisFrame > 0)) // enable d-buffer flag value is being interpreted more like enable decals in general now that we have clustered
if ((hdCamera.frameSettings.enableDBuffer) && (DecalSystem.m_DecalsVisibleThisFrame > 0)) // enable d-buffer flag value is being interpreted more like enable decals in general now that we have clustered
{
DecalSystem.instance.SetAtlas(cmd); // for clustered decals
}

cmd.SetGlobalBuffer(HDShaderIDs._DebugScreenSpaceTracingData, m_DebugScreenSpaceTracingData);
cmd.SetRandomWriteTarget(7, m_DebugScreenSpaceTracingData);
}
RenderTransparentRenderList(cullResults, camera, renderContext, cmd, m_AllTransparentPassNames, m_currentRendererConfigurationBakedLighting, pass == ForwardPass.PreRefraction ? HDRenderQueue.k_RenderQueue_PreRefraction : HDRenderQueue.k_RenderQueue_Transparent);
RenderTransparentRenderList(cullResults, hdCamera, renderContext, cmd, m_AllTransparentPassNames, m_currentRendererConfigurationBakedLighting, pass == ForwardPass.PreRefraction ? HDRenderQueue.k_RenderQueue_PreRefraction : HDRenderQueue.k_RenderQueue_Transparent);
if (debugSSTThisPass)
cmd.ClearRandomWriteTargets();
}

if (pass == ForwardPass.Opaque)
{
RenderOpaqueRenderList(cullResults, hdCamera.camera, renderContext, cmd, m_ForwardErrorPassNames, 0, null, null, m_ErrorMaterial);
RenderOpaqueRenderList(cullResults, hdCamera, renderContext, cmd, m_ForwardErrorPassNames, 0, null, null, m_ErrorMaterial);
RenderTransparentRenderList(cullResults, hdCamera.camera, renderContext, cmd, m_ForwardErrorPassNames, 0, pass == ForwardPass.PreRefraction ? HDRenderQueue.k_RenderQueue_PreRefraction : HDRenderQueue.k_RenderQueue_Transparent, null, m_ErrorMaterial);
RenderTransparentRenderList(cullResults, hdCamera, renderContext, cmd, m_ForwardErrorPassNames, 0, pass == ForwardPass.PreRefraction ? HDRenderQueue.k_RenderQueue_PreRefraction : HDRenderQueue.k_RenderQueue_Transparent, null, m_ErrorMaterial);
}
}
}

if (!m_FrameSettings.enableTransparentPostpass)
if (!hdCamera.frameSettings.enableTransparentPostpass)
RenderTransparentRenderList(cullResults, hdCamera.camera, renderContext, cmd, m_TransparentDepthPostpassNames);
RenderTransparentRenderList(cullResults, hdCamera, renderContext, cmd, m_TransparentDepthPostpassNames);
void RenderObjectsVelocity(CullResults cullResults, HDCamera hdcamera, ScriptableRenderContext renderContext, CommandBuffer cmd)
void RenderObjectsVelocity(CullResults cullResults, HDCamera hdCamera, ScriptableRenderContext renderContext, CommandBuffer cmd)
if (!m_FrameSettings.enableMotionVectors || !m_FrameSettings.enableObjectMotionVectors)
if (!hdCamera.frameSettings.enableMotionVectors || !hdCamera.frameSettings.enableObjectMotionVectors)
return;
using (new ProfilingSample(cmd, "Objects Velocity", CustomSamplerId.ObjectsVelocity.GetSampler()))

hdcamera.camera.depthTextureMode |= DepthTextureMode.MotionVectors | DepthTextureMode.Depth;
hdCamera.camera.depthTextureMode |= DepthTextureMode.MotionVectors | DepthTextureMode.Depth;
HDUtils.SetRenderTarget(cmd, hdcamera, m_VelocityBuffer, m_CameraDepthStencilBuffer);
RenderOpaqueRenderList(cullResults, hdcamera.camera, renderContext, cmd, HDShaderPassNames.s_MotionVectorsName, RendererConfiguration.PerObjectMotionVectors);
HDUtils.SetRenderTarget(cmd, hdCamera, m_VelocityBuffer, m_CameraDepthStencilBuffer);
RenderOpaqueRenderList(cullResults, hdCamera, renderContext, cmd, HDShaderPassNames.s_MotionVectorsName, RendererConfiguration.PerObjectMotionVectors);
void RenderCameraVelocity(CullResults cullResults, HDCamera hdcamera, ScriptableRenderContext renderContext, CommandBuffer cmd)
void RenderCameraVelocity(CullResults cullResults, HDCamera hdCamera, ScriptableRenderContext renderContext, CommandBuffer cmd)
if (!m_FrameSettings.enableMotionVectors)
if (!hdCamera.frameSettings.enableMotionVectors)
return;
using (new ProfilingSample(cmd, "Camera Velocity", CustomSamplerId.CameraVelocity.GetSampler()))

hdcamera.camera.depthTextureMode |= DepthTextureMode.MotionVectors | DepthTextureMode.Depth;
hdCamera.camera.depthTextureMode |= DepthTextureMode.MotionVectors | DepthTextureMode.Depth;
HDUtils.DrawFullScreen(cmd, hdcamera, m_CameraMotionVectorsMaterial, m_VelocityBuffer, m_CameraDepthStencilBuffer, null, 0);
PushFullScreenDebugTexture(cmd, m_VelocityBuffer, hdcamera, FullScreenDebugMode.MotionVectors);
HDUtils.DrawFullScreen(cmd, hdCamera, m_CameraMotionVectorsMaterial, m_VelocityBuffer, m_CameraDepthStencilBuffer, null, 0);
PushFullScreenDebugTexture(hdCamera, cmd, m_VelocityBuffer, FullScreenDebugMode.MotionVectors);
}
}

{
if (!m_FrameSettings.enableRoughRefraction)
if (!hdCamera.frameSettings.enableRoughRefraction)
if (!m_FrameSettings.enableDistortion && !m_FrameSettings.enablePostprocess && !m_FrameSettings.enableSSR)
if (!hdCamera.frameSettings.enableDistortion && !hdCamera.frameSettings.enablePostprocess && !hdCamera.frameSettings.enableSSR)
return;
}

m_BufferPyramid.RenderColorPyramid(hdCamera, cmd, renderContext, m_CameraColorBuffer, cameraRT);
Vector2 pyramidScale = m_BufferPyramid.GetPyramidToScreenScale(hdCamera, cameraRT);
PushFullScreenDebugTextureMip(cmd, cameraRT, m_BufferPyramid.GetPyramidLodCount(new Vector2Int(hdCamera.actualWidth, hdCamera.actualHeight)), new Vector4(pyramidScale.x, pyramidScale.y, 0.0f, 0.0f), hdCamera, isPreRefraction ? FullScreenDebugMode.PreRefractionColorPyramid : FullScreenDebugMode.FinalColorPyramid);
PushFullScreenDebugTextureMip(hdCamera, cmd, cameraRT, m_BufferPyramid.GetPyramidLodCount(new Vector2Int(hdCamera.actualWidth, hdCamera.actualHeight)), new Vector4(pyramidScale.x, pyramidScale.y, 0.0f, 0.0f), isPreRefraction ? FullScreenDebugMode.PreRefractionColorPyramid : FullScreenDebugMode.FinalColorPyramid);
if (!m_FrameSettings.enableRoughRefraction)
if (!hdCamera.frameSettings.enableRoughRefraction)
return;
var cameraRT = hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.DepthPyramid)

m_BufferPyramid.RenderDepthPyramid(hdCamera, cmd, renderContext, GetDepthTexture(), cameraRT);
Vector2 pyramidScale = m_BufferPyramid.GetPyramidToScreenScale(hdCamera, cameraRT);
PushFullScreenDebugTextureMip(cmd, cameraRT, m_BufferPyramid.GetPyramidLodCount(new Vector2Int(hdCamera.actualWidth, hdCamera.actualHeight)), new Vector4(pyramidScale.x, pyramidScale.y, 0.0f, 0.0f), hdCamera, debugMode);
PushFullScreenDebugTextureMip(hdCamera, cmd, cameraRT, m_BufferPyramid.GetPyramidLodCount(new Vector2Int(hdCamera.actualWidth, hdCamera.actualHeight)), new Vector4(pyramidScale.x, pyramidScale.y, 0.0f, 0.0f), debugMode);
}
void RenderPostProcess(HDCamera hdcamera, CommandBuffer cmd, PostProcessLayer layer)

}
// TODO TEMP: Not sure I want to keep this special case. Gotta see how to get rid of it (not sure it will work correctly for non-full viewports.
public void PushColorPickerDebugTexture(CommandBuffer cmd, RenderTargetIdentifier textureID, HDCamera hdCamera)
public void PushColorPickerDebugTexture(HDCamera hdCamera, CommandBuffer cmd, RenderTargetIdentifier textureID)
{
if (m_CurrentDebugDisplaySettings.colorPickerDebugSettings.colorPickerMode != ColorPickerDebugMode.None)
{

}
}
public void PushFullScreenDebugTexture(CommandBuffer cmd, RTHandleSystem.RTHandle textureID, HDCamera hdCamera, FullScreenDebugMode debugMode)
public void PushFullScreenDebugTexture(HDCamera hdCamera, CommandBuffer cmd, RTHandleSystem.RTHandle textureID, FullScreenDebugMode debugMode)
{
if (debugMode == m_CurrentDebugDisplaySettings.fullScreenDebugMode)
{

}
void PushFullScreenDebugTextureMip(CommandBuffer cmd, RTHandleSystem.RTHandle texture, int lodCount, Vector4 scaleBias, HDCamera hdCamera, FullScreenDebugMode debugMode)
void PushFullScreenDebugTextureMip(HDCamera hdCamera, CommandBuffer cmd, RTHandleSystem.RTHandle texture, int lodCount, Vector4 scaleBias, FullScreenDebugMode debugMode)
{
if (debugMode == m_CurrentDebugDisplaySettings.fullScreenDebugMode)
{

m_DebugFullScreen.SetTexture(HDShaderIDs._DepthPyramidTexture, hdCamera.GetPreviousFrameRT((int)HDCameraFrameHistoryType.DepthPyramid));
HDUtils.DrawFullScreen(cmd, hdCamera, m_DebugFullScreen, (RenderTargetIdentifier)BuiltinRenderTextureType.CameraTarget);
PushColorPickerDebugTexture(cmd, (RenderTargetIdentifier)BuiltinRenderTextureType.CameraTarget, hdCamera);
PushColorPickerDebugTexture(hdCamera, cmd, (RenderTargetIdentifier)BuiltinRenderTextureType.CameraTarget);
}
// Then overlays

// TODO: As we are in development and have not all the setup pass we still clear the color in emissive buffer and gbuffer, but this will be removed later.
// Clear GBuffers
if (!m_FrameSettings.enableForwardRenderingOnly)
if (!hdCamera.frameSettings.enableForwardRenderingOnly)
{
using (new ProfilingSample(cmd, "Clear GBuffer", CustomSamplerId.ClearGBuffer.GetSampler()))
{

}
}
void StartStereoRendering(ScriptableRenderContext renderContext, Camera cam)
void StartStereoRendering(ScriptableRenderContext renderContext, HDCamera hdCamera)
if (m_FrameSettings.enableStereo)
renderContext.StartMultiEye(cam);
if (hdCamera.frameSettings.enableStereo)
renderContext.StartMultiEye(hdCamera.camera);
void StopStereoRendering(ScriptableRenderContext renderContext, Camera cam)
void StopStereoRendering(ScriptableRenderContext renderContext, HDCamera hdCamera)
if (m_FrameSettings.enableStereo)
renderContext.StopMultiEye(cam);
if (hdCamera.frameSettings.enableStereo)
renderContext.StopMultiEye(hdCamera.camera);
}
}
}

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDRenderPipelineAsset.cs


{
maxPlanarReflectionProbePerCamera = renderPipelineSettings.lightLoopSettings.planarReflectionProbeCacheSize,
maxActivePlanarReflectionProbe = 512,
planarReflectionProbeSize = renderPipelineSettings.lightLoopSettings.planarReflectionTextureSize
planarReflectionProbeSize = (int)renderPipelineSettings.lightLoopSettings.planarReflectionTextureSize
};
}
}

6
ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDStringConstants.cs


public static readonly int _LtcDisneyDiffuseMatrix = Shader.PropertyToID("_LtcDisneyDiffuseMatrix");
public static readonly int _LtcMultiGGXFresnelDisneyDiffuse = Shader.PropertyToID("_LtcMultiGGXFresnelDisneyDiffuse");
public static readonly int _MainDepthTexture = Shader.PropertyToID("_MainDepthTexture");
public static readonly int _DeferredShadowTexture = Shader.PropertyToID("_DeferredShadowTexture");
public static readonly int _DeferredShadowTextureUAV = Shader.PropertyToID("_DeferredShadowTextureUAV");
public static readonly int _DirectionalShadowIndex = Shader.PropertyToID("_DirectionalShadowIndex");

public static readonly int _AmbientProbeCoeffs = Shader.PropertyToID("_AmbientProbeCoeffs");
public static readonly int _GlobalExtinction = Shader.PropertyToID("_GlobalExtinction");
public static readonly int _GlobalScattering = Shader.PropertyToID("_GlobalScattering");
public static readonly int _GlobalAsymmetry = Shader.PropertyToID("_GlobalAsymmetry");
public static readonly int _GlobalAnisotropy = Shader.PropertyToID("_GlobalAnisotropy");
public static readonly int _VBufferUvScaleAndLimit = Shader.PropertyToID("_VBufferUvScaleAndLimit");
public static readonly int _VBufferPrevUvScaleAndLimit = Shader.PropertyToID("_VBufferPrevUvScaleAndLimit");
public static readonly int _VBufferPrevDepthEncodingParams = Shader.PropertyToID("_VBufferPrevDepthEncodingParams");
public static readonly int _VBufferPrevDepthDecodingParams = Shader.PropertyToID("_VBufferPrevDepthDecodingParams");
public static readonly int _VBufferCoordToViewDirWS = Shader.PropertyToID("_VBufferCoordToViewDirWS");

18
ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDUtils.cs


{
// Will set the correct camera viewport as well.
SetRenderTarget(cmd, camera, destination);
BlitTexture(cmd, source, destination, camera.scaleBias, mipLevel, bilinear);
BlitTexture(cmd, source, destination, camera.viewportScale, mipLevel, bilinear);
}
// This case, both source and destination are camera-scaled but we want to override the scale/bias parameter.

{
SetRenderTarget(cmd, camera, destination);
cmd.SetViewport(destViewport);
BlitTexture(cmd, source, destination, camera.scaleBias, mipLevel, bilinear);
BlitTexture(cmd, source, destination, camera.viewportScale, mipLevel, bilinear);
cmd.Blit(source, destination, new Vector2(camera.scaleBias.x, camera.scaleBias.y), Vector2.zero);
cmd.Blit(source, destination, new Vector2(camera.viewportScale.x, camera.viewportScale.y), Vector2.zero);
}
// This particular case is for blitting a non-scaled texture into a scaled texture. So we setup the partial viewport but don't scale the input UVs.

MaterialPropertyBlock properties = null, int shaderPassId = 0)
{
HDUtils.SetRenderTarget(commandBuffer, camera, colorBuffer);
commandBuffer.SetGlobalVector(HDShaderIDs._ScreenToTargetScale, camera.scaleBias);
commandBuffer.SetGlobalVector(HDShaderIDs._ScreenToTargetScale, camera.doubleBufferedViewportScale);
commandBuffer.DrawProcedural(Matrix4x4.identity, material, shaderPassId, MeshTopology.Triangles, 3, 1, properties);
}

{
HDUtils.SetRenderTarget(commandBuffer, camera, colorBuffer, depthStencilBuffer);
commandBuffer.SetGlobalVector(HDShaderIDs._ScreenToTargetScale, camera.scaleBias);
commandBuffer.SetGlobalVector(HDShaderIDs._ScreenToTargetScale, camera.doubleBufferedViewportScale);
commandBuffer.DrawProcedural(Matrix4x4.identity, material, shaderPassId, MeshTopology.Triangles, 3, 1, properties);
}

{
HDUtils.SetRenderTarget(commandBuffer, camera, colorBuffers, depthStencilBuffer);
commandBuffer.SetGlobalVector(HDShaderIDs._ScreenToTargetScale, camera.scaleBias);
commandBuffer.SetGlobalVector(HDShaderIDs._ScreenToTargetScale, camera.doubleBufferedViewportScale);
commandBuffer.DrawProcedural(Matrix4x4.identity, material, shaderPassId, MeshTopology.Triangles, 3, 1, properties);
}

{
CoreUtils.SetRenderTarget(commandBuffer, colorBuffer);
commandBuffer.SetGlobalVector(HDShaderIDs._ScreenToTargetScale, camera.scaleBias);
commandBuffer.SetGlobalVector(HDShaderIDs._ScreenToTargetScale, camera.doubleBufferedViewportScale);
commandBuffer.DrawProcedural(Matrix4x4.identity, material, shaderPassId, MeshTopology.Triangles, 3, 1, properties);
}

Vector2 mousePixelCoord = MousePositionDebug.instance.GetMousePosition(camera.screenSize.y);
return new Vector4(mousePixelCoord.x, mousePixelCoord.y, camera.scaleBias.x * mousePixelCoord.x / camera.screenSize.x, camera.scaleBias.y * mousePixelCoord.y / camera.screenSize.y);
return new Vector4(mousePixelCoord.x, mousePixelCoord.y, camera.viewportScale.x * mousePixelCoord.x / camera.screenSize.x, camera.viewportScale.y * mousePixelCoord.y / camera.screenSize.y);
}
// Returns mouse click coordinates: (x,y) in pixels and (z,w) normalized inside the render target (not the viewport)

return new Vector4(mousePixelCoord.x, mousePixelCoord.y, camera.scaleBias.x * mousePixelCoord.x / camera.screenSize.x, camera.scaleBias.y * mousePixelCoord.y / camera.screenSize.y);
return new Vector4(mousePixelCoord.x, mousePixelCoord.y, camera.viewportScale.x * mousePixelCoord.x / camera.screenSize.x, camera.viewportScale.y * mousePixelCoord.y / camera.screenSize.y);
}
}
}

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Deferred.shader


// This need to stay in sync with deferred.compute
// input.positionCS is SV_Position
float depth = LOAD_TEXTURE2D(_MainDepthTexture, input.positionCS.xy).x;
float depth = LOAD_TEXTURE2D(_CameraDepthTexture, input.positionCS.xy).x;
PositionInputs posInput = GetPositionInput(input.positionCS.xy, _ScreenSize.zw, depth, UNITY_MATRIX_I_VP, UNITY_MATRIX_V, uint2(input.positionCS.xy) / GetTileSize());
float3 V = GetWorldSpaceNormalizeViewDir(posInput.positionWS);

8
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/DeferredDirectionalShadow.compute


#include "CoreRP/ShaderLibrary/Common.hlsl"
#include "../ShaderVariables.hlsl"
#include "Lighting.hlsl"
#include "Lighting.hlsl"
#pragma only_renderers d3d11 ps4 xboxone vulkan metal switch

float2 startUV = rayStartCS.xy * 0.5f + 0.5f;
startUV.y = 1.0 - startUV.y;
// Pixel to light ray in
// Pixel to light ray in
float2 rayUV = rayCS.xy * 0.5f;
rayUV.y = -rayUV.y;

float raySampleDepth = startDepth + rayDepth * sampleStep;
// Depth buffer depth for this sample
float sampleDepth = SAMPLE_TEXTURE2D_LOD(_MainDepthTexture, sampler_MainDepthTexture, sampleUV, 0.0).x;
float sampleDepth = SAMPLE_TEXTURE2D_LOD(_CameraDepthTexture, s_point_clamp_sampler, sampleUV, 0.0).x;
bool Hit = false;
float depthDiff = sampleDepth - raySampleDepth;

uint2 pixelCoord = groupId * DEFERRED_SHADOW_TILE_SIZE + groupThreadId;
uint2 tileCoord = groupId;
float depth = LOAD_TEXTURE2D(_MainDepthTexture, pixelCoord.xy).x;
float depth = LOAD_TEXTURE2D(_CameraDepthTexture, pixelCoord.xy).x;
if (depth == UNITY_RAW_FAR_CLIP_VALUE)
return;

3
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Light/HDAdditionalLightData.cs


[Range(0.0f, 1.0f)]
public float lightDimmer = 1.0f;
[Range(0.0f, 1.0f)]
public float volumetricDimmer = 1.0f;
// Not used for directional lights.
public float fadeDistance = 10000.0f;

4
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightDefinition.cs


public int dynamicShadowCasterOnly; // Use with ShadowMask feature // TODO: make it a bool
public Vector4 shadowMaskSelector; // Use with ShadowMask feature
public float volumetricDimmer; // TODO: improve the cache locality
};
[GenerateHLSL]

public Vector2 size; // Used by area (X = length or width, Y = height) and box projector lights (X = range (depth))
public GPULightType lightType;
public float minRoughness; // This is use to give a small "area" to punctual light, as if we have a light with a radius.
public float volumetricDimmer; // TODO: improve the cache locality
};

10
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightDefinition.cs.hlsl


float unused0;
int dynamicShadowCasterOnly;
float4 shadowMaskSelector;
float volumetricDimmer;
};
// Generated from UnityEngine.Experimental.Rendering.HDPipeline.LightData

float2 size;
int lightType;
float minRoughness;
float volumetricDimmer;
};
// Generated from UnityEngine.Experimental.Rendering.HDPipeline.EnvLightData

{
return value.shadowMaskSelector;
}
float GetVolumetricDimmer(DirectionalLightData value)
{
return value.volumetricDimmer;
}
//
// Accessors for UnityEngine.Experimental.Rendering.HDPipeline.LightData

float GetMinRoughness(LightData value)
{
return value.minRoughness;
}
float GetVolumetricDimmer(LightData value)
{
return value.volumetricDimmer;
}
//

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/Deferred.compute


// This need to stay in sync with deferred.shader
float depth = LOAD_TEXTURE2D(_MainDepthTexture, pixelCoord.xy).x;
float depth = LOAD_TEXTURE2D(_CameraDepthTexture, pixelCoord.xy).x;
PositionInputs posInput = GetPositionInput(pixelCoord.xy, _ScreenSize.zw, depth, UNITY_MATRIX_I_VP, UNITY_MATRIX_V, tileCoord);
// For indirect case: we can still overlap inside a tile with the sky/background, reject it

63
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/GlobalLightLoopSettings.cs


// There is a dedicated RenderRenderPipelineSettings for each platform
[Serializable]
public enum CubeReflectionResolution
{
CubeReflectionResolution128 = 128,
CubeReflectionResolution256 = 256,
CubeReflectionResolution512 = 512,
CubeReflectionResolution1024 = 1024,
CubeReflectionResolution2048 = 2048,
CubeReflectionResolution4096 = 4096
}
[Serializable]
public enum PlanarReflectionResolution
{
PlanarReflectionResolution64 = 64,
PlanarReflectionResolution128 = 128,
PlanarReflectionResolution256 = 256,
PlanarReflectionResolution512 = 512,
PlanarReflectionResolution1024 = 1024,
PlanarReflectionResolution2048 = 2048,
PlanarReflectionResolution4096 = 4096,
PlanarReflectionResolution8192 = 8192,
PlanarReflectionResolution16384 = 16384
}
[Serializable]
public enum CookieResolution
{
CookieResolution64 = 64,
CookieResolution128 = 128,
CookieResolution256 = 256,
CookieResolution512 = 512,
CookieResolution1024 = 1024,
CookieResolution2048 = 2048,
CookieResolution4096 = 4096,
CookieResolution8192 = 8192,
CookieResolution16384 = 16384
}
[Serializable]
public enum CubeCookieResolution
{
CubeCookieResolution64 = 64,
CubeCookieResolution128 = 128,
CubeCookieResolution256 = 256,
CubeCookieResolution512 = 512,
CubeCookieResolution1024 = 1024,
CubeCookieResolution2048 = 2048,
CubeCookieResolution4096 = 4096
}
[Serializable]
public int cookieSize = 128;
public CookieResolution cookieSize = CookieResolution.CookieResolution128;
public int pointCookieSize = 128;
public CubeCookieResolution pointCookieSize = CubeCookieResolution.CubeCookieResolution128;
public int reflectionProbeCacheSize = 2;
public int planarReflectionProbeCacheSize = 1024;
public int reflectionCubemapSize = 128;
public int planarReflectionTextureSize = 128;
public int planarReflectionProbeCacheSize = 2;
public PlanarReflectionResolution planarReflectionTextureSize = PlanarReflectionResolution.PlanarReflectionResolution1024;
public int reflectionProbeCacheSize = 128;
public CubeReflectionResolution reflectionCubemapSize = CubeReflectionResolution.CubeReflectionResolution128;
public bool reflectionCacheCompressed = false;
public bool planarReflectionCacheCompressed = false;
public SkyResolution skyReflectionSize = SkyResolution.SkyResolution256;

15
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoop.cs


GlobalLightLoopSettings gLightLoopSettings = hdAsset.GetRenderPipelineSettings().lightLoopSettings;
m_CookieTexArray = new TextureCache2D("Cookie");
m_CookieTexArray.AllocTextureArray(gLightLoopSettings.cookieTexArraySize, gLightLoopSettings.cookieSize, gLightLoopSettings.cookieSize, TextureFormat.RGBA32, true);
m_CookieTexArray.AllocTextureArray(gLightLoopSettings.cookieTexArraySize, (int)gLightLoopSettings.cookieSize, (int)gLightLoopSettings.cookieSize, TextureFormat.RGBA32, true);
m_CubeCookieTexArray.AllocTextureArray(gLightLoopSettings.cubeCookieTexArraySize, gLightLoopSettings.pointCookieSize, TextureFormat.RGBA32, true, m_CubeToPanoMaterial);
m_CubeCookieTexArray.AllocTextureArray(gLightLoopSettings.cubeCookieTexArraySize, (int)gLightLoopSettings.pointCookieSize, TextureFormat.RGBA32, true, m_CubeToPanoMaterial);
m_ReflectionProbeCache = new ReflectionProbeCache(hdAsset, iblFilterGGX, gLightLoopSettings.reflectionProbeCacheSize, gLightLoopSettings.reflectionCubemapSize, probeCacheFormat, true);
m_ReflectionProbeCache = new ReflectionProbeCache(hdAsset, iblFilterGGX, gLightLoopSettings.reflectionProbeCacheSize, (int)gLightLoopSettings.reflectionCubemapSize, probeCacheFormat, true);
m_ReflectionPlanarProbeCache = new PlanarReflectionProbeCache(hdAsset, iblFilterGGX, gLightLoopSettings.planarReflectionProbeCacheSize, gLightLoopSettings.planarReflectionTextureSize, planarProbeCacheFormat, true);
m_ReflectionPlanarProbeCache = new PlanarReflectionProbeCache(hdAsset, iblFilterGGX, gLightLoopSettings.planarReflectionProbeCacheSize, (int)gLightLoopSettings.planarReflectionTextureSize, planarProbeCacheFormat, true);
s_GenAABBKernel = buildScreenAABBShader.FindKernel("ScreenBoundsAABB");

directionalLightData.diffuseScale = additionalData.affectDiffuse ? diffuseDimmer : 0.0f;
directionalLightData.specularScale = additionalData.affectSpecular ? specularDimmer : 0.0f;
directionalLightData.volumetricDimmer = additionalData.volumetricDimmer;
directionalLightData.shadowIndex = directionalLightData.cookieIndex = -1;
if (light.light.cookie != null)

lightData.diffuseScale = additionalLightData.affectDiffuse ? lightScale * m_FrameSettings.diffuseGlobalDimmer : 0.0f;
lightData.specularScale = additionalLightData.affectSpecular ? lightScale * m_FrameSettings.specularGlobalDimmer : 0.0f;
lightData.volumetricDimmer = additionalLightData.volumetricDimmer;
if (lightData.diffuseScale <= 0.0f && lightData.specularScale <= 0.0f)
return false;

cmd.SetComputeIntParam(deferredDirectionalShadowComputeShader, HDShaderIDs._DirectionalShadowIndex, m_CurrentSunLightShadowIndex);
cmd.SetComputeVectorParam(deferredDirectionalShadowComputeShader, HDShaderIDs._DirectionalLightDirection, -m_CurrentSunLight.transform.forward);
cmd.SetComputeTextureParam(deferredDirectionalShadowComputeShader, kernel, HDShaderIDs._DeferredShadowTextureUAV, deferredShadowRT);
cmd.SetComputeTextureParam(deferredDirectionalShadowComputeShader, kernel, HDShaderIDs._MainDepthTexture, depthTexture);
cmd.SetComputeTextureParam(deferredDirectionalShadowComputeShader, kernel, HDShaderIDs._CameraDepthTexture, depthTexture);
int deferredShadowTileSize = 16; // Must match DeferreDirectionalShadow.compute
int numTilesX = (hdCamera.actualWidth + (deferredShadowTileSize - 1)) / deferredShadowTileSize;

}
}
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._MainDepthTexture, depthTexture);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._CameraDepthTexture, depthTexture);
// TODO: Is it possible to setup this outside the loop ? Can figure out how, get this: Property (specularLightingUAV) at kernel index (21) is not set
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs.specularLightingUAV, colorBuffers[0]);

27
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoopDef.hlsl


#define SINGLE_PASS_CONTEXT_SAMPLE_REFLECTION_PROBES 0
#define SINGLE_PASS_CONTEXT_SAMPLE_SKY 1
// The EnvLightData of the sky light contains a bunch of compile-time constants.
// This function sets them directly to allow the compiler to propagate them and optimize the code.
EnvLightData InitSkyEnvLightData(int envIndex)
{
EnvLightData output;
ZERO_INITIALIZE(EnvLightData, output);
output.influenceShapeType = ENVSHAPETYPE_SKY;
// 31 bit index, 1 bit cache type
output.envIndex = ENVCACHETYPE_CUBEMAP | (envIndex << 1);
output.influenceForward = float3(0.0, 0.0, 1.0);
output.influenceUp = float3(0.0, 1.0, 0.0);
output.influenceRight = float3(1.0, 0.0, 0.0);
output.influencePositionWS = float3(0.0, 0.0, 0.0);
output.weight = 1.0;
output.multiplier = 1.0;
// proxy
output.proxyForward = float3(0.0, 0.0, 1.0);
output.proxyUp = float3(0.0, 1.0, 0.0);
output.proxyRight = float3(1.0, 0.0, 0.0);
output.minProjectionDistance = 65504.0f;
return output;
}
bool IsEnvIndexCubemap(int index) { return (index & 1) == ENVCACHETYPE_CUBEMAP; }
bool IsEnvIndexTexture2D(int index) { return (index & 1) == ENVCACHETYPE_TEXTURE2D; }

1
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Lighting.hlsl


#define HAS_LIGHTLOOP // Allow to not define LightLoop related function in Material.hlsl
#include "../Lighting/LightDefinition.cs.hlsl"
#include "../Lighting/LightUtilities.hlsl"
#include "LightLoop/Shadow.hlsl"

6
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Reflection/PlanarReflectionProbeCache.cs


using System;
using System;
using UnityEngine.Rendering;
namespace UnityEngine.Experimental.Rendering.HDPipeline

m_TempRenderTexture.dimension = TextureDimension.Tex2D;
m_TempRenderTexture.useMipMap = true;
m_TempRenderTexture.autoGenerateMips = false;
m_TempRenderTexture.name = CoreUtils.GetRenderTargetAutoName(m_ProbeSize, m_ProbeSize, RenderTextureFormat.ARGBHalf, "PlanarReflectionTemp", mips : true);
m_TempRenderTexture.name = CoreUtils.GetRenderTargetAutoName(m_ProbeSize, m_ProbeSize, 1, RenderTextureFormat.ARGBHalf, "PlanarReflectionTemp", mips : true);
m_TempRenderTexture.Create();
m_ConvolutionTargetTexture = new RenderTexture(m_ProbeSize, m_ProbeSize, 1, RenderTextureFormat.ARGBHalf);

m_ConvolutionTargetTexture.autoGenerateMips = false;
m_ConvolutionTargetTexture.name = CoreUtils.GetRenderTargetAutoName(m_ProbeSize, m_ProbeSize, RenderTextureFormat.ARGBHalf, "PlanarReflectionConvolution", mips: true);
m_ConvolutionTargetTexture.name = CoreUtils.GetRenderTargetAutoName(m_ProbeSize, m_ProbeSize, 1, RenderTextureFormat.ARGBHalf, "PlanarReflectionConvolution", mips: true);
m_ConvolutionTargetTexture.Create();
InitializeProbeBakingStates();

6
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Reflection/ReflectionProbeCache.cs


using System;
using System;
using UnityEngine.Rendering;
namespace UnityEngine.Experimental.Rendering.HDPipeline

m_TempRenderTexture.dimension = TextureDimension.Cube;
m_TempRenderTexture.useMipMap = true;
m_TempRenderTexture.autoGenerateMips = false;
m_TempRenderTexture.name = CoreUtils.GetRenderTargetAutoName(m_ProbeSize, m_ProbeSize, RenderTextureFormat.ARGBHalf, "ReflectionProbeTemp", mips : true);
m_TempRenderTexture.name = CoreUtils.GetRenderTargetAutoName(m_ProbeSize, m_ProbeSize, 1, RenderTextureFormat.ARGBHalf, "ReflectionProbeTemp", mips : true);
m_TempRenderTexture.Create();
m_ConvolutionTargetTexture = new RenderTexture(m_ProbeSize, m_ProbeSize, 1, RenderTextureFormat.ARGBHalf);

m_ConvolutionTargetTexture.autoGenerateMips = false;
m_ConvolutionTargetTexture.name = CoreUtils.GetRenderTargetAutoName(m_ProbeSize, m_ProbeSize, RenderTextureFormat.ARGBHalf, "ReflectionProbeConvolution", mips : true);
m_ConvolutionTargetTexture.name = CoreUtils.GetRenderTargetAutoName(m_ProbeSize, m_ProbeSize, 1, RenderTextureFormat.ARGBHalf, "ReflectionProbeConvolution", mips : true);
m_ConvolutionTargetTexture.Create();
InitializeProbeBakingStates();

43
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Reflection/ReflectionSystemInternal.cs


using System;
using System;
using System.Collections.Generic;
using UnityEngine.Rendering;

for (var i = 0; i < length; i++)
{
var probe = m_PlanarReflectionProbe_RealtimeUpdate_WorkArray[i];
var hdCamera = HDCamera.Get(renderCamera, null, probe.frameSettings);
var hdCamera = HDCamera.Get(renderCamera);
if (hdCamera == null)
{
// Warning: this is a bad design pattern.
// An individual system should not create an HDCamera (which is a shared resource).
hdCamera = HDCamera.Create(renderCamera, null);
}
hdCamera.Update(probe.frameSettings, null, null);
if (!IsRealtimeTextureValid(probe.realtimeTexture, hdCamera))
{
if (probe.realtimeTexture != null)

for (var i = 0; i < length; i++)
{
var probe = m_PlanarReflectionProbe_RealtimeUpdate_WorkArray[i];
var hdCamera = HDCamera.Get(camera, null, probe.frameSettings);
var hdCamera = HDCamera.Get(camera);
if (hdCamera == null)
{
// Warning: this is a bad design pattern.
// An individual system should not create an HDCamera (which is a shared resource).
hdCamera = HDCamera.Create(camera, null);
}
hdCamera.Update(probe.frameSettings, null, null);
if (!IsRealtimeTextureValid(probe.realtimeTexture, hdCamera))
{
if (probe.realtimeTexture != null)

// No hide and don't save for this one
rt.useMipMap = true;
rt.autoGenerateMips = false;
rt.name = CoreUtils.GetRenderTargetAutoName(m_Parameters.planarReflectionProbeSize, m_Parameters.planarReflectionProbeSize, RenderTextureFormat.ARGBHalf, "PlanarProbeRT");
rt.name = CoreUtils.GetRenderTargetAutoName(m_Parameters.planarReflectionProbeSize, m_Parameters.planarReflectionProbeSize, 1, RenderTextureFormat.ARGBHalf, "PlanarProbeRT");
rt.Create();
return rt;
}

probe.frameSettings.CopyTo(s_RenderCameraData.GetFrameSettings());
return HDCamera.Get(camera, null, probe.frameSettings);
var hdCamera = HDCamera.Get(camera);
if (hdCamera == null)
{
// Warning: this is a bad design pattern.
// An individual system should not create an HDCamera (which is a shared resource).
hdCamera = HDCamera.Create(camera, null);
}
hdCamera.Update(probe.frameSettings, null, null);
return hdCamera;
}
static Camera GetRenderCamera()

8
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/SphericalHarmonics.cs


{
public float[] coeffs; // Must have the size of 3
public static ZonalHarmonicsL2 GetHenyeyGreensteinPhaseFunction(float asymmetry)
public static ZonalHarmonicsL2 GetHenyeyGreensteinPhaseFunction(float anisotropy)
float g = asymmetry;
float g = anisotropy;
var zh = new ZonalHarmonicsL2();
zh.coeffs = new float[3];

return zh;
}
public static ZonalHarmonicsL2 GetCornetteShanksPhaseFunction(float asymmetry)
public static ZonalHarmonicsL2 GetCornetteShanksPhaseFunction(float anisotropy)
float g = asymmetry;
float g = anisotropy;
var zh = new ZonalHarmonicsL2();
zh.coeffs = new float[3];

3
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Volumetrics/DensityVolumeManager.cs


{
volumeAtlas.RemoveTexture(volume.parameters.volumeMask);
}
//Upon removal we have to refresh the texture list.
TriggerVolumeAtlasRefresh();
}
public DensityVolume[] PrepareDensityVolumeData(CommandBuffer cmd)

27
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Volumetrics/VBuffer.hlsl


// Compute the linear interpolation weight.
float t = saturate((z - z0) / (z1 - z0));
// Do not saturate here, we want to know whether we are outside of the near/far plane bounds.
return d0 + t * rcpNumSlices;
}

float linearDepth,
float4 VBufferResolution,
float2 VBufferSliceCount,
float2 VBufferUvScale,
float2 VBufferUvLimit,
float4 VBufferDepthEncodingParams,
float4 VBufferDepthDecodingParams,
bool correctLinearInterpolation,

if (clampToBorder)
{
// Compute the distance to the edge, and remap it to the [0, 1] range.
// TODO: add support for the HW border clamp sampler.
// Smoothly fade from the center of the edge texel to the black border color.
float weightU = saturate((1 - 2 * abs(uv.x - 0.5)) * VBufferResolution.x);
float weightV = saturate((1 - 2 * abs(uv.y - 0.5)) * VBufferResolution.y);
float weightW = saturate((1 - 2 * abs(w - 0.5)) * VBufferSliceCount.x);

float2 weights[2], offsets[2];
BiquadraticFilter(1 - fc, weights, offsets); // Inverse-translate the filter centered around 0.5
result = (weights[0].x * weights[0].y) * SAMPLE_TEXTURE3D_LOD(VBuffer, clampSampler, float3((ic + float2(offsets[0].x, offsets[0].y)) * VBufferResolution.zw, w), 0) // Top left
+ (weights[1].x * weights[0].y) * SAMPLE_TEXTURE3D_LOD(VBuffer, clampSampler, float3((ic + float2(offsets[1].x, offsets[0].y)) * VBufferResolution.zw, w), 0) // Top right
+ (weights[0].x * weights[1].y) * SAMPLE_TEXTURE3D_LOD(VBuffer, clampSampler, float3((ic + float2(offsets[0].x, offsets[1].y)) * VBufferResolution.zw, w), 0) // Bottom left
+ (weights[1].x * weights[1].y) * SAMPLE_TEXTURE3D_LOD(VBuffer, clampSampler, float3((ic + float2(offsets[1].x, offsets[1].y)) * VBufferResolution.zw, w), 0); // Bottom right
// Apply the viewport scale right at the end.
// TODO: precompute (VBufferResolution.zw * VBufferUvScale).
result = (weights[0].x * weights[0].y) * SAMPLE_TEXTURE3D_LOD(VBuffer, clampSampler, float3(min((ic + float2(offsets[0].x, offsets[0].y)) * (VBufferResolution.zw * VBufferUvScale), VBufferUvLimit), w), 0) // Top left
+ (weights[1].x * weights[0].y) * SAMPLE_TEXTURE3D_LOD(VBuffer, clampSampler, float3(min((ic + float2(offsets[1].x, offsets[0].y)) * (VBufferResolution.zw * VBufferUvScale), VBufferUvLimit), w), 0) // Top right
+ (weights[0].x * weights[1].y) * SAMPLE_TEXTURE3D_LOD(VBuffer, clampSampler, float3(min((ic + float2(offsets[0].x, offsets[1].y)) * (VBufferResolution.zw * VBufferUvScale), VBufferUvLimit), w), 0) // Bottom left
+ (weights[1].x * weights[1].y) * SAMPLE_TEXTURE3D_LOD(VBuffer, clampSampler, float3(min((ic + float2(offsets[1].x, offsets[1].y)) * (VBufferResolution.zw * VBufferUvScale), VBufferUvLimit), w), 0); // Bottom right
result = SAMPLE_TEXTURE3D_LOD(VBuffer, clampSampler, float3(uv, w), 0);
// Apply the viewport scale right at the end.
result = SAMPLE_TEXTURE3D_LOD(VBuffer, clampSampler, float3(min(uv * VBufferUvScale, VBufferUvLimit), w), 0);
}
result *= fadeWeight;

float4x4 viewProjMatrix,
float4 VBufferResolution,
float2 VBufferSliceCount,
float2 VBufferUvScale,
float2 VBufferUvLimit,
float4 VBufferDepthEncodingParams,
float4 VBufferDepthDecodingParams,
bool correctLinearInterpolation,

linearDepth,
VBufferResolution,
VBufferSliceCount,
VBufferUvScale,
VBufferUvLimit,
VBufferDepthEncodingParams,
VBufferDepthDecodingParams,
correctLinearInterpolation,

float linearDepth,
float4 VBufferResolution,
float2 VBufferSliceCount,
float2 VBufferUvScale,
float2 VBufferUvLimit,
float4 VBufferDepthEncodingParams,
float4 VBufferDepthDecodingParams,
bool correctLinearInterpolation,

linearDepth,
VBufferResolution,
VBufferSliceCount,
VBufferUvScale,
VBufferUvLimit,
VBufferDepthEncodingParams,
VBufferDepthDecodingParams,
correctLinearInterpolation,

42
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Volumetrics/VolumetricLighting.compute


// #pragma enable_d3d11_debug_symbols
#define SHADOW_USE_ONLY_VIEW_BASED_BIASING 1 // We don't use normal biasing as it is not available when doing volumetric
#include "../../ShaderPass/ShaderPass.cs.hlsl"
#define SHADERPASS SHADERPASS_VOLUMETRIC_LIGHTING

// Computes the light integral (in-scattered radiance) within the voxel.
// Multiplication by the scattering coefficient and the phase function is performed outside.
VoxelLighting EvaluateVoxelLighting(LightLoopContext context, uint featureFlags, PositionInputs posInput, float3 centerWS,
DualRay ray, float t0, float t1, float dt, float rndVal, float extinction, float asymmetry
DualRay ray, float t0, float t1, float dt, float rndVal, float extinction, float anisotropy
#ifdef USE_CLUSTERED_LIGHTLIST
, uint lightClusters[2])
#else

// function) is not possible. We work around this issue by reprojecting
// lighting not affected by the phase function. This basically removes
// the phase function from the temporal integration process. It is a hack.
// The downside is that asymmetry no longer benefits from temporal averaging,
// and any temporal instability of asymmetry causes causes visible jitter.
// The downside is that anisotropy no longer benefits from temporal averaging,
// and any temporal instability of anisotropy causes causes visible jitter.
// asymmetry-related calculations.
// anisotropy-related calculations.
float phase = CornetteShanksPhasePartVarying(asymmetry, cosTheta);
float phase = CornetteShanksPhasePartVarying(anisotropy, cosTheta);
float intensity = attenuation * weight;
float intensity = light.volumetricDimmer * attenuation * weight;
// Compute the amount of in-scattered radiance.
lighting.radianceNoPhase += intensity * color;

// function) is not possible. We work around this issue by reprojecting
// lighting not affected by the phase function. This basically removes
// the phase function from the temporal integration process. It is a hack.
// The downside is that asymmetry no longer benefits from temporal averaging,
// and any temporal instability of asymmetry causes causes visible jitter.
// The downside is that anisotropy no longer benefits from temporal averaging,
// and any temporal instability of anisotropy causes causes visible jitter.
// asymmetry-related calculations.
// anisotropy-related calculations.
float phase = CornetteShanksPhasePartVarying(asymmetry, cosTheta);
float phase = CornetteShanksPhasePartVarying(anisotropy, cosTheta);
float intensity = attenuation * rcpPdf;
float intensity = light.volumetricDimmer * attenuation * rcpPdf;
// Compute transmittance from 't0' to 't'.
intensity *= TransmittanceHomogeneousMedium(extinction, t - t0);

// function) is not possible. We work around this issue by reprojecting
// lighting not affected by the phase function. This basically removes
// the phase function from the temporal integration process. It is a hack.
// The downside is that asymmetry no longer benefits from temporal averaging,
// and any temporal instability of asymmetry causes causes visible jitter.
// The downside is that anisotropy no longer benefits from temporal averaging,
// and any temporal instability of anisotropy causes causes visible jitter.
// asymmetry-related calculations.
float3 centerL = light.positionWS - centerWS;
// anisotropy-related calculations.
float3 centerL = light.positionWS - centerWS;
float phase = CornetteShanksPhasePartVarying(asymmetry, cosTheta);
float phase = CornetteShanksPhasePartVarying(anisotropy, cosTheta);
float intensity = attenuation * weight;
float intensity = light.volumetricDimmer * attenuation * weight;
// Compute transmittance from 't0' to 'tEntr'.
intensity *= TransmittanceHomogeneousMedium(extinction, tEntr - t0);

// TODO: piecewise linear.
float3 scattering = LOAD_TEXTURE3D(_VBufferDensity, voxelCoord).rgb;
float extinction = LOAD_TEXTURE3D(_VBufferDensity, voxelCoord).a;
float asymmetry = _GlobalAsymmetry;
float anisotropy = _GlobalAnisotropy;
// Prevent division by 0.
extinction = max(extinction, FLT_MIN);

#endif
VoxelLighting lighting = EvaluateVoxelLighting(context, featureFlags, posInput, centerWS,
ray, t0, t1, dt, rndVal, extinction, asymmetry
ray, t0, t1, dt, rndVal, extinction, anisotropy
#ifdef USE_CLUSTERED_LIGHTLIST
, lightClusters);
#else

_PrevViewProjMatrix,
_VBufferPrevResolution,
_VBufferPrevSliceCount.xy,
_VBufferPrevUvScaleAndLimit.xy,
_VBufferPrevUvScaleAndLimit.zw,
_VBufferPrevDepthEncodingParams,
_VBufferPrevDepthDecodingParams,
false, false, true);

485
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Volumetrics/VolumetricLighting.cs


using System;
using UnityEngine.Rendering;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{

Count
} // enum VolumetricLightingPreset
[Serializable]
public struct ControllerParameters
public struct VBufferParameters
public float vBufferNearPlane; // Distance in meters
public float vBufferFarPlane; // Distance in meters
public float depthSliceDistributionUniformity; // Controls the exponential depth distribution: [0, 1]
} // struct ControllerParameters
public class VBuffer
{
public struct Parameters
{
public Vector4 resolution;
public Vector2 sliceCount;
public Vector4 depthEncodingParams;
public Vector4 depthDecodingParams;
public Parameters(int w, int h, int d, ControllerParameters controlParams)
{
resolution = new Vector4(w, h, 1.0f / w, 1.0f / h);
sliceCount = new Vector2(d, 1.0f / d);
depthEncodingParams = Vector4.zero; // C# doesn't allow function calls before all members have been init
depthDecodingParams = Vector4.zero; // C# doesn't allow function calls before all members have been init
Update(controlParams);
}
public void Update(ControllerParameters controlParams)
{
float n = controlParams.vBufferNearPlane;
float f = controlParams.vBufferFarPlane;
float c = 2 - 2 * controlParams.depthSliceDistributionUniformity; // remap [0, 1] -> [2, 0]
depthEncodingParams = ComputeLogarithmicDepthEncodingParams(n, f, c);
depthDecodingParams = ComputeLogarithmicDepthDecodingParams(n, f, c);
}
} // struct Parameters
const int k_NumFrames = 2; // Double-buffer history and feedback
const int k_NumBuffers = 4; // See the list below
const int k_IndexDensity = 0;
const int k_IndexIntegral = 1;
const int k_IndexHistory = 2; // Depends on frame ID
const int k_IndexFeedback = 3; // Depends on frame ID
long m_ViewID = -1; // (m_ViewID > 0) if valid
RenderTexture[] m_Textures = null;
RenderTargetIdentifier[] m_Identifiers = null;
Parameters[] m_Params = null; // For the current and the previous frame
public long GetViewID()
{
return m_ViewID;
}
public bool IsValid()
{
return m_ViewID > 0 && m_Textures != null && m_Textures[0] != null;
}
public Vector4 resolution;
public Vector2 sliceCount;
public Vector4 uvScaleAndLimit; // Necessary to work with sub-allocation (resource aliasing) in the RTHandle system
public Vector4 depthEncodingParams;
public Vector4 depthDecodingParams;
public Parameters GetParameters(uint frameIndex)
public VBufferParameters(Vector3Int viewportResolution, Vector3Int bufferResolution, Vector2 depthRange, float depthDistributionUniformity)
return m_Params[frameIndex & 1];
}
int w = viewportResolution.x;
int h = viewportResolution.y;
int d = viewportResolution.z;
public void SetParameters(Parameters parameters, uint frameIndex)
{
m_Params[frameIndex & 1] = parameters;
}
// The depth is fixed for now.
Vector2 uvScale = new Vector2((float)w / (float)bufferResolution.x,
(float)h / (float)bufferResolution.y);
public RenderTargetIdentifier GetDensityBuffer()
{
Debug.Assert(IsValid());
return m_Identifiers[k_IndexDensity];
}
// vp_scale = vp_dim / tex_dim.
// clamp to (vp_dim - 0.5) / tex_dim = vp_scale - 0.5 * (1 / tex_dim) =
// vp_scale - 0.5 * (vp_scale / vp_dim) = vp_scale * (1 - 0.5 / vp_dim).
Vector2 uvLimit = new Vector2((w - 0.5f) / (float)bufferResolution.x,
(h - 0.5f) / (float)bufferResolution.y);
public RenderTargetIdentifier GetLightingIntegralBuffer() // Of the current frame
{
Debug.Assert(IsValid());
return m_Identifiers[k_IndexIntegral];
}
resolution = new Vector4(w, h, 1.0f / w, 1.0f / h);
sliceCount = new Vector2(d, 1.0f / d);
uvScaleAndLimit = new Vector4(uvScale.x, uvScale.y, uvLimit.x, uvLimit.y);
public RenderTargetIdentifier GetLightingHistoryBuffer(uint frameIndex) // From the previous frame
{
Debug.Assert(IsValid());
return m_Identifiers[k_IndexHistory + (frameIndex & 1)];
}
float n = depthRange.x;
float f = depthRange.y;
float c = 2 - 2 * depthDistributionUniformity; // remap [0, 1] -> [2, 0]
public RenderTargetIdentifier GetLightingFeedbackBuffer(uint frameIndex) // For the next frame
{
Debug.Assert(IsValid());
return m_Identifiers[k_IndexFeedback - (frameIndex & 1)];
depthEncodingParams = ComputeLogarithmicDepthEncodingParams(n, f, c);
depthDecodingParams = ComputeLogarithmicDepthDecodingParams(n, f, c);
public void Create(long viewID, int w, int h, int d, ControllerParameters controlParams)
{
Debug.Assert(viewID > 0);
Debug.Assert(w > 0 && h > 0 && d > 0);
// Clean up first.
Destroy();
m_ViewID = viewID;
m_Textures = new RenderTexture[k_NumBuffers];
m_Identifiers = new RenderTargetIdentifier[k_NumBuffers];
m_Params = new Parameters[k_NumFrames];
for (int i = 0; i < k_NumBuffers; i++)
{
m_Textures[i] = new RenderTexture(w, h, 0, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear);
m_Textures[i].hideFlags = HideFlags.HideAndDontSave;
m_Textures[i].filterMode = FilterMode.Trilinear; // Custom
m_Textures[i].dimension = TextureDimension.Tex3D; // TODO: request the thick 3D tiling layout
m_Textures[i].volumeDepth = d;
m_Textures[i].enableRandomWrite = true;
m_Textures[i].name = CoreUtils.GetRenderTargetAutoName(w, h, RenderTextureFormat.ARGBHalf, String.Format("VBuffer{0}", i));
m_Textures[i].Create();
// TODO: clear the texture. Clearing 3D textures does not appear to work right now.
m_Identifiers[i] = new RenderTargetIdentifier(m_Textures[i]);
}
// Start with the same parameters for both frames. Then incrementally update them.
Parameters parameters = new Parameters(w, h, d, controlParams);
m_Params[0] = parameters;
m_Params[1] = parameters;
}
public void Destroy()
{
if (m_Textures != null)
{
for (int i = 0; i < k_NumBuffers; i++)
{
if (m_Textures[i] != null)
{
m_Textures[i].Release();
}
}
}
m_ViewID = -1;
m_Textures = null;
m_Identifiers = null;
m_Params = null;
}
} // class VBuffer
} // struct Parameters
public VolumetricLightingPreset preset { get { return (VolumetricLightingPreset)Math.Min(ShaderConfig.s_VolumetricLightingPreset, (int)VolumetricLightingPreset.Count); } }

List<VBuffer> m_VBuffers = null;
List<OrientedBBox> m_VisibleVolumeBounds = null;
List<DensityVolumeData> m_VisibleVolumeData = null;
public const int k_MaxVisibleVolumeCount = 512;

static ComputeBuffer s_VisibleVolumeDataBuffer = null;
// These two buffers do not depend on the frameID and are therefore shared by all views.
RTHandleSystem.RTHandle m_DensityBufferHandle;
RTHandleSystem.RTHandle m_LightingBufferHandle;
m_VolumeVoxelizationCS = asset.renderPipelineResources.volumeVoxelizationCS;
m_VolumetricLightingCS = asset.renderPipelineResources.volumetricLightingCS;
m_VBuffers = new List<VBuffer>();
m_VisibleVolumeBounds = new List<OrientedBBox>();
m_VisibleVolumeData = new List<DensityVolumeData>();
s_VisibleVolumeBoundsBuffer = new ComputeBuffer(k_MaxVisibleVolumeCount, System.Runtime.InteropServices.Marshal.SizeOf(typeof(OrientedBBox)));
s_VisibleVolumeDataBuffer = new ComputeBuffer(k_MaxVisibleVolumeCount, System.Runtime.InteropServices.Marshal.SizeOf(typeof(DensityVolumeData)));
m_VolumeVoxelizationCS = asset.renderPipelineResources.volumeVoxelizationCS;
m_VolumetricLightingCS = asset.renderPipelineResources.volumetricLightingCS;
CreateBuffers();
public void Cleanup()
// RTHandleSystem API expects a function which computes the resolution. We define it here.
Vector2Int ComputeVBufferResolutionXY(Vector2Int screenSize)
if (preset == VolumetricLightingPreset.Off) return;
Vector3Int resolution = ComputeVBufferResolution(preset, screenSize.x, screenSize.y);
m_VolumeVoxelizationCS = null;
m_VolumetricLightingCS = null;
return new Vector2Int(resolution.x, resolution.y);
}
for (int i = 0, n = m_VBuffers.Count; i < n; i++)
// RTHandleSystem API expects a function which computes the resolution. We define it here.
Vector2Int ComputeHistoryVBufferResolutionXY(Vector2Int screenSize)
{
Vector2Int resolution = ComputeVBufferResolutionXY(screenSize);
// Since the buffers owned by the VolumetricLightingSystem may have different lifetimes compared
// to those owned by the HDCamera, we need to make sure that the buffer resolution is the same
// (in order to share the UV scale and the UV limit).
if (m_LightingBufferHandle != null)
m_VBuffers[i].Destroy();
resolution.x = Math.Max(resolution.x, m_LightingBufferHandle.rt.width);
resolution.y = Math.Max(resolution.y, m_LightingBufferHandle.rt.height);
m_VBuffers = null;
m_VisibleVolumeBounds = null;
m_VisibleVolumeData = null;
CoreUtils.SafeRelease(s_VisibleVolumeBoundsBuffer);
CoreUtils.SafeRelease(s_VisibleVolumeDataBuffer);
return resolution;
public void ResizeVBufferAndUpdateProperties(HDCamera camera, uint frameIndex)
// BufferedRTHandleSystem API expects an allocator function. We define it here.
RTHandleSystem.RTHandle HistoryBufferAllocatorFunction(string viewName, int frameIndex, RTHandleSystem rtHandleSystem)
if (preset == VolumetricLightingPreset.Off) return;
var visualEnvironment = VolumeManager.instance.stack.GetComponent<VisualEnvironment>();
if (visualEnvironment == null || visualEnvironment.fogType != FogType.Volumetric) return;
frameIndex &= 1;
var controller = camera.camera.GetComponent<VolumetricLightingController>();
int d = ComputeVBufferSliceCount(preset);
if (camera.camera.cameraType == CameraType.SceneView)
{
// HACK: since it's not possible to add a component to a scene camera,
// we take one from the "main" camera (if present).
Camera mainCamera = Camera.main;
return rtHandleSystem.Alloc(scaleFunc: ComputeHistoryVBufferResolutionXY,
slices: d,
dimension: TextureDimension.Tex3D,
colorFormat: RenderTextureFormat.ARGBHalf,
sRGB: false,
enableRandomWrite: true,
enableMSAA: false,
/* useDynamicScale: true, // <- TODO */
name: string.Format("{0}_VBufferHistory{1}", viewName, frameIndex)
);
}
if (mainCamera != null)
{
controller = mainCamera.GetComponent<VolumetricLightingController>();
}
}
void CreateBuffers()
{
Debug.Assert(m_VolumetricLightingCS != null);
if (controller == null) return;
m_VisibleVolumeBounds = new List<OrientedBBox>();
m_VisibleVolumeData = new List<DensityVolumeData>();
s_VisibleVolumeBoundsBuffer = new ComputeBuffer(k_MaxVisibleVolumeCount, Marshal.SizeOf(typeof(OrientedBBox)));
s_VisibleVolumeDataBuffer = new ComputeBuffer(k_MaxVisibleVolumeCount, Marshal.SizeOf(typeof(DensityVolumeData)));
int screenWidth = (int)camera.screenSize.x;
int screenHeight = (int)camera.screenSize.y;
long viewID = camera.GetViewID();
int d = ComputeVBufferSliceCount(preset);
Debug.Assert(viewID > 0);
m_DensityBufferHandle = RTHandles.Alloc(scaleFunc: ComputeVBufferResolutionXY,
slices: d,
dimension: TextureDimension.Tex3D,
colorFormat: RenderTextureFormat.ARGBHalf,
sRGB: false,
enableRandomWrite: true,
enableMSAA: false,
/* useDynamicScale: true, // <- TODO */
name: "VBufferDensity");
int w = 0, h = 0, d = 0;
ComputeVBufferResolutionAndScale(preset, screenWidth, screenHeight, ref w, ref h, ref d);
m_LightingBufferHandle = RTHandles.Alloc(scaleFunc: ComputeVBufferResolutionXY,
slices: d,
dimension: TextureDimension.Tex3D,
colorFormat: RenderTextureFormat.ARGBHalf,
sRGB: false,
enableRandomWrite: true,
enableMSAA: false,
/* useDynamicScale: true, // <- TODO */
name: "VBufferIntegral");
}
VBuffer vBuffer = FindVBuffer(viewID);
// For the initial allocation, no suballocation happens (the texture is full size).
VBufferParameters ComputeVBufferParameters(HDCamera hdCamera, bool isInitialAllocation)
{
Vector3Int viewportResolution = ComputeVBufferResolution(preset, hdCamera.camera.pixelWidth, hdCamera.camera.pixelHeight);
Vector3Int bufferResolution; // Could be higher due to sub-allocation (resource aliasing) in the RTHandle system
if (vBuffer != null)
if (isInitialAllocation)
VBuffer.Parameters frameParams = vBuffer.GetParameters(frameIndex);
// Found, check resolution.
if (w == frameParams.resolution.x &&
h == frameParams.resolution.y &&
d == frameParams.sliceCount.x)
{
// The resolution matches.
// Depth parameters may have changed, so update those.
frameParams.Update(controller.parameters);
vBuffer.SetParameters(frameParams, frameIndex);
return;
}
bufferResolution = viewportResolution;
// Not found - grow the array.
vBuffer = new VBuffer();
m_VBuffers.Add(vBuffer);
// All V-Buffers of the current frame should have the same size (you have to double-buffer history, of course).
bufferResolution = new Vector3Int(m_LightingBufferHandle.rt.width, m_LightingBufferHandle.rt.height, m_LightingBufferHandle.rt.volumeDepth);
vBuffer.Create(viewID, w, h, d, controller.parameters);
var controller = VolumeManager.instance.stack.GetComponent<VolumetricLightingController>();
// We must not allow the V-Buffer to extend outside of the camera's frustum.
float n = hdCamera.camera.nearClipPlane;
float f = hdCamera.camera.farClipPlane;
Vector2 vBufferDepthRange = controller.depthRange.value;
vBufferDepthRange.y = Mathf.Clamp(vBufferDepthRange.y, n, f); // far
vBufferDepthRange.x = Mathf.Clamp(vBufferDepthRange.x, n, vBufferDepthRange.y); // near
float vBufferDepthDistributionUniformity = controller.depthDistributionUniformity.value;
return new VBufferParameters(viewportResolution, bufferResolution, vBufferDepthRange, vBufferDepthDistributionUniformity);
VBuffer FindVBuffer(long viewID)
public void InitializePerCameraData(HDCamera hdCamera)
Debug.Assert(viewID > 0);
if (preset == VolumetricLightingPreset.Off) return;
VBuffer vBuffer = null;
// Start with the same parameters for both frames. Then update them one by one every frame.
var parameters = ComputeVBufferParameters(hdCamera, true);
hdCamera.vBufferParams = new VBufferParameters[2];
hdCamera.vBufferParams[0] = parameters;
hdCamera.vBufferParams[1] = parameters;
if (m_VBuffers != null)
if (hdCamera.camera.cameraType == CameraType.Game ||
hdCamera.camera.cameraType == CameraType.SceneView)
int n = m_VBuffers.Count;
for (int i = 0; i < n; i++)
{
// Check whether domain reload killed it...
if (viewID == m_VBuffers[i].GetViewID() && m_VBuffers[i].IsValid())
{
vBuffer = m_VBuffers[i];
}
}
// We don't need reprojection for other view types, such as reflection and preview.
hdCamera.AllocHistoryFrameRT((int)HDCameraFrameHistoryType.VolumetricLighting, HistoryBufferAllocatorFunction);
}
return vBuffer;
// This function relies on being called once per camera per frame.
// The results are undefined otherwise.
public void UpdatePerCameraData(HDCamera hdCamera)
{
if (preset == VolumetricLightingPreset.Off) return;
var parameters = ComputeVBufferParameters(hdCamera, false);
// Double-buffer. I assume the cost of copying is negligible (don't want to use the frame index).
hdCamera.vBufferParams[1] = hdCamera.vBufferParams[0];
hdCamera.vBufferParams[0] = parameters;
// Note: resizing of history buffer is automatic (handled by the BufferedRTHandleSystem).
}
void DestroyBuffers()
{
RTHandles.Release(m_DensityBufferHandle);
RTHandles.Release(m_LightingBufferHandle);
CoreUtils.SafeRelease(s_VisibleVolumeBoundsBuffer);
CoreUtils.SafeRelease(s_VisibleVolumeDataBuffer);
m_VisibleVolumeBounds = null;
m_VisibleVolumeData = null;
}
public void Cleanup()
{
if (preset == VolumetricLightingPreset.Off) return;
DestroyBuffers();
m_VolumeVoxelizationCS = null;
m_VolumetricLightingCS = null;
}
static int ComputeVBufferTileSize(VolumetricLightingPreset preset)

}
}
// Since a single voxel corresponds to a tile (e.g. 8x8) of pixels,
// the VBuffer can potentially extend past the boundaries of the viewport.
// The function returns the fraction of the {width, height} of the VBuffer visible on screen.
// Note: for performance reasons, the scale is unused (implicitly 1). The error is typically under 1%.
static Vector2 ComputeVBufferResolutionAndScale(VolumetricLightingPreset preset,
int screenWidth, int screenHeight,
ref int w, ref int h, ref int d)
static Vector3Int ComputeVBufferResolution(VolumetricLightingPreset preset,
int screenWidth, int screenHeight)
// Ceil(ScreenSize / TileSize).
w = (screenWidth + t - 1) / t;
h = (screenHeight + t - 1) / t;
d = ComputeVBufferSliceCount(preset);
// ceil(ScreenSize / TileSize).
int w = (screenWidth + (t - 1)) / t;
int h = (screenHeight + (t - 1)) / t;
int d = ComputeVBufferSliceCount(preset);
return new Vector2((float)screenWidth / (float)(w * t), (float)screenHeight / (float)(h * t));
return new Vector3Int(w, h, d);
}
// See EncodeLogarithmicDepthGeneralized().

return depthParams;
}
void SetPreconvolvedAmbientLightProbe(CommandBuffer cmd, float asymmetry)
void SetPreconvolvedAmbientLightProbe(CommandBuffer cmd, float anisotropy)
ZonalHarmonicsL2 phaseZH = ZonalHarmonicsL2.GetCornetteShanksPhaseFunction(asymmetry);
ZonalHarmonicsL2 phaseZH = ZonalHarmonicsL2.GetCornetteShanksPhaseFunction(anisotropy);
float CornetteShanksPhasePartConstant(float asymmetry)
float CornetteShanksPhasePartConstant(float anisotropy)
float g = asymmetry;
float g = anisotropy;
public void PushGlobalParams(HDCamera camera, CommandBuffer cmd, uint frameIndex)
public void PushGlobalParams(HDCamera hdCamera, CommandBuffer cmd, uint frameIndex)
if (visualEnvironment.fogType != FogType.Volumetric) return;
// VisualEnvironment sets global fog parameters: _GlobalAsymmetry, _GlobalScattering, _GlobalExtinction.
// VisualEnvironment sets global fog parameters: _GlobalAnisotropy, _GlobalScattering, _GlobalExtinction.
VBuffer vBuffer = FindVBuffer(camera.GetViewID());
if (vBuffer == null)
if (visualEnvironment.fogType != FogType.Volumetric)
{
// Set the neutral black texture.
cmd.SetGlobalTexture(HDShaderIDs._VBufferLighting, CoreUtils.blackVolumeTexture);

// Get the interpolated asymmetry value.
// Get the interpolated anisotropy value.
SetPreconvolvedAmbientLightProbe(cmd, fog.asymmetry);
SetPreconvolvedAmbientLightProbe(cmd, fog.anisotropy);
var currFrameParams = vBuffer.GetParameters(frameIndex);
var prevFrameParams = vBuffer.GetParameters(frameIndex - 1);
var currFrameParams = hdCamera.vBufferParams[0];
var prevFrameParams = hdCamera.vBufferParams[1];
cmd.SetGlobalVector( HDShaderIDs._VBufferUvScaleAndLimit, currFrameParams.uvScaleAndLimit);
cmd.SetGlobalVector( HDShaderIDs._VBufferPrevUvScaleAndLimit, prevFrameParams.uvScaleAndLimit);
cmd.SetGlobalTexture(HDShaderIDs._VBufferLighting, vBuffer.GetLightingIntegralBuffer());
cmd.SetGlobalTexture(HDShaderIDs._VBufferLighting, m_LightingBufferHandle);
public DensityVolumeList PrepareVisibleDensityVolumeList(HDCamera camera, CommandBuffer cmd)
public DensityVolumeList PrepareVisibleDensityVolumeList(HDCamera hdCamera, CommandBuffer cmd)
{
DensityVolumeList densityVolumes = new DensityVolumeList();

if (visualEnvironment.fogType != FogType.Volumetric) return densityVolumes;
VBuffer vBuffer = FindVBuffer(camera.GetViewID());
if (vBuffer == null) return densityVolumes;
Vector3 camPosition = camera.camera.transform.position;
Vector3 camPosition = hdCamera.camera.transform.position;
Vector3 camOffset = Vector3.zero; // World-origin-relative
if (ShaderConfig.s_CameraRelativeRendering != 0)

m_VisibleVolumeData.Clear();
// Collect all visible finite volume data, and upload it to the GPU.
DensityVolume[] volumes = DensityVolumeManager.manager.PrepareDensityVolumeData(cmd);
DensityVolume[] volumes = DensityVolumeManager.manager.PrepareDensityVolumeData(cmd);
for (int i = 0; i < Math.Min(volumes.Length, k_MaxVisibleVolumeCount); i++)
{

obb.center -= camOffset;
// Frustum cull on the CPU for now. TODO: do it on the GPU.
if (GeometryUtils.Overlap(obb, camera.frustum, 6, 8))
// TODO: account for custom near and far planes of the V-Buffer's frustum.
// It's typically much shorter (along the Z axis) than the camera's frustum.
if (GeometryUtils.Overlap(obb, hdCamera.frustum, 6, 8))
{
// TODO: cache these?
var data = volume.parameters.GetData();

}
}
public void VolumeVoxelizationPass(DensityVolumeList densityVolumes, HDCamera camera, CommandBuffer cmd, FrameSettings settings, uint frameIndex)
public void VolumeVoxelizationPass(HDCamera hdCamera, CommandBuffer cmd, uint frameIndex, DensityVolumeList densityVolumes)
VBuffer vBuffer = FindVBuffer(camera.GetViewID());
if (vBuffer == null) return;
using (new ProfilingSample(cmd, "Volume Voxelization"))
{

// Use the workaround by running the full shader with 0 density
}
bool enableClustered = settings.lightLoopSettings.enableTileAndCluster;
bool enableClustered = hdCamera.frameSettings.lightLoopSettings.enableTileAndCluster;
var frameParams = vBuffer.GetParameters(frameIndex);
var frameParams = hdCamera.vBufferParams[0];
float vFoV = camera.camera.fieldOfView * Mathf.Deg2Rad;
float vFoV = hdCamera.camera.fieldOfView * Mathf.Deg2Rad;
Matrix4x4 transform = HDUtils.ComputePixelCoordToWorldSpaceViewDirectionMatrix(vFoV, resolution, camera.viewMatrix, false);
Matrix4x4 transform = HDUtils.ComputePixelCoordToWorldSpaceViewDirectionMatrix(vFoV, resolution, hdCamera.viewMatrix, false);
Texture3D volumeAtlas = DensityVolumeManager.manager.volumeAtlas.volumeAtlas;
Vector2 volumeAtlasDimensions = new Vector2(0.0f, 0.0f);

volumeAtlasDimensions.y = 1.0f / volumeAtlas.width;
}
cmd.SetComputeTextureParam(m_VolumeVoxelizationCS, kernel, HDShaderIDs._VBufferDensity, vBuffer.GetDensityBuffer());
cmd.SetComputeTextureParam(m_VolumeVoxelizationCS, kernel, HDShaderIDs._VBufferDensity, m_DensityBufferHandle);
cmd.SetComputeBufferParam( m_VolumeVoxelizationCS, kernel, HDShaderIDs._VolumeBounds, s_VisibleVolumeBoundsBuffer);
cmd.SetComputeBufferParam( m_VolumeVoxelizationCS, kernel, HDShaderIDs._VolumeData, s_VisibleVolumeDataBuffer);
cmd.SetComputeTextureParam(m_VolumeVoxelizationCS, kernel, HDShaderIDs._VolumeMaskAtlas, volumeAtlas);

return coords;
}
public void VolumetricLightingPass(HDCamera camera, CommandBuffer cmd, FrameSettings settings, uint frameIndex)
public void VolumetricLightingPass(HDCamera hdCamera, CommandBuffer cmd, uint frameIndex)
{
if (preset == VolumetricLightingPreset.Off) return;

VBuffer vBuffer = FindVBuffer(camera.GetViewID());
if (vBuffer == null) return;
bool enableClustered = settings.lightLoopSettings.enableTileAndCluster;
bool enableReprojection = Application.isPlaying && camera.camera.cameraType == CameraType.Game;
bool enableClustered = hdCamera.frameSettings.lightLoopSettings.enableTileAndCluster;
bool enableReprojection = Application.isPlaying && hdCamera.camera.cameraType == CameraType.Game;
int kernel;

: "VolumetricLightingBruteforce");
}
var frameParams = vBuffer.GetParameters(frameIndex);
var frameParams = hdCamera.vBufferParams[0];
float vFoV = camera.camera.fieldOfView * Mathf.Deg2Rad;
float vFoV = hdCamera.camera.fieldOfView * Mathf.Deg2Rad;
Matrix4x4 transform = HDUtils.ComputePixelCoordToWorldSpaceViewDirectionMatrix(vFoV, resolution, camera.viewMatrix, false);
Matrix4x4 transform = HDUtils.ComputePixelCoordToWorldSpaceViewDirectionMatrix(vFoV, resolution, hdCamera.viewMatrix, false);
Vector2[] xySeq = GetHexagonalClosePackedSpheres7();

// Currently, we assume that they are completely uncorrelated, but maybe we should correlate them somehow.
Vector4 offset = new Vector4(xySeq[sampleIndex].x, xySeq[sampleIndex].y, zSeq[sampleIndex], frameIndex);
// Get the interpolated asymmetry value.
// Get the interpolated anisotropy value.
var fog = VolumeManager.instance.stack.GetComponent<VolumetricFog>();
// TODO: set 'm_VolumetricLightingPreset'.

cmd.SetComputeFloatParam( m_VolumetricLightingCS, HDShaderIDs._CornetteShanksConstant, CornetteShanksPhasePartConstant(fog.asymmetry));
cmd.SetComputeTextureParam(m_VolumetricLightingCS, kernel, HDShaderIDs._VBufferDensity, vBuffer.GetDensityBuffer()); // Read
cmd.SetComputeTextureParam(m_VolumetricLightingCS, kernel, HDShaderIDs._VBufferLightingIntegral, vBuffer.GetLightingIntegralBuffer()); // Write
cmd.SetComputeFloatParam( m_VolumetricLightingCS, HDShaderIDs._CornetteShanksConstant, CornetteShanksPhasePartConstant(fog.anisotropy));
cmd.SetComputeTextureParam(m_VolumetricLightingCS, kernel, HDShaderIDs._VBufferDensity, m_DensityBufferHandle); // Read
cmd.SetComputeTextureParam(m_VolumetricLightingCS, kernel, HDShaderIDs._VBufferLightingIntegral, m_LightingBufferHandle); // Write
cmd.SetComputeTextureParam(m_VolumetricLightingCS, kernel, HDShaderIDs._VBufferLightingFeedback, vBuffer.GetLightingFeedbackBuffer(frameIndex)); // Write
cmd.SetComputeTextureParam(m_VolumetricLightingCS, kernel, HDShaderIDs._VBufferLightingHistory, vBuffer.GetLightingHistoryBuffer(frameIndex)); // Read
cmd.SetComputeTextureParam(m_VolumetricLightingCS, kernel, HDShaderIDs._VBufferLightingHistory, hdCamera.GetPreviousFrameRT((int)HDCameraFrameHistoryType.VolumetricLighting)); // Read
cmd.SetComputeTextureParam(m_VolumetricLightingCS, kernel, HDShaderIDs._VBufferLightingFeedback, hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.VolumetricLighting)); // Write
}
int w = (int)resolution.x;

52
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Volumetrics/VolumetricLightingController.cs


namespace UnityEngine.Experimental.Rendering.HDPipeline
{
[ExecuteInEditMode]
[AddComponentMenu("Rendering/Volumetric Lighting Controller", 1101)]
public class VolumetricLightingController : MonoBehaviour
public class VolumetricLightingController : VolumeComponent
public VolumetricLightingSystem.ControllerParameters parameters;
public VolumetricLightingController()
{
parameters.vBufferNearPlane = 0.5f;
parameters.vBufferFarPlane = 64.0f;
parameters.depthSliceDistributionUniformity = 0.75f;
}
private void Awake()
{
}
private void OnEnable()
{
}
private void OnDisable()
{
}
private void Update()
{
}
private void OnValidate()
{
var camera = GetComponent<Camera>();
if (camera != null)
{
// We must not allow the V-Buffer to extend past the camera's frustum.
float n = camera.nearClipPlane;
float f = camera.farClipPlane;
parameters.vBufferFarPlane = Mathf.Clamp(parameters.vBufferFarPlane, n, f);
parameters.vBufferNearPlane = Mathf.Clamp(parameters.vBufferNearPlane, n, parameters.vBufferFarPlane);
parameters.depthSliceDistributionUniformity = Mathf.Clamp01(parameters.depthSliceDistributionUniformity);
}
else
{
Debug.Log("Volumetric Lighting Controller must be attached to a camera!");
}
}
[Tooltip("Near and far planes of camera's volumetric lighting buffers (in meters).")]
public FloatRangeParameter depthRange = new FloatRangeParameter(new Vector2(0.5f, 64.0f), 0.01f, 10000.0f);
[Tooltip("Controls the slice distribution: 0 = exponential (more slices near the camera, fewer slices far away), 1 = linear (uniform spacing).")]
public ClampedFloatParameter depthDistributionUniformity = new ClampedFloatParameter(0.75f, 0, 1);
}
} // UnityEngine.Experimental.Rendering.HDPipeline

4
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/DBufferManager.cs


cmd.SetGlobalTexture(HDShaderIDs._DecalHTileTexture, m_HTile);
}
public void PushGlobalParams(CommandBuffer cmd, FrameSettings frameSettings)
public void PushGlobalParams(HDCamera hdCamera, CommandBuffer cmd)
if (frameSettings.enableDBuffer)
if (hdCamera.frameSettings.enableDBuffer)
{
cmd.SetGlobalInt(HDShaderIDs._EnableDBuffer, vsibleDecalCount > 0 ? 1 : 0);
cmd.SetGlobalVector(HDShaderIDs._DecalAtlasResolution, new Vector2(HDUtils.hdrpSettings.decalSettings.atlasWidth, HDUtils.hdrpSettings.decalSettings.atlasHeight));

14
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/GGXConvolution/RuntimeFilterIBL.cs


using UnityEngine.Rendering;
using UnityEngine.Rendering;
using System;
using System.Collections.Generic;

m_GgxIblSampleData.autoGenerateMips = false;
m_GgxIblSampleData.enableRandomWrite = true;
m_GgxIblSampleData.filterMode = FilterMode.Point;
m_GgxIblSampleData.name = CoreUtils.GetRenderTargetAutoName(m_GgxIblMaxSampleCount, k_GgxIblMipCountMinusOne, RenderTextureFormat.ARGBHalf, "GGXIblSampleData");
m_GgxIblSampleData.name = CoreUtils.GetRenderTargetAutoName(m_GgxIblMaxSampleCount, k_GgxIblMipCountMinusOne, 1, RenderTextureFormat.ARGBHalf, "GGXIblSampleData");
m_GgxIblSampleData.hideFlags = HideFlags.HideAndDontSave;
m_GgxIblSampleData.Create();

var lodIsMissing = i >= m_PlanarColorMips.Count;
RenderTexture rt = null;
var createRT = lodIsMissing
var createRT = lodIsMissing
? RenderTextureReadWrite.sRGB
? RenderTextureReadWrite.sRGB
: RenderTextureReadWrite.Linear
);

}
int HashRenderTextureProperties(
int width,
int width,
int depth,
RenderTextureFormat format,
int depth,
RenderTextureFormat format,
RenderTextureReadWrite sRGB)
{
return width.GetHashCode()

56
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/Lit.hlsl


// Warning: the contents are later overwritten for Standard and SSS!
outGBuffer0 = float4(surfaceData.baseColor, surfaceData.specularOcclusion);
// The sign of the Z component of the normal MUST round-trip through the G-Buffer, otherwise
// the reconstruction of the tangent frame for anisotropic GGX creates a seam along the Z axis.
// The constant was eye-balled to not cause artifacts.
// TODO: find a proper solution. E.g. we could re-shuffle the faces of the octahedron
// s.t. the sign of the Z component round-trips.
const float seamThreshold = 1.0/1024.0;
surfaceData.normalWS.z = CopySign(max(seamThreshold, abs(surfaceData.normalWS.z)), surfaceData.normalWS.z);
// With octahedral quad packing we get an artifact for reconstructed tangent at the center of this quad. We use rect packing instead to avoid it.
float2 octNormalWS = PackNormalOctRectEncode(surfaceData.normalWS);
float2 octNormalWS = PackNormalOctQuadEncode(surfaceData.normalWS);
float3 packNormalWS = PackFloat2To888(saturate(octNormalWS * 0.5 + 0.5));
// We store perceptualRoughness instead of roughness because it is perceptually linear.
outGBuffer1 = float4(packNormalWS, PerceptualSmoothnessToPerceptualRoughness(surfaceData.perceptualSmoothness));

float3 packNormalWS = inGBuffer1.rgb;
float2 octNormalWS = Unpack888ToFloat2(packNormalWS);
bsdfData.normalWS = UnpackNormalOctRectEncode(octNormalWS * 2.0 - 1.0);
bsdfData.normalWS = UnpackNormalOctQuadEncode(octNormalWS * 2.0 - 1.0);
bsdfData.perceptualRoughness = inGBuffer1.a;
bakeDiffuseLighting = inGBuffer3.rgb;

float3x3 ltcTransformCoat; // Inverse transformation for GGX (4x VGPRs)
float ltcMagnitudeCoatFresnel;
#if HAS_REFRACTION
#endif
ZERO_INITIALIZE(PreLightData, preLightData);
// Don't init to zero to allow to track warning about uninitialized data
float3 N = bsdfData.normalWS;
preLightData.NdotV = dot(N, V);

ltcGGXFresnelMagnitude = ltcMagnitude.g;
preLightData.ltcMagnitudeCoatFresnel = (CLEAR_COAT_F0 * ltcGGXFresnelMagnitudeDiff + ltcGGXFresnelMagnitude) * bsdfData.coatMask;
}
else
{
preLightData.ltcTransformCoat = 0.0;
preLightData.ltcMagnitudeCoatFresnel = 0.0;
}
#ifdef REFRACTION_MODEL
#if HAS_REFRACTION
RefractionModelResult refraction = REFRACTION_MODEL(V, posInput, bsdfData);
preLightData.transparentRefractV = refraction.rayWS;
preLightData.transparentPositionWS = refraction.positionWS;

}
}
// In the "thin object" mode (for cards), we assume that the geometry is very thin.
// We apply wrapped lighting to compensate for that, and do not modify the shading position.
// Otherwise, in the "thick object" mode, we can have EITHER reflected (front) lighting
// OR transmitted (back) lighting, never both at the same time. For transmitted lighting,
// we need to push the shading position back to avoid self-shadowing problems.
// Note: 'bsdfData.thickness' is in world units, and already accounts for the transmission mode.
float3 ComputeThicknessDisplacement(BSDFData bsdfData, float3 L, float NdotL)
{
// Compute the thickness in world units along the light vector.
// We need a max(x, 0) here, but the saturate() is free,
// and we don't expect the total displacement of over 1 meter.
float displacement = saturate(bsdfData.thickness / -NdotL);
return displacement * L;
}
// Currently, we only model diffuse transmission. Specular transmission is not yet supported.
// Transmitted lighting is computed as follows:
// - we assume that the object is a thick plane (slab);

float3 R = preLightData.iblR;
#if HAS_REFRACTION
#endif
// Note: using influenceShapeType and projectionShapeType instead of (lightData|proxyData).shapeType allow to make compiler optimization in case the type is know (like for sky)
EvaluateLight_EnvIntersection(positionWS, bsdfData.normalWS, lightData, influenceShapeType, R, weight);

R = lerp(R, preLightData.iblR, saturate(smoothstep(0, 1, roughness * roughness)));
float3 F = preLightData.specularFGD;
float iblMipLevel = PerceptualRoughnessToMipmapLevel(preLightData.iblPerceptualRoughness);
// Specific case for Texture2Ds, their convolution is a gaussian one and not a GGX one.
// So we use another roughness mip mapping.
float iblMipLevel;
// TODO: We need to match the PerceptualRoughnessToMipmapLevel formula for planar, so we don't do this test (which is specific to our current lightloop)
// Specific case for Texture2Ds, their convolution is a gaussian one and not a GGX one - So we use another roughness mip mapping.
else
{
iblMipLevel = PerceptualRoughnessToMipmapLevel(preLightData.iblPerceptualRoughness);
}
float4 preLD = SampleEnv(lightLoopContext, lightData.envIndex, R, iblMipLevel);
weight *= preLD.a; // Used by planar reflection to discard pixel

// Can't attenuate diffuse lighting here, may try to apply something on bakeLighting in PostEvaluateBSDF
}
}
#if HAS_REFRACTION
else
{
// No clear coat support with refraction

envLighting = (1.0 - F) * preLD.rgb * preLightData.transparentTransmittance;
}
#endif
#endif // LIT_DISPLAY_REFERENCE_IBL

if (GPUImageBasedLightingType == GPUIMAGEBASEDLIGHTINGTYPE_REFLECTION)
lighting.specularReflected = envLighting;
#if HAS_REFRACTION
#endif
return lighting;
}

23
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/ShaderPass/LitDepthPass.hlsl


// Varying - Use for pixel shader
// This second set of define allow to say which varyings will be output in the vertex (no more tesselation)
#if REQUIRE_TANGENT_TO_WORLD
#define VARYINGS_NEED_POSITION_WS // Required to get view vector
#define VARYINGS_NEED_TEXCOORD0
#ifdef LAYERED_LIT_SHADER
#define VARYINGS_NEED_POSITION_WS // Required to get view vector and to get planar/triplanar mapping working
#define VARYINGS_NEED_TEXCOORD0
#if defined(_REQUIRE_UV2) || defined(_REQUIRE_UV3)
#define VARYINGS_NEED_TEXCOORD2
#endif
#if defined(_REQUIRE_UV3)
#define VARYINGS_NEED_TEXCOORD3
#endif
#ifdef ATTRIBUTES_NEED_TEXCOORD2
#define VARYINGS_NEED_TEXCOORD2
#endif
#ifdef ATTRIBUTES_NEED_TEXCOORD3
#define VARYINGS_NEED_TEXCOORD3
#endif
#ifdef ATTRIBUTES_NEED_COLOR
#define VARYINGS_NEED_COLOR
#endif
#if REQUIRE_VERTEX_COLOR
#define VARYINGS_NEED_COLOR
#endif
// This include will define the various Attributes/Varyings structure

39
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/ShaderPass/LitDistortionPass.hlsl


#endif
// Attributes
#define REQUIRE_UV_FOR_TESSELATION (defined(TESSELLATION_ON) && defined(_TESSELLATION_DISPLACEMENT))
#define REQUIRE_VERTEX_COLOR_FOR_TESSELATION REQUIRE_UV_FOR_TESSELATION
#define REQUIRE_TANGENT_TO_WORLD (defined(_HEIGHTMAP) && defined(_PIXEL_DISPLACEMENT))
#define REQUIRE_TANGENT_TO_WORLD defined(_PIXEL_DISPLACEMENT)
#define REQUIRE_NORMAL defined(TESSELLATION_ON) || REQUIRE_TANGENT_TO_WORLD || defined(_VERTEX_WIND) || defined(_VERTEX_DISPLACEMENT)
#define REQUIRE_VERTEX_COLOR (defined(_VERTEX_DISPLACEMENT) || defined(_TESSELLATION_DISPLACEMENT) || (defined(LAYERED_LIT_SHADER) && (defined(_LAYER_MASK_VERTEX_COLOR_MUL) || defined(_LAYER_MASK_VERTEX_COLOR_ADD))) || defined(_VERTEX_WIND))
#if defined(TESSELLATION_ON) || REQUIRE_TANGENT_TO_WORLD || defined(_VERTEX_WIND)
#if REQUIRE_NORMAL
#ifdef _VERTEX_WIND
#if REQUIRE_VERTEX_COLOR
#define ATTRIBUTES_NEED_COLOR
#endif

#define ATTRIBUTES_NEED_TEXCOORD0
#define ATTRIBUTES_NEED_TEXCOORD0 // Always present, distortion use TexCoord0
#if REQUIRE_UV_FOR_TESSELATION || REQUIRE_TANGENT_TO_WORLD || defined(_ALPHATEST_ON)
#if defined(_VERTEX_DISPLACEMENT) || REQUIRE_TANGENT_TO_WORLD || defined(_ALPHATEST_ON) || defined(_TESSELLATION_DISPLACEMENT)
#define ATTRIBUTES_NEED_TEXCOORD1
#if defined(_REQUIRE_UV2) || defined(_REQUIRE_UV3)
#define ATTRIBUTES_NEED_TEXCOORD2

#endif
#endif
#if REQUIRE_VERTEX_COLOR_FOR_TESSELATION
#define ATTRIBUTES_NEED_COLOR
#endif
#define VARYINGS_NEED_POSITION_WS // Can be require if we have planar or triplanar distortion
#define VARYINGS_NEED_POSITION_WS // Required to get view vector
#define VARYINGS_NEED_TEXCOORD0
#define VARYINGS_NEED_TEXCOORD0 // Always use with distortion
#ifdef LAYERED_LIT_SHADER
#if defined(_REQUIRE_UV2) || defined(_REQUIRE_UV3)
#define VARYINGS_NEED_TEXCOORD2
#endif
#if defined(_REQUIRE_UV3)
#define VARYINGS_NEED_TEXCOORD3
#endif
#ifdef ATTRIBUTES_NEED_TEXCOORD2
#define VARYINGS_NEED_TEXCOORD2
#endif
#ifdef ATTRIBUTES_NEED_TEXCOORD3
#define VARYINGS_NEED_TEXCOORD3
#endif
#ifdef ATTRIBUTES_NEED_COLOR
#define VARYINGS_NEED_COLOR
#endif
#endif

23
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/ShaderPass/LitVelocityPass.hlsl


// Varying - Use for pixel shader
// This second set of define allow to say which varyings will be output in the vertex (no more tesselation)
#define VARYINGS_NEED_POSITION_WS
#define VARYINGS_NEED_POSITION_WS // Can be require if we have planar or triplanar distortion
#if REQUIRE_TANGENT_TO_WORLD
#define VARYINGS_NEED_TANGENT_TO_WORLD

#define VARYINGS_NEED_TEXCOORD0
#ifdef LAYERED_LIT_SHADER
#define VARYINGS_NEED_TEXCOORD0
#if defined(_REQUIRE_UV2) || defined(_REQUIRE_UV3)
#define VARYINGS_NEED_TEXCOORD2
#endif
#if defined(_REQUIRE_UV3)
#define VARYINGS_NEED_TEXCOORD3
#endif
#ifdef ATTRIBUTES_NEED_TEXCOORD2
#define VARYINGS_NEED_TEXCOORD2
#endif
#ifdef ATTRIBUTES_NEED_TEXCOORD3
#define VARYINGS_NEED_TEXCOORD3
#endif
#ifdef ATTRIBUTES_NEED_COLOR
#define VARYINGS_NEED_COLOR
#endif
#if REQUIRE_VERTEX_COLOR
#define VARYINGS_NEED_COLOR
#endif
// This include will define the various Attributes/Varyings structure

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/PreIntegratedFGD/PreIntegratedFGD.cs


m_PreIntegratedFGD.filterMode = FilterMode.Bilinear;
m_PreIntegratedFGD.wrapMode = TextureWrapMode.Clamp;
m_PreIntegratedFGD.hideFlags = HideFlags.DontSave;
m_PreIntegratedFGD.name = CoreUtils.GetRenderTargetAutoName(128, 128, RenderTextureFormat.ARGB2101010, "PreIntegratedFGD");
m_PreIntegratedFGD.name = CoreUtils.GetRenderTargetAutoName(128, 128, 1, RenderTextureFormat.ARGB2101010, "PreIntegratedFGD");
m_PreIntegratedFGD.Create();
m_isInit = false;

117
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/StackLit.hlsl


}//...BSDF
float3 EvaluateTransmission(BSDFData bsdfData, float3 transmittance, float NdotL, float NdotV, float LdotV, float attenuation)
{
// Apply wrapped lighting to better handle thin objects at grazing angles.
float wrappedNdotL = ComputeWrappedDiffuseLighting(-NdotL, SSS_WRAP_LIGHT);
// Apply BSDF-specific diffuse transmission to attenuation. See also: [SSS-NOTE-TRSM]
// We don't multiply by 'bsdfData.diffuseColor' here. It's done only once in PostEvaluateBSDF().
attenuation *= Lambert();
float intensity = attenuation * wrappedNdotL;
return intensity * transmittance;
}
//-----------------------------------------------------------------------------
// EvaluateBSDF_Directional
//-----------------------------------------------------------------------------

float3 N = bsdfData.normalWS;
float3 L = -lightData.forward; // Lights point backward in Unity
//float NdotV = ClampNdotV(preLightData.NdotV);
float NdotV = ClampNdotV(preLightData.NdotV);
//float LdotV = dot(L, V);
float LdotV = dot(L, V);
// color and attenuation are outputted by EvaluateLight:
float3 color;

lighting.specular *= intensity * lightData.specularScale;
}
// NEWLITTODO: Mixed thickness, transmission
// The mixed thickness mode is not supported by directional lights due to poor quality and high performance impact.
bool mixedThicknessMode = HasFeatureFlag(bsdfData.materialFeatures, MATERIAL_FEATURE_FLAGS_TRANSMISSION_MODE_MIXED_THICKNESS);
if (HasFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_STACK_LIT_TRANSMISSION) && !mixedThicknessMode)
{
// We use diffuse lighting for accumulation since it is going to be blurred during the SSS pass.
lighting.diffuse += EvaluateTransmission(bsdfData, bsdfData.transmittance, NdotL, NdotV, LdotV, attenuation * lightData.diffuseScale);
}
// Save ALU by applying light and cookie colors only once.
lighting.diffuse *= color;

float NdotL = dot(N, L);
float LdotV = dot(L, V);
// NEWLITTODO: mixedThickness, transmission
bool mixedThicknessMode = HasFeatureFlag(bsdfData.materialFeatures, MATERIAL_FEATURE_FLAGS_TRANSMISSION_MODE_MIXED_THICKNESS)
&& NdotL < 0 && lightData.shadowIndex >= 0;
// Save the original version for the transmission code below.
int originalShadowIndex = lightData.shadowIndex;
if (mixedThicknessMode)
{
// Make sure we do not sample the shadow map twice.
lightData.shadowIndex = -1;
}
float3 color;
float attenuation;

// Restore the original shadow index.
lightData.shadowIndex = originalShadowIndex;
float intensity = max(0, attenuation * NdotL); // Warning: attenuation can be greater than 1 due to the inverse square attenuation (when position is close to light)

lighting.specular *= intensity * lightData.specularScale;
}
//NEWLITTODO : transmission
if (HasFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_STACK_LIT_TRANSMISSION))
{
float3 transmittance = bsdfData.transmittance;
if (mixedThicknessMode)
{
// Recompute transmittance using the thickness value computed from the shadow map.
// Compute the distance from the light to the back face of the object along the light direction.
float distBackFaceToLight = GetPunctualShadowClosestDistance(lightLoopContext.shadowContext, s_linear_clamp_sampler,
posInput.positionWS, lightData.shadowIndex, L, lightData.positionWS);
// Our subsurface scattering models use the semi-infinite planar slab assumption.
// Therefore, we need to find the thickness along the normal.
float distFrontFaceToLight = distances.x;
float thicknessInUnits = (distFrontFaceToLight - distBackFaceToLight) * -NdotL;
float thicknessInMeters = thicknessInUnits * _WorldScales[bsdfData.diffusionProfile].x;
float thicknessInMillimeters = thicknessInMeters * MILLIMETERS_PER_METER;
#if SHADEROPTIONS_USE_DISNEY_SSS
// We need to make sure it's not less than the baked thickness to minimize light leaking.
float thicknessDelta = max(0, thicknessInMillimeters - bsdfData.thickness);
float3 S = _ShapeParams[bsdfData.diffusionProfile].rgb;
// Approximate the decrease of transmittance by e^(-1/3 * dt * S).
#if 0
float3 expOneThird = exp(((-1.0 / 3.0) * thicknessDelta) * S);
#else
// Help the compiler.
float k = (-1.0 / 3.0) * LOG2_E;
float3 p = (k * thicknessDelta) * S;
float3 expOneThird = exp2(p);
#endif
transmittance *= expOneThird;
#else // SHADEROPTIONS_USE_DISNEY_SSS
// We need to make sure it's not less than the baked thickness to minimize light leaking.
thicknessInMillimeters = max(thicknessInMillimeters, bsdfData.thickness);
transmittance = ComputeTransmittanceJimenez(_HalfRcpVariancesAndWeights[bsdfData.diffusionProfile][0].rgb,
_HalfRcpVariancesAndWeights[bsdfData.diffusionProfile][0].a,
_HalfRcpVariancesAndWeights[bsdfData.diffusionProfile][1].rgb,
_HalfRcpVariancesAndWeights[bsdfData.diffusionProfile][1].a,
_TransmissionTintsAndFresnel0[bsdfData.diffusionProfile].rgb,
thicknessInMillimeters);
#endif // SHADEROPTIONS_USE_DISNEY_SSS
}
// Note: we do not modify the distance to the light, or the light angle for the back face.
// This is a performance-saving optimization which makes sense as long as the thickness is small.
// We use diffuse lighting for accumulation since it is going to be blurred during the SSS pass.
lighting.diffuse += EvaluateTransmission(bsdfData, transmittance, NdotL, NdotV, LdotV, attenuation * lightData.diffuseScale);
}
// Save ALU by applying light and cookie colors only once.
lighting.diffuse *= color;

R[i] = lerp(R[i], preLightData.iblR[i], saturate(smoothstep(0, 1, roughness * roughness)));
float iblMipLevel = PerceptualRoughnessToMipmapLevel(preLightData.iblPerceptualRoughness[i]);
float iblMipLevel;
// TODO: We need to match the PerceptualRoughnessToMipmapLevel formula for planar, so we don't do this test (which is specific to our current lightloop)
// Specific case for Texture2Ds, their convolution is a gaussian one and not a GGX one - So we use another roughness mip mapping.
if (IsEnvIndexTexture2D(lightData.envIndex))
{
// Empirical remapping
iblMipLevel = PositivePow(preLightData.iblPerceptualRoughness[i], 0.8) * uint(max(_ColorPyramidScale.z - 1, 0));
}
else
{
iblMipLevel = PerceptualRoughnessToMipmapLevel(preLightData.iblPerceptualRoughness[i]);
}
float4 preLD = SampleEnv(lightLoopContext, lightData.envIndex, R[i], iblMipLevel);
// Used by planar reflection to discard pixel:

bakeDiffuseLighting *= aoFactor.indirectAmbientOcclusion;
lighting.direct.diffuse *= aoFactor.directAmbientOcclusion;
// Subsurface scattering mdoe
uint texturingMode = (bsdfData.materialFeatures >> MATERIAL_FEATURE_FLAGS_SSS_TEXTURING_MODE_OFFSET) & 3;
float3 modifiedDiffuseColor = ApplySubsurfaceScatteringTexturingMode(texturingMode, bsdfData.diffuseColor);
// Apply the albedo to the direct diffuse lighting (only once). The indirect (baked)
diffuseLighting = bsdfData.diffuseColor * lighting.direct.diffuse + bakeDiffuseLighting;
diffuseLighting = modifiedDiffuseColor * lighting.direct.diffuse + bakeDiffuseLighting;
specularLighting = lighting.direct.specular + lighting.indirect.specularReflected;

16
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/StackLitData.hlsl


#endif
}
float3 SampleTexture2DTriplanarNormalScaleBias(TEXTURE2D_ARGS(textureName, samplerName), float textureNameUV, float textureNameUVLocal, float4 textureNameST, float textureNameObjSpace, TextureUVMapping uvMapping, float2 scale)
float3 SampleTexture2DTriplanarNormalScaleBias(TEXTURE2D_ARGS(textureName, samplerName), float textureNameUV, float textureNameUVLocal, float4 textureNameST, float textureNameObjSpace, TextureUVMapping uvMapping, float scale)
{
if (textureNameObjSpace)
{

// Standard
surfaceData.baseColor = SAMPLE_TEXTURE2D_SCALE_BIAS(_BaseColorMap).rgb * _BaseColor.rgb;
float3 gradient = SAMPLE_TEXTURE2D_NORMAL_SCALE_BIAS(_NormalMap, float2(_NormalScale.xx));
float3 gradient = SAMPLE_TEXTURE2D_NORMAL_SCALE_BIAS(_NormalMap, _NormalScale);
//TODO: bentNormalTS
surfaceData.perceptualSmoothnessA = dot(SAMPLE_TEXTURE2D_SCALE_BIAS(_SmoothnessAMap), _SmoothnessAMapChannelMask);

builtinData.opacity = alpha;
builtinData.bakeDiffuseLighting = SampleBakedGI(input.positionWS, surfaceData.normalWS, input.texCoord1, input.texCoord2);
// It is safe to call this function here as surfaceData have been filled
// We want to know if we must enable transmission on GI for SSS material, if the material have no SSS, this code will be remove by the compiler.
BSDFData bsdfData = ConvertSurfaceDataToBSDFData(surfaceData);
if (HasFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_STACK_LIT_TRANSMISSION))
{
// For now simply recall the function with inverted normal, the compiler should be able to optimize the lightmap case to not resample the directional lightmap
// however it will not optimize the lightprobe case due to the proxy volume relying on dynamic if (we rely must get right of this dynamic if), not a problem for SH9, but a problem for proxy volume.
// TODO: optimize more this code.
// Add GI transmission contribution by resampling the GI for inverted vertex normal
builtinData.bakeDiffuseLighting += SampleBakedGI(input.positionWS, -input.worldToTangent[2], input.texCoord1, input.texCoord2) * bsdfData.transmittance;
}
// Emissive Intensity is only use here, but is part of BuiltinData to enforce UI parameters as we want the users to fill one color and one intensity
builtinData.emissiveIntensity = _EmissiveIntensity; // We still store intensity here so we can reuse it with debug code

23
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/SubsurfaceScattering/SubsurfaceScattering.compute


#define GROUP_SIZE_2D (GROUP_SIZE_1D * GROUP_SIZE_1D)
#define TEXTURE_CACHE_BORDER 2
#define TEXTURE_CACHE_SIZE_1D (GROUP_SIZE_1D + 2 * TEXTURE_CACHE_BORDER)
#define TEXTURE_CACHE_SIZE_2D (TEXTURE_CACHE_SIZE_1D * TEXTURE_CACHE_SIZE_1D)
// Check for support of typed UAV loads from FORMAT_R16G16B16A16_FLOAT.
// TODO: query the format support more precisely.

float4 _FilterKernels[DIFFUSION_PROFILE_COUNT][SSS_N_SAMPLES_NEAR_FIELD]; // XY = near field, ZW = far field; 0 = radius, 1 = reciprocal of the PDF
TEXTURE2D(_DepthTexture); // Z-buffer
TEXTURE2D(_SSSHTile); // DXGI_FORMAT_R8_UINT is not supported by Unity
TEXTURE2D(_SSSHTile); // DXGI_FORMAT_R8_UINT is not supported by Unity
TEXTURE2D(_IrradianceSource); // Includes transmitted light
#ifdef USE_INTERMEDIATE_BUFFER

// 6656 bytes used. It appears that the reserved LDS space must be a multiple of 512 bytes.
#if SSS_USE_LDS_CACHE
groupshared float4 textureCache[TEXTURE_CACHE_SIZE_1D * TEXTURE_CACHE_SIZE_1D]; // {irradiance, linearDepth}
groupshared float2 textureCache0[TEXTURE_CACHE_SIZE_2D]; // {irradiance.rg}
groupshared float2 textureCache1[TEXTURE_CACHE_SIZE_2D]; // {irradiance.b, linearDepth}
void StoreSampleToCacheMemory(float4 value, int2 cacheCoord)
{
int linearCoord = Mad24(TEXTURE_CACHE_SIZE_1D, cacheCoord.y, cacheCoord.x);
textureCache0[linearCoord] = value.rg;
textureCache1[linearCoord] = value.ba;
}
return textureCache[Mad24(TEXTURE_CACHE_SIZE_1D, cacheCoord.y, cacheCoord.x)];
int linearCoord = Mad24(TEXTURE_CACHE_SIZE_1D, cacheCoord.y, cacheCoord.x);
return float4(textureCache0[linearCoord],
textureCache1[linearCoord]);
}
#endif

#if SSS_USE_LDS_CACHE
uint2 cacheCoord = groupCoord + TEXTURE_CACHE_BORDER;
// Populate the central region of the LDS cache.
textureCache[Mad24(TEXTURE_CACHE_SIZE_1D, cacheCoord.y, cacheCoord.x)] = float4(centerIrradiance, centerViewZ);
StoreSampleToCacheMemory(float4(centerIrradiance, centerViewZ), cacheCoord);
uint numBorderQuadsPerWave = TEXTURE_CACHE_SIZE_1D / 2 - 1;
uint halfCacheWidthInQuads = TEXTURE_CACHE_SIZE_1D / 4;

}
// Populate the border region of the LDS cache.
textureCache[Mad24(TEXTURE_CACHE_SIZE_1D, cacheCoord2.y, cacheCoord2.x)] = float4(irradiance2, viewZ2);
StoreSampleToCacheMemory(float4(irradiance2, viewZ2), cacheCoord2);
}
// Wait for the LDS.

4
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/SubsurfaceScattering/SubsurfaceScattering.shader


// Reconstruct the view-space position.
float2 centerPosSS = posInput.positionNDC;
float2 cornerPosSS = centerPosSS + 0.5 * _ScreenSize.zw;
float centerDepth = LOAD_TEXTURE2D(_MainDepthTexture, centerPosition).r;
float centerDepth = LOAD_TEXTURE2D(_CameraDepthTexture, centerPosition).r;
float3 centerPosVS = ComputeViewSpacePosition(centerPosSS, centerDepth, UNITY_MATRIX_I_P);
float3 cornerPosVS = ComputeViewSpacePosition(cornerPosSS, centerDepth, UNITY_MATRIX_I_P);

// Apply bilateral weighting.
// Ref #1: Skin Rendering by Pseudo–Separable Cross Bilateral Filtering.
// Ref #2: Separable SSS, Supplementary Materials, Section E.
float rawDepth = LOAD_TEXTURE2D(_MainDepthTexture, samplePosition).r;
float rawDepth = LOAD_TEXTURE2D(_CameraDepthTexture, samplePosition).r;
float sampleDepth = LinearEyeDepth(rawDepth, _ZBufferParams);
float zDistance = centimPerUnit * sampleDepth - (centimPerUnit * centerPosVS.z);
sampleWeight *= exp(-zDistance * zDistance * halfRcpVariance);

12
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs


RTHandles.Release(m_HTile);
}
public void PushGlobalParams(CommandBuffer cmd, DiffusionProfileSettings sssParameters, FrameSettings frameSettings)
public void PushGlobalParams(HDCamera hdCamera, CommandBuffer cmd, DiffusionProfileSettings sssParameters)
cmd.SetGlobalInt(HDShaderIDs._EnableSubsurfaceScattering, frameSettings.enableSubsurfaceScattering ? 1 : 0);
cmd.SetGlobalInt(HDShaderIDs._EnableSubsurfaceScattering, hdCamera.frameSettings.enableSubsurfaceScattering ? 1 : 0);
unsafe
{
// Warning: Unity is not able to losslessly transfer integers larger than 2^24 to the shader system.

cmd.SetGlobalVectorArray(HDShaderIDs._ShapeParams, sssParameters.shapeParams);
cmd.SetGlobalVectorArray(HDShaderIDs._HalfRcpVariancesAndWeights, sssParameters.halfRcpVariancesAndWeights);
// To disable transmission, we simply nullify the transmissionTint
cmd.SetGlobalVectorArray(HDShaderIDs._TransmissionTintsAndFresnel0, frameSettings.enableTransmission ? sssParameters.transmissionTintsAndFresnel0 : sssParameters.disabledTransmissionTintsAndFresnel0);
cmd.SetGlobalVectorArray(HDShaderIDs._TransmissionTintsAndFresnel0, hdCamera.frameSettings.enableTransmission ? sssParameters.transmissionTintsAndFresnel0 : sssParameters.disabledTransmissionTintsAndFresnel0);
cmd.SetGlobalVectorArray(HDShaderIDs._WorldScales, sssParameters.worldScales);
}

}
// Combines specular lighting and diffuse lighting with subsurface scattering.
public void SubsurfaceScatteringPass(HDCamera hdCamera, CommandBuffer cmd, DiffusionProfileSettings sssParameters, FrameSettings frameSettings,
public void SubsurfaceScatteringPass(HDCamera hdCamera, CommandBuffer cmd, DiffusionProfileSettings sssParameters,
if (sssParameters == null || !frameSettings.enableSubsurfaceScattering)
if (sssParameters == null || !hdCamera.frameSettings.enableSubsurfaceScattering)
return;
// TODO: For MSAA, at least initially, we can only support Jimenez, because we can't

HDUtils.SetRenderTarget(cmd, hdCamera, m_HTile, ClearFlag.Color, CoreUtils.clearColorAllBlack);
HDUtils.SetRenderTarget(cmd, hdCamera, depthStencilBufferRT); // No need for color buffer here
cmd.SetRandomWriteTarget(1, m_HTile);
cmd.SetRandomWriteTarget(1, m_HTile); // This need to be done AFTER SetRenderTarget
// Generate HTile for the split lighting stencil usage. Don't write into stencil texture (shaderPassId = 2)
// Use ShaderPassID 1 => "Pass 2 - Export HTILE for stencilRef to output"
CoreUtils.DrawFullScreen(cmd, m_CopyStencilForSplitLighting, null, 2);

7
ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipeline/FrameSettings.cs


public bool enableSSAO = true;
public bool enableSubsurfaceScattering = true;
public bool enableTransmission = true; // Caution: this is only for debug, it doesn't save the cost of Transmission execution
public bool enableVolumetric = true;
// Setup by system
public float diffuseGlobalDimmer = 1.0f;

aggregate.enableSSAO = srcFrameSettings.enableSSAO && renderPipelineSettings.supportSSAO;
aggregate.enableSubsurfaceScattering = camera.cameraType != CameraType.Reflection && srcFrameSettings.enableSubsurfaceScattering && renderPipelineSettings.supportSubsurfaceScattering;
aggregate.enableTransmission = srcFrameSettings.enableTransmission;
aggregate.enableVolumetric = srcFrameSettings.enableVolumetric && renderPipelineSettings.supportVolumetric;
// TODO: Add support of volumetric in planar reflection
if (camera.cameraType == CameraType.Reflection)
aggregate.enableVolumetric = false;
// We have to fall back to forward-only rendering when scene view is using wireframe rendering mode
// as rendering everything in wireframe + deferred do not play well together

aggregate.enablePostprocess = false;
aggregate.enableStereo = false;
aggregate.enableShadowMask = false;
aggregate.enableVolumetric = false;
}
LightLoopSettings.InitializeLightLoopSettings(camera, aggregate, renderPipelineSettings, srcFrameSettings, ref aggregate.lightLoopSettings);

1
ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipeline/RenderPipelineSettings.cs


public bool supportSubsurfaceScattering = true;
public bool supportForwardOnly = false;
public bool enableUltraQualitySSS = false;
public bool supportVolumetric = true;
// Engine
public bool supportDBuffer = false;

6
ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/CameraMotionVectors.shader


float4 Frag(Varyings input) : SV_Target
{
float depth = LOAD_TEXTURE2D(_MainDepthTexture, input.positionCS.xy).x;
float depth = LOAD_TEXTURE2D(_CameraDepthTexture, input.positionCS.xy).x;
PositionInputs posInput = GetPositionInput(input.positionCS.xy, _ScreenSize.zw, depth, UNITY_MATRIX_I_VP, UNITY_MATRIX_V);
float4 worldPos = float4(posInput.positionWS, 1.0);

SubShader
{
Tags{ "RenderPipeline" = "HDRenderPipeline" }
Pass
{
// We will perform camera motion velocity only where there is no object velocity

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderPass/ShaderPassDBuffer.hlsl


{
FragInputs input = UnpackVaryingsMeshToFragInputs(packedInput.vmesh);
float depth = LOAD_TEXTURE2D(_MainDepthTexture, input.positionSS.xy).x;
float depth = LOAD_TEXTURE2D(_CameraDepthTexture, input.positionSS.xy).x;
PositionInputs posInput = GetPositionInput(input.positionSS.xy, _ScreenSize.zw, depth, UNITY_MATRIX_I_VP, UNITY_MATRIX_V);
// Transform from world space to decal space (DS) to clip the decal.

7
ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderPass/ShaderPassLightTransport.hlsl


output.vmesh.positionWS = positionWS;
#endif
// Not required for meta pass but to silent the shader compiler warning in case it is declare
output.vmesh.normalWS = float3(0.0, 0.0, 0.0);
output.vmesh.tangentWS = float4(0.0, 0.0, 0.0, 0.0);
// Normal is required for triplanar mapping
output.vmesh.normalWS = TransformObjectToWorldNormal(inputMesh.normalOS);
// Not required but assign to silent compiler warning
output.vmesh.tangentWS = float4(1.0, 0.0, 0.0, 0.0);
#endif
#ifdef VARYINGS_NEED_TEXCOORD0

16
ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderVariables.hlsl


// ----------------------------------------------------------------------------
TEXTURE2D(_MainDepthTexture);
SAMPLER(sampler_MainDepthTexture);
TEXTURE2D(_CameraDepthTexture);
SAMPLER(sampler_CameraDepthTexture);
// Main lightmap
TEXTURE2D(unity_Lightmap);

// ----------------------------------------------------------------------------
// TODO: all affine matrices should be 3x4.
// Note: please use UNITY_MATRIX_X macros instead of referencing matrix variables directly.
// Important: please use macros or functions to access the CBuffer data.
// The member names and data layout can (and will) change!
// TODO: all affine matrices should be 3x4.
float4x4 _ViewMatrix;
float4x4 _InvViewMatrix;
float4x4 _ProjMatrix;

#endif
float _DetViewMatrix; // determinant(_ViewMatrix)
float4 _ScreenSize; // { w, h, 1 / w, 1 / h }
float4 _ScreenToTargetScale; // { w / RTHandle.maxWidth, h / RTHandle.maxHeight, 0, 0 }
float4 _ScreenToTargetScale; // { w / RTHandle.maxWidth, h / RTHandle.maxHeight } : xy = currFrame, zw = prevFrame
// Values used to linearize the Z buffer (http://www.humus.name/temp/Linearize%20depth.txt)
// x = 1 - f/n

float4 _FrustumPlanes[6]; // { (a, b, c) = N, d = -dot(N, P) } [L, R, T, B, N, F]
// TAA Frame Index ranges from 0 to 7. This gives you two rotations per cycle.
float4 _TaaFrameRotation; // { sin(taaFrame * PI/2), cos(taaFrame * PI/2), 0, 0 }
// t = animateMaterials ? Time.realtimeSinceStartup : 0.
float4 _Time; // { t/20, t, t*2, t*3 }

// Volumetric lighting.
float4 _AmbientProbeCoeffs[7]; // 3 bands of SH, packed, rescaled and convolved with the phase function
float _GlobalAsymmetry;
float _GlobalAnisotropy;
float4 _VBufferUvScaleAndLimit; // Necessary us to work with sub-allocation (resource aliasing) in the RTHandle system
float4 _VBufferDepthEncodingParams; // See the call site for description
float4 _VBufferDepthDecodingParams; // See the call site for description

float4 _VBufferPrevResolution;
float4 _VBufferPrevSliceCount;
float4 _VBufferPrevUvScaleAndLimit;
float4 _VBufferPrevDepthEncodingParams;
float4 _VBufferPrevDepthDecodingParams;
CBUFFER_END

14
ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderVariablesFunctions.hlsl


return GetFullScreenTriangleTexCoord(vertexID) * _ScreenToTargetScale.xy;
}
// The size of the render target can be larger than the size of the viewport.
// This function returns the fraction of the render target covered by the viewport:
// ViewportScale = ViewportResolution / RenderTargetResolution.
// Do not assume that their size is the same, or that sampling outside of the viewport returns 0.
float2 GetViewportScaleCurrentFrame()
{
return _ScreenToTargetScale.xy;
}
float2 GetViewportScalePreviousFrame()
{
return _ScreenToTargetScale.zw;
}
#endif // UNITY_SHADER_VARIABLES_FUNCTIONS_INCLUDED

8
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/AtmosphericScattering/AtmosphericScattering.cs


[Tooltip("Distance at which maximum mip of blurred sky texture is used as fog color.")]
public MinFloatParameter mipFogFar = new MinFloatParameter(1000.0f, 0.0f);
public abstract void PushShaderParameters(CommandBuffer cmd, FrameSettings frameSettings);
public abstract void PushShaderParameters(HDCamera hdCamera, CommandBuffer cmd);
public static void PushNeutralShaderParameters(CommandBuffer cmd)
{

cmd.SetGlobalVector(HDShaderIDs._GlobalScattering, data.scattering);
cmd.SetGlobalFloat( HDShaderIDs._GlobalExtinction, data.extinction);
cmd.SetGlobalFloat( HDShaderIDs._GlobalAsymmetry, 0.0f);
cmd.SetGlobalFloat( HDShaderIDs._GlobalAnisotropy, 0.0f);
public void PushShaderParametersCommon(CommandBuffer cmd, FogType type, FrameSettings frameSettings)
public void PushShaderParametersCommon(HDCamera hdCamera, CommandBuffer cmd, FogType type)
Debug.Assert(frameSettings.enableAtmosphericScattering);
Debug.Assert(hdCamera.frameSettings.enableAtmosphericScattering);
cmd.SetGlobalInt(HDShaderIDs._AtmosphericScatteringType, (int)type);

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/AtmosphericScattering/AtmosphericScattering.hlsl


posInput.linearDepth,
_VBufferResolution,
_VBufferSliceCount.xy,
_VBufferUvScaleAndLimit.xy,
_VBufferUvScaleAndLimit.zw,
_VBufferDepthEncodingParams,
_VBufferDepthDecodingParams,
true, true);

6
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/AtmosphericScattering/ExponentialFog.cs


public FloatParameter fogBaseHeight = new FloatParameter(0.0f);
public ClampedFloatParameter fogHeightAttenuation = new ClampedFloatParameter(0.2f, 0.0f, 1.0f);
public override void PushShaderParameters(CommandBuffer cmd, FrameSettings frameSettings)
public override void PushShaderParameters(HDCamera hdCamera, CommandBuffer cmd)
PushShaderParametersCommon(cmd, FogType.Exponential, frameSettings);
PushShaderParametersCommon(hdCamera, cmd, FogType.Exponential);
}
}

6
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/AtmosphericScattering/LinearFog.cs


public FloatParameter fogHeightStart = new FloatParameter(0.0f);
public FloatParameter fogHeightEnd = new FloatParameter(10.0f);
public override void PushShaderParameters(CommandBuffer cmd, FrameSettings frameSettings)
public override void PushShaderParameters(HDCamera hdCamera, CommandBuffer cmd)
PushShaderParametersCommon(cmd, FogType.Linear, frameSettings);
PushShaderParametersCommon(hdCamera,cmd, FogType.Linear);
}
}

18
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/AtmosphericScattering/VolumetricFog.cs


{
public ColorParameter albedo = new ColorParameter(new Color(0.5f, 0.5f, 0.5f));
public MinFloatParameter meanFreePath = new MinFloatParameter(1000000.0f, 1.0f);
public ClampedFloatParameter asymmetry = new ClampedFloatParameter(0.0f, -1.0f, 1.0f);
public ClampedFloatParameter anisotropy = new ClampedFloatParameter(0.0f, -1.0f, 1.0f);
// Override the volume blending function.
public override void Override(VolumeComponent state, float interpFactor)

float otherExtinction = VolumeRenderingUtils.ExtinctionFromMeanFreePath(other.meanFreePath);
Vector3 otherScattering = VolumeRenderingUtils.ScatteringFromExtinctionAndAlbedo(otherExtinction, (Vector3)(Vector4)other.albedo.value);
float blendExtinction = Mathf.Lerp(otherExtinction, thisExtinction, interpFactor);
Vector3 blendScattering = Vector3.Lerp(otherScattering, thisScattering, interpFactor);
float blendAsymmetry = Mathf.Lerp(other.asymmetry, asymmetry, interpFactor);
float blendExtinction = Mathf.Lerp(otherExtinction, thisExtinction, interpFactor);
Vector3 blendScattering = Vector3.Lerp(otherScattering, thisScattering, interpFactor);
float blendAsymmetry = Mathf.Lerp(other.anisotropy, anisotropy, interpFactor);
float blendMeanFreePath = VolumeRenderingUtils.MeanFreePathFromExtinction(blendExtinction);
Color blendAlbedo = (Color)(Vector4)VolumeRenderingUtils.AlbedoFromMeanFreePathAndScattering(blendMeanFreePath, blendScattering);

other.albedo.value = blendAlbedo;
}
if (asymmetry.overrideState)
if (anisotropy.overrideState)
other.asymmetry.value = blendAsymmetry;
other.anisotropy.value = blendAsymmetry;
public override void PushShaderParameters(CommandBuffer cmd, FrameSettings frameSettings)
public override void PushShaderParameters(HDCamera hdCamera, CommandBuffer cmd)
DensityVolumeParameters param = new DensityVolumeParameters(albedo, meanFreePath, asymmetry);
DensityVolumeParameters param = new DensityVolumeParameters(albedo, meanFreePath, anisotropy);
DensityVolumeData data = param.GetData();

cmd.SetGlobalFloat( HDShaderIDs._GlobalExtinction, data.extinction);
cmd.SetGlobalFloat( HDShaderIDs._GlobalAsymmetry, asymmetry);
cmd.SetGlobalFloat( HDShaderIDs._GlobalAnisotropy, anisotropy);
}
}
}

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/OpaqueAtmosphericScattering.shader


float4 Frag(Varyings input) : SV_Target
{
float depth = LOAD_TEXTURE2D(_MainDepthTexture, input.positionCS.xy).x;
float depth = LOAD_TEXTURE2D(_CameraDepthTexture, input.positionCS.xy).x;
PositionInputs posInput = GetPositionInput(input.positionCS.xy, _ScreenSize.zw, depth, UNITY_MATRIX_I_VP, UNITY_MATRIX_V);
if (depth == UNITY_RAW_FAR_CLIP_VALUE)

10
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/VisualEnvironment.cs


public IntParameter skyType = new IntParameter(0);
public FogTypeParameter fogType = new FogTypeParameter(FogType.None);
public void PushFogShaderParameters(CommandBuffer cmd, FrameSettings frameSettings)
public void PushFogShaderParameters(HDCamera hdCamera, CommandBuffer cmd)
if (!frameSettings.enableAtmosphericScattering)
if (!hdCamera.frameSettings.enableAtmosphericScattering)
{
AtmosphericScattering.PushNeutralShaderParameters(cmd);
return;

case FogType.Linear:
{
var fogSettings = VolumeManager.instance.stack.GetComponent<LinearFog>();
fogSettings.PushShaderParameters(cmd, frameSettings);
fogSettings.PushShaderParameters(hdCamera, cmd);
fogSettings.PushShaderParameters(cmd, frameSettings);
fogSettings.PushShaderParameters(hdCamera, cmd);
fogSettings.PushShaderParameters(cmd, frameSettings);
fogSettings.PushShaderParameters(hdCamera, cmd);
break;
}
}

1
ScriptableRenderPipeline/LightweightPipeline/LWRP/LightweightPipeline.cs


private RenderTargetIdentifier m_CopyColorRT;
private RenderTargetIdentifier m_DepthRT;
private RenderTargetIdentifier m_CopyDepth;
private RenderTargetIdentifier m_Color;
private float[] m_OpaqueScalerValues = {1.0f, 0.5f, 0.25f, 0.25f};
private float m_RenderScale;

1
Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/011_UnlitSprites/Scripts/Oscilate.cs


private float elapsed;
Vector3 startPosition;
private float time;
void Start()
{

32
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightUtilities.hlsl


#ifndef UNITY_LIGHT_UTILITIES_INCLUDED
#define UNITY_LIGHT_UTILITIES_INCLUDED
#include "LightDefinition.cs.hlsl"
// The EnvLightData of the sky light contains a bunch of compile-time constants.
// This function sets them directly to allow the compiler to propagate them and optimize the code.
EnvLightData InitSkyEnvLightData(int envIndex)
{
EnvLightData output;
ZERO_INITIALIZE(EnvLightData, output);
output.influenceShapeType = ENVSHAPETYPE_SKY;
output.envIndex = envIndex;
output.influenceForward = float3(0.0, 0.0, 1.0);
output.influenceUp = float3(0.0, 1.0, 0.0);
output.influenceRight = float3(1.0, 0.0, 0.0);
output.influencePositionWS = float3(0.0, 0.0, 0.0);
output.weight = 1.0;
output.multiplier = 1.0;
// proxy
output.proxyForward = float3(0.0, 0.0, 1.0);
output.proxyUp = float3(0.0, 1.0, 0.0);
output.proxyRight = float3(1.0, 0.0, 0.0);
output.minProjectionDistance = 65504.0f;
return output;
}
#endif // UNITY_LIGHT_UTILITIES_INCLUDED

9
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightUtilities.hlsl.meta


fileFormatVersion: 2
guid: be2a44d9e57c5b943ab80fa5fc334d99
timeCreated: 1480423337
licenseType: Pro
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:
正在加载...
取消
保存