浏览代码

Merge remote-tracking branch 'origin/LWRP' into LW-DistortionPass

/LW-DistortionPass
Matt Dean 7 年前
当前提交
f98f82d0
共有 177 个文件被更改,包括 7168 次插入6567 次删除
  1. 2
      .gitignore
  2. 999
      ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1102_Unlit_Distortion.unity.png
  3. 3
      ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1102_Unlit_Distortion.unity.png.meta
  4. 999
      ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1103_Unlit_Distortion_DepthTest.unity.png
  5. 3
      ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1103_Unlit_Distortion_DepthTest.unity.png.meta
  6. 999
      ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1201_Lit_Features.unity.png
  7. 48
      ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1201_Lit_Features.unity.png.meta
  8. 663
      ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1204_Lit_Transparent_Fog.unity.png
  9. 48
      ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1204_Lit_Transparent_Fog.unity.png.meta
  10. 999
      ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1206_Lit_Transparent_Distortion.unity.png
  11. 999
      ImageTemplates/HDRenderPipeline/Scenes/2xxx_Lighting/2002_Dynamic_Mix.unity.png
  12. 3
      ImageTemplates/HDRenderPipeline/Scenes/2xxx_Lighting/2002_Dynamic_Mix.unity.png.meta
  13. 999
      ImageTemplates/HDRenderPipeline/Scenes/2xxx_Lighting/2101_GI_Metapass.unity.png
  14. 999
      ImageTemplates/HDRenderPipeline/Scenes/2xxx_Lighting/2102_GI_Emission.unity.png
  15. 999
      ImageTemplates/HDRenderPipeline/Scenes/2xxx_Lighting/2103_BakeMixed.unity.png
  16. 6
      ImageTemplates/HDRenderPipeline/Scenes/2xxx_Lighting/2201_ReflectionProbes_Priority.unity.png
  17. 998
      ImageTemplates/HDRenderPipeline/Scenes/2xxx_Lighting/2401_Light_on_Tesselation.unity.png
  18. 4
      README.md
  19. 16
      ScriptableRenderPipeline/Core/CoreRP/Editor/Debugging/DebugWindow.cs
  20. 51
      ScriptableRenderPipeline/Core/CoreRP/Editor/MaterialUpgrader.cs
  21. 16
      ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/Common.hlsl
  22. 137
      ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/Shadow/ShadowAlgorithms.hlsl
  23. 9
      ScriptableRenderPipeline/Core/CoreRP/Shadow/DebugDisplayShadowMap.shader
  24. 19
      ScriptableRenderPipeline/Core/CoreRP/Shadow/Shadow.cs
  25. 19
      ScriptableRenderPipeline/Core/CoreRP/Shadow/ShadowBase.cs
  26. 870
      ScriptableRenderPipeline/HDRenderPipeline/Documentation/HDRenderPipeline.md
  27. 3
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Camera/HDCamera.cs
  28. 17
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugDisplay.cs
  29. 1
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugDisplay.hlsl
  30. 6
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugDisplayLatlong.shader
  31. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/LightingDebug.cs
  32. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/HDLightEditor.cs
  33. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/LayeredLit/LayeredLitUI.cs
  34. 10
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/Lit/LitUI.cs
  35. 5
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Shadows/HDShadowSettingsEditor.cs
  36. 14
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDRenderPipeline.cs
  37. 1
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDStringConstants.cs
  38. 14
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoop.cs
  39. 5
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoop.hlsl
  40. 6
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/Shadow.hlsl
  41. 184
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/Lit.hlsl
  42. 6
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Shadows/HDShadowSettings.cs
  43. 2
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Data/LightweightPipelineAsset.cs
  44. 32
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Editor/ShaderGUI/LightweightStandardSimpleLightingGUI.cs
  45. 98
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Editor/ShaderGraph/lightweightPBRExtraPasses.template
  46. 67
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Editor/ShaderGraph/lightweightUnlitExtraPasses.template
  47. 4
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Editor/ShaderGraph/lightweightUnlitPass.template
  48. 2
      ScriptableRenderPipeline/LightweightPipeline/LWRP/LightweightConstantBuffer.cs
  49. 177
      ScriptableRenderPipeline/LightweightPipeline/LWRP/LightweightPipeline.cs
  50. 22
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/Core.hlsl
  51. 2
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/Input.hlsl
  52. 53
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/InputBuiltin.hlsl
  53. 19
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/Lighting.hlsl
  54. 314
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/LightweightPassLit.hlsl
  55. 45
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/LightweightPassShadow.hlsl
  56. 84
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/Particles.hlsl
  57. 68
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/Shadows.hlsl
  58. 41
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/LightweightPassMetaCommon.hlsl
  59. 11
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightScreenSpaceShadows.shader
  60. 53
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightStandard.shader
  61. 4
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightStandardParticles.shader
  62. 13
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightStandardParticlesSimpleLighting.shader
  63. 8
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightStandardParticlesUnlit.shader
  64. 58
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightStandardSimpleLighting.shader
  65. 9
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightStandardTerrain.shader
  66. 41
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightStandardUnlit.shader
  67. 84
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/SkySettings/HDRP_Black_Sky_Shadow50.asset
  68. 85
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/SkySettings/HDRP_Black_Sky_Shadow500.asset
  69. 2
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/SkySettings/HDRP_Default_Sky.asset
  70. 2
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/SkySettings/HDRP_Default_Sky_2.asset
  71. 2
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/SkySettings/HDRP_Default_Sky_3.asset
  72. 2
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/SkySettings/HDRP_Default_Sky_4.asset
  73. 19
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/1xxx_Materials/1301_SubSurfaceScattering.unity
  74. 2
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/1xxx_Materials/1301_SubSurfaceScattering/GroundLeaf_Transmission-Regular.mat
  75. 6
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/2xxx_Lighting/2002_Dynamic_Mix.unity
  76. 328
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/2xxx_Lighting/2101_GI_Metapass.unity
  77. 21
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/2xxx_Lighting/2102_GI_Emission.unity
  78. 48
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/2xxx_Lighting/2201_ReflectionProbes_Priority.unity
  79. 84
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/2xxx_Lighting/2301_Shadow_Mask/HDRP_Black_Sky.asset
  80. 40
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/2xxx_Lighting/2401_Light_on_Tesselation/HDRP_Default_Sky_SmallDist.asset
  81. 8
      ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images.meta
  82. 71
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/InputSurfaceCommon.hlsl
  83. 97
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/InputSurfacePBR.hlsl
  84. 9
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/InputSurfacePBR.hlsl.meta
  85. 33
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/InputSurfaceSimple.hlsl
  86. 9
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/InputSurfaceSimple.hlsl.meta
  87. 15
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/InputSurfaceUnlit.hlsl
  88. 9
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/InputSurfaceUnlit.hlsl.meta
  89. 34
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/LightweightPassDepthOnly.hlsl
  90. 9
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/LightweightPassDepthOnly.hlsl.meta
  91. 146
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/LightweightPassLitSimple.hlsl
  92. 9
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/LightweightPassLitSimple.hlsl.meta
  93. 22
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/LightweightPassMetaPBR.hlsl
  94. 9
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/LightweightPassMetaPBR.hlsl.meta
  95. 17
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/LightweightPassMetaSimple.hlsl
  96. 9
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/LightweightPassMetaSimple.hlsl.meta
  97. 33
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/ParticlesPBR.hlsl
  98. 9
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/ParticlesPBR.hlsl.meta
  99. 48
      ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/GettingStarted1.png

2
.gitignore


*.resS
*.sdf
*.sln
*.sublime-project
*.sublime-workspace
*.suo
*.userprefs

999
ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1102_Unlit_Distortion.unity.png
文件差异内容过多而无法显示
查看文件

3
ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1102_Unlit_Distortion.unity.png.meta


spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spritePixelsToUnits: 100
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 0
spriteTessellationDetail: -1

999
ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1103_Unlit_Distortion_DepthTest.unity.png
文件差异内容过多而无法显示
查看文件

3
ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1103_Unlit_Distortion_DepthTest.unity.png.meta


spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spritePixelsToUnits: 100
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 0
spriteTessellationDetail: -1

999
ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1201_Lit_Features.unity.png
文件差异内容过多而无法显示
查看文件

48
ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1201_Lit_Features.unity.png.meta


serializedVersion: 5
mipmaps:
mipMapMode: 0
enableMipMap: 0
enableMipMap: 1
sRGBTexture: 1
linearTexture: 0
fadeOut: 0

filterMode: -1
aniso: -1
mipBias: -1
wrapU: 1
wrapV: 1
wrapW: 1
nPOTScale: 0
wrapU: -1
wrapV: -1
wrapW: -1
nPOTScale: 1
lightmap: 0
compressionQuality: 50
spriteMode: 0

spritePivot: {x: 0.5, y: 0.5}
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
alphaUsage: 0
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 0
spriteTessellationDetail: -1
textureType: 0

platformSettings:
- serializedVersion: 2
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 0
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- serializedVersion: 2
buildTarget: Standalone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 0
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- serializedVersion: 2
buildTarget: iPhone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 0
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- serializedVersion: 2
buildTarget: Windows Store Apps
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1

663
ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1204_Lit_Transparent_Fog.unity.png

之前 之后
宽度: 850  |  高度: 480  |  大小: 86 KiB

48
ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1204_Lit_Transparent_Fog.unity.png.meta


serializedVersion: 5
mipmaps:
mipMapMode: 0
enableMipMap: 0
enableMipMap: 1
sRGBTexture: 1
linearTexture: 0
fadeOut: 0

filterMode: -1
aniso: -1
mipBias: -1
wrapU: 1
wrapV: 1
wrapW: 1
nPOTScale: 0
wrapU: -1
wrapV: -1
wrapW: -1
nPOTScale: 1
lightmap: 0
compressionQuality: 50
spriteMode: 0

spritePivot: {x: 0.5, y: 0.5}
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
alphaUsage: 0
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 0
spriteTessellationDetail: -1
textureType: 0

platformSettings:
- serializedVersion: 2
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 0
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- serializedVersion: 2
buildTarget: Standalone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 0
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- serializedVersion: 2
buildTarget: iPhone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 0
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- serializedVersion: 2
buildTarget: Windows Store Apps
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1

999
ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1206_Lit_Transparent_Distortion.unity.png
文件差异内容过多而无法显示
查看文件

999
ImageTemplates/HDRenderPipeline/Scenes/2xxx_Lighting/2002_Dynamic_Mix.unity.png
文件差异内容过多而无法显示
查看文件

3
ImageTemplates/HDRenderPipeline/Scenes/2xxx_Lighting/2002_Dynamic_Mix.unity.png.meta


spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spritePixelsToUnits: 100
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 0
spriteTessellationDetail: -1

999
ImageTemplates/HDRenderPipeline/Scenes/2xxx_Lighting/2101_GI_Metapass.unity.png
文件差异内容过多而无法显示
查看文件

999
ImageTemplates/HDRenderPipeline/Scenes/2xxx_Lighting/2102_GI_Emission.unity.png
文件差异内容过多而无法显示
查看文件

999
ImageTemplates/HDRenderPipeline/Scenes/2xxx_Lighting/2103_BakeMixed.unity.png
文件差异内容过多而无法显示
查看文件

6
ImageTemplates/HDRenderPipeline/Scenes/2xxx_Lighting/2201_ReflectionProbes_Priority.unity.png
文件差异内容过多而无法显示
查看文件

998
ImageTemplates/HDRenderPipeline/Scenes/2xxx_Lighting/2401_Light_on_Tesselation.unity.png
文件差异内容过多而无法显示
查看文件

4
README.md


This feature is currently a work in progress. We cannot promise that features will work as expected in their current state. Some features may change or be removed before we move to a full release.
[Lightweight Pipeline Blogpost](https://blogs.unity3d.com/2018/02/21/the-lightweight-render-pipeline-optimizing-real-time-performance/)
[High Definition Pipeline Blogpost](https://blogs.unity3d.com/2018/03/16/the-high-definition-render-pipeline-focused-on-visual-quality/)
## How to use the latest version
__Note: The Master branch is our current development branch and may not work on the latest publicly available version of Unity. You should always use the latest release tag and latest Unity beta version for testing purposes.__
To use the latest version of the SRP, follow the instructions below:

16
ScriptableRenderPipeline/Core/CoreRP/Editor/Debugging/DebugWindow.cs


if (m_Settings == null)
m_Settings = CreateInstance<DebugWindowSettings>();
if (m_WidgetStates == null)
// States are ScriptableObjects (necessary for Undo/Redo) but are not saved on disk so when the editor is closed then reopened, any existing debug window will have its states set to null
// Since we don't care about persistance in this case, we just re-init everything.
if (m_WidgetStates == null || !AreWidgetStatesValid())
m_WidgetStates = new WidgetStateDictionary();
if (s_WidgetStateMap == null || s_WidgetDrawerMap == null || s_TypeMapDirty)

m_WidgetStates.Clear();
}
}
bool AreWidgetStatesValid()
{
foreach (var state in m_WidgetStates)
{
if(state.Value == null)
{
return false;
}
}
return true;
}
void MarkDirty()

51
ScriptableRenderPipeline/Core/CoreRP/Editor/MaterialUpgrader.cs


namespace UnityEditor.Experimental.Rendering
{
public static class DialogText
{
public static readonly string title = "Material Upgrader";
public static readonly string proceed = "Proceed";
public static readonly string ok = "Ok";
public static readonly string cancel = "Cancel";
public static readonly string noSelectionMessage = "You must select at least one material.";
public static readonly string projectBackMessage = "Make sure to have a project backup before proceeding.";
}
public class MaterialUpgrader
{
public delegate void MaterialFinalizer(Material mat);

private static readonly string projectBackMessage = "Make sure to have a project backup before proceeding.";
MaterialFinalizer m_Finalizer;
Dictionary<string, string> m_TextureRename = new Dictionary<string, string>();

public static void UpgradeProjectFolder(List<MaterialUpgrader> upgraders, string progressBarName, UpgradeFlags flags = UpgradeFlags.None)
{
if (!EditorUtility.DisplayDialog("Material Upgrader", "The upgrade will overwrite materials in your project. " + projectBackMessage, "Proceed", "Cancel"))
if (!EditorUtility.DisplayDialog(DialogText.title, "The upgrade will overwrite materials in your project. " + DialogText.projectBackMessage, DialogText.proceed, DialogText.cancel))
return;
int totalMaterialCount = 0;

public static void Upgrade(Material material, List<MaterialUpgrader> upgraders, UpgradeFlags flags)
{
if (material == null)
return;
var upgrader = GetUpgrader(upgraders, material);
if (upgrader != null)

{
var selection = Selection.objects;
if (selection == null || selection.Length == 0)
if (EditorUtility.DisplayDialog("Material Upgrader", "You must select at least one material.", "Ok"))
return;
if (selection == null)
{
EditorUtility.DisplayDialog(DialogText.title, DialogText.noSelectionMessage, DialogText.ok);
return;
}
List<Material> selectedMaterials = new List<Material>(selection.Length);
for (int i = 0; i < selection.Length; ++i)
{
Material mat = selection[i] as Material;
if (mat != null)
selectedMaterials.Add(mat);
}
int selectedMaterialsCount = selectedMaterials.Count;
if (selectedMaterialsCount == 0)
{
EditorUtility.DisplayDialog(DialogText.title, DialogText.noSelectionMessage, DialogText.ok);
return;
}
if (!EditorUtility.DisplayDialog("Material Upgrader", string.Format("The upgrade will overwrite {0} selected material{1}. ", selection.Length, (selection.Length > 1) ? "s" : "") +
projectBackMessage, "Proceed", "Cancel"))
if (!EditorUtility.DisplayDialog(DialogText.title, string.Format("The upgrade will overwrite {0} selected material{1}. ", selectedMaterialsCount, selectedMaterialsCount > 1 ? "s" : "") +
DialogText.projectBackMessage, DialogText.proceed, DialogText.cancel))
Debug.Log(selection.Length);
for (int i = 0; i < selection.Length; i++)
for (int i = 0; i < selectedMaterialsCount; i++)
if (UnityEditor.EditorUtility.DisplayCancelableProgressBar(progressBarName, string.Format("({0} of {1}) {2}", i, selection.Length, lastMaterialName), (float)i / (float)selection.Length))
if (UnityEditor.EditorUtility.DisplayCancelableProgressBar(progressBarName, string.Format("({0} of {1}) {2}", i, selectedMaterialsCount, lastMaterialName), (float)i / (float)selectedMaterialsCount))
var material = selection[i] as Material;
var material = selectedMaterials[i];
Upgrade(material, upgraders, flags);
if (material != null)
lastMaterialName = material.name;

16
ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/Common.hlsl


#define real3x3 half3x3
#define real3x4 half3x4
#define real4x3 half4x3
#define real4x4 half4x4
#define real4x4 half4x4
#define half min16float
#define half2 min16float2
#define half3 min16float3
#define half4 min16float4
#define half2x2 min16float2x2
#define half2x3 min16float2x3
#define half3x2 min16float3x2
#define half3x3 min16float3x3
#define half3x4 min16float3x4
#define half4x3 min16float4x3
#define half4x4 min16float4x4
#define REAL_MIN HALF_MIN
#define REAL_MAX HALF_MAX

// We want to have a symmetry between 0..0.5 ditherFactor and 0.5..1 so no pixels are transparent during the transition
// this is handled by this test which reverse the pattern
// TODO: replace the test (ditherFactor >= 0.5) with (isLod0) to avoid the distracting pattern flip around 0.5.
p = (ditherFactor >= 0.5) ? p : 1 - p;
clip(ditherFactor - p);
}

137
ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/Shadow/ShadowAlgorithms.hlsl


return EvalShadow_GetTexcoords( sd, positionWS, ndc, perspProj );
}
uint2 EvalShadow_GetTexcoords( ShadowData sd, real3 positionWS, out real2 closestSampleNDC, bool perspProj )
real2 EvalShadow_GetTexcoords( ShadowData sd, real3 positionWS, out real2 closestSampleNDC, bool perspProj )
{
real4 posCS = EvalShadow_WorldToShadow( sd, positionWS, perspProj );
real2 posNDC = perspProj ? (posCS.xy / posCS.w) : posCS.xy;

return uint2( (posTC * sd.scaleOffset.xy + sd.scaleOffset.zw) * sd.textureSize.xy );
return posTC * sd.scaleOffset.xy + sd.scaleOffset.zw;
uint2 EvalShadow_GetIntTexcoords( ShadowData sd, real3 positionWS, out real2 closestSampleNDC, bool perspProj )
{
real2 texCoords = EvalShadow_GetTexcoords(sd, positionWS, closestSampleNDC, perspProj);
return uint2(texCoords * sd.textureSize.xy);
}
//
// Biasing functions

real3 tcs = EvalShadow_GetTexcoords( sd, pos, perspProj );
weight = SampleCompShadow_T2DA( shadowContext, texIdx, sampIdx, tcs, sd.slice ).x;
}
return lerp( 1.0, weight, EvalShadow_ReceiverBiasWeightFlag( sd.normalBias.w ) );
}

// get the algorithm
uint shadowType, shadowAlgorithm;
UnpackShadowType( sd.shadowType, shadowType, shadowAlgorithm );
// get the texture
// get the texture
uint texIdx, sampIdx;
UnpackShadowmapId( sd.id, texIdx, sampIdx );
// bias the world position

sd.scaleOffset.zw = shadowContext.shadowDatas[index + CubeMapFaceID( -L ) + 1].scaleOffset.zw;
sd.slice = shadowContext.shadowDatas[index + CubeMapFaceID( -L ) + 1].slice;
}
uint texIdx, sampIdx;
UnpackShadowmapId( sd.id, texIdx, sampIdx );
// bias the world position

sd.viewBias.w = shadowContext.shadowDatas[index].viewBias.w;
}
int EvalShadow_GetSplitIndex( ShadowContext shadowContext, int index, real3 positionWS, out uint payloadOffset, out real alpha )
int EvalShadow_GetSplitIndex( ShadowContext shadowContext, int index, real3 positionWS, out uint payloadOffset, out real alpha, out int cascadeCount )
{
payloadOffset = shadowContext.shadowDatas[index].payloadOffset;

float distSq = dot( wposDir, wposDir );
relDistance = distSq / sphere.w;
if( relDistance > 0.0 && relDistance <= 1.0 )
{
{
splitSphere = sphere.xyz;
wposDir /= sqrt( distSq );
break;

payloadOffset = shadowContext.shadowDatas[index].payloadOffset + kMaxShadowCascades;
real3 cascadeDir = asfloat( shadowContext.payloads[payloadOffset].xyz );
cascadeCount = shadowContext.payloads[payloadOffset].w;
payloadOffset++;
real border = asfloat( shadowContext.payloads[payloadOffset][shadowSplitIndex] );
payloadOffset++;

real EvalShadow_CascadedDepth_Blend( ShadowContext shadowContext, real3 positionWS, real3 normalWS, int index, real3 L )
{
// load the right shadow data for the current face
uint payloadOffset;
real alpha;
int shadowSplitIndex = EvalShadow_GetSplitIndex( shadowContext, index, positionWS, payloadOffset, alpha );
uint payloadOffset;
real alpha;
int cascadeCount;
int shadowSplitIndex = EvalShadow_GetSplitIndex( shadowContext, index, positionWS, payloadOffset, alpha, cascadeCount );
if( shadowSplitIndex < 0 )
return 1.0;

real shadow1 = 1.0;
shadowSplitIndex++;
if( shadowSplitIndex < kMaxShadowCascades )
if( shadowSplitIndex < cascadeCount )
{
shadow1 = shadow;

{ \
uint payloadOffset; \
real alpha; \
int shadowSplitIndex = EvalShadow_GetSplitIndex(shadowContext, index, positionWS, payloadOffset, alpha ); \
int cascadeCount; \
int shadowSplitIndex = EvalShadow_GetSplitIndex(shadowContext, index, positionWS, payloadOffset, alpha, cascadeCount ); \
\
if( shadowSplitIndex < 0 ) \
return 1.0; \

real shadow1 = 1.0; \
\
shadowSplitIndex++; \
if( shadowSplitIndex < kMaxShadowCascades ) \
if( shadowSplitIndex < cascadeCount ) \
{ \
shadow1 = shadow; \
\

real EvalShadow_CascadedDepth_Dither( ShadowContext shadowContext, real3 positionWS, real3 normalWS, int index, real3 L )
{
// load the right shadow data for the current face
uint payloadOffset;
real alpha;
int shadowSplitIndex = EvalShadow_GetSplitIndex(shadowContext, index, positionWS, payloadOffset, alpha);
uint payloadOffset;
real alpha;
int cascadeCount;
int shadowSplitIndex = EvalShadow_GetSplitIndex( shadowContext, index, positionWS, payloadOffset, alpha, cascadeCount );
if( shadowSplitIndex < 0 )
return 1.0;

UnpackShadowmapId( sd.id, texIdx, sampIdx );
uint shadowType, shadowAlgorithm;
UnpackShadowType( sd.shadowType, shadowType, shadowAlgorithm );
// normal based bias
real3 orig_pos = positionWS;
real recvBiasWeight = EvalShadow_ReceiverBiasWeight( shadowContext, shadowAlgorithm, sd, texIdx, sampIdx, positionWS, normalWS, L, 1.0, false );

int nextSplit = min( shadowSplitIndex+1, kMaxShadowCascades-1 );
int nextSplit = min( shadowSplitIndex+1, cascadeCount-1 );
if( shadowSplitIndex < nextSplit && step( EvalShadow_hash12( posTC.xy ), alpha ) )
{

// sample the texture
real2 sampleBias = EvalShadow_SampleBias_Ortho( sd, normalWS );
real shadow = SampleShadow_SelectAlgorithm( shadowContext, sd, payloadOffset, posTC, sampleBias, shadowAlgorithm, texIdx, sampIdx );
return shadowSplitIndex < (kMaxShadowCascades-1) ? shadow : lerp( shadow, 1.0, alpha );
return shadowSplitIndex < (cascadeCount-1) ? shadow : lerp( shadow, 1.0, alpha );
}
#define EvalShadow_CascadedDepth_( _samplerType ) \

uint payloadOffset; \
real alpha; \
int shadowSplitIndex = EvalShadow_GetSplitIndex(shadowContext, index, positionWS, payloadOffset, alpha ); \
int cascadeCount; \
int shadowSplitIndex = EvalShadow_GetSplitIndex( shadowContext, index, positionWS, payloadOffset, alpha, cascadeCount ); \
\
if( shadowSplitIndex < 0 ) \
return 1.0; \

/* get shadowmap texcoords */ \
real3 posTC = EvalShadow_GetTexcoords( sd, positionWS, false ); \
\
int nextSplit = min( shadowSplitIndex+1, kMaxShadowCascades-1 ); \
int nextSplit = min( shadowSplitIndex+1, cascadeCount-1 ); \
\
if( shadowSplitIndex != nextSplit && step( EvalShadow_hash12( posTC.xy ), alpha ) ) \
{ \

/* sample the texture */ \
real2 sampleBias = EvalShadow_SampleBias_Ortho( sd, normalWS ); \
real shadow = SampleShadow_SelectAlgorithm( shadowContext, sd, payloadOffset, posTC, sampleBias, shadowAlgorithms[shadowSplitIndex], tex, samp ); \
return shadowSplitIndex < (kMaxShadowCascades-1) ? shadow : lerp( shadow, 1.0, alpha ); \
return shadowSplitIndex < (cascadeCount-1) ? shadow : lerp( shadow, 1.0, alpha ); \
} \
\
real EvalShadow_CascadedDepth_Dither( ShadowContext shadowContext, uint shadowAlgorithm, Texture2DArray tex, _samplerType samp, real3 positionWS, real3 normalWS, int index, real3 L ) \

sd = shadowContext.shadowDatas[index + faceIndex];
real4 closestNDC = { 0,0,0,1 };
uint2 texelIdx = EvalShadow_GetTexcoords( sd, positionWS, closestNDC.xy, true );
uint2 texelIdx = EvalShadow_GetIntTexcoords( sd, positionWS, closestNDC.xy, true );
// load the texel
uint texIdx, sampIdx;

sd = shadowContext.shadowDatas[index + faceIndex];
real4 closestNDC = { 0,0,0,1 };
uint2 texelIdx = EvalShadow_GetTexcoords( sd, positionWS, closestNDC.xy, true );
uint2 texelIdx = EvalShadow_GetIntTexcoords( sd, positionWS, closestNDC.xy, true );
// load the texel
closestNDC.z = LOAD_TEXTURE2D_ARRAY_LOD( tex, texelIdx, sd.slice, 0 ).x;

ShadowData sd = shadowContext.shadowDatas[index];
real4 closestNDC = { 0,0,0,1 };
uint2 texelIdx = EvalShadow_GetTexcoords( sd, positionWS, closestNDC.xy, true );
uint2 texelIdx = EvalShadow_GetIntTexcoords( sd, positionWS, closestNDC.xy, true );
// load the texel
uint texIdx, sampIdx;

ShadowData sd = shadowContext.shadowDatas[index];
real4 closestNDC = { 0,0,0,1 };
uint2 texelIdx = EvalShadow_GetTexcoords( sd, positionWS, closestNDC.xy, true );
uint2 texelIdx = EvalShadow_GetIntTexcoords( sd, positionWS, closestNDC.xy, true );
// load the texel
closestNDC.z = LOAD_TEXTURE2D_ARRAY_LOD( tex, texelIdx, sd.slice, 0 ).x;

sd = shadowContext.shadowDatas[index + faceIndex];
real4 closestNDC = { 0,0,0,1 };
uint2 texelIdx = EvalShadow_GetTexcoords( sd, positionWS, closestNDC.xy, true );
uint2 texelIdx = EvalShadow_GetIntTexcoords( sd, positionWS, closestNDC.xy, true );
// load the texel
uint texIdx, sampIdx;

sd = shadowContext.shadowDatas[index + faceIndex];
real4 closestNDC = { 0,0,0,1 };
uint2 texelIdx = EvalShadow_GetTexcoords( sd, positionWS, closestNDC.xy, true );
uint2 texelIdx = EvalShadow_GetIntTexcoords( sd, positionWS, closestNDC.xy, true );
// load the texel
closestNDC.z = LOAD_TEXTURE2D_ARRAY_LOD( tex, texelIdx, sd.slice, 0 ).x;

return closestWS.xyz / closestWS.w;
}
real EvalShadow_SampleClosestDistance_Punctual( ShadowContext shadowContext, Texture2DArray tex, SamplerState sampl,
real3 positionWS, int index, real3 L, real3 lightPositionWS )
{
// get the algorithm
ShadowData sd = shadowContext.shadowDatas[index];
uint shadowType;
UnpackShadowType( sd.shadowType, shadowType );
// load the right shadow data for the current face
int faceIndex = shadowType == GPUSHADOWTYPE_POINT ? (CubeMapFaceID( -L ) + 1) : 0;
sd = shadowContext.shadowDatas[index + faceIndex];
real4 closestNDC = { 0,0,0,1 };
real2 texelIdx = EvalShadow_GetTexcoords( sd, positionWS, closestNDC.xy, true );
// sample the shadow map
closestNDC.z = SAMPLE_TEXTURE2D_ARRAY_LOD( tex, sampl, texelIdx, sd.slice, 0 ).x;
// reconstruct depth position
real4 closestWS = mul( closestNDC, sd.shadowToWorld );
real3 occluderPosWS = closestWS.xyz / closestWS.w;
return distance( occluderPosWS, lightPositionWS );
}
int shadowSplitIndex = EvalShadow_GetSplitIndex( shadowContext, index, positionWS, payloadOffset, alpha );
int cascadeCount;
int shadowSplitIndex = EvalShadow_GetSplitIndex( shadowContext, index, positionWS, payloadOffset, alpha, cascadeCount );
return 1.0;
return 0.0;
uint2 texelIdx = EvalShadow_GetTexcoords( sd, positionWS, closestNDC.xy, false );
uint2 texelIdx = EvalShadow_GetIntTexcoords( sd, positionWS, closestNDC.xy, false );
// load the texel
uint texIdx, sampIdx;

// load the right shadow data for the current face
uint payloadOffset;
real alpha;
int shadowSplitIndex = EvalShadow_GetSplitIndex( shadowContext, index, positionWS, payloadOffset, alpha );
int cascadeCount;
int shadowSplitIndex = EvalShadow_GetSplitIndex( shadowContext, index, positionWS, payloadOffset, alpha, cascadeCount );
return 1.0;
return 0.0;
uint2 texelIdx = EvalShadow_GetTexcoords( sd, positionWS, closestNDC.xy, false );
uint2 texelIdx = EvalShadow_GetIntTexcoords( sd, positionWS, closestNDC.xy, false );
// load the texel
uint texIdx, sampIdx;

real4 closestWS = mul( closestNDC, sd.shadowToWorld );
return closestWS.xyz / closestWS.w;
}
real EvalShadow_SampleClosestDistance_Cascade( ShadowContext shadowContext, Texture2DArray tex, SamplerState sampl,
real3 positionWS, real3 normalWS, int index, real4 L, out real3 nearPlanePositionWS )
{
// load the right shadow data for the current face
uint payloadOffset;
real alpha;
int cascadeCount;
int shadowSplitIndex = EvalShadow_GetSplitIndex( shadowContext, index, positionWS, payloadOffset, alpha, cascadeCount );
if( shadowSplitIndex < 0 )
return 0.0;
ShadowData sd = shadowContext.shadowDatas[index + 1 + shadowSplitIndex];
real4 closestNDC = { 0,0,0,1 };
real2 texelIdx = EvalShadow_GetTexcoords( sd, positionWS, closestNDC.xy, false );
// sample the shadow map
uint texIdx, sampIdx;
UnpackShadowmapId( sd.id, texIdx, sampIdx );
closestNDC.z = SAMPLE_TEXTURE2D_ARRAY_LOD( tex, sampl, texelIdx, sd.slice, 0 ).x;
// reconstruct depth position
real4 closestWS = mul( closestNDC, sd.shadowToWorld );
real3 occluderPosWS = closestWS.xyz / closestWS.w;
// TODO: avoid the matrix multiplication here.
real4 nearPlanePos = mul( real4( 0,0,1,1 ), sd.shadowToWorld ); // Note the reversed Z
nearPlanePositionWS = nearPlanePos.xyz / nearPlanePos.w;
return distance( occluderPosWS, nearPlanePositionWS );
}

9
ScriptableRenderPipeline/Core/CoreRP/Shadow/DebugDisplayShadowMap.shader


float4 _TextureScaleBias;
float _TextureSlice;
float2 _ValidRange;
float _RequireToFlipInputTexture;
SamplerState ltc_linear_clamp_sampler;
TEXTURE2D_ARRAY(_AtlasTexture);

{
Varyings output;
output.positionCS = GetFullScreenTriangleVertexPosition(input.vertexID);
output.texcoord = GetFullScreenTriangleTexCoord(input.vertexID) * _TextureScaleBias.xy + _TextureScaleBias.zw;
output.texcoord = GetFullScreenTriangleTexCoord(input.vertexID);
if (_RequireToFlipInputTexture > 0.0f)
{
output.texcoord.y = 1.0f - output.texcoord.y;
}
output.texcoord = output.texcoord *_TextureScaleBias.xy + _TextureScaleBias.zw;
return output;
}
ENDHLSL

19
ScriptableRenderPipeline/Core/CoreRP/Shadow/Shadow.cs


sp.Set( (m_TmpSplits[second] - m_TmpSplits[first]).normalized );
else
sp.Set( 0.0f, 0.0f, 0.0f, 0.0f );
sp.p3 = (int) sr.facecount;
payload[payloadOffset] = sp;
payloadOffset++;

// shadow atlas layouting
CachedEntry ce = m_EntryCache[i];
Rect vp = ce.current.viewport;
curh = curh >= vp.height ? curh : vp.height;
curh = vp.height;
}
if( curx + vp.width > xmax || cury + curh > ymax )
{

curh = vp.height;
}
if( curx + vp.width > xmax || cury + curh > ymax || curslice == m_Slices )
{

ce.current.slice = curslice;
m_EntryCache[i] = ce;
curx += vp.width;
curh = curh >= vp.height ? curh : vp.height;
}
return true;
}

m_EntryPool.Add( ce );
}
override public void DisplayShadowMap(CommandBuffer debugCB, Material debugMaterial, Vector4 scaleBias, uint slice, float screenX, float screenY, float screenSizeX, float screenSizeY, float minValue, float maxValue)
override public void DisplayShadowMap(CommandBuffer debugCB, Material debugMaterial, Vector4 scaleBias, uint slice, float screenX, float screenY, float screenSizeX, float screenSizeY, float minValue, float maxValue, bool flipY)
{
Vector4 validRange = new Vector4(minValue, 1.0f / (maxValue - minValue));

propertyBlock.SetFloat("_TextureSlice", (float)slice);
propertyBlock.SetVector("_ValidRange", validRange);
propertyBlock.SetFloat("_RequireToFlipInputTexture", flipY ? 1.0f : 0.0f);
debugCB.SetViewport(new Rect(screenX, screenY, screenSizeX, screenSizeY));
debugCB.DrawProcedural(Matrix4x4.identity, debugMaterial, debugMaterial.FindPass("REGULARSHADOW"), MeshTopology.Triangles, 3, 1, propertyBlock);
}

cb.EndSample("VSM conversion");
}
override public void DisplayShadowMap(CommandBuffer debugCB, Material debugMaterial, Vector4 scaleBias, uint slice, float screenX, float screenY, float screenSizeX, float screenSizeY, float minValue, float maxValue)
override public void DisplayShadowMap(CommandBuffer debugCB, Material debugMaterial, Vector4 scaleBias, uint slice, float screenX, float screenY, float screenSizeX, float screenSizeY, float minValue, float maxValue, bool flipY)
{
Vector4 validRange = new Vector4(minValue, 1.0f / (maxValue - minValue));

propertyBlock.SetFloat("_TextureSlice", (float)slice);
propertyBlock.SetVector("_ValidRange", validRange);
propertyBlock.SetFloat("_RequireToFlipInputTexture", flipY ? 1.0f : 0.0f);
debugCB.SetViewport(new Rect(screenX, screenY, screenSizeX, screenSizeY));
debugCB.DrawProcedural(Matrix4x4.identity, debugMaterial, debugMaterial.FindPass("VARIANCESHADOW"), MeshTopology.Triangles, 3, 1, propertyBlock);
}

}
}
public override void DisplayShadow(CommandBuffer cmd, Material debugMaterial, int shadowRequestIndex, uint faceIndex, float screenX, float screenY, float screenSizeX, float screenSizeY, float minValue, float maxValue)
public override void DisplayShadow(CommandBuffer cmd, Material debugMaterial, int shadowRequestIndex, uint faceIndex, float screenX, float screenY, float screenSizeX, float screenSizeY, float minValue, float maxValue, bool flipY)
{
if (m_ShadowIndices.Count() == 0)
return;

ShadowData faceData = shadowDatas[(uint)(m_ShadowIndices[index] + offset + faceIndex)];
uint texID, samplerID;
faceData.UnpackShadowmapId(out texID, out samplerID);
m_Shadowmaps[texID].DisplayShadowMap(cmd, debugMaterial, faceData.scaleOffset, (uint) faceData.slice, screenX, screenY, screenSizeX, screenSizeY, minValue, maxValue);
m_Shadowmaps[texID].DisplayShadowMap(cmd, debugMaterial, faceData.scaleOffset, (uint) faceData.slice, screenX, screenY, screenSizeX, screenSizeY, minValue, maxValue, flipY);
public override void DisplayShadowMap(CommandBuffer cmd, Material debugMaterial, uint shadowMapIndex, uint sliceIndex, float screenX, float screenY, float screenSizeX, float screenSizeY, float minValue, float maxValue)
public override void DisplayShadowMap(CommandBuffer cmd, Material debugMaterial, uint shadowMapIndex, uint sliceIndex, float screenX, float screenY, float screenSizeX, float screenSizeY, float minValue, float maxValue, bool flipY)
m_Shadowmaps[index].DisplayShadowMap(cmd, debugMaterial, new Vector4(1.0f, 1.0f, 0.0f, 0.0f), sliceIndex, screenX, screenY, screenSizeX, screenSizeY, minValue, maxValue);
m_Shadowmaps[index].DisplayShadowMap(cmd, debugMaterial, new Vector4(1.0f, 1.0f, 0.0f, 0.0f), sliceIndex, screenX, screenY, screenSizeX, screenSizeY, minValue, maxValue, flipY);
}
public override void SyncData()

19
ScriptableRenderPipeline/Core/CoreRP/Shadow/ShadowBase.cs


m_HeightRcp = 1.0f / initializer.height;
m_MaxPayloadCount = initializer.maxPayloadCount;
m_ShadowSupport = initializer.shadowSupport;
if( IsNativeDepth() && m_Slices > 1 )
{
// TODO: Right now when using any of the SetRendertarget functions we ultimately end up in RenderTextureD3D11.cpp
// SetRenderTargetD3D11Internal. This function sets the correct slice only for RTVs, whereas depth textures only
// support one DSV. So there's currently no way to have individual DSVs per slice to render into (ignoring going through a geometry shader and selecting the slice there).
Debug.LogError( "Unity does not allow direct rendering into specific depth slices, yet. Defaulting back to one array slice." );
m_Slices = 1;
}
}
protected bool IsNativeDepth()

abstract public void Fill( ShadowContextStorage cs );
abstract public void CreateShadowmap();
abstract protected void Register( GPUShadowType type, ShadowRegistry registry );
abstract public void DisplayShadowMap(CommandBuffer cmd, Material debugMaterial, Vector4 scaleBias, uint slice, float screenX, float screenY, float screenSizeX, float screenSizeY, float minValue, float maxValue);
abstract public void DisplayShadowMap(CommandBuffer cmd, Material debugMaterial, Vector4 scaleBias, uint slice, float screenX, float screenY, float screenSizeX, float screenSizeY, float minValue, float maxValue, bool flipY);
}
public interface IShadowManager

// Renders all shadows for lights the were deemed shadow casters after the last call to ProcessShadowRequests
void RenderShadows( FrameId frameId, ScriptableRenderContext renderContext, CommandBuffer cmd, CullResults cullResults, List<VisibleLight> lights);
// Debug function to display a shadow at the screen coordinate
void DisplayShadow(CommandBuffer cmd, Material debugMaterial, int shadowIndex, uint faceIndex, float screenX, float screenY, float screenSizeX, float screenSizeY, float minValue, float maxValue);
void DisplayShadowMap(CommandBuffer cmd, Material debugMaterial, uint shadowMapIndex, uint sliceIndex, float screenX, float screenY, float screenSizeX, float screenSizeY, float minValue, float maxValue);
void DisplayShadow(CommandBuffer cmd, Material debugMaterial, int shadowIndex, uint faceIndex, float screenX, float screenY, float screenSizeX, float screenSizeY, float minValue, float maxValue, bool flipY);
void DisplayShadowMap(CommandBuffer cmd, Material debugMaterial, uint shadowMapIndex, uint sliceIndex, float screenX, float screenY, float screenSizeX, float screenSizeY, float minValue, float maxValue, bool flipY);
// Synchronize data with GPU buffers
void SyncData();
// Binds resources to shader stages just before rendering the lighting pass

{
public abstract void ProcessShadowRequests( FrameId frameId, CullResults cullResults, Camera camera, bool cameraRelativeRendering, List<VisibleLight> lights, ref uint shadowRequestsCount, int[] shadowRequests, out int[] shadowDataIndices );
public abstract void RenderShadows( FrameId frameId, ScriptableRenderContext renderContext, CommandBuffer cmd, CullResults cullResults, List<VisibleLight> lights);
public abstract void DisplayShadow(CommandBuffer cmd, Material debugMaterial, int shadowIndex, uint faceIndex, float screenX, float screenY, float screenSizeX, float screenSizeY, float minValue, float maxValue);
public abstract void DisplayShadowMap(CommandBuffer cmd, Material debugMaterial, uint shadowMapIndex, uint sliceIndex, float screenX, float screenY, float screenSizeX, float screenSizeY, float minValue, float maxValue);
public abstract void DisplayShadow(CommandBuffer cmd, Material debugMaterial, int shadowIndex, uint faceIndex, float screenX, float screenY, float screenSizeX, float screenSizeY, float minValue, float maxValue, bool flipY);
public abstract void DisplayShadowMap(CommandBuffer cmd, Material debugMaterial, uint shadowMapIndex, uint sliceIndex, float screenX, float screenY, float screenSizeX, float screenSizeY, float minValue, float maxValue, bool flipY);
public abstract void SyncData();
public abstract void BindResources( CommandBuffer cmd, ComputeShader computeShader, int computeKernel);
public abstract void UpdateCullingParameters( ref ScriptableCullingParameters cullingParams );

870
ScriptableRenderPipeline/HDRenderPipeline/Documentation/HDRenderPipeline.md


# High Definition Render Pipeline
![](https://blogs.unity3d.com/wp-content/uploads/2018/01/image2.jpg)
The High Definition Render Pipeline (HDRP) is a high-fidelity Scriptable Render Pipeline built by Unity to target modern (Compute Shader compatible) platforms.

* Modern consoles (Sony PS4 and Microsoft Xbox One)
__HDRP does not support OpenGL or OpenGL ES devices.__
# Getting Started with High Definition Render Pipeline
This page details the initial setup of a project using the High Definition Render Pipeline (HDRP) and notes on upgrading existing projects to HDRP.
## Setting up a new Project
### Using Unity Hub
To set up a new HDRP project using Unity Hub, click the New button, then select High Definition - Preview from the Template drop-down box. After clicking Create Project, Unity will automatically create a Project with the High Definition Render Pipeline package installed.
![](Images/GettingStarted1.png)
## Upgrading an Existing Project
To upgrade an existing Project, you must first download the High Definition Render Pipeline using the Package Manager UI.
Navigate to **Window > Package Manager** to open the Package Manager UI. Then click the All button to open the packages list.
Left click on Render-pipelines.high-definition to select it, then click the Install button to add HDRP to your project.
![](Images/GettingStarted2.png)
After you have installed HDRP from the Package Manager UI you must add the HDRP Asset to the Scriptable Render Pipeline Graphics settings field.
Navigate to Edit > Settings > Graphics Settings, then Assign the HDRP Asset to the Scriptable Render Pipeline field by dragging in the HDRP Asset, or using the radio button to select the Asset from the popup window.
## Building from source code
The latest version of the Scriptable Render Pipeline (SRP) repo can be found at the following link: https://github.com/Unity-Technologies/ScriptableRenderPipeline
### Github Desktop or Git command line tools
#### Cloning the repo using the GitHub Desktop App:
Open the GitHub Desktop App and click Clone a Repository.
Click the URL tab in the Clone a Repository window
Enter the following URL: https://github.com/Unity-Technologies/ScriptableRenderPipeline
Click the Choose… button to navigate to your project’s Asset folder.
Click the Clone button.
After the repo has been cloned you must run the following console commands from the ScriptableRenderPipeline folder:
`git checkout Unity-2018.1.0b2 (or the latest tag)`
`git submodule update --init --recursive --remote`
#### Cloning the repo using Git console commands:
Enter the following commands in your console application of choice:
`cd <Path to your Unity project>/Assets`
`git clone https://github.com/Unity-Technologies/ScriptableRenderPipeline`
`cd ScriptableRenderPipeline`
`git checkout Unity-2018.1.0b2 (or the latest tag)`
`git submodule update --init --recursive --remote`
Once you have cloned the repo, re-open your project and follow the below instructions:
Navigate to **Edit > Project Settings > Graphics** and add the HDRenderPipelineAsset Asset to the Render Pipeline Settings field.
Create a copy of the HDRenderPipelineAsset and store it outside of the Scriptable Render Pipeline folder. This ensures that your HDRP settings are not lost when merging new changes from the SRP repo.
HDRP will be ready to use in your project after following the above instructions.
## Upgrading Shaders
The built-in Unity shaders are incompatible with Scriptable Render Pipelines, as such, any preexisting Shaders in your project must be updated to work with the HDRP.
Navigate to **Edit > Render Pipelines > Upgrade Project Materials to High Definition Materials** to run the automatic upgrade script. This script with automatically update all preexisting shaders in your project to the new HDRP shaders.
# The HD Render Pipeline Lit Shader
The lit shader is the default shader when using HDRenderPipeline (HDRP). This shader can be set with subsurface scattering, iridescence, vertex or pixel displacement and many other new parameters. This shader allows to users to produce more realistic assets with the use of HDRP. A version call LitTessellation is used to activate the tessellation.
## Creating a Lit Shader
In HDRP, when a new material is created it is by default a lit shader.
![](/Images/LitShader1.png)
![](Images/LitShader2.png)
## How to set a Lit Shader?
### Surface options
__Surface type:__
![](/Images/LitShader3.png)
Surface can be set as Opaque or Transparent. Transparent is an alpha blend and it is more costly.
__Alpha Cutoff:__
![](Images/LitShader4.png)
This check box enable the alpha cutoff to use an alpha test. The handle set the value of the test. All the values under the handle value is totally transparent and the values equal or above the handle value is opaque.
__Double sided:__
![](Images/LitShader5.png)
This option allows the double side. The faces are rendered on the two sides. The normal mode manages the normal behaviour on the backfaces. By default the mode is mirror.
__Material type:__
Material type introduces new behaviour for shaders to create realistic assets.
* Standard: Common use with basic parameters. The standard type uses a metallic workflow.
* Subsurface scattering (SSS): Mainly use to do a skin shader. This material type simulates the light transport inside a material and create softer micro shadows.
Also a new parameter appears: Enable transmission. This parameter simulate the translucency of an object and it is managed by a thickness map.
SSS and transmission are setting by a diffusion profile explain later in this document.
* Anisotropy: The anisotropy determines the shape of the highlight. The surface vector is managed by a tangent map, an anisotropy map modulate the anisotropy intensity and a handle modulate and orient to horizontally or vertical the anisotropic effect. These parameters are more explain later in the documentation.
* Iridescence: Use to create an iridescent effect. The effect is modulate by an iridescence mask, iridescence thickness map and an handle iridescence thickness.
* Specular Color: Instead of standard type, the specular color type uses a specular workflow. In this way the specular can be colorize even for a not metallic matter.
* Translucent: This type is used to simulate only the transmission. It can be handy for vegetation and more light than a SSS type.This type use a profile like the SSS type to manage the transmission.
__Enable Decal:__
Allow the material to receive decals.
__Enable MotionVector For Vertex Animation:__
Use it to remove ghosting coming from vertex animation.
__Displacement mode:__
* None: no change.
* Vertex displacement: Use a height map to displace the vertices.
* Pixel displacement: Use a height map to displace the pixels. Use it only on plane surface. The surface can be only digged.
## Vertex animation / Enable wind
Prototype feature, don’t use it.
## Inputs
__Base color + opacity__: RGB channels are used as base color and alpha channel is used for opacity.
__Smoothness__ handle: This handle modulate (0 to 1) the smoothness value coming from the Mask map alpha channel.
__Mask map:__
* Red channel: Metallic mask. 0 = not metallic, 1 = metallic.
* Green channel: Ambient occlusion.
* Blue channel: Detail map mask.
* Alpha channel: Smoothness.
__Normal map space:__
By default the normal map space is in tangent space. The normal map space can be set to object space.
__Normal map:__
Use to assign the normal map. The handle modulate the normal intensity between 0 and 2.
__Bent normal map:__
The bent normal is used to have a better ambient occlusion. It works only with diffuse lighting like lightmap or light probe.
__Coat Mask:__
By default the value is 0. The mask is used to modulate the clear coat effect base on the handle value (0 to 1).
__Base UV mapping:__
UV can be set to UV0, UV1 (used by the lightmap), UV2, UV3, planar or triplanar.
Planar and triplanar use a world scale. This ratio depends about the size of the textures and the texel ratio wanted. By default it is 1, that means the material is applied on 1 meter. A value of 0.5 applies the material on 2 meters.
__Tiling:__
Set the X/Y values to tile the material.
__Offset:__
Set on X/Y offset for the UV.
## Detail inputs
The detail map is a composited map used to add micro details into the material. The detail map visibility is managed by the blue channel of the Mask map.
![](Images/LitShader6.png)
__Detail map:__
* Red channel: Grey scale used as albedo.
* Green channel: Green channel of the detail normal map.
* Blue channel: Detail smoothness.
* Alpha channel: Red channel of the detail normal map.
Channels are organised like this due the different compressions quality of each channels.
__Detail UV mapping:__
UV0, UV1, UV2 or UV3 can be set. If the material UV are set to planar or triplanar, the detail UV are also set to planar or triplanar.
__Lock to base Tiling/Offset:__
By default a detail texture is linked to the material aspect because it is done to add a micro detail in it. If for any reason the link have to be removed, just uncheck this checkbox.
__Tiling:__
Set the tiling of the detail texture inside a tile of the material.
For example if the material is tiled by 2 on a plane and the detail texture is also tile by 2, the detail will appears tile by 4 on the plane.
In this condition the tile of the material can be changed without set another time the detail UV to keep the good appearance.
__Offset:__
Set on X/Y offset for the detail UV.
__Detail AlbedoScale:__
This handle modulate (0 to 2) the detail albedo (red channel) like an overlay effect. The default value is 1 and has no scale.
__Detail NormalScale:__
This handle modulate (0 to 2) the intensity of the detail normal map. The default value is 1 and has no scale.
__Detail SmoothnessScale:__
This handle modulate (0 to 2) the detail smoothness (blue channel) like an overlay effect. The default value is 1 and has no scale.
## Emissive inputs
__Emissive color:__
The emissive color can be managed by a map or a single color. If both are used they are multiplied.
__Emissive intensity:__
Set the power of the emissive effect. By default the value is 0 and doesn’t produce any emissive effect.
__Albedo Affect Emissive:__
By default it is on and allows the albedo to produce color for the emissive. In this case the albedo is multiplied by emissive color and color picker to produce the emissive final color.
For example the emissive color map can be used as an emissive mask, the albedo used to do the color and the color picker to modulate it.
## Advanced options:
__Enable GPU instancing:__
If objects are not static batched and identical, all objects with this material become instanced.
For example, objects with an animation base on the object pivot can’t be static batched (unique pivot for all) but they can be instanced by GPU.
__Enable Specular Occlusion from Bent normal:__
This option used the bent normal assign in the bent normal slot to do a specular occlusion for the reflection probe.
## Specific setting from material type
### Subsurface scattering
![](Images/LitShader7.png)
__Enable transmission: __
On/off the transmission effect. The transmission is managed by a profile and a thickness map. More the object is set thin more lighting cross it.
__Specific subsurface settings:__
![](Images/LitShader8.png)
Diffusion profile:
Rollout menu to choose the profile. Profiles are set in the SSSSettings.asset file. Goto button select the the SSSSettings file.
Subsurface mask map:
This map uses the red channel to manage the visibility (0 = not visible, 1= totally visible) of the SSS effect. This map is modulated by the handle value (0 to 1, 1 is the default).
Thickness map:
This map uses the red channel to set the thickness inside the range set in the profile. 0 is the min range value and 1 is the max range value.
__The profile:__
![](Images/LitShader9.png)
* Name: Name of the profile
* Scattering value: It is a HDR value to manage the color and the scatter of the SSS.
* Max radius: It is an information value and linked to the scattering value. It is the effective radius in millimeters. The blur is energy-preserving, so a wide result in a large area provides a small contribution of individual samples. A short distance increases the sharpness of the result.
* Index of Refraction: To set the real index of refraction. It is 1.4 for skin and between 1.3 and 1.5 for most other material.
* World scale: Set the size of the world unit in meters. Default it is 1 and shouldn’t be modified except if the world unit used is customized.
__Subsurface scattering only:__
Texturing mode: Specifies when the diffuse texture should be applied.
__Transmission only:__
Transmission mode: Regular or Thin object. Really thin object need a specific use.
Transmission tint: Set a HDR value to color the transmission.
Min/Max thickness (mm): Set the range of the thickness. This range is modulate by the thickness map (0 = min, 1 = max).
Thickness remap: This setting allows to remap the thickness without to change the min/max values. The range can be moved without losing the thickness values.
Profile preview: Shows the fraction of lights scattered from the source located in the center.The distance to the boundary of the image corresponds to the max radius. Display is not HDR, so the intensity of pixels around the center may be clipped.
![](Images/LitShader10.png)
Transmission preview: Shows the fraction of light passing through the object for thickness values from the remap. Can be viewed as a cross section of a slab of material illuminated by white light from the left.
![](Images/LitShader11.png)
### Anisotropy
Anisotropic materials don’t have an uniform specular shape.
Real anisotropy example:
![](Images/LitShader12.png)
Anisotropy is used to deform the specular shape on an axe.
![](Images/LitShader13.png)
__Tangent map: __
It is a vector map. Red and Green channel orient the specular shape.
__Anisotropy:__
This handle modulate the intensity of the anisotropic effect and modify the shape orientation, horizontally or vertically, coming from the tangent map.
![](Images/LitShader14.png)
__Anisotropy map:__
This map uses the red channel to modulate the anisotropic effect intensity.
### Iridescence
The iridescence (Thin-film interference) is a natural phenomenon in which lightwaves reflected by the upper and lower boundaries of a thin film interfere with one another, either enhancing or reducing the reflected[ ](https://en.wikipedia.org/wiki/Reflected_light)light.
![](Images/LitShader15.png)
![](Images/LitShader16.png)
__Iridescence Mask:__
This map uses the red channel to manage the visibility of the iridescence effect. The handle can modulate the mask or the visibility if no mask is assigned.
__Iridescence Layer thickness map:__
If no map is assigned, by default the value is 1. The iridescence gradient color is linked to the thickness. When the thickness change the gradient color change too. The handle modulate the thickness also and it is multiplied when a map is assigned.
![](Images/LitShader17.png)
FYI: If the base color is white no iridescence can be visible. For a white base color no lighting enter the matter. All the lighting is reflected to produce a pure white color, so no iridescence can be produce.
### Specular color
When the specular color shader type is chosen, the specular color is defined by a dedicated map not anymore by the albedo value.
![](Images/LitShader18.png)
__Specular color:__
RGB map to set the specular color. When no map is assigned the default value is 1.
__Picker color:__
Uniform color used for the specular. It is multiply by the Specular color map.
## Translucent
The translucency is the transmission of a part of light across the matter.
![](Images/LitShader19.png)
![](Images/LitShader20.png)
The translucency is manage by a profile and a thickness map like for the subsurface scattering.
## How to set a Lit Shader Tessellation?
From a lit shader, use the shader rollout menu to choose the LayeredLitTessellation shader.
![](Images/LitShader21.png)
In case of lit shader tessellation only standard, subsurface scattering and translucent types are available.
__Displacement mode:__
![](Images/LitShader22.png)
None: No displacement is applied. The tessellation is used only to smooth the surface.
Tessellation displacement: A height map (red channel) is used in the inputs to displace the mesh vertices.
![](Images/LitShader23.png)
![](Images/LitShader24.png)
* Lock with object scale: the height map appearance doesn’t change when the object is scaled.
* Lock with height map tiling rate: the height map appearance doesn’t change when the material is tiled.
__Tessellations options:__
![](Images/LitShader25.png)
Tessellation mode:
* None: no smooth is aplied.
* Phong: the tessellation applied a smooth effect.
Tessellation factor:
Between 0 and 64 this factor modulate the tessellation quantity. Higher value mean a surface more tessellated. Above 15 is costly. For XBox one and Playstation4 the maximum is set to 15.
Start fade distance:
It is the distance (in Unity unit) to the camera where the tessellation start to fade out.
End fade distance:
It is the maximum distance (in Unity unit) to the camera where triangle are tessellated.
Triangle size:
Desired screen space size of triangle (in pixel). A smaller value mean smaller triangle.
__Height map parameterization:__
Two parametrizations are available.
Min/Max:
![](Images/LitShader26.png)
In this mode the base of the height map is linked to the base of the mesh. It is used if the height map has uniform values on the map.
Min: Set the height value for the 0 value on the map.
Max: Set the height value for the 1 (255) value on the map.
Offset: Can up and down the height map without modify the min/max values.
Amplitude:
![](Images/LitShader27.png)
Amplitude mode is more used in case of height map with a dedicated center. In this case the height map uses often none uniform values. In case of non uniform values a range of the map is not used to store values, it is clamped in positive or negative.
Amplitude: The amplitude is the double value of the maximum value in negative or in positive.
Base: It is the reference of the base mesh into the height map. By default the base is at 0.5.
Offset: Can up and down the height map without modify the other values.
# Sky and Fog
In HDRP, sky and fog are setup via the interpolation volume framework. The goal is for the user to be able to dynamically change the look of the sky and fog depending on the camera position.
We also provide the necessary tools to offer consistent baking of lightmaps and probes.
The Sky Framework used by HDRP is also designed in a way that it is easy for users to write their own custom sky and use it in their project with minimal effort.
As part of the Volume framework, all local settings components described below are actually VolumeComponents which need to be added to a VolumeComponent on a regular GameObject. As such, all their parameters can be interpolated between different volumes.
## Setting up the Sky
Setting up a sky has two goals: The first one is to define what will be displayed in the background of the scene for a given camera. The second one is to define environment lighting, namely sky reflection and sky ambient probe which is then later used to render lightmaps (real-time or baked).
Settings are split between global settings which are per project/platform and local settings that use the volume framework and can change depending on the scene or camera position.
### Global Sky Settings
Global settings for the sky are in the HDRenderPipeline configuration asset:
![](Images/SkyAndFog1.png)
__Sky Reflection Size__
This parameter drives the size of the cubemap generated from the sky and used for fallback reflection when no local reflection probes are present. It has no effect on the quality of the sky rendered in the background.
__Sky Lighting Override Mask__
In some cases, users may want to dissociate lighting environment from what is rendered in the background (a typical example is to have a very dark sky at night but have a brighter lighting so that the player can still see).
In order to achieve this, users can define the sky lighting override mask which is a Layer mask. If any volumes are present in this layer then environment lighting will use these volumes instead of those from the main camera. If this mask is set to **Nothing**or if there are no volume in this mask then lighting will come from volumes setup in the main camera volume layer mask.
In practice this means that user can define two sets of masks, one for the visual sky and the other for the lighting. Both sets of volume will then be interpolated independently from each other.
Note that lighting override does not affect baked lighting.
### Local Sky Settings
Once global parameters are set, users need to setup volumes with the correct components to setup local parameters for the sky. Currently HDRP provides two different kind of skies.
__Procedural Sky__
This sky is similar to the procedural sky provided with the built-in Unity Render Pipelines.
![](Images/SkyAndFog2.png)
| Property| Function |
|:---|:---|
| __Enable Sun Disk__| Display sun disk |
| __Sun Size__| Size of the sun disk |
| __Sun Size Convergence__| |
| __Atmospheric Thickness__| |
| __Sky Tint__| Color of the sky hemisphere |
| __Ground Color__| Color of the ground hemisphere |
| __Exposure__| Exposure applied to the sky |
| __Multiplier__| Multiplier applied to the sky |
| __Update Mode__| Rate at which the sky environment (reflection en ambient probe) should be updated |
| On Changed| Sky environment is updated when one of its parameter changes |
| On Demand| Sky Environment is explicitly updated by the script |
| Realtime| Sky environment is updated regularly |
| Update Period| Period (in seconds) at which the realtime sky is updated (0 means every frame) |
__HDRI Sky__
Simple sky represented by a cubemap texture.
![](Images/SkyAndFog3.png)
| Property| Function |
|:---|:---|
| __Hdri sky__| Cubemap representing the sky |
| __Exposure__| Exposure applied to the sky |
| __Multiplier__| Multiplier applied to the sky |
| __Rotation__| Rotation applied to the cubemap in degrees |
| __Update Mode__| Rate at which the sky environment (reflection en ambient probe) should be updated |
| On Changed| Sky environment is updated when one of its parameter changes |
| On Demand| Sky Environment is explicitly updated by the script |
| Realtime| Sky environment is updated regularly |
| Update Period| Period (in seconds) at which the realtime sky is updated (0 means every frame) |
### Baking Global Illumination with the sky
In HDRP the sky is completely controlled by the volume system. It means that in the editor, the current state of the sky will depend on the camera position. The consequence is that for users to get a consistent lighting baking, we can’t rely on what is in the scene.
Instead the sky used for baking is set explicitly by the user through the Baking Sky component.
![](Images/SkyAndFog4.png)
User should select a volume profile which contains the sky intended to be used for baking and then choose the right type (in case the profile contains different kinds of skies). If the component is added to a game object that already has a Volume, the profile property will be automatically populated with the corresponding profile asset.
This sky setting will live outside of the volume framework and thus will never be interpolated based on the camera position. Any time the baking is required, this is the sky that will be used.
Only one such component can be present in the editor at any given time. Any additional component of the same type will generate a warning and be ignored.
## Setting up the Fog
Fog is the effect of overlaying a color onto objects dependant on the distance from the camera. This is used to simulate fog or mist in outdoor environments and is also typically used to hide clipping of objects when a camera’s far clip plane has been moved forward for performance.
In HDRP, users can choose between two different kind of fogs, linear and exponential fog. All types of materials (lit or unlit) will react correctly to the fog. Depending on the type of fog, density will evolve differently with respect to distance from camera and world space height.
Instead of using a constant color, both types of fog can choose to use the background sky as a source for color. In this case, the color will be sampled from different mip maps of the cubemap generated from the current sky settings. Chosen mip will vary linearly between the blurriest one to the highest resolution one depending on the distance from camera and the "Mip Fog" parameters. Users can also choose to limit the resolution of the higher mip used.
For both types of fog, density is computed from camera distance and world space height independently and then multiplied together to obtain the final result.
__Linear Fog__
Density will increase linearly with view distance and world space height depending on the provided parameters.
![](Images/SkyAndFog5.png)
| Property| Function |
|:---|:---|
| __Density__| Global multiplier for the fog density |
| __Color Mode__| Source of the fog color |
| Constant Color| Fog is a constant color |
| Color| Color of the fog |
| Sky Color| Fog color is sampled from the sky |
| Mip Fog Near| Distance at which the blurriest sky mip is used |
| Mip Fog Far| Distance at which the higher sky mip (see "Mip Fog Max Mip" ) is used |
| Mip Fog Max Mip| Maximum mip map used to sample the color (1.0 being highest resolution and 0.0 lowest resolution). |
| __Fog Start__| Distance from camera at which fog density starts to increase from zero. |
| __Fog End__| Distance from camera at which fog density is maximum. |
| __Fog Height Start__| Height at which fog density starts to decrease |
| __Fog Height End__| Height at which fog density is zero |
__Exponential Fog__
Density will increase exponentially with view distance and world space height depending on the provided parameters.
![](Images/SkyAndFog6.png)
| Property| Function |
|:---|:---|
| __Density__| Global multiplier for the fog density |
| __Color Mode__| Source of the fog color |
| Constant Color| Fog is a constant color |
| Color| Color of the fog |
| Sky Color| Fog color is sampled from the sky |
| Mip Fog Near| Distance at which the blurriest sky mip is used |
| Mip Fog Far| Distance at which the higher sky mip (see "Mip Fog Max Mip" ) is used |
| Mip Fog Max Mip| Maximum mip map used to sample the color (1.0 being highest resolution and 0.0 lowest resolution). |
| __Fog Distance__| Distance from camera at will reach maximum |
| __Fog Base Height__| World space height at which fog density starts to decrease from 1.0 |
| __Fog Height Attenuation__| Fall off of height fog attenuation (bigger values will make attenuation sharper) |
## Visual Environment
Once the proper components have been setup, users need to specify what kind of sky and fog should be used for rendering. This is done through the Visual Environment component.
![](Images/SkyAndFog7.png)
| Property| Function |
|:---|:---|
| __Sky Type__| Type of sky used for rendering. This list will be automatically updated with any custom sky written by users |
| __Fog Type__| Type of fog used for rendering |
To help setting things up more easily, users can use the contextual menu to directly create a game object named "Scene Settings" and go from there. This game object is already setup with a default procedural sky and exponential fog inside a global Volume (it also contains default shadow settings).
![](Images/SkyAndFog8.png)
## Writing Custom Sky Renderers
The sky system is setup in a way that allows users to develop their own kind of sky with their own parameters and shaders.
Three things are needed in order to write your own sky.
__SkySettings__
Create a new class that inherits from *SkySettings*. This class will contain all parameters specific to the particular sky renderer user is writing. Please refer to the Volume system documentation to learn how to declare volume parameters.
Three things are mandatory to write:
* SkyUniqueID attribute: This must be an integer unique to this particular sky. Must not clash with any other sky settings. The SkyType enum is available for users to see what values are already used by HDRP.
* GetHashCode: This is used by the sky system to determine when to re-render the sky reflection cubemap.
* CreateRenderer: This is used by the sky system to instantiate the proper renderer.
Exemple: HDRI Sky
```
[SkyUniqueID(87248]<br/> public class HDRISky : SkySettings
{
[Tooltip("Cubemap used to render the sky.")]
public CubemapParameter hdriSky = new CubemapParameter(null);
public override SkyRenderer CreateRenderer()
{
return new HDRISkyRenderer(this);
}
public override int GetHashCode()
{
int hash = base.GetHashCode();
unchecked
{
hash = hdriSky.value != null ? hash * 23 + hdriSky.GetHashCode() : hash;
}
return hash;
}
}
```
__SkyRenderer__
This is the class that will actually render the sky, either into a cubemap for lighting or on the background. This is where users must implement all their specific rendering.
It must implement this interface:
```
public abstract class SkyRenderer
{
// Method used to initialize any resource for the sky rendering (shaders, …)
public abstract void Build();
// Method used to clean up any resource previously allocated
public abstract void Cleanup();
// SkyRenderer is responsible for setting up render targets provided in builtinParams
public abstract void SetRenderTargets(BuiltinSkyParameters builtinParams);
// renderForCubemap: When rendering into a cube map, no depth buffer is available so user has to make sure not to use depth testing or the depth texture.
public abstract void RenderSky(BuiltinSkyParameters builtinParams, bool renderForCubemap);
// Returns true if provided sky setting parameters are valid.
public abstract bool IsValid();
}
```
Exemple: HDRISkyRenderer:
```
public class HDRISkyRenderer : SkyRenderer<br/>{
Material m_SkyHDRIMaterial; // Renders a cubemap into a render texture (can be cube or 2D)
MaterialPropertyBlock m_PropertyBlock;
HDRISky m_HdriSkyParams;
public HDRISkyRenderer(HDRISky hdriSkyParams)
{
m_HdriSkyParams = hdriSkyParams;
m_PropertyBlock = new MaterialPropertyBlock();
}
public override void Build()
{
var hdrp = GraphicsSettings.renderPipelineAsset as HDRenderPipelineAsset;
m_SkyHDRIMaterial = CoreUtils.CreateEngineMaterial(hdrp.renderPipelineResources.hdriSky);
}
public override void Cleanup()
{
CoreUtils.Destroy(m_SkyHDRIMaterial);
}
public override void SetRenderTargets(BuiltinSkyParameters builtinParams)
{
if (builtinParams.depthBuffer == BuiltinSkyParameters.nullRT)
{
HDUtils.SetRenderTarget(builtinParams.commandBuffer, builtinParams.hdCamera, builtinParams.colorBuffer);
}
else
{
HDUtils.SetRenderTarget(builtinParams.commandBuffer, builtinParams.hdCamera, builtinParams.colorBuffer, builtinParams.depthBuffer);
}
}
public override void RenderSky(BuiltinSkyParameters builtinParams, bool renderForCubemap)
{
m_PropertyBlock.SetTexture(HDShaderIDs._Cubemap, m_HdriSkyParams.hdriSky);
m_PropertyBlock.SetVector(HDShaderIDs._SkyParam, new Vector4(m_HdriSkyParams.exposure, m_HdriSkyParams.multiplier, -m_HdriSkyParams.rotation, 0.0f)); // -rotation to match Legacy...
// This matrix needs to be updated at the draw call frequency.
m_PropertyBlock.SetMatrix(HDShaderIDs._PixelCoordToViewDirWS, builtinParams.pixelCoordToViewDirMatrix);
CoreUtils.DrawFullScreen(builtinParams.commandBuffer, m_SkyHDRIMaterial, m_PropertyBlock, renderForCubemap ? 0 : 1);
}
public override bool IsValid()
{
return m_HdriSkyParams != null && m_SkyHDRIMaterial != null;
}
}
```
__Rendering Shader__
This is highly dependent on what the particular sky is supposed to look like. Here we’ll just show the example of HDRISky.
Note that we implemented two passes, one that uses Depth Test for rendering the sky in the background (so that it’s occluded by geometry) and the other that does not for when the sky is rendered into the reflection cubemap.
```
Shader "Hidden/HDRenderPipeline/Sky/HDRISky"<br/>{
HLSLINCLUDE
#pragma vertex Vert
#pragma fragment Frag
#pragma target 4.5
#pragma only_renderers d3d11 ps4 xboxone vulkan metal
#include "CoreRP/ShaderLibrary/Common.hlsl"
#include "CoreRP/ShaderLibrary/Color.hlsl"
#include "CoreRP/ShaderLibrary/CommonLighting.hlsl"
TEXTURECUBE(_Cubemap);
SAMPLER(sampler_Cubemap);
float4 _SkyParam; // x exposure, y multiplier, z rotation
float4x4 _PixelCoordToViewDirWS; // Actually just 3x3, but Unity can only set 4x4
struct Attributes
{
uint vertexID : SV_VertexID;
};
struct Varyings
{
float4 positionCS : SV_POSITION;
};
Varyings Vert(Attributes input)
{
Varyings output;
output.positionCS = GetFullScreenTriangleVertexPosition(input.vertexID, UNITY_RAW_FAR_CLIP_VALUE);
return output;
}
float4 Frag(Varyings input) : SV_Target
{
// Points towards the camera
float3 viewDirWS = normalize(mul(float3(input.positionCS.xy, 1.0), (float3x3)_PixelCoordToViewDirWS));
// Reverse it to point into the scene
float3 dir = -viewDirWS;
// Rotate direction
float phi = DegToRad(_SkyParam.z);
float cosPhi, sinPhi;
sincos(phi, sinPhi, cosPhi);
float3 rotDirX = float3(cosPhi, 0, -sinPhi);
float3 rotDirY = float3(sinPhi, 0, cosPhi);
dir = float3(dot(rotDirX, dir), dir.y, dot(rotDirY, dir));
float3 skyColor = ClampToFloat16Max(SAMPLE_TEXTURECUBE_LOD(_Cubemap, sampler_Cubemap, dir, 0).rgb * exp2(_SkyParam.x) * _SkyParam.y);
return float4(skyColor, 1.0);
}
ENDHLSL
SubShader
{
Pass
{
ZWrite Off
ZTest Always
Blend Off
Cull Off
HLSLPROGRAM
ENDHLSL
}
Pass
{
ZWrite Off
ZTest LEqual
Blend Off
Cull Off
HLSLPROGRAM
ENDHLSL
}
}
Fallback Off
}
```
After doing all this, the new Sky should automatically appear in the combo box in the *Visual Environment* component.

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


// If TAA is enabled projMatrix will hold a jittered projection matrix. The original,
// non-jittered projection matrix can be accessed via nonJitteredProjMatrix.
bool taaEnabled = camera.cameraType == CameraType.Game &&
CoreUtils.IsTemporalAntialiasingActive(postProcessLayer);
CoreUtils.IsTemporalAntialiasingActive(postProcessLayer) &&
frameSettings.enablePostprocess;
var nonJitteredCameraProj = camera.projectionMatrix;
var cameraProj = taaEnabled

17
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugDisplay.cs


{
children =
{
new DebugUI.UIntField { displayName = "Shadow Atlas Index", getter = () => lightingDebugSettings.shadowAtlasIndex, setter = value => lightingDebugSettings.shadowAtlasIndex = value, min = () => 0u, max = () => (uint)(RenderPipelineManager.currentPipeline as HDRenderPipeline).GetShadowAtlasCount() - 1u }
new DebugUI.UIntField { displayName = "Shadow Atlas Index", getter = () => lightingDebugSettings.shadowAtlasIndex, setter = value => lightingDebugSettings.shadowAtlasIndex = value, min = () => 0u, max = () => (uint)(RenderPipelineManager.currentPipeline as HDRenderPipeline).GetShadowAtlasCount() - 1u },
new DebugUI.UIntField { displayName = "Shadow Slice Index", getter = () => lightingDebugSettings.shadowSliceIndex, setter = value => lightingDebugSettings.shadowSliceIndex = value, min = () => 0u, max = () => (uint)(RenderPipelineManager.currentPipeline as HDRenderPipeline).GetShadowSliceCount(lightingDebugSettings.shadowAtlasIndex) - 1u }
}
});
}

list.Add(new DebugUI.BoolField { displayName = "Override Normal", getter = () => lightingDebugSettings.overrideNormal, setter = value => lightingDebugSettings.overrideNormal = value });
list.Add(new DebugUI.BoolField { displayName = "Override Specular Color", getter = () => lightingDebugSettings.overrideSpecularColor, setter = value => lightingDebugSettings.overrideSpecularColor = value, onValueChanged = RefreshLightingDebug });
if (lightingDebugSettings.overrideSpecularColor)
{
list.Add(new DebugUI.Container
{
children =
{
new DebugUI.ColorField { displayName = "Specular Color", getter = () => lightingDebugSettings.overrideSpecularColorValue, setter = value => lightingDebugSettings.overrideSpecularColorValue = value, showAlpha = false, hdr = false }
}
});
}
list.Add(new DebugUI.EnumField { displayName = "Tile/Cluster Debug", getter = () => (int)lightingDebugSettings.tileClusterDebug, setter = value => lightingDebugSettings.tileClusterDebug = (LightLoop.TileClusterDebug)value, autoEnum = typeof(LightLoop.TileClusterDebug), onValueChanged = RefreshLightingDebug });
if (lightingDebugSettings.tileClusterDebug != LightLoop.TileClusterDebug.None && lightingDebugSettings.tileClusterDebug != LightLoop.TileClusterDebug.MaterialFeatureVariants)
{

UnregisterDebugItems(k_PanelDisplayStats, m_DebugDisplayStatsItems);
UnregisterDebugItems(k_PanelMaterials, m_DebugMaterialItems);
UnregisterDebugItems(k_PanelLighting, m_DebugLightingItems);
UnregisterDebugItems(k_PanelRendering, m_DebugLightingItems);
UnregisterDebugItems(k_PanelRendering, m_DebugRenderingItems);
}
void UnregisterDebugItems(string panelName, DebugUI.Widget[] items)

1
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugDisplay.hlsl


float4 _DebugLightingAlbedo; // x == bool override, yzw = albedo for diffuse
float4 _DebugLightingSmoothness; // x == bool override, y == override value
float4 _DebugLightingNormal; // x == bool override
float4 _DebugLightingSpecularColor; // x == bool override, yzw = specular color
float4 _MousePixelCoord; // xy unorm, zw norm
float _DebugEnvironmentProxyDepthScale;
CBUFFER_END

6
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugDisplayLatlong.shader


TEXTURECUBE(_InputCubemap);
SAMPLER(sampler_InputCubemap);
float _Mipmap;
float _RequireToFlipInputTexture;
struct Attributes
{

Varyings output;
output.positionCS = GetFullScreenTriangleVertexPosition(input.vertexID);
output.texcoord = GetFullScreenTriangleTexCoord(input.vertexID);// *_TextureScaleBias.xy + _TextureScaleBias.zw;
if (_RequireToFlipInputTexture > 0.0f)
{
output.texcoord.y = 1.0f - output.texcoord.y;
}
return output;
}

4
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/LightingDebug.cs


public bool shadowDebugUseSelection = false;
public uint shadowMapIndex = 0;
public uint shadowAtlasIndex = 0;
public uint shadowSliceIndex = 0;
public float shadowMinValue = 0.0f;
public float shadowMaxValue = 1.0f;

public Color overrideAlbedoValue = new Color(0.5f, 0.5f, 0.5f);
public bool overrideNormal = false;
public bool overrideSpecularColor = false;
public Color overrideSpecularColorValue = new Color(1.0f, 1.0f, 1.0f);
public bool displaySkyReflection = false;
public float skyReflectionMipmap = 0.0f;

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


UpdateLightIntensity();
}
settings.DrawBounceIntensity();
settings.DrawLightmapping();
EditorGUI.BeginChangeCheck(); // For GI we need to detect any change on additional data and call SetLightDirty

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/LayeredLit/LayeredLitUI.cs


namespace UnityEditor.Experimental.Rendering.HDPipeline
{
internal class LayeredLitGUI : LitGUI
public class LayeredLitGUI : LitGUI
{
public enum VertexColorMode
{

10
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/Lit/LitUI.cs


namespace UnityEditor.Experimental.Rendering.HDPipeline
{
class LitGUI : BaseLitGUI
public class LitGUI : BaseLitGUI
{
protected static class Styles
{

public static GUIContent thicknessRemapText = new GUIContent("Thickness Remap", "Remaps values of the thickness map from [0, 1] to the specified range.");
// Iridescence
public static GUIContent iridescenceMaskText = new GUIContent("Iridescence Mask", "Control intensity of the iridescence");
public static GUIContent iridescenceMaskText = new GUIContent("Iridescence Mask (R)", "Control intensity of the iridescence");
public static GUIContent iridescenceThicknessMapText = new GUIContent("Iridescence Layer Thickness map");
public static GUIContent iridescenceThicknessMapText = new GUIContent("Iridescence Layer Thickness map (R)");
public static GUIContent iridescenceThicknessRemapText = new GUIContent("Iridescence Layer Thickness remap");
// Clear Coat

{
m_MaterialEditor.TexturePropertySingleLine(Styles.iridescenceMaskText, iridescenceMaskMap, iridescenceMask);
m_MaterialEditor.TexturePropertySingleLine(Styles.iridescenceThicknessMapText, iridescenceThicknessMap);
m_MaterialEditor.TexturePropertySingleLine(Styles.iridescenceThicknessMapText, iridescenceThicknessMap);
// Display the remap of texture values.
Vector2 remap = iridescenceThicknessRemap.vectorValue;
EditorGUI.BeginChangeCheck();

else
{
// Allow the user to set the constant value of thickness if no thickness map is provided.
m_MaterialEditor.ShaderProperty(iridescenceThickness, Styles.iridescenceThicknessText);
m_MaterialEditor.TexturePropertySingleLine(Styles.iridescenceThicknessMapText, iridescenceThicknessMap, iridescenceThickness);
}
}

5
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Shadows/HDShadowSettingsEditor.cs


SerializedDataParameter[] m_CascadeShadowSplits = new SerializedDataParameter[3];
SerializedDataParameter[] m_CascadeShadowBorders = new SerializedDataParameter[4];
// For now we don't use borders so we hide the UI.
bool m_bShowBorders = false;
public override void OnEnable()
{
var o = new PropertyFetcher<HDShadowSettings>(serializedObject);

PropertyField(m_CascadeShadowSplits[i], CoreEditorUtils.GetContent(string.Format("Split {0}", i + 1)));
}
if(m_bShowBorders)
if(LightLoop.s_UseCascadeBorders)
{
EditorGUILayout.Space();

14
ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDRenderPipeline.cs


public int GetCurrentShadowCount() { return m_LightLoop.GetCurrentShadowCount(); }
public int GetShadowAtlasCount() { return m_LightLoop.GetShadowAtlasCount(); }
public int GetShadowSliceCount(uint atlasIndex) { return m_LightLoop.GetShadowSliceCount(atlasIndex); }
readonly SkyManager m_SkyManager = new SkyManager();
readonly LightLoop m_LightLoop = new LightLoop();

}
}
// Disable postprocess if we enable debug mode
if (m_CurrentDebugDisplaySettings.fullScreenDebugMode == FullScreenDebugMode.None && m_CurrentDebugDisplaySettings.IsDebugDisplayEnabled())
var postProcessLayer = camera.GetComponent<PostProcessLayer>();
// Disable post process if we enable debug mode or if the post process layer is disabled
if (m_CurrentDebugDisplaySettings.fullScreenDebugMode != FullScreenDebugMode.None || m_CurrentDebugDisplaySettings.IsDebugDisplayEnabled() || !CoreUtils.IsPostProcessingActive(postProcessLayer))
var postProcessLayer = camera.GetComponent<PostProcessLayer>();
var hdCamera = HDCamera.Get(camera, postProcessLayer, m_FrameSettings);
Resize(hdCamera);

StartStereoRendering(renderContext, hdCamera.camera);
// Final blit
if (m_FrameSettings.enablePostprocess && CoreUtils.IsPostProcessingActive(postProcessLayer))
if (m_FrameSettings.enablePostprocess)
{
RenderPostProcess(hdCamera, cmd, postProcessLayer);
}

var debugAlbedo = new Vector4(lightingDebugSettings.overrideAlbedo ? 1.0f : 0.0f, lightingDebugSettings.overrideAlbedoValue.r, lightingDebugSettings.overrideAlbedoValue.g, lightingDebugSettings.overrideAlbedoValue.b);
var debugSmoothness = new Vector4(lightingDebugSettings.overrideSmoothness ? 1.0f : 0.0f, lightingDebugSettings.overrideSmoothnessValue, 0.0f, 0.0f);
var debugNormal = new Vector4(lightingDebugSettings.overrideNormal ? 1.0f : 0.0f, 0.0f, 0.0f, 0.0f);
var debugSpecularColor = new Vector4(lightingDebugSettings.overrideSpecularColor ? 1.0f : 0.0f, lightingDebugSettings.overrideSpecularColorValue.r, lightingDebugSettings.overrideSpecularColorValue.g, lightingDebugSettings.overrideSpecularColorValue.b);
cmd.SetGlobalInt(HDShaderIDs._DebugViewMaterial, (int)m_CurrentDebugDisplaySettings.GetDebugMaterialIndex());
cmd.SetGlobalInt(HDShaderIDs._DebugLightingMode, (int)m_CurrentDebugDisplaySettings.GetDebugLightingMode());

cmd.SetGlobalVector(HDShaderIDs._DebugLightingSmoothness, debugSmoothness);
cmd.SetGlobalVector(HDShaderIDs._DebugLightingNormal, debugNormal);
cmd.SetGlobalVector(HDShaderIDs._DebugLightingSpecularColor, debugSpecularColor);
cmd.SetGlobalTexture(HDShaderIDs._DebugFont, m_Asset.renderPipelineResources.debugFontTexture);
}
else

var skyReflection = m_SkyManager.skyReflection;
m_SharedPropertyBlock.SetTexture(HDShaderIDs._InputCubemap, skyReflection);
m_SharedPropertyBlock.SetFloat(HDShaderIDs._Mipmap, lightingDebug.skyReflectionMipmap);
m_SharedPropertyBlock.SetFloat(HDShaderIDs._RequireToFlipInputTexture, hdCamera.camera.cameraType != CameraType.SceneView ? 1.0f : 0.0f);
cmd.SetViewport(new Rect(x, y, overlaySize, overlaySize));
cmd.DrawProcedural(Matrix4x4.identity, m_DebugDisplayLatlong, 0, MeshTopology.Triangles, 3, 1, m_SharedPropertyBlock);
HDUtils.NextOverlayCoord(ref x, ref y, overlaySize, overlaySize, hdCamera.actualWidth);

1
ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDStringConstants.cs


public static readonly int _DebugLightingAlbedo = Shader.PropertyToID("_DebugLightingAlbedo");
public static readonly int _DebugLightingSmoothness = Shader.PropertyToID("_DebugLightingSmoothness");
public static readonly int _DebugLightingNormal = Shader.PropertyToID("_DebugLightingNormal");
public static readonly int _DebugLightingSpecularColor = Shader.PropertyToID("_DebugLightingSpecularColor");
public static readonly int _AmbientOcclusionTexture = Shader.PropertyToID("_AmbientOcclusionTexture");
public static readonly int _DebugMipMapMode = Shader.PropertyToID("_DebugMipMapMode");

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


EnvironmentAndPunctual = 5,
EnvironmentAndArea = 6,
EnvironmentAndAreaAndPunctual = 7,
Decal = 8
Decal = 8
};
public const int k_MaxDirectionalLightsOnScreen = 4;

TextureCache2D m_CookieTexArray;
TextureCacheCubemap m_CubeCookieTexArray;
List<Matrix4x4> m_Env2DCaptureVP = new List<Matrix4x4>();
// For now we don't use shadow cascade borders.
static public readonly bool s_UseCascadeBorders = false;
public class LightList
{

return (m_ShadowMgr == null) ? 0 : (int)m_ShadowMgr.GetShadowMapCount();
}
public int GetShadowSliceCount(uint atlasIndex)
{
return (m_ShadowMgr == null) ? 0 : (int)m_ShadowMgr.GetShadowMapSliceCount(atlasIndex);
}
public void UpdateCullingParameters(ref ScriptableCullingParameters cullingParams)
{
m_ShadowMgr.UpdateCullingParameters( ref cullingParams );

uint faceCount = m_ShadowMgr.GetShadowRequestFaceCount((uint)index);
for (uint i = 0; i < faceCount; ++i)
{
m_ShadowMgr.DisplayShadow(cmd, m_DebugShadowMapMaterial, index, i, x, y, overlaySize, overlaySize, lightingDebug.shadowMinValue, lightingDebug.shadowMaxValue);
m_ShadowMgr.DisplayShadow(cmd, m_DebugShadowMapMaterial, index, i, x, y, overlaySize, overlaySize, lightingDebug.shadowMinValue, lightingDebug.shadowMaxValue, hdCamera.camera.cameraType != CameraType.SceneView);
HDUtils.NextOverlayCoord(ref x, ref y, overlaySize, overlaySize, hdCamera.actualWidth);
}
}

m_ShadowMgr.DisplayShadowMap(cmd, m_DebugShadowMapMaterial, lightingDebug.shadowAtlasIndex, 0, x, y, overlaySize, overlaySize, lightingDebug.shadowMinValue, lightingDebug.shadowMaxValue);
m_ShadowMgr.DisplayShadowMap(cmd, m_DebugShadowMapMaterial, lightingDebug.shadowAtlasIndex, lightingDebug.shadowSliceIndex, x, y, overlaySize, overlaySize, lightingDebug.shadowMinValue, lightingDebug.shadowMaxValue, hdCamera.camera.cameraType != CameraType.SceneView);
HDUtils.NextOverlayCoord(ref x, ref y, overlaySize, overlaySize, hdCamera.actualWidth);
}
}

5
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoop.hlsl


float3(1.0, 1.0, 1.0)
};
diffuseLighting = float3(0.0, 0.0, 0.0);
diffuseLighting = float3(1.0, 1.0, 1.0);
if (_DirectionalLightCount > 0)
{
int shadowIdx = _DirectionalLightDatas[0].shadowIndex;

int shadowSplitIndex = EvalShadow_GetSplitIndex(lightLoopContext.shadowContext, shadowIdx, positionWS, payloadOffset, alpha);
int cascadeCount;
int shadowSplitIndex = EvalShadow_GetSplitIndex(lightLoopContext.shadowContext, shadowIdx, positionWS, payloadOffset, alpha, cascadeCount);
if (shadowSplitIndex >= 0)
{
diffuseLighting = lerp(s_CascadeColors[shadowSplitIndex], s_CascadeColors[shadowSplitIndex+1], alpha) * shadow;

6
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/Shadow.hlsl


{
return EvalShadow_GetClosestSample_Punctual( shadowContext, shadowContext.tex2DArray[SHADOW_DISPATCH_PUNC_TEX], positionWS, index, L );
}
float GetPunctualShadowClosestDistance( ShadowContext shadowContext, SamplerState sampl, real3 positionWS, int index, float3 L, float3 lightPositionWS)
{
return EvalShadow_SampleClosestDistance_Punctual( shadowContext, shadowContext.tex2DArray[SHADOW_DISPATCH_PUNC_TEX], sampl, positionWS, index, L, lightPositionWS );
}
#endif
// cleanup the defines

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


// Additional bits set in 'bsdfData.materialFeatures' to save registers and simplify feature tracking.
#define MATERIAL_FEATURE_FLAGS_SSS_OUTPUT_SPLIT_LIGHTING ((MATERIAL_FEATURE_MASK_FLAGS + 1) << 0)
#define MATERIAL_FEATURE_FLAGS_SSS_TEXTURING_MODE_OFFSET FastLog2((MATERIAL_FEATURE_MASK_FLAGS + 1) << 1) // 2 bits
#define MATERIAL_FEATURE_FLAGS_TRANSMISSION_MODE_AUTO_THICKNESS ((MATERIAL_FEATURE_MASK_FLAGS + 1) << 3)
#define MATERIAL_FEATURE_FLAGS_TRANSMISSION_MODE_MIXED_THICKNESS ((MATERIAL_FEATURE_MASK_FLAGS + 1) << 3)
uint FeatureFlagsToTileVariant(uint featureFlags)
{

// the current object. That's not a problem, since large thickness will result in low intensity.
bool useThinObjectMode = IsBitSet(asuint(_TransmissionFlags), diffusionProfile);
bsdfData.materialFeatures |= useThinObjectMode ? 0 : MATERIAL_FEATURE_FLAGS_TRANSMISSION_MODE_AUTO_THICKNESS;
bsdfData.materialFeatures |= useThinObjectMode ? 0 : MATERIAL_FEATURE_FLAGS_TRANSMISSION_MODE_MIXED_THICKNESS;
// Compute transmittance using baked thickness here. It may be overridden for direct lighting
// in the auto-thickness mode (but is always be used for indirect lighting).

#endif
}
// This function is similar to ApplyDebugToSurfaceData but for BSDFData
void ApplyDebugToBSDFData(inout BSDFData bsdfData)
{
#ifdef DEBUG_DISPLAY
// Override value if requested by user
// this can be use also in case of debug lighting mode like specular only
bool overrideSpecularColor = _DebugLightingSpecularColor.x != 0.0;
if (overrideSpecularColor)
{
float3 overrideSpecularColor = _DebugLightingSpecularColor.yzw;
bsdfData.fresnel0 = overrideSpecularColor;
}
#endif
}
SSSData ConvertSurfaceDataToSSSData(SurfaceData surfaceData)
{
SSSData sssData;

FillMaterialTransparencyData( surfaceData.baseColor, surfaceData.metallic, surfaceData.ior, surfaceData.transmittanceColor, surfaceData.atDistance,
surfaceData.thickness, surfaceData.transmittanceMask, bsdfData);
#endif
ApplyDebugToBSDFData(bsdfData);
return bsdfData;
}

// Decompress feature-agnostic data from the G-Buffer.
float3 baseColor = inGBuffer0.rgb;
bsdfData.specularOcclusion = inGBuffer0.a; // Later possibly overwritten by SSS
bsdfData.perceptualRoughness = inGBuffer1.a;
bsdfData.perceptualRoughness = inGBuffer1.a;
bakeDiffuseLighting = inGBuffer3.rgb;

FillMaterialTransmission(sssData.diffusionProfile, inGBuffer2.g, bsdfData);
}
}
else
{
bsdfData.specularOcclusion = inGBuffer0.a;
}
// Special handling for anisotropy: When anisotropy is present in a tile, the whole tile will use anisotropy to avoid divergent evaluation of GGX that increase the cost
// Note that it mean that when we have the worse case, we always use Anisotropy and shader like deferred.shader are always the worst case (but only used for debugging)

// perceptualRoughness is not clamped, and is meant to be used for IBL.
// perceptualRoughness can be modify by FillMaterialClearCoatData, so ConvertAnisotropyToClampRoughness must be call after
ConvertAnisotropyToClampRoughness(bsdfData.perceptualRoughness, bsdfData.anisotropy, bsdfData.roughnessT, bsdfData.roughnessB);
ApplyDebugToBSDFData(bsdfData);
return pixelFeatureFlags;
}

// - we integrate the diffuse reflectance profile w.r.t. the radius (while also accounting
// for the thickness) to compute the transmittance;
// - we multiply the transmitted radiance by the transmittance.
float3 EvaluateTransmission(BSDFData bsdfData, float3 transmittance, float NdotL, float NdotV, float attenuation)
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 negatedNdotL = -NdotL;
// Apply wrapped lighting to better handle thin objects (cards) at grazing angles.
bool autoThicknessMode = HasFeatureFlag(bsdfData.materialFeatures, MATERIAL_FEATURE_FLAGS_TRANSMISSION_MODE_AUTO_THICKNESS);
float backNdotL = autoThicknessMode ? negatedNdotL : wrappedNdotL;
// 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 *= INV_PI * F_Transm_Schlick(0, 0.5, NdotV) * F_Transm_Schlick(0, 0.5, abs(backNdotL));
attenuation *= DisneyDiffuse(NdotV, max(0, -NdotL), LdotV, bsdfData.perceptualRoughness);
float intensity = max(0, attenuation * backNdotL); // Warning: attenuation can be greater than 1 due to the inverse square attenuation (when position is close to light)
float intensity = attenuation * wrappedNdotL;
return intensity * transmittance;
}

float3 N = bsdfData.normalWS;
float3 L = -lightData.forward; // Lights point backward in Unity
float NdotL = dot(N, L); // Note: Ideally this N here should be vertex normal - use for transmisison
float3 transmittance = bsdfData.transmittance;
bool autoThicknessMode = HasFeatureFlag(bsdfData.materialFeatures, MATERIAL_FEATURE_FLAGS_TRANSMISSION_MODE_AUTO_THICKNESS);
UNITY_BRANCH
if (autoThicknessMode && NdotL < 0 && lightData.shadowIndex >= 0)
{
// TODO: perform bilinear filtering of the shadow map.
// Recompute transmittance using the thickness value computed from the shadow map.
float3 occluderPosWS = GetDirectionalShadowClosestSample(lightLoopContext.shadowContext, posInput.positionWS, bsdfData.normalWS, lightData.shadowIndex, float4(L, 0));
float thicknessInUnits = distance(posInput.positionWS, occluderPosWS);
float thicknessInMeters = thicknessInUnits * _WorldScales[bsdfData.diffusionProfile].x;
float thicknessInMillimeters = thicknessInMeters * MILLIMETERS_PER_METER;
// TODO: optimize.
#if SHADEROPTIONS_USE_DISNEY_SSS
transmittance = ComputeTransmittanceDisney(_ShapeParams[bsdfData.diffusionProfile].rgb,
_TransmissionTintsAndFresnel0[bsdfData.diffusionProfile].rgb,
thicknessInMillimeters);
#else
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
// Make sure we do not sample the shadow map twice.
lightData.shadowIndex = -1;
// 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.
}
float NdotV = ClampNdotV(preLightData.NdotV);
float NdotL = dot(N, L);
float LdotV = dot(L, V);
float3 color;
float attenuation;

lighting.specular *= intensity * lightData.specularScale;
}
// TODO: move this before BSDF() to save VGPRs.
if (HasFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_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_LIT_TRANSMISSION) && !mixedThicknessMode)
lighting.diffuse += EvaluateTransmission(bsdfData, transmittance, NdotL, ClampNdotV(preLightData.NdotV), attenuation * lightData.diffuseScale);
lighting.diffuse += EvaluateTransmission(bsdfData, bsdfData.transmittance, NdotL, NdotV, LdotV, attenuation * lightData.diffuseScale);
}
// Save ALU by applying light and cookie colors only once.

}
float3 N = bsdfData.normalWS;
float NdotV = ClampNdotV(preLightData.NdotV);
float3 transmittance = bsdfData.transmittance;
bool autoThicknessMode = HasFeatureFlag(bsdfData.materialFeatures, MATERIAL_FEATURE_FLAGS_TRANSMISSION_MODE_AUTO_THICKNESS);
float LdotV = dot(L, V);
UNITY_BRANCH
if (autoThicknessMode && NdotL < 0 && lightData.shadowIndex >= 0)
{
// TODO: perform bilinear filtering of the shadow map.
// Recompute transmittance using the thickness value computed from the shadow map.
float3 occluderPosWS = GetPunctualShadowClosestSample(lightLoopContext.shadowContext, posInput.positionWS, lightData.shadowIndex, L);
bool mixedThicknessMode = HasFeatureFlag(bsdfData.materialFeatures, MATERIAL_FEATURE_FLAGS_TRANSMISSION_MODE_MIXED_THICKNESS)
&& NdotL < 0 && lightData.shadowIndex >= 0;
float thicknessInUnits = distance(posInput.positionWS, occluderPosWS);
float thicknessInMeters = thicknessInUnits * _WorldScales[bsdfData.diffusionProfile].x;
float thicknessInMillimeters = thicknessInMeters * MILLIMETERS_PER_METER;
// TODO: optimize.
#if SHADEROPTIONS_USE_DISNEY_SSS
transmittance = ComputeTransmittanceDisney(_ShapeParams[bsdfData.diffusionProfile].rgb,
_TransmissionTintsAndFresnel0[bsdfData.diffusionProfile].rgb,
thicknessInMillimeters);
#else
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
// Save the original version for the transmission code below.
int originalShadowIndex = lightData.shadowIndex;
if (mixedThicknessMode)
{
// 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.
}
float3 color;

// 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)
// Note: We use NdotL here to early out, but in case of clear coat this is not correct. But we are ok with this

lighting.specular *= intensity * lightData.specularScale;
}
// TODO: move this before BSDF() to save VGPRs.
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.
lighting.diffuse += EvaluateTransmission(bsdfData, transmittance, NdotL, ClampNdotV(preLightData.NdotV), attenuation * lightData.diffuseScale);
lighting.diffuse += EvaluateTransmission(bsdfData, transmittance, NdotL, NdotV, LdotV, attenuation * lightData.diffuseScale);
}
// Save ALU by applying light and cookie colors only once.

6
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Shadows/HDShadowSettings.cs


m_CascadeShadowBorders[1] = cascadeShadowBorder1;
m_CascadeShadowBorders[2] = cascadeShadowBorder2;
m_CascadeShadowBorders[3] = cascadeShadowBorder3;
// For now we don't use shadow cascade borders but we still want to have the last split fading out.
if(!LightLoop.s_UseCascadeBorders)
{
m_CascadeShadowBorders[cascadeShadowSplitCount - 1] = 0.2f;
}
return m_CascadeShadowBorders;
}
}

2
ScriptableRenderPipeline/LightweightPipeline/LWRP/Data/LightweightPipelineAsset.cs


private Material GetMaterial(DefaultMaterialType materialType)
{
#if UNITY_EDITOR
if (editorResources == null)
return null;
switch (materialType)
{

32
ScriptableRenderPipeline/LightweightPipeline/LWRP/Editor/ShaderGUI/LightweightStandardSimpleLightingGUI.cs


StandardSimpleLightingUpgrader.UpdateMaterialKeywords(material);
}
private bool RequiresAlpha()
{
SurfaceType surfaceType = (SurfaceType) surfaceTypeProp.floatValue;
return alphaClip.floatValue > 0.0f || surfaceType == SurfaceType.Transparent;
}
private void DoSurfaceArea()
{
int surfaceTypeValue = (int)surfaceTypeProp.floatValue;

bool alphaClipEnabled = EditorGUILayout.Toggle(Styles.alphaClipLabel, alphaClip.floatValue == 1);
if (EditorGUI.EndChangeCheck())
alphaClip.floatValue = alphaClipEnabled ? 1 : 0;
EditorGUILayout.Space();
if ((SurfaceType)surfaceTypeValue == SurfaceType.Opaque)

m_MaterialEditor.TexturePropertySingleLine(Styles.specularGlossMapLabels[(int)glossinessSourceProp.floatValue], specularGlossMapProp, hasSpecularMap ? null : specularColorProp);
EditorGUI.indentLevel += 2;
GUI.enabled = hasSpecularMap;
int glossinessSource = hasSpecularMap ? (int)glossinessSourceProp.floatValue : (int)GlossinessSource.BaseAlpha;
EditorGUI.BeginChangeCheck();
glossinessSource = EditorGUILayout.Popup(Styles.glossinessSourceLabel, glossinessSource, Styles.glossinessSourceNames);
if (EditorGUI.EndChangeCheck())
glossinessSourceProp.floatValue = glossinessSource;
GUI.enabled = true;
if (RequiresAlpha())
{
GUI.enabled = false;
glossinessSourceProp.floatValue = (float)EditorGUILayout.Popup(Styles.glossinessSourceLabel, (int) GlossinessSource.SpecularAlpha, Styles.glossinessSourceNames);
GUI.enabled = true;
}
else
{
int glossinessSource = (int)glossinessSourceProp.floatValue;
EditorGUI.BeginChangeCheck();
glossinessSource = EditorGUILayout.Popup(Styles.glossinessSourceLabel, glossinessSource, Styles.glossinessSourceNames);
if (EditorGUI.EndChangeCheck())
glossinessSourceProp.floatValue = glossinessSource;
GUI.enabled = true;
}
kMinShininessValue, 1.0f);
kMinShininessValue, 1.0f);
if (EditorGUI.EndChangeCheck())
shininessProp.floatValue = shininess;
EditorGUI.indentLevel -= 2;

98
ScriptableRenderPipeline/LightweightPipeline/LWRP/Editor/ShaderGraph/lightweightPBRExtraPasses.template


Pass
{
Tags{"LightMode" = "ShadowCaster"}
Tags{"LightMode" = "ShadowCaster"}
ZWrite On
ZTest LEqual
Cull ${Culling}
HLSLPROGRAM
// Required to compile gles 2.0 with standard srp library
#pragma prefer_hlslcc gles
#pragma target 2.0
ZWrite On
ZTest LEqual
Cull ${Culling}
//--------------------------------------
// GPU Instancing
#pragma multi_compile_instancing
HLSLPROGRAM
// Required to compile gles 2.0 with standard srp library
#pragma prefer_hlslcc gles
#pragma target 2.0
//--------------------------------------
// GPU Instancing
#pragma multi_compile_instancing
#pragma vertex ShadowPassVertex
#pragma fragment ShadowPassFragment
#pragma vertex ShadowPassVertex
#pragma fragment LitPassFragmentNull
#include "LWRP/ShaderLibrary/InputSurfacePBR.hlsl"
#include "LWRP/ShaderLibrary/LightweightPassShadow.hlsl"
#include "LWRP/ShaderLibrary/LightweightPassShadow.hlsl"
ENDHLSL
ENDHLSL
Tags{"LightMode" = "DepthOnly"}
Tags{"LightMode" = "DepthOnly"}
ZWrite On
ColorMask 0
ZWrite On
ColorMask 0
HLSLPROGRAM
// Required to compile gles 2.0 with standard srp library
#pragma prefer_hlslcc gles
#pragma target 2.0
//--------------------------------------
// GPU Instancing
#pragma multi_compile_instancing
HLSLPROGRAM
// Required to compile gles 2.0 with standard srp library
#pragma prefer_hlslcc gles
#pragma target 2.0
#pragma vertex LitPassVertex
#pragma fragment LitPassFragmentNull
#pragma vertex DepthOnlyVertex
#pragma fragment DepthOnlyFragment
//--------------------------------------
// GPU Instancing
#pragma multi_compile_instancing
#include "LWRP/ShaderLibrary/LightweightPassLit.hlsl"
ENDHLSL
#include "LWRP/ShaderLibrary/InputSurfacePBR.hlsl"
#include "LWRP/ShaderLibrary/LightweightPassDepthOnly.hlsl"
ENDHLSL
Tags{"LightMode" = "Meta"}
Tags{"LightMode" = "Meta"}
Cull Off
Cull Off
HLSLPROGRAM
// Required to compile gles 2.0 with standard srp library
#pragma prefer_hlslcc gles
HLSLPROGRAM
// Required to compile gles 2.0 with standard srp library
#pragma prefer_hlslcc gles
#pragma vertex LightweightVertexMeta
#pragma fragment LightweightFragmentMeta
#pragma vertex LightweightVertexMeta
#pragma fragment LightweightFragmentMeta
#pragma shader_feature _SPECULAR_SETUP
#pragma shader_feature _EMISSION
#pragma shader_feature _METALLICSPECGLOSSMAP
#pragma shader_feature _ _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
#pragma shader_feature EDITOR_VISUALIZATION
#pragma shader_feature _SPECULAR_SETUP
#pragma shader_feature _EMISSION
#pragma shader_feature _METALLICSPECGLOSSMAP
#pragma shader_feature _ _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
#pragma shader_feature EDITOR_VISUALIZATION
#pragma shader_feature _SPECGLOSSMAP
#pragma shader_feature _SPECGLOSSMAP
#include "LWRP/ShaderLibrary/LightweightPassMeta.hlsl"
ENDHLSL
}
#include "LWRP/ShaderLibrary/InputSurfacePBR.hlsl"
#include "LWRP/ShaderLibrary/LightweightPassMetaPBR.hlsl"
ENDHLSL
}

67
ScriptableRenderPipeline/LightweightPipeline/LWRP/Editor/ShaderGraph/lightweightUnlitExtraPasses.template


Pass
{
Tags{"LightMode" = "ShadowCaster"}
Tags{"LightMode" = "ShadowCaster"}
ZWrite On
ZTest LEqual
Cull ${Culling}
ZWrite On
ZTest LEqual
Cull ${Culling}
HLSLPROGRAM
// Required to compile gles 2.0 with standard srp library
#pragma prefer_hlslcc gles
#pragma target 2.0
//--------------------------------------
// GPU Instancing
#pragma multi_compile_instancing
HLSLPROGRAM
// Required to compile gles 2.0 with standard srp library
#pragma prefer_hlslcc gles
#pragma target 2.0
#pragma vertex ShadowPassVertex
#pragma fragment LitPassFragmentNull
//--------------------------------------
// GPU Instancing
#pragma multi_compile_instancing
#pragma vertex ShadowPassVertex
#pragma fragment ShadowPassFragment
#include "LWRP/ShaderLibrary/LightweightPassShadow.hlsl"
ENDHLSL
#include "LWRP/ShaderLibrary/InputSurfaceUnlit.hlsl"
#include "LWRP/ShaderLibrary/LightweightPassShadow.hlsl"
ENDHLSL
Tags{"LightMode" = "DepthOnly"}
Tags{"LightMode" = "DepthOnly"}
ZWrite On
ColorMask 0
ZWrite On
ColorMask 0
HLSLPROGRAM
// Required to compile gles 2.0 with standard srp library
#pragma prefer_hlslcc gles
#pragma target 2.0
HLSLPROGRAM
// Required to compile gles 2.0 with standard srp library
#pragma prefer_hlslcc gles
#pragma target 2.0
//--------------------------------------
// GPU Instancing
#pragma multi_compile_instancing
#pragma vertex DepthOnlyVertex
#pragma fragment DepthOnlyFragment
#pragma vertex LitPassVertex
#pragma fragment LitPassFragmentNull
//--------------------------------------
// GPU Instancing
#pragma multi_compile_instancing
#include "LWRP/ShaderLibrary/LightweightPassLit.hlsl"
ENDHLSL
}
#include "LWRP/ShaderLibrary/InputSurfaceUnlit.hlsl"
#include "LWRP/ShaderLibrary/LightweightPassDepthOnly.hlsl"
ENDHLSL
}

4
ScriptableRenderPipeline/LightweightPipeline/LWRP/Editor/ShaderGraph/lightweightUnlitPass.template


#include "LWRP/ShaderLibrary/Core.hlsl"
#include "LWRP/ShaderLibrary/Lighting.hlsl"
#include "CoreRP/ShaderLibrary/Color.hlsl"
#include "LWRP/ShaderLibrary/InputSurface.hlsl"
#include "LWRP/ShaderLibrary/InputSurfaceUnlit.hlsl"
#include "ShaderGraphLibrary/Functions.hlsl"
${Defines}

float AlphaClipThreshold = 0;
${SurfaceOutputRemap}
#if _AlphaClip
#if _AlphaClip
clip(Alpha - AlphaClipThreshold);
#endif
return half4(Color, Alpha);

2
ScriptableRenderPipeline/LightweightPipeline/LWRP/LightweightConstantBuffer.cs


public static int _AdditionalLightDistanceAttenuation;
public static int _AdditionalLightSpotDir;
public static int _AdditionalLightSpotAttenuation;
public static int _ScaledScreenParams;
}
public static class ShadowConstantBuffer

177
ScriptableRenderPipeline/LightweightPipeline/LWRP/LightweightPipeline.cs


private static readonly int kMaxVertexLights = 4;
private static readonly float kRenderScaleThreshold = 0.05f;
private bool m_IsOffscreenCamera;
private Vector4 kDefaultLightPosition = new Vector4(0.0f, 0.0f, 1.0f, 0.0f);

private int m_ScreenSpaceShadowMapRTID;
private Matrix4x4[] m_ShadowMatrices = new Matrix4x4[kMaxCascades + 1];
private RenderTargetIdentifier m_CurrCameraColorRT;
private RenderTargetIdentifier m_ShadowMapRT;
private RenderTexture m_ShadowMapRT;
private RenderTargetIdentifier m_ScreenSpaceShadowMapRT;
private RenderTargetIdentifier m_ColorRT;
private RenderTargetIdentifier m_CopyColorRT;

private RenderTargetIdentifier m_OpaqueRT;
private float[] m_OpaqueScalerValues = {1.0f, 0.5f, 0.25f, 0.25f};
private float m_RenderScale;
private bool m_IntermediateTextureArray;
private bool m_RequireDepthTexture;

PerCameraBuffer._AdditionalLightDistanceAttenuation = Shader.PropertyToID("_AdditionalLightDistanceAttenuation");
PerCameraBuffer._AdditionalLightSpotDir = Shader.PropertyToID("_AdditionalLightSpotDir");
PerCameraBuffer._AdditionalLightSpotAttenuation = Shader.PropertyToID("_AdditionalLightSpotAttenuation");
PerCameraBuffer._ScaledScreenParams = Shader.PropertyToID("_ScaledScreenParams");
ShadowConstantBuffer._WorldToShadow = Shader.PropertyToID("_WorldToShadow");
ShadowConstantBuffer._ShadowData = Shader.PropertyToID("_ShadowData");

m_SampleOffset = Shader.PropertyToID("_SampleOffset");
m_ShadowMapRT = new RenderTargetIdentifier(m_ShadowMapRTID);
m_ScreenSpaceShadowMapRT = new RenderTargetIdentifier(m_ScreenSpaceShadowMapRTID);
m_ColorRT = new RenderTargetIdentifier(CameraRenderTargetID.color);

Array.Sort(cameras, m_CameraComparer);
foreach (Camera camera in cameras)
{
RenderPipeline.BeginCameraRendering(camera);
m_CurrCamera = camera;
bool sceneViewCamera = m_CurrCamera.cameraType == CameraType.SceneView;
bool stereoEnabled = IsStereoEnabled(m_CurrCamera);
// Disregard variations around kRenderScaleThreshold.
m_RenderScale = (Mathf.Abs(1.0f - m_Asset.RenderScale) < kRenderScaleThreshold) ? 1.0f : m_Asset.RenderScale;
bool sceneViewCamera = camera.cameraType == CameraType.SceneView;
bool stereoEnabled = XRSettings.isDeviceActive && !sceneViewCamera && (camera.stereoTargetEye == StereoTargetEyeMask.Both);
m_CurrCamera = camera;
// XR has it's own scaling mechanism.
m_RenderScale = (m_CurrCamera.cameraType == CameraType.Game && !stereoEnabled) ? m_RenderScale : 1.0f;
var cmd = CommandBufferPool.Get("");
cmd.BeginSample("LightweightPipeline.Render");
context.ExecuteCommandBuffer(cmd);
cmd.Clear();
SetupPerCameraShaderConstants();
RenderPipeline.BeginCameraRendering(m_CurrCamera);
{
cmd.EndSample("LightweightPipeline.Render");
context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);
}
var cmd = CommandBufferPool.Get("");
cullingParameters.shadowDistance = Mathf.Min(m_ShadowSettings.maxShadowDistance,
m_CurrCamera.farClipPlane);

FrameRenderingConfiguration frameRenderingConfiguration;
SetupFrameRenderingConfiguration(out frameRenderingConfiguration, shadows, stereoEnabled, sceneViewCamera);
SetupIntermediateResources(frameRenderingConfiguration, ref context);
SetupIntermediateResources(frameRenderingConfiguration, shadows, ref context);
// SetupCameraProperties does the following:
// Setup Camera RenderTarget and Viewport

if (shadows && m_ShadowSettings.screenSpace)
ShadowCollectPass(visibleLights, ref context, ref lightData, frameRenderingConfiguration);
if (!shadows)
{
var setRT = CommandBufferPool.Get("Generate Small Shadow Buffer");
if (m_ShadowSettings.screenSpace)
setRT.GetTemporaryRT(m_ScreenSpaceShadowMapRTID, 4, 4, 0, FilterMode.Bilinear, m_ShadowSettings.screenspaceShadowmapTextureFormat);
else
setRT.GetTemporaryRT(m_ShadowMapRTID, 4, 4, 0, FilterMode.Bilinear, m_ShadowSettings.shadowmapTextureFormat);
setRT.Blit(Texture2D.whiteTexture, m_ScreenSpaceShadowMapRT);
context.ExecuteCommandBuffer(setRT);
}
ForwardPass(visibleLights, frameRenderingConfiguration, ref context, ref lightData, stereoEnabled);

if (sceneViewCamera)
CopyTexture(cmd, CameraRenderTargetID.depth, BuiltinRenderTextureType.CameraTarget, m_CopyDepthMaterial, true);
#endif
cmd.ReleaseTemporaryRT(m_ShadowMapRTID);
cmd.ReleaseTemporaryRT(m_ScreenSpaceShadowMapRTID);
cmd.ReleaseTemporaryRT(CameraRenderTargetID.depthCopy);
cmd.ReleaseTemporaryRT(CameraRenderTargetID.depth);

cmd.EndSample("LightweightPipeline.Render");
if (m_ShadowMapRT)
{
RenderTexture.ReleaseTemporary(m_ShadowMapRT);
m_ShadowMapRT = null;
}
m_ShadowMapRT = null;
if (m_Asset.AreShadowsEnabled() && lightData.mainLightIndex != -1)
{
VisibleLight mainLight = visibleLights[lightData.mainLightIndex];

CommandBuffer cmd = CommandBufferPool.Get("Collect Shadows");
SetShadowCollectPassKeywords(cmd, visibleLights[lightData.mainLightIndex], ref lightData);
// TODO: Support RenderScale for the SSSM target. Should probably move allocation elsewhere, or at
// least propogate RenderTextureDescriptor generation
if (LightweightUtils.HasFlag(frameRenderingConfiguration, FrameRenderingConfiguration.Stereo))
{
var desc = XRSettings.eyeTextureDesc;
desc.depthBufferBits = 0;
desc.colorFormat = m_ShadowSettings.screenspaceShadowmapTextureFormat;
cmd.GetTemporaryRT(m_ScreenSpaceShadowMapRTID, desc, FilterMode.Bilinear);
}
else
{
cmd.GetTemporaryRT(m_ScreenSpaceShadowMapRTID, m_CurrCamera.pixelWidth, m_CurrCamera.pixelHeight, 0, FilterMode.Bilinear, m_ShadowSettings.screenspaceShadowmapTextureFormat);
}
// Note: The source isn't actually 'used', but there's an engine peculiarity (bug) that
// doesn't like null sources when trying to determine a stereo-ized blit. So for proper

m_IntermediateTextureArray = false;
bool hdrEnabled = m_Asset.SupportsHDR && m_CurrCamera.allowHDR;
bool defaultRenderScale = Mathf.Approximately(GetRenderScale(), 1.0f);
m_Asset.RenderScale < 1.0f || hdrEnabled;
!defaultRenderScale || hdrEnabled;
m_ColorFormat = hdrEnabled ? RenderTextureFormat.DefaultHDR : RenderTextureFormat.Default;
m_RequireCopyColor = false;

else
desc = new RenderTextureDescriptor(m_CurrCamera.pixelWidth, m_CurrCamera.pixelHeight);
float renderScale = (m_CurrCamera.cameraType == CameraType.Game) ? m_Asset.RenderScale : 1.0f;
float renderScale = GetRenderScale();
private void SetupIntermediateResources(FrameRenderingConfiguration renderingConfig, ref ScriptableRenderContext context)
private void SetupIntermediateResources(FrameRenderingConfiguration renderingConfig, bool shadows, ref ScriptableRenderContext context)
{
CommandBuffer cmd = CommandBufferPool.Get("Setup Intermediate Resources");

if (LightweightUtils.HasFlag(renderingConfig, FrameRenderingConfiguration.IntermediateTexture) || m_RequireDepthTexture)
SetupIntermediateRenderTextures(cmd, renderingConfig, msaaSamples);
SetupIntermediateRenderTextures(cmd, renderingConfig, shadows, msaaSamples);
private void SetupIntermediateRenderTextures(CommandBuffer cmd, FrameRenderingConfiguration renderingConfig, int msaaSamples)
private void SetupIntermediateRenderTextures(CommandBuffer cmd, FrameRenderingConfiguration renderingConfig, bool shadows, int msaaSamples)
// TODO: Might be worth caching baseDesc for allocation of other targets (Screen-space Shadow Map?)
RenderTextureDescriptor baseDesc = CreateRTDesc(renderingConfig);
if (m_RequireDepthTexture)

if (LightweightUtils.HasFlag(renderingConfig, FrameRenderingConfiguration.DepthCopy))
cmd.GetTemporaryRT(CameraRenderTargetID.depthCopy, depthRTDesc, FilterMode.Bilinear);
if (shadows && m_ShadowSettings.screenSpace)
{
var screenspaceShadowmapDesc = baseDesc;
screenspaceShadowmapDesc.depthBufferBits = 0;
screenspaceShadowmapDesc.colorFormat = m_ShadowSettings.screenspaceShadowmapTextureFormat;
cmd.GetTemporaryRT(m_ScreenSpaceShadowMapRTID, screenspaceShadowmapDesc, FilterMode.Bilinear);
}
}
var colorRTDesc = baseDesc;

Shader.SetGlobalVector(PerFrameBuffer._SubtractiveShadowColor, CoreUtils.ConvertSRGBToActiveColorSpace(RenderSettings.subtractiveShadowColor));
}
private void SetupPerCameraShaderConstants()
{
float cameraWidth = GetScaledCameraWidth(m_CurrCamera);
float cameraHeight = GetScaledCameraHeight(m_CurrCamera);
Shader.SetGlobalVector(PerCameraBuffer._ScaledScreenParams, new Vector4(cameraWidth, cameraHeight, 1.0f + 1.0f / cameraWidth, 1.0f + 1.0f / cameraHeight));
}
private void SetupShaderLightConstants(CommandBuffer cmd, List<VisibleLight> lights, ref LightData lightData)
{
// Main light has an optimized shader path for main light. This will benefit games that only care about a single light.

float invShadowResolution = 1.0f / m_Asset.ShadowAtlasResolution;
float invHalfShadowResolution = 0.5f * invShadowResolution;
cmd.Clear();
cmd.SetGlobalTexture(m_ShadowMapRTID, m_ShadowMapRT);
cmd.SetGlobalMatrixArray(ShadowConstantBuffer._WorldToShadow, m_ShadowMatrices);
cmd.SetGlobalVector(ShadowConstantBuffer._ShadowData, new Vector4(light.shadowStrength, 0.0f, 0.0f, 0.0f));
cmd.SetGlobalVectorArray(ShadowConstantBuffer._DirShadowSplitSpheres, m_DirectionalShadowSplitDistances);

CoreUtils.SetKeyword(cmd, "_MIXED_LIGHTING_SUBTRACTIVE", m_MixedLightingSetup == MixedLightingSetup.Subtractive);
CoreUtils.SetKeyword(cmd, "_VERTEX_LIGHTS", vertexLightsCount > 0);
CoreUtils.SetKeyword(cmd, "SOFTPARTICLES_ON", m_RequireDepthTexture && m_Asset.RequireSoftParticles);
bool linearFogModeEnabled = false;
bool exponentialFogModeEnabled = false;
if (RenderSettings.fog)
{
if (RenderSettings.fogMode == FogMode.Linear)
linearFogModeEnabled = true;
else
exponentialFogModeEnabled = true;
}
CoreUtils.SetKeyword(cmd, "FOG_LINEAR", linearFogModeEnabled);
CoreUtils.SetKeyword(cmd, "FOG_EXP2", exponentialFogModeEnabled);
}
private void SetShadowCollectPassKeywords(CommandBuffer cmd, VisibleLight shadowLight, ref LightData lightData)

bool success = false;
var cmd = CommandBufferPool.Get("Prepare Shadowmap");
cmd.GetTemporaryRT(m_ShadowMapRTID, m_ShadowSettings.shadowAtlasWidth,
m_ShadowSettings.shadowAtlasHeight, kShadowBufferBits, FilterMode.Bilinear, m_ShadowSettings.shadowmapTextureFormat);
RenderTextureDescriptor shadowmapDescriptor = new RenderTextureDescriptor(m_ShadowSettings.shadowAtlasWidth,
m_ShadowSettings.shadowAtlasHeight, m_ShadowSettings.shadowmapTextureFormat, kShadowBufferBits);
shadowmapDescriptor.shadowSamplingMode = ShadowSamplingMode.CompareDepths;
m_ShadowMapRT = RenderTexture.GetTemporary(shadowmapDescriptor);
m_ShadowMapRT.filterMode = FilterMode.Bilinear;
m_ShadowMapRT.wrapMode = TextureWrapMode.Clamp;
// LightweightPipeline.SetRenderTarget is meant to be used with camera targets, not shadowmaps
CoreUtils.SetRenderTarget(cmd, m_ShadowMapRT, ClearFlag.Depth, CoreUtils.ConvertSRGBToActiveColorSpace(m_CurrCamera.backgroundColor));

{
cmd.SetViewport(new Rect(m_ShadowSlices[cascadeIndex].atlasX, m_ShadowSlices[cascadeIndex].atlasY,
m_ShadowSlices[cascadeIndex].shadowResolution, m_ShadowSlices[cascadeIndex].shadowResolution));
cmd.EnableScissorRect(new Rect(m_ShadowSlices[cascadeIndex].atlasX + 4, m_ShadowSlices[cascadeIndex].atlasY + 4,
m_ShadowSlices[cascadeIndex].shadowResolution - 8, m_ShadowSlices[cascadeIndex].shadowResolution - 8));
cmd.Clear();
cmd.DisableScissorRect();
context.ExecuteCommandBuffer(cmd);
cmd.Clear();
}

depthRT = m_DepthRT;
}
if (ForceClear())
ClearFlag clearFlag = ClearFlag.None;
CameraClearFlags cameraClearFlags = m_CurrCamera.clearFlags;
if (cameraClearFlags != CameraClearFlags.Nothing)
SetRenderTarget(cmd, colorRT, depthRT, ClearFlag.All);
clearFlag |= ClearFlag.Depth;
if (cameraClearFlags == CameraClearFlags.Color || cameraClearFlags == CameraClearFlags.Skybox)
clearFlag |= ClearFlag.Color;
else
{
ClearFlag clearFlag = ClearFlag.None;
CameraClearFlags cameraClearFlags = m_CurrCamera.clearFlags;
if (cameraClearFlags != CameraClearFlags.Nothing)
{
clearFlag |= ClearFlag.Depth;
if (cameraClearFlags == CameraClearFlags.Color || cameraClearFlags == CameraClearFlags.Skybox)
clearFlag |= ClearFlag.Color;
}
SetRenderTarget(cmd, colorRT, depthRT, clearFlag);
}
SetRenderTarget(cmd, colorRT, depthRT, clearFlag);
// If rendering to an intermediate RT we resolve viewport on blit due to offset not being supported
// while rendering to a RT.

}
}
RendererConfiguration GetRendererSettings(ref LightData lightData)
private bool IsStereoEnabled(Camera camera)
{
bool isSceneViewCamera = camera.cameraType == CameraType.SceneView;
return XRSettings.isDeviceActive && !isSceneViewCamera && (camera.stereoTargetEye == StereoTargetEyeMask.Both);
}
private float GetRenderScale()
{
return m_RenderScale;
}
private float GetScaledCameraWidth(Camera camera)
{
return (float) camera.pixelWidth * GetRenderScale();
}
private float GetScaledCameraHeight(Camera camera)
{
return (float) camera.pixelHeight * GetRenderScale();
}
private RendererConfiguration GetRendererSettings(ref LightData lightData)
{
RendererConfiguration settings = RendererConfiguration.PerObjectReflectionProbes | RendererConfiguration.PerObjectLightmaps | RendererConfiguration.PerObjectLightProbe;
if (lightData.totalAdditionalLightsCount > 0)

private int GetLightUnsortedIndex(int index)
{
return (index < m_SortedLightIndexMap.Count) ? m_SortedLightIndexMap[index] : index;
}
private bool ForceClear()
{
// Clear RenderTarget to avoid tile initialization on mobile GPUs
// https://community.arm.com/graphics/b/blog/posts/mali-performance-2-how-to-correctly-handle-framebuffers
return (Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer);
}
private void Blit(CommandBuffer cmd, FrameRenderingConfiguration renderingConfig, RenderTargetIdentifier sourceRT, RenderTargetIdentifier destRT, Material material = null)

22
ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/Core.hlsl


#endif
#endif
#ifndef BUMP_SCALE_NOT_SUPPORTED
#define BUMP_SCALE_NOT_SUPPORTED !SHADER_HINT_NICE_QUALITY
#endif
///////////////////////////////////////////////////////////////////////////////
#ifdef _NORMALMAP
#define OUTPUT_NORMAL(IN, OUT) OutputTangentToWorld(IN.tangent, IN.normal, OUT.tangent.xyz, OUT.binormal.xyz, OUT.normal.xyz)

#define UNITY_Z_0_FAR_FROM_CLIPSPACE(coord) (coord)
#endif
float4 GetScaledScreenParams()
{
return _ScaledScreenParams;
}
void AlphaDiscard(half alpha, half cutoff, half offset = 0.0h)
{
#ifdef _ALPHATEST_ON

void OutputTangentToWorld(half4 vertexTangent, half3 vertexNormal, out half3 tangentWS, out half3 binormalWS, out half3 normalWS)
{
// mikkts space compliant. only normalize when extracting normal at frag.
tangentWS = normalize(mul((half3x3)UNITY_MATRIX_M, vertexTangent.xyz));
tangentWS = TransformObjectToWorldDir(vertexTangent.xyz);
binormalWS = cross(normalWS, tangentWS) * sign;
}

// factor = (end-z)/(end-start) = z * (-1/(end-start)) + (end/(end-start))
float fogFactor = saturate(clipZ_01 * unity_FogParams.z + unity_FogParams.w);
return half(fogFactor);
#elif defined(FOG_EXP2)
#elif defined(FOG_EXP) || defined(FOG_EXP2)
// factor = exp(-(density*z)^2)
// -density * z computed at vertex
return half(unity_FogParams.x * clipZ_01);

void ApplyFogColor(inout half3 color, half3 fogColor, half fogFactor)
{
#if defined (FOG_LINEAR) || defined(FOG_EXP2)
#if defined(FOG_EXP2)
#if defined(FOG_LINEAR) || defined(FOG_EXP) || defined(FOG_EXP2)
#if defined(FOG_EXP)
// factor = exp(-density*z)
// fogFactor = density*z compute at vertex
fogFactor = saturate(exp2(-fogFactor));
#elif defined(FOG_EXP2)
// factor = exp(-(density*z)^2)
// fogFactor = density*z compute at vertex
fogFactor = saturate(exp2(-fogFactor*fogFactor));

2
ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/Input.hlsl


half4 _AdditionalLightDistanceAttenuation[MAX_VISIBLE_LIGHTS];
half4 _AdditionalLightSpotDir[MAX_VISIBLE_LIGHTS];
half4 _AdditionalLightSpotAttenuation[MAX_VISIBLE_LIGHTS];
float4 _ScaledScreenParams;
CBUFFER_END
#define UNITY_MATRIX_M unity_ObjectToWorld

53
ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/InputBuiltin.hlsl


float4x4 unity_ObjectToWorld;
float4x4 unity_WorldToObject;
float4 unity_LODFade; // x is the fade value ranging within [0,1]. y is x quantized into 16 levels
real4 unity_LODFade; // x is the fade value ranging within [0,1]. y is x quantized into 16 levels
float4 unity_DynamicLightmapST;
float4 unity_SHAr;
float4 unity_SHAg;
float4 unity_SHAb;
float4 unity_SHBr;
float4 unity_SHBg;
float4 unity_SHBb;
float4 unity_SHC;
// x = Disabled(0)/Enabled(1)
// y = Computation are done in global space(0) or local space(1)
// z = Texel size on U texture coordinate
float4 unity_ProbeVolumeParams;
float4x4 unity_ProbeVolumeWorldToObject;
float3 unity_ProbeVolumeSizeInv;
float3 unity_ProbeVolumeMin;
real4 unity_SHAr;
real4 unity_SHAg;
real4 unity_SHAb;
real4 unity_SHBr;
real4 unity_SHBg;
real4 unity_SHBb;
real4 unity_SHC;
float4 unity_ProbesOcclusion;
real4 unity_ProbesOcclusion;
half4 unity_SpecCube0_HDR;
real4 unity_SpecCube0_HDR;
half4 unity_Lightmap_HDR;
real4 unity_Lightmap_HDR;
half4 unity_LightIndicesOffsetAndCount;
half4 unity_4LightIndices0;
half4 unity_4LightIndices1;
real4 unity_LightIndicesOffsetAndCount;
real4 unity_4LightIndices0;
real4 unity_4LightIndices1;
CBUFFER_END

#if defined(USING_STEREO_MATRICES) && defined(UNITY_STEREO_MULTIVIEW_ENABLED)
CBUFFER_START(UnityStereoEyeIndices)
float4 unity_StereoEyeIndices[2];
real4 unity_StereoEyeIndices[2];
CBUFFER_END
#endif

// ----------------------------------------------------------------------------
CBUFFER_START(UnityPerFrame)
float4 glstate_lightmodel_ambient;
float4 unity_AmbientSky;
float4 unity_AmbientEquator;
float4 unity_AmbientGround;
float4 unity_IndirectSpecColor;
real4 glstate_lightmodel_ambient;
real4 unity_AmbientSky;
real4 unity_AmbientEquator;
real4 unity_AmbientGround;
real4 unity_IndirectSpecColor;
half4 unity_FogColor;
real4 unity_FogColor;
#if !defined(USING_STEREO_MATRICES)
float4x4 glstate_matrix_projection;

int unity_StereoEyeIndex;
#endif
float4 unity_ShadowColor;
real4 unity_ShadowColor;
CBUFFER_END
// ----------------------------------------------------------------------------

19
ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/Lighting.hlsl


half roughness;
half roughness2;
half grazingTerm;
// We save some light invariant BRDF terms so we don't have to recompute
// them in the light loop. Take a look at DirectBRDF function for detailed explaination.
half normalizationTerm; // roughness * 4.0 + 2.0
half roughness2MinusOne; // roughness² - 1.0
};
half ReflectivitySpecular(half3 specular)

outBRDFData.roughness = PerceptualRoughnessToRoughness(outBRDFData.perceptualRoughness);
outBRDFData.roughness2 = outBRDFData.roughness * outBRDFData.roughness;
outBRDFData.normalizationTerm = outBRDFData.roughness * 4.0h + 2.0h;
outBRDFData.roughness2MinusOne = outBRDFData.roughness2 - 1.0h;
#ifdef _ALPHAPREMULTIPLY_ON
outBRDFData.diffuse *= alpha;
alpha = alpha * oneMinusReflectivity + reflectivity;

half LoH = saturate(dot(lightDirectionWS, halfDir));
// GGX Distribution multiplied by combined approximation of Visibility and Fresnel
// BRDFspec = (D * V * F) / 4.0
// D = roughness² / ( NoH² * (roughness² - 1) + 1 )²
// V * F = 1.0 / ( LoH² * (roughness + 0.5) )
half d = NoH * NoH * (brdfData.roughness2 - 1.h) + 1.00001h;
// Final BRDFspec = roughness² / ( NoH² * (roughness² - 1) + 1 )² * (LoH² * (roughness + 0.5) * 4.0)
// We further optimize a few light invariant terms
// brdfData.normalizationTerm = (roughness + 0.5) * 4.0 rewritten as roughness * 4.0 + 2.0 to a fit a MAD.
half d = NoH * NoH * brdfData.roughness2MinusOne + 1.00001h;
half specularTerm = brdfData.roughness2 / ((d * d) * max(0.1h, LoH2) * (brdfData.roughness + 0.5h) * 4);
half specularTerm = brdfData.roughness2 / ((d * d) * max(0.1h, LoH2) * brdfData.normalizationTerm);
// on mobiles (where half actually means something) denominator have risk of overflow
// clamp below was added specifically to "fix" that, but dx compiler (we convert bytecode to metal/gles)

314
ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/LightweightPassLit.hlsl


#ifndef LIGHTWEIGHT_PASS_LIT_INCLUDED
#define LIGHTWEIGHT_PASS_LIT_INCLUDED
#include "LWRP/ShaderLibrary/InputSurface.hlsl"
#include "LWRP/ShaderLibrary/Lighting.hlsl"
struct LightweightVertexInput
{
float4 vertex : POSITION;
float3 normal : NORMAL;
float4 tangent : TANGENT;
float2 texcoord : TEXCOORD0;
float2 lightmapUV : TEXCOORD1;
UNITY_VERTEX_INPUT_INSTANCE_ID
};
struct LightweightVertexOutput
{
float2 uv : TEXCOORD0;
DECLARE_LIGHTMAP_OR_SH(lightmapUV, vertexSH, 1);
float4 posWSShininess : TEXCOORD2; // xyz: posWS, w: Shininess * 128
#ifdef _NORMALMAP
half4 normal : TEXCOORD3; // xyz: normal, w: viewDir.x
half4 tangent : TEXCOORD4; // xyz: tangent, w: viewDir.y
half4 binormal : TEXCOORD5; // xyz: binormal, w: viewDir.z
#else
half3 normal : TEXCOORD3;
half3 viewDir : TEXCOORD4;
#endif
half4 fogFactorAndVertexLight : TEXCOORD6; // x: fogFactor, yzw: vertex light
float4 shadowCoord : TEXCOORD7;
float4 clipPos : SV_POSITION;
UNITY_VERTEX_INPUT_INSTANCE_ID
UNITY_VERTEX_OUTPUT_STEREO
};
void InitializeInputData(LightweightVertexOutput IN, half3 normalTS, out InputData inputData)
{
inputData.positionWS = IN.posWSShininess.xyz;
#ifdef _NORMALMAP
half3 viewDir = half3(IN.normal.w, IN.tangent.w, IN.binormal.w);
inputData.normalWS = TangentToWorldNormal(normalTS, IN.tangent.xyz, IN.binormal.xyz, IN.normal.xyz);
#else
half3 viewDir = IN.viewDir;
inputData.normalWS = FragmentNormalWS(IN.normal);
#endif
inputData.viewDirectionWS = FragmentViewDirWS(viewDir);
inputData.shadowCoord = IN.shadowCoord;
inputData.fogCoord = IN.fogFactorAndVertexLight.x;
inputData.vertexLighting = IN.fogFactorAndVertexLight.yzw;
inputData.bakedGI = SAMPLE_GI(IN.lightmapUV, IN.vertexSH, inputData.normalWS);
}
///////////////////////////////////////////////////////////////////////////////
// Vertex and Fragment functions //
///////////////////////////////////////////////////////////////////////////////
// Vertex: Used for Standard and StandardSimpleLighting shaders
LightweightVertexOutput LitPassVertex(LightweightVertexInput v)
{
LightweightVertexOutput o = (LightweightVertexOutput)0;
UNITY_SETUP_INSTANCE_ID(v);
UNITY_TRANSFER_INSTANCE_ID(v, o);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
o.uv = TRANSFORM_TEX(v.texcoord, _MainTex);
o.posWSShininess.xyz = TransformObjectToWorld(v.vertex.xyz);
o.posWSShininess.w = _Shininess * 128.0;
o.clipPos = TransformWorldToHClip(o.posWSShininess.xyz);
half3 viewDir = VertexViewDirWS(GetCameraPositionWS() - o.posWSShininess.xyz);
#ifdef _NORMALMAP
o.normal.w = viewDir.x;
o.tangent.w = viewDir.y;
o.binormal.w = viewDir.z;
#else
o.viewDir = viewDir;
#endif
// initializes o.normal and if _NORMALMAP also o.tangent and o.binormal
OUTPUT_NORMAL(v, o);
// We either sample GI from lightmap or SH.
// Lightmap UV and vertex SH coefficients use the same interpolator ("float2 lightmapUV" for lightmap or "half3 vertexSH" for SH)
// see DECLARE_LIGHTMAP_OR_SH macro.
// The following funcions initialize the correct variable with correct data
OUTPUT_LIGHTMAP_UV(v.lightmapUV, unity_LightmapST, o.lightmapUV);
OUTPUT_SH(o.normal.xyz, o.vertexSH);
half3 vertexLight = VertexLighting(o.posWSShininess.xyz, o.normal.xyz);
half fogFactor = ComputeFogFactor(o.clipPos.z);
o.fogFactorAndVertexLight = half4(fogFactor, vertexLight);
#if SHADOWS_SCREEN
o.shadowCoord = ComputeShadowCoord(o.clipPos);
#else
o.shadowCoord = TransformWorldToShadowCoord(o.posWSShininess.xyz);
#endif
return o;
}
// Used for Standard shader
half4 LitPassFragment(LightweightVertexOutput IN) : SV_Target
{
UNITY_SETUP_INSTANCE_ID(IN);
SurfaceData surfaceData;
InitializeStandardLitSurfaceData(IN.uv, surfaceData);
InputData inputData;
InitializeInputData(IN, surfaceData.normalTS, inputData);
half4 color = LightweightFragmentPBR(inputData, surfaceData.albedo, surfaceData.metallic, surfaceData.specular, surfaceData.smoothness, surfaceData.occlusion, surfaceData.emission, surfaceData.alpha);
ApplyFog(color.rgb, inputData.fogCoord);
return color;
}
// Used for Standard shader
half4 LitPassFragmentNull(LightweightVertexOutput IN) : SV_Target
{
LitPassFragment(IN);
return 0;
}
// Used for StandardSimpleLighting shader
half4 LitPassFragmentSimple(LightweightVertexOutput IN) : SV_Target
{
UNITY_SETUP_INSTANCE_ID(IN);
float2 uv = IN.uv;
half4 diffuseAlpha = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, uv);
half3 diffuse = diffuseAlpha.rgb * _Color.rgb;
half alpha = diffuseAlpha.a * _Color.a;
AlphaDiscard(alpha, _Cutoff);
#ifdef _ALPHAPREMULTIPLY_ON
diffuse *= alpha;
#endif
#ifdef _NORMALMAP
half3 normalTS = Normal(uv);
#else
half3 normalTS = half3(0, 0, 1);
#endif
half3 emission = Emission(uv);
half4 specularGloss = SpecularGloss(uv, diffuseAlpha.a);
half shininess = IN.posWSShininess.w;
InputData inputData;
InitializeInputData(IN, normalTS, inputData);
return LightweightFragmentBlinnPhong(inputData, diffuse, specularGloss, shininess, emission, alpha);
};
// Used for StandardSimpleLighting shader
half4 LitPassFragmentSimpleNull(LightweightVertexOutput IN) : SV_Target
{
half4 result = LitPassFragmentSimple(IN);
return result.a;
}
#endif
#ifndef LIGHTWEIGHT_PASS_LIT_INCLUDED
#define LIGHTWEIGHT_PASS_LIT_INCLUDED
#include "LWRP/ShaderLibrary/Lighting.hlsl"
struct LightweightVertexInput
{
float4 vertex : POSITION;
float3 normal : NORMAL;
float4 tangent : TANGENT;
float2 texcoord : TEXCOORD0;
float2 lightmapUV : TEXCOORD1;
UNITY_VERTEX_INPUT_INSTANCE_ID
};
struct LightweightVertexOutput
{
float2 uv : TEXCOORD0;
DECLARE_LIGHTMAP_OR_SH(lightmapUV, vertexSH, 1);
float3 posWS : TEXCOORD2;
#ifdef _NORMALMAP
half4 normal : TEXCOORD3; // xyz: normal, w: viewDir.x
half4 tangent : TEXCOORD4; // xyz: tangent, w: viewDir.y
half4 binormal : TEXCOORD5; // xyz: binormal, w: viewDir.z
#else
half3 normal : TEXCOORD3;
half3 viewDir : TEXCOORD4;
#endif
half4 fogFactorAndVertexLight : TEXCOORD6; // x: fogFactor, yzw: vertex light
#ifdef _SHADOWS_ENABLED
float4 shadowCoord : TEXCOORD7;
#endif
float4 clipPos : SV_POSITION;
UNITY_VERTEX_INPUT_INSTANCE_ID
UNITY_VERTEX_OUTPUT_STEREO
};
void InitializeInputData(LightweightVertexOutput IN, half3 normalTS, out InputData inputData)
{
inputData = (InputData)0;
inputData.positionWS = IN.posWS;
#ifdef _NORMALMAP
half3 viewDir = half3(IN.normal.w, IN.tangent.w, IN.binormal.w);
inputData.normalWS = TangentToWorldNormal(normalTS, IN.tangent.xyz, IN.binormal.xyz, IN.normal.xyz);
#else
half3 viewDir = IN.viewDir;
inputData.normalWS = FragmentNormalWS(IN.normal);
#endif
inputData.viewDirectionWS = FragmentViewDirWS(viewDir);
#ifdef _SHADOWS_ENABLED
inputData.shadowCoord = IN.shadowCoord;
#else
inputData.shadowCoord = float4(0, 0, 0, 0);
#endif
inputData.fogCoord = IN.fogFactorAndVertexLight.x;
inputData.vertexLighting = IN.fogFactorAndVertexLight.yzw;
inputData.bakedGI = SAMPLE_GI(IN.lightmapUV, IN.vertexSH, inputData.normalWS);
}
///////////////////////////////////////////////////////////////////////////////
// Vertex and Fragment functions //
///////////////////////////////////////////////////////////////////////////////
// Used in Standard (Physically Based) shader
LightweightVertexOutput LitPassVertex(LightweightVertexInput v)
{
LightweightVertexOutput o = (LightweightVertexOutput)0;
UNITY_SETUP_INSTANCE_ID(v);
UNITY_TRANSFER_INSTANCE_ID(v, o);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
o.uv = TRANSFORM_TEX(v.texcoord, _MainTex);
float3 posWS = TransformObjectToWorld(v.vertex.xyz);
o.clipPos = TransformWorldToHClip(posWS);
half3 viewDir = VertexViewDirWS(GetCameraPositionWS() - posWS);
#ifdef _NORMALMAP
o.normal.w = viewDir.x;
o.tangent.w = viewDir.y;
o.binormal.w = viewDir.z;
#else
o.viewDir = viewDir;
#endif
// initializes o.normal and if _NORMALMAP also o.tangent and o.binormal
OUTPUT_NORMAL(v, o);
// We either sample GI from lightmap or SH.
// Lightmap UV and vertex SH coefficients use the same interpolator ("float2 lightmapUV" for lightmap or "half3 vertexSH" for SH)
// see DECLARE_LIGHTMAP_OR_SH macro.
// The following funcions initialize the correct variable with correct data
OUTPUT_LIGHTMAP_UV(v.lightmapUV, unity_LightmapST, o.lightmapUV);
OUTPUT_SH(o.normal.xyz, o.vertexSH);
half3 vertexLight = VertexLighting(posWS, o.normal.xyz);
half fogFactor = ComputeFogFactor(o.clipPos.z);
o.fogFactorAndVertexLight = half4(fogFactor, vertexLight);
#ifdef _SHADOWS_ENABLED
#if SHADOWS_SCREEN
o.shadowCoord = ComputeShadowCoord(o.clipPos);
#else
o.shadowCoord = TransformWorldToShadowCoord(posWS);
#endif
#endif
o.posWS = posWS;
return o;
}
// Used in Standard (Physically Based) shader
half4 LitPassFragment(LightweightVertexOutput IN) : SV_Target
{
UNITY_SETUP_INSTANCE_ID(IN);
SurfaceData surfaceData;
InitializeStandardLitSurfaceData(IN.uv, surfaceData);
InputData inputData;
InitializeInputData(IN, surfaceData.normalTS, inputData);
half4 color = LightweightFragmentPBR(inputData, surfaceData.albedo, surfaceData.metallic, surfaceData.specular, surfaceData.smoothness, surfaceData.occlusion, surfaceData.emission, surfaceData.alpha);
ApplyFog(color.rgb, inputData.fogCoord);
return color;
}
#endif

45
ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/LightweightPassShadow.hlsl


#ifndef LIGHTWEIGHT_PASS_SHADOW_INCLUDED
#define LIGHTWEIGHT_PASS_SHADOW_INCLUDED
#include "LWRP/ShaderLibrary/LightweightPassLit.hlsl"
#include "LWRP/ShaderLibrary/Core.hlsl"
LightweightVertexOutput ShadowPassVertex(LightweightVertexInput v)
struct VertexInput
{
float4 position : POSITION;
float3 normal : NORMAL;
float2 texcoord : TEXCOORD0;
UNITY_VERTEX_INPUT_INSTANCE_ID
};
struct VertexOutput
{
float2 uv : TEXCOORD0;
float4 clipPos : SV_POSITION;
};
float4 GetShadowPositionHClip(VertexInput v)
LightweightVertexOutput o = LitPassVertex(v);
float3 positionWS = TransformObjectToWorld(v.position.xyz);
float3 normalWS = TransformObjectToWorldDir(v.normal);
float invNdotL = 1.0 - saturate(dot(_LightDirection, o.normal));
float invNdotL = 1.0 - saturate(dot(_LightDirection, normalWS));
o.posWSShininess.xyz = o.normal * scale.xxx + o.posWSShininess.xyz;
float4 clipPos = TransformWorldToHClip(o.posWSShininess.xyz);
positionWS = normalWS * scale.xxx + positionWS;
float4 clipPos = TransformWorldToHClip(positionWS);
// _ShadowBias.x sign depens on if platform has reversed z buffer
clipPos.z += _ShadowBias.x;

clipPos.z = max(clipPos.z, clipPos.w * UNITY_NEAR_CLIP_VALUE);
#endif
o.clipPos = clipPos;
return clipPos;
}
VertexOutput ShadowPassVertex(VertexInput v)
{
VertexOutput o;
UNITY_SETUP_INSTANCE_ID(v);
o.uv = TRANSFORM_TEX(v.texcoord, _MainTex);
o.clipPos = GetShadowPositionHClip(v);
half4 ShadowPassFragment(VertexOutput IN) : SV_TARGET
{
Alpha(SampleAlbedoAlpha(IN.uv, TEXTURE2D_PARAM(_MainTex, sampler_MainTex)).a, _Color, _Cutoff);
return 0;
}
#endif

84
ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/Particles.hlsl


#ifndef LIGHTWEIGHT_PARTICLES_INCLUDED
#define LIGHTWEIGHT_PARTICLES_INCLUDED
#include "InputSurface.hlsl"
#include "InputSurfaceCommon.hlsl"
TEXTURE2D(_CameraDepthTexture);
SAMPLER(sampler_CameraDepthTexture);
CBUFFER_START(UnityPerMaterial)
float4 _MainTex_ST;
half4 _Color;
half4 _EmissionColor;
half4 _SpecColor;
#if defined (_COLORADDSUBDIFF_ON)
half4 _ColorAddSubDiff;
#endif
half _Cutoff;
half _Shininess;
half _Metallic;
half _Glossiness;
half _BumpScale;
CBUFFER_END
TEXTURE2D(_CameraDepthTexture); SAMPLER(sampler_CameraDepthTexture);
TEXTURE2D(_SpecGlossMap); SAMPLER(sampler_SpecGlossMap);
#define SOFT_PARTICLE_NEAR_FADE _SoftParticleFadeParams.x
#define SOFT_PARTICLE_INV_FADE_DISTANCE _SoftParticleFadeParams.y

#if defined (_COLORADDSUBDIFF_ON)
half4 _ColorAddSubDiff;
#endif
// Color function
#if defined(UNITY_PARTICLE_INSTANCING_ENABLED)

return color;
}
half3 NormalTS(VertexOutputLit IN)
half3 SampleNormalTS(VertexOutputLit IN, TEXTURE2D_ARGS(bumpMap, sampler_bumpMap), half scale = 1.0h)
half4 n = readTexture(TEXTURE2D_PARAM(bumpMap, sampler_bumpMap), IN);
return UnpackNormal(readTexture(_BumpMap, sampler_BumpMap, IN));
return UnpackNormal(n);
return UnpackNormalScale(readTexture(_BumpMap, sampler_BumpMap, IN), _BumpScale);
return UnpackNormalScale(n, scale);
#endif
#else
return half3(0.0h, 0.0h, 1.0h);

half3 Emission(VertexOutputLit IN)
half3 SampleEmission(VertexOutputLit IN, half3 emissionColor, TEXTURE2D_ARGS(emissionMap, sampler_emissionMap))
return readTexture(_EmissionMap, sampler_EmissionMap, IN).rgb * _EmissionColor.rgb;
return readTexture(TEXTURE2D_PARAM(emissionMap, sampler_emissionMap), IN).rgb * emissionColor.rgb;
half4 Albedo(VertexOutputLit IN)
half4 SampleAlbedo(VertexOutputLit IN, TEXTURE2D_ARGS(albedoMap, sampler_albedoMap))
half4 albedo = readTexture(TEXTURE2D_PARAM(_MainTex, sampler_MainTex), IN) * IN.color;
half4 albedo = readTexture(TEXTURE2D_PARAM(albedoMap, sampler_albedoMap), IN) * IN.color;
// No distortion Support
fragColorMode(IN);

return albedo;
}
half4 SpecularGloss(VertexOutputLit IN, half alpha)
half4 SampleSpecularGloss(VertexOutputLit IN, half alpha, half4 specColor, TEXTURE2D_ARGS(specGlossMap, sampler_specGlossMap))
specularGloss = readTexture(_SpecGlossMap, sampler_SpecGlossMap, IN);
specularGloss = readTexture(TEXTURE2D_PARAM(specGlossMap, sampler_specGlossMap), IN);
specularGloss = _SpecColor;
specularGloss = specColor;
#endif
#ifdef _GLOSSINESS_FROM_BASE_ALPHA

}
half AlphaBlendAndTest(half alpha)
half AlphaBlendAndTest(half alpha, half cutoff)
{
#if defined(_ALPHABLEND_ON) || defined(_ALPHAPREMULTIPLY_ON) || defined(_ALPHAOVERLAY_ON)
half result = alpha;

AlphaDiscard(result, _Cutoff, 0.0001h);
AlphaDiscard(result, cutoff, 0.0001h);
return result;
}

#endif
}
void InitializeSurfaceData(VertexOutputLit IN, out SurfaceData surfaceData)
{
half4 albedo = Albedo(IN);
#if defined(_METALLICGLOSSMAP)
half2 metallicGloss = readTexture(_MetallicGlossMap, sampler_MetallicGlossMap, IN).ra * half2(1.0, _Glossiness);
#else
half2 metallicGloss = half2(_Metallic, _Glossiness);
#endif
half3 normalTS = NormalTS(IN);
half3 emission = Emission(IN);
surfaceData.albedo = albedo.rbg;
surfaceData.specular = half3(0.0h, 0.0h, 0.0h);
surfaceData.normalTS = normalTS;
surfaceData.emission = emission;
surfaceData.metallic = metallicGloss.r;
surfaceData.smoothness = metallicGloss.g;
surfaceData.occlusion = 1.0;
surfaceData.alpha = AlphaBlendAndTest(albedo.a);
surfaceData.albedo = AlphaModulate(surfaceData.albedo, surfaceData.alpha);
}
void InitializeInputData(VertexOutputLit IN, half3 normalTS, out InputData input)
{
input.positionWS = IN.posWS.xyz;

input.viewDirectionWS = FragmentViewDirWS(IN.viewDirShininess.xyz);
input.shadowCoord = float4(0, 0, 0, 0);
input.fogCoord = IN.posWS.w;
input.fogCoord = (half)IN.posWS.w;
#endif // LIGHTWEIGHT_PARTICLES_INCLUDED

68
ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/Shadows.hlsl


#define BEYOND_SHADOW_FAR(shadowCoord) shadowCoord.z >= UNITY_RAW_FAR_CLIP_VALUE
#endif
#define OUTSIDE_SHADOW_BOUNDS(shadowCoord) shadowCoord.x <= 0 || shadowCoord.x >= 1 || shadowCoord.y <= 0 || shadowCoord.y >= 1 || BEYOND_SHADOW_FAR(shadowCoord)
half GetShadowStrength()
{
return _ShadowData.x;

attenuation = dot(attenuation4, 0.25);
#else
#ifdef _SHADOWS_CASCADE //Assume screen space shadows when cascades enabled
real fetchesWeights[16];
real2 fetchesUV[16];
float fetchesWeights[16];
float2 fetchesUV[16];
attenuation = fetchesWeights[0] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, real3(fetchesUV[0].xy, shadowCoord.z));
attenuation += fetchesWeights[1] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, real3(fetchesUV[1].xy, shadowCoord.z));
attenuation += fetchesWeights[2] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, real3(fetchesUV[2].xy, shadowCoord.z));
attenuation += fetchesWeights[3] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, real3(fetchesUV[3].xy, shadowCoord.z));
attenuation += fetchesWeights[4] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, real3(fetchesUV[4].xy, shadowCoord.z));
attenuation += fetchesWeights[5] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, real3(fetchesUV[5].xy, shadowCoord.z));
attenuation += fetchesWeights[6] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, real3(fetchesUV[6].xy, shadowCoord.z));
attenuation += fetchesWeights[7] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, real3(fetchesUV[7].xy, shadowCoord.z));
attenuation += fetchesWeights[8] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, real3(fetchesUV[8].xy, shadowCoord.z));
attenuation += fetchesWeights[9] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, real3(fetchesUV[9].xy, shadowCoord.z));
attenuation += fetchesWeights[10] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, real3(fetchesUV[10].xy, shadowCoord.z));
attenuation += fetchesWeights[11] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, real3(fetchesUV[11].xy, shadowCoord.z));
attenuation += fetchesWeights[12] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, real3(fetchesUV[12].xy, shadowCoord.z));
attenuation += fetchesWeights[13] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, real3(fetchesUV[13].xy, shadowCoord.z));
attenuation += fetchesWeights[14] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, real3(fetchesUV[14].xy, shadowCoord.z));
attenuation += fetchesWeights[15] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, real3(fetchesUV[15].xy, shadowCoord.z));
attenuation = fetchesWeights[0] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, float3(fetchesUV[0].xy, shadowCoord.z));
attenuation += fetchesWeights[1] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, float3(fetchesUV[1].xy, shadowCoord.z));
attenuation += fetchesWeights[2] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, float3(fetchesUV[2].xy, shadowCoord.z));
attenuation += fetchesWeights[3] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, float3(fetchesUV[3].xy, shadowCoord.z));
attenuation += fetchesWeights[4] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, float3(fetchesUV[4].xy, shadowCoord.z));
attenuation += fetchesWeights[5] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, float3(fetchesUV[5].xy, shadowCoord.z));
attenuation += fetchesWeights[6] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, float3(fetchesUV[6].xy, shadowCoord.z));
attenuation += fetchesWeights[7] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, float3(fetchesUV[7].xy, shadowCoord.z));
attenuation += fetchesWeights[8] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, float3(fetchesUV[8].xy, shadowCoord.z));
attenuation += fetchesWeights[9] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, float3(fetchesUV[9].xy, shadowCoord.z));
attenuation += fetchesWeights[10] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, float3(fetchesUV[10].xy, shadowCoord.z));
attenuation += fetchesWeights[11] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, float3(fetchesUV[11].xy, shadowCoord.z));
attenuation += fetchesWeights[12] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, float3(fetchesUV[12].xy, shadowCoord.z));
attenuation += fetchesWeights[13] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, float3(fetchesUV[13].xy, shadowCoord.z));
attenuation += fetchesWeights[14] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, float3(fetchesUV[14].xy, shadowCoord.z));
attenuation += fetchesWeights[15] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, float3(fetchesUV[15].xy, shadowCoord.z));
real fetchesWeights[9];
real2 fetchesUV[9];
float fetchesWeights[9];
float2 fetchesUV[9];
attenuation = fetchesWeights[0] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, real3(fetchesUV[0].xy, shadowCoord.z));
attenuation += fetchesWeights[1] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, real3(fetchesUV[1].xy, shadowCoord.z));
attenuation += fetchesWeights[2] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, real3(fetchesUV[2].xy, shadowCoord.z));
attenuation += fetchesWeights[3] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, real3(fetchesUV[3].xy, shadowCoord.z));
attenuation += fetchesWeights[4] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, real3(fetchesUV[4].xy, shadowCoord.z));
attenuation += fetchesWeights[5] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, real3(fetchesUV[5].xy, shadowCoord.z));
attenuation += fetchesWeights[6] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, real3(fetchesUV[6].xy, shadowCoord.z));
attenuation += fetchesWeights[7] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, real3(fetchesUV[7].xy, shadowCoord.z));
attenuation += fetchesWeights[8] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, real3(fetchesUV[8].xy, shadowCoord.z));
attenuation = fetchesWeights[0] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, float3(fetchesUV[0].xy, shadowCoord.z));
attenuation += fetchesWeights[1] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, float3(fetchesUV[1].xy, shadowCoord.z));
attenuation += fetchesWeights[2] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, float3(fetchesUV[2].xy, shadowCoord.z));
attenuation += fetchesWeights[3] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, float3(fetchesUV[3].xy, shadowCoord.z));
attenuation += fetchesWeights[4] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, float3(fetchesUV[4].xy, shadowCoord.z));
attenuation += fetchesWeights[5] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, float3(fetchesUV[5].xy, shadowCoord.z));
attenuation += fetchesWeights[6] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, float3(fetchesUV[6].xy, shadowCoord.z));
attenuation += fetchesWeights[7] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, float3(fetchesUV[7].xy, shadowCoord.z));
attenuation += fetchesWeights[8] * SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, float3(fetchesUV[8].xy, shadowCoord.z));
#endif
#endif
#else

#endif
// Shadow coords that fall out of the light frustum volume must always return attenuation 1.0
return (OUTSIDE_SHADOW_BOUNDS(shadowCoord)) ? 1.0 : attenuation;
return BEYOND_SHADOW_FAR(shadowCoord) ? 1.0 : attenuation;
}
inline half ComputeCascadeIndex(float3 positionWS)

half RealtimeShadowAttenuation(float4 shadowCoord)
{
#if NO_SHADOWS
#ifndef _SHADOWS_ENABLED
return 1.0h;
#endif
#if defined(NO_SHADOWS)
return 1.0h;
#elif SHADOWS_SCREEN
return SampleScreenSpaceShadowMap(shadowCoord);

41
ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/LightweightPassMetaCommon.hlsl


#ifndef LIGHTWEIGHT_PASS_META_INCLUDED
#define LIGHTWEIGHT_PASS_META_INCLUDED
#include "LWRP/ShaderLibrary/InputSurface.hlsl"
#include "LWRP/ShaderLibrary/Lighting.hlsl"
CBUFFER_START(UnityMetaPass)

float2 uv : TEXCOORD0;
};
float4 MetaVertexPosition(float4 vertex, float2 uv1, float2 uv2, float4 lightmapST, float4 dynlightmapST)
float4 MetaVertexPosition(float4 vertex, float2 uv1, float2 uv2, float4 lightmapST)
{
if (unity_MetaVertexControl.x)
{

vertex.z = vertex.z > 0 ? 1.0e-4f : 0.0f;
}
if (unity_MetaVertexControl.y)
{
vertex.xy = uv2 * dynlightmapST.xy + dynlightmapST.zw;
// OpenGL right now needs to actually use incoming vertex position,
// so use it in a very dummy way
vertex.z = vertex.z > 0 ? 1.0e-4f : 0.0f;
vertex.z = vertex.z > 0 ? REAL_MIN : 0.0f;
}
return TransformWorldToHClip(vertex.xyz); // Need to transfer from world to clip compared to legacy
}

MetaVertexOuput LightweightVertexMeta(MetaVertexInput v)
{
MetaVertexOuput o;
o.pos = MetaVertexPosition(v.vertex, v.uv1.xy, v.uv2.xy, unity_LightmapST, unity_DynamicLightmapST);
o.pos = MetaVertexPosition(v.vertex, v.uv1.xy, v.uv2.xy, unity_LightmapST);
}
half4 LightweightFragmentMeta(MetaVertexOuput i) : SV_Target
{
SurfaceData surfaceData;
InitializeStandardLitSurfaceData(i.uv, surfaceData);
BRDFData brdfData;
InitializeBRDFData(surfaceData.albedo, surfaceData.metallic, surfaceData.specular, surfaceData.smoothness, surfaceData.alpha, brdfData);
MetaInput o;
o.Albedo = brdfData.diffuse + brdfData.specular * brdfData.roughness * 0.5;
o.SpecularColor = surfaceData.specular;
o.Emission = surfaceData.emission;
return MetaFragment(o);
}
half4 LightweightFragmentMetaSimple(MetaVertexOuput i) : SV_Target
{
float2 uv = i.uv;
MetaInput o;
o.Albedo = _Color.rgb * SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, uv).rgb;
o.SpecularColor = SpecularGloss(uv, 1.0).xyz;
o.Emission = Emission(uv);
return MetaFragment(o);
}
#endif

11
ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightScreenSpaceShadows.shader


{
SubShader
{
Tags{ "RenderPipeline" = "LightweightPipeline" }
Tags{ "RenderPipeline" = "LightweightPipeline" "IgnoreProjector" = "True"}
//Keep compiler quiet about Shadows.hlsl.
//Keep compiler quiet about Shadows.hlsl.
#include "CoreRP/ShaderLibrary/Common.hlsl"
#include "CoreRP/ShaderLibrary/EntityLighting.hlsl"
#include "CoreRP/ShaderLibrary/ImageBasedLighting.hlsl"

SCREENSPACE_TEXTURE(_CameraDepthTexture);
#if defined(UNITY_STEREO_INSTANCING_ENABLED) || defined(UNITY_STEREO_MULTIVIEW_ENABLED)
TEXTURE2D_ARRAY(_CameraDepthTexture);
#else
TEXTURE2D(_CameraDepthTexture);
#endif // defined(UNITY_STEREO_INSTANCING_ENABLED) || defined(UNITY_STEREO_MULTIVIEW_ENABLED)
SAMPLER(sampler_CameraDepthTexture);
struct VertexInput

53
ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightStandard.shader


// Lightweight Pipeline tag is required. If Lightweight pipeline is not set in the graphics settings
// this Subshader will fail. One can add a subshader below or fallback to Standard built-in to make this
// material work with both Lightweight Pipeline and Builtin Unity Pipeline
Tags{"RenderType" = "Opaque" "RenderPipeline" = "LightweightPipeline"}
Tags{"RenderType" = "Opaque" "RenderPipeline" = "LightweightPipeline" "IgnoreProjector" = "True"}
LOD 300
// ------------------------------------------------------------------

// Required to compile gles 2.0 with standard SRP library
// All shaders must be compiled with HLSLcc and currently only gles is not using HLSLcc by default
#pragma prefer_hlslcc gles
#pragma exclude_renderers d3d11_9x
#pragma shader_feature _ALPHATEST_ON
#pragma shader_feature _ALPHATEST_ON
#pragma shader_feature _ALPHAPREMULTIPLY_ON
#pragma shader_feature _EMISSION
#pragma shader_feature _METALLICSPECGLOSSMAP

#pragma multi_compile _ _ADDITIONAL_LIGHTS
#pragma multi_compile _ _VERTEX_LIGHTS
#pragma multi_compile _ _MIXED_LIGHTING_SUBTRACTIVE
#pragma multi_compile _ FOG_LINEAR FOG_EXP2
#pragma multi_compile _ _SHADOWS_ENABLED
#pragma multi_compile_fog
//--------------------------------------
// GPU Instancing

#pragma fragment LitPassFragment
#include "LWRP/ShaderLibrary/InputSurfacePBR.hlsl"
#include "LWRP/ShaderLibrary/LightweightPassLit.hlsl"
ENDHLSL
}

HLSLPROGRAM
// Required to compile gles 2.0 with standard srp library
#pragma prefer_hlslcc gles
#pragma exclude_renderers d3d11_9x
#pragma shader_feature _NORMALMAP
#pragma shader_feature _ALPHATEST_ON
#pragma shader_feature _ALPHAPREMULTIPLY_ON
#pragma shader_feature _EMISSION
#pragma shader_feature _METALLICSPECGLOSSMAP
#pragma shader_feature _ALPHATEST_ON
#pragma shader_feature _OCCLUSIONMAP
#pragma shader_feature _SPECULARHIGHLIGHTS_OFF
#pragma shader_feature _GLOSSYREFLECTIONS_OFF
#pragma shader_feature _SPECULAR_SETUP
//--------------------------------------
// GPU Instancing

#pragma fragment LitPassFragmentNull
#pragma fragment ShadowPassFragment
#include "LWRP/ShaderLibrary/InputSurfacePBR.hlsl"
#include "LWRP/ShaderLibrary/LightweightPassShadow.hlsl"
ENDHLSL
}

HLSLPROGRAM
// Required to compile gles 2.0 with standard srp library
#pragma prefer_hlslcc gles
#pragma exclude_renderers d3d11_9x
#pragma vertex DepthOnlyVertex
#pragma fragment DepthOnlyFragment
#pragma shader_feature _NORMALMAP
#pragma shader_feature _ALPHATEST_ON
#pragma shader_feature _ALPHAPREMULTIPLY_ON
#pragma shader_feature _EMISSION
#pragma shader_feature _METALLICSPECGLOSSMAP
#pragma shader_feature _ALPHATEST_ON
#pragma shader_feature _OCCLUSIONMAP
#pragma shader_feature _SPECULARHIGHLIGHTS_OFF
#pragma shader_feature _GLOSSYREFLECTIONS_OFF
#pragma shader_feature _SPECULAR_SETUP
#pragma vertex LitPassVertex
#pragma fragment LitPassFragmentNull
#include "LWRP/ShaderLibrary/LightweightPassLit.hlsl"
#include "LWRP/ShaderLibrary/InputSurfacePBR.hlsl"
#include "LWRP/ShaderLibrary/LightweightPassDepthOnly.hlsl"
ENDHLSL
}

#pragma shader_feature _SPECGLOSSMAP
#include "LWRP/ShaderLibrary/LightweightPassMeta.hlsl"
#include "LWRP/ShaderLibrary/InputSurfacePBR.hlsl"
#include "LWRP/ShaderLibrary/LightweightPassMetaPBR.hlsl"
ENDHLSL
}

4
ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightStandardParticles.shader


HLSLPROGRAM
// Required to compile gles 2.0 with standard srp library
#pragma prefer_hlslcc gles
#pragma exclude_renderers d3d11_9x
#pragma vertex ParticlesLitVertex
#pragma fragment ParticlesLitFragment
#pragma multi_compile __ SOFTPARTICLES_ON

#define NO_SHADOWS 1
#include "LWRP/ShaderLibrary/Particles.hlsl"
#include "LWRP/ShaderLibrary/ParticlesPBR.hlsl"
#include "LWRP/ShaderLibrary/Lighting.hlsl"
VertexOutputLit ParticlesLitVertex(appdata_particles v)

o.posWS.w = ComputeFogFactor(o.clipPos.z);
o.clipPos = TransformWorldToHClip(o.posWS.xyz);
o.viewDirShininess.xyz = VertexViewDirWS(GetCameraPositionWS() - o.posWS.xyz);
o.viewDirShininess.w = 0.0;
vertTexcoord(v, o);
vertFading(o, o.posWS, o.clipPos);
return o;

13
ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightStandardParticlesSimpleLighting.shader


#pragma vertex ParticlesLitVertex
#pragma fragment ParticlesLitFragment
#pragma multi_compile __ SOFTPARTICLES_ON
#pragma exclude_renderers d3d11_9x
#pragma target 2.0
#pragma shader_feature _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON _ALPHAMODULATE_ON

#define BUMP_SCALE_NOT_SUPPORTED 1
#define NO_SHADOWS 1
#include "LWRP/ShaderLibrary/Particles.hlsl"
#include "LWRP/ShaderLibrary/Lighting.hlsl"

half4 ParticlesLitFragment(VertexOutputLit IN) : SV_Target
{
half4 albedo = Albedo(IN);
half alpha = AlphaBlendAndTest(albedo.a);
half4 albedo = SampleAlbedo(IN, TEXTURE2D_PARAM(_MainTex, sampler_MainTex));
half alpha = AlphaBlendAndTest(albedo.a, _Cutoff);
half3 normalTS = NormalTS(IN);
half3 emission = Emission(IN);
half4 specularGloss = SpecularGloss(IN, albedo.a);
half3 normalTS = SampleNormalTS(IN, TEXTURE2D_PARAM(_BumpMap, sampler_BumpMap));
half3 emission = SampleEmission(IN, _EmissionColor.rgb, TEXTURE2D_PARAM(_EmissionMap, sampler_EmissionMap));
half4 specularGloss = SampleSpecularGloss(IN, albedo.a, _SpecColor, TEXTURE2D_PARAM(_SpecGlossMap, sampler_SpecGlossMap));
half shininess = IN.viewDirShininess.w;
InputData inputData;

8
ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightStandardParticlesUnlit.shader


HLSLPROGRAM
// Required to compile gles 2.0 with standard srp library
#pragma prefer_hlslcc gles
#pragma exclude_renderers d3d11_9x
#pragma multi_compile __ SOFTPARTICLES_ON
#pragma multi_compile_fog
#pragma target 2.0

#pragma fragment fragParticleUnlit
#include "LWRP/ShaderLibrary/Particles.hlsl"
#include "LWRP/ShaderLibrary/Core.hlsl"
VertexOutputLit vertParticleUnlit(appdata_particles v)
{

half4 fragParticleUnlit(VertexOutputLit IN) : SV_Target
{
half4 albedo = Albedo(IN);
half alpha = AlphaBlendAndTest(albedo.a);
half3 emission = Emission(IN);
half4 albedo = SampleAlbedo(IN, TEXTURE2D_PARAM(_MainTex, sampler_MainTex));
half alpha = AlphaBlendAndTest(albedo.a, _Cutoff);
half3 emission = SampleEmission(IN, _EmissionColor.rgb, TEXTURE2D_PARAM(_EmissionMap, sampler_EmissionMap));
half3 diffuse = AlphaModulate(albedo.rgb, alpha);
half3 result = diffuse + emission;

58
ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightStandardSimpleLighting.shader


SubShader
{
Tags { "RenderType" = "Opaque" "RenderPipeline" = "LightweightPipeline" }
Tags { "RenderType" = "Opaque" "RenderPipeline" = "LightweightPipeline" "IgnoreProjector" = "True"}
LOD 300
Pass

HLSLPROGRAM
// Required to compile gles 2.0 with standard srp library
#pragma prefer_hlslcc gles
#pragma exclude_renderers d3d11_9x
#pragma shader_feature _ALPHATEST_ON
#pragma shader_feature _ALPHATEST_ON
#pragma shader_feature _ _GLOSSINESS_FROM_BASE_ALPHA
#pragma shader_feature _GLOSSINESS_FROM_BASE_ALPHA
#pragma shader_feature _NORMALMAP
#pragma shader_feature _EMISSION

#pragma multi_compile _ _VERTEX_LIGHTS
#pragma multi_compile _ _MIXED_LIGHTING_SUBTRACTIVE
#pragma multi_compile _ FOG_LINEAR FOG_EXP2
#pragma multi_compile _ _SHADOWS_ENABLED
#pragma multi_compile_fog
#pragma vertex LitPassVertex
#pragma vertex LitPassVertexSimple
#include "LWRP/ShaderLibrary/LightweightPassLit.hlsl"
#include "LWRP/ShaderLibrary/InputSurfaceSimple.hlsl"
#include "LWRP/ShaderLibrary/LightweightPassLitSimple.hlsl"
Tags{"Lightmode" = "ShadowCaster"}
Tags{"LightMode" = "ShadowCaster"}
ZWrite On
ZTest LEqual

// Required to compile gles 2.0 with standard srp library
#pragma prefer_hlslcc gles
#pragma exclude_renderers d3d11_9x
#pragma shader_feature _ALPHATEST_ON
#pragma shader_feature _ALPHAPREMULTIPLY_ON
#pragma shader_feature _ _SPECGLOSSMAP _SPECULAR_COLOR
#pragma shader_feature _ _GLOSSINESS_FROM_BASE_ALPHA
#pragma shader_feature _NORMALMAP
#pragma shader_feature _EMISSION
#pragma shader_feature _ALPHATEST_ON
#pragma shader_feature _GLOSSINESS_FROM_BASE_ALPHA
//--------------------------------------
// GPU Instancing

#pragma fragment LitPassFragmentSimpleNull
#pragma fragment ShadowPassFragment
#define BUMP_SCALE_NOT_SUPPORTED 1
#include "LWRP/ShaderLibrary/InputSurfaceSimple.hlsl"
#include "LWRP/ShaderLibrary/LightweightPassShadow.hlsl"
ENDHLSL
}

Tags{"Lightmode" = "DepthOnly"}
Tags{"LightMode" = "DepthOnly"}
ZWrite On
ColorMask 0

#pragma prefer_hlslcc gles
#pragma exclude_renderers d3d11_9x
#pragma vertex DepthOnlyVertex
#pragma fragment DepthOnlyFragment
#pragma shader_feature _ALPHATEST_ON
#pragma shader_feature _ALPHAPREMULTIPLY_ON
#pragma shader_feature _ _SPECGLOSSMAP _SPECULAR_COLOR
#pragma shader_feature _ _GLOSSINESS_FROM_BASE_ALPHA
#pragma shader_feature _NORMALMAP
#pragma shader_feature _EMISSION
#pragma shader_feature _ALPHATEST_ON
#pragma shader_feature _GLOSSINESS_FROM_BASE_ALPHA
#pragma vertex LitPassVertex
#pragma fragment LitPassFragmentSimpleNull
#define BUMP_SCALE_NOT_SUPPORTED 1
#include "LWRP/ShaderLibrary/LightweightPassLit.hlsl"
#include "LWRP/ShaderLibrary/InputSurfaceSimple.hlsl"
#include "LWRP/ShaderLibrary/LightweightPassDepthOnly.hlsl"
ENDHLSL
}

#pragma shader_feature _EMISSION
#pragma shader_feature _SPECGLOSSMAP
#include "LWRP/ShaderLibrary/LightweightPassMeta.hlsl"
#include "LWRP/ShaderLibrary/InputSurfaceSimple.hlsl"
#include "LWRP/ShaderLibrary/LightweightPassMetaSimple.hlsl"
ENDHLSL
}
}

9
ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightStandardTerrain.shader


SubShader
{
Tags { "Queue" = "Geometry-100" "RenderType" = "Opaque" "RenderPipeline" = "LightweightPipeline" }
Tags { "Queue" = "Geometry-100" "RenderType" = "Opaque" "RenderPipeline" = "LightweightPipeline" "IgnoreProjector" = "True"}
Pass
{

#pragma prefer_hlslcc gles
#pragma exclude_renderers d3d11_9x
#pragma target 3.0
#pragma vertex SplatmapVert

#pragma multi_compile _ _ADDITIONAL_LIGHTS
#pragma multi_compile _ _VERTEX_LIGHTS
#pragma multi_compile _ _MIXED_LIGHTING_SUBTRACTIVE
#pragma multi_compile _ FOG_LINEAR FOG_EXP2
#pragma multi_compile _ _SHADOWS_ENABLED
#pragma multi_compile_fog
#pragma multi_compile __ _TERRAIN_NORMAL_MAP

HLSLPROGRAM
// Required to compile gles 2.0 with standard srp library
#pragma prefer_hlslcc gles
#pragma exclude_renderers d3d11_9x
#pragma target 2.0
#pragma vertex vert
#pragma fragment frag

41
ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightStandardUnlit.shader


}
SubShader
{
Tags { "RenderType" = "Opaque" "IgnoreProjectors" = "True" "RenderPipeline" = "LightweightPipeline" }
Tags { "RenderType" = "Opaque" "IgnoreProjectors" = "True" "RenderPipeline" = "LightweightPipeline" "IgnoreProjector" = "True"}
LOD 100
Blend [_SrcBlend][_DstBlend]

HLSLPROGRAM
// Required to compile gles 2.0 with standard srp library
#pragma prefer_hlslcc gles
#pragma exclude_renderers d3d11_9x
#pragma vertex vert
#pragma fragment frag
#pragma multi_compile_fog

// Lighting include is needed because of GI
#include "LWRP/ShaderLibrary/Lighting.hlsl"
#include "LWRP/ShaderLibrary/InputSurface.hlsl"
#include "LWRP/ShaderLibrary/InputSurfaceUnlit.hlsl"
struct VertexInput
{

UNITY_SETUP_INSTANCE_ID(v);
UNITY_TRANSFER_INSTANCE_ID(v, o);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
o.vertex = TransformObjectToHClip(v.vertex.xyz);
o.uv0AndFogCoord.xy = TRANSFORM_TEX(v.uv, _MainTex);
o.uv0AndFogCoord.z = ComputeFogFactor(o.vertex.z);

half2 uv = IN.uv0AndFogCoord.xy;
half4 texColor = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, uv);
half3 color = texColor.rgb * _Color.rgb;
half alpha = texColor.a * _Color.a;
half alpha = texColor.a * _Color.a;
AlphaDiscard(alpha, _Cutoff);
#if _SAMPLE_GI

color *= SampleGI(IN.lightmapOrVertexSH, normalWS);
#endif
ApplyFog(color, IN.uv0AndFogCoord.z);
ENDHLSL
}
Pass
{
Tags{"LightMode" = "DepthOnly"}
ZWrite On
ColorMask 0
HLSLPROGRAM
// Required to compile gles 2.0 with standard srp library
#pragma prefer_hlslcc gles
#pragma exclude_renderers d3d11_9x
#pragma target 2.0
#pragma vertex DepthOnlyVertex
#pragma fragment DepthOnlyFragment
// -------------------------------------
// Material Keywords
#pragma shader_feature _ALPHATEST_ON
//--------------------------------------
// GPU Instancing
#pragma multi_compile_instancing
#include "LWRP/ShaderLibrary/InputSurfaceUnlit.hlsl"
#include "LWRP/ShaderLibrary/LightweightPassDepthOnly.hlsl"
ENDHLSL
}
}

84
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/SkySettings/HDRP_Black_Sky_Shadow50.asset


m_EditorClassIdentifier:
active: 1
rotation:
m_OverrideState: 0
m_OverrideState: 1
m_OverrideState: 0
m_OverrideState: 1
m_OverrideState: 0
m_OverrideState: 1
m_OverrideState: 0
m_OverrideState: 1
m_OverrideState: 0
m_OverrideState: 1
skyHDRI:
hdriSky:
m_OverrideState: 1
m_Value: {fileID: 8900000, guid: 75f8ba90acb52d14d9ead53b2a9e4190, type: 3}
--- !u!114 &114436604167779146

m_OverrideState: 0
m_Value: 500
min: 0
cascadeShadowSplitCount:
m_OverrideState: 0
m_Value: 4
min: 1
max: 4
cascadeShadowSplit0:
m_OverrideState: 0
m_Value: 0.05
min: 0
max: 1
cascadeShadowSplit1:
m_OverrideState: 0
m_Value: 0.15
min: 0
max: 1
cascadeShadowSplit2:
m_OverrideState: 0
m_Value: 0.3
min: 0
max: 1
cascadeShadowBorder0:
m_OverrideState: 0
m_Value: 0
min: 0
cascadeShadowBorder1:
m_OverrideState: 0
m_Value: 0
min: 0
cascadeShadowBorder2:
m_OverrideState: 0
m_Value: 0
min: 0
cascadeShadowBorder3:
m_OverrideState: 0
m_Value: 0
min: 0
--- !u!114 &114660440207994068
MonoBehaviour:
m_ObjectHideFlags: 3

m_OverrideState: 1
m_Value: 50
min: 0
cascadeShadowSplitCount:
m_OverrideState: 0
m_Value: 4
min: 1
max: 4
cascadeShadowSplit0:
m_OverrideState: 0
m_Value: 0.05
min: 0
max: 1
cascadeShadowSplit1:
m_OverrideState: 0
m_Value: 0.15
min: 0
max: 1
cascadeShadowSplit2:
m_OverrideState: 0
m_Value: 0.3
min: 0
max: 1
cascadeShadowBorder0:
m_OverrideState: 0
m_Value: 0
min: 0
cascadeShadowBorder1:
m_OverrideState: 0
m_Value: 0
min: 0
cascadeShadowBorder2:
m_OverrideState: 0
m_Value: 0
min: 0
cascadeShadowBorder3:
m_OverrideState: 0
m_Value: 0
min: 0

85
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/SkySettings/HDRP_Black_Sky_Shadow500.asset


m_EditorClassIdentifier:
active: 1
rotation:
m_OverrideState: 0
m_OverrideState: 1
m_OverrideState: 0
m_OverrideState: 1
m_OverrideState: 0
m_OverrideState: 1
m_OverrideState: 0
m_OverrideState: 1
m_OverrideState: 0
m_OverrideState: 1
useForBaking: 1
skyHDRI:
hdriSky:
m_OverrideState: 1
m_Value: {fileID: 8900000, guid: 75f8ba90acb52d14d9ead53b2a9e4190, type: 3}
--- !u!114 &114436604167779146

m_OverrideState: 0
m_Value: 500
min: 0
cascadeShadowSplitCount:
m_OverrideState: 0
m_Value: 4
min: 1
max: 4
cascadeShadowSplit0:
m_OverrideState: 0
m_Value: 0.05
min: 0
max: 1
cascadeShadowSplit1:
m_OverrideState: 0
m_Value: 0.15
min: 0
max: 1
cascadeShadowSplit2:
m_OverrideState: 0
m_Value: 0.3
min: 0
max: 1
cascadeShadowBorder0:
m_OverrideState: 0
m_Value: 0
min: 0
cascadeShadowBorder1:
m_OverrideState: 0
m_Value: 0
min: 0
cascadeShadowBorder2:
m_OverrideState: 0
m_Value: 0
min: 0
cascadeShadowBorder3:
m_OverrideState: 0
m_Value: 0
min: 0
--- !u!114 &114660440207994068
MonoBehaviour:
m_ObjectHideFlags: 3

m_OverrideState: 1
m_Value: 500
min: 0
cascadeShadowSplitCount:
m_OverrideState: 0
m_Value: 4
min: 1
max: 4
cascadeShadowSplit0:
m_OverrideState: 0
m_Value: 0.05
min: 0
max: 1
cascadeShadowSplit1:
m_OverrideState: 0
m_Value: 0.15
min: 0
max: 1
cascadeShadowSplit2:
m_OverrideState: 0
m_Value: 0.3
min: 0
max: 1
cascadeShadowBorder0:
m_OverrideState: 0
m_Value: 0
min: 0
cascadeShadowBorder1:
m_OverrideState: 0
m_Value: 0
min: 0
cascadeShadowBorder2:
m_OverrideState: 0
m_Value: 0
min: 0
cascadeShadowBorder3:
m_OverrideState: 0
m_Value: 0
min: 0

2
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/SkySettings/HDRP_Default_Sky.asset


active: 1
rotation:
m_OverrideState: 1
m_Value: 160
m_Value: 200
min: 0
max: 360
exposure:

2
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/SkySettings/HDRP_Default_Sky_2.asset


active: 1
rotation:
m_OverrideState: 1
m_Value: 160
m_Value: 200
min: 0
max: 360
exposure:

2
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/SkySettings/HDRP_Default_Sky_3.asset


active: 1
rotation:
m_OverrideState: 1
m_Value: 160
m_Value: 200
min: 0
max: 360
exposure:

2
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/SkySettings/HDRP_Default_Sky_4.asset


active: 1
rotation:
m_OverrideState: 1
m_Value: 160
m_Value: 200
min: 0
max: 360
exposure:

19
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/1xxx_Materials/1301_SubSurfaceScattering.unity


m_ReflectionIntensity: 1
m_CustomReflection: {fileID: 0}
m_Sun: {fileID: 0}
m_IndirectSpecularColor: {r: 0.03660911, g: 0.038467497, b: 0.04252398, a: 1}
m_IndirectSpecularColor: {r: 0, g: 0, b: 0, a: 1}
m_UseRadianceAmbientProbe: 0
--- !u!157 &3
LightmapSettings:

objectReference: {fileID: 0}
- target: {fileID: 4295600896743834, guid: b186ef7597e8a464c9a4af7b87825a5f, type: 2}
propertyPath: m_LocalScale.z
value: 1
objectReference: {fileID: 0}
- target: {fileID: 114663566010530930, guid: b186ef7597e8a464c9a4af7b87825a5f,
type: 2}
propertyPath: m_Enabled
value: 1
objectReference: {fileID: 0}
m_RemovedComponents: []

shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05
- 0.05
- 0.05
- 0.15
- 0.3
- 0.2
- 0.2
- 0.2
- 0.2
- 0
- 0
- 0
- 0
shadowAlgorithm: 0
shadowVariant: 3
shadowPrecision: 0

2
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/1xxx_Materials/1301_SubSurfaceScattering/GroundLeaf_Transmission-Regular.mat


m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MaskMap:
m_Texture: {fileID: 2800000, guid: b24f69ff4ace9194fb0d9eee4f5cf1a4, type: 3}
m_Texture: {fileID: 2800000, guid: bb365ecc385707e4393520c6e7893cc8, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _NormalMap:

6
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/2xxx_Lighting/2002_Dynamic_Mix.unity


m_ReflectionIntensity: 1
m_CustomReflection: {fileID: 0}
m_Sun: {fileID: 0}
m_IndirectSpecularColor: {r: 0.3661957, g: 0.3847838, b: 0.4253666, a: 1}
m_IndirectSpecularColor: {r: 0.36615336, g: 0.38474482, b: 0.42534754, a: 1}
m_UseRadianceAmbientProbe: 0
--- !u!157 &3
LightmapSettings:

shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
viewBiasMin: 0.5
viewBiasMin: 2.25
viewBiasScale: 1
viewBiasScale: 8
normalBiasMin: 0.2
normalBiasMax: 4
normalBiasScale: 1

328
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/2xxx_Lighting/2101_GI_Metapass.unity
文件差异内容过多而无法显示
查看文件

21
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/2xxx_Lighting/2102_GI_Emission.unity


m_AmbientSkyColor: {r: 0.212, g: 0.227, b: 0.259, a: 1}
m_AmbientEquatorColor: {r: 0.114, g: 0.125, b: 0.133, a: 1}
m_AmbientGroundColor: {r: 0.047, g: 0.043, b: 0.035, a: 1}
m_AmbientIntensity: 1
m_AmbientIntensity: 0
m_AmbientMode: 0
m_SubtractiveShadowColor: {r: 0.42, g: 0.478, b: 0.627, a: 1}
m_SkyboxMaterial: {fileID: 0}

m_DefaultReflectionMode: 0
m_DefaultReflectionResolution: 128
m_ReflectionBounces: 1
m_ReflectionIntensity: 1
m_ReflectionIntensity: 0
m_IndirectSpecularColor: {r: 0, g: 0, b: 0, a: 1}
m_IndirectSpecularColor: {r: 0, g: 0, b: 0, a: 0}
m_UseRadianceAmbientProbe: 0
--- !u!157 &3
LightmapSettings:

- target: {fileID: 4209882255362944, guid: c07ace9ab142ca9469fa377877c2f1e7, type: 2}
propertyPath: m_LocalPosition.z
value: -7.36
objectReference: {fileID: 0}
- target: {fileID: 114482499083377642, guid: c07ace9ab142ca9469fa377877c2f1e7,
type: 2}
propertyPath: backgroundColorHDR.r
value: 0.18447503
objectReference: {fileID: 0}
- target: {fileID: 114482499083377642, guid: c07ace9ab142ca9469fa377877c2f1e7,
type: 2}
propertyPath: backgroundColorHDR.g
value: 0.18447503
objectReference: {fileID: 0}
- target: {fileID: 114482499083377642, guid: c07ace9ab142ca9469fa377877c2f1e7,
type: 2}
propertyPath: backgroundColorHDR.b
value: 0.18447503
objectReference: {fileID: 0}
m_RemovedComponents: []
m_ParentPrefab: {fileID: 100100000, guid: c07ace9ab142ca9469fa377877c2f1e7, type: 2}

48
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/2xxx_Lighting/2201_ReflectionProbes_Priority.unity


m_EditorClassIdentifier:
m_Version: 1
influenceShape: 0
dimmer: 1
multiplier: 1
weight: 1
influenceSphereRadius: 3
sphereReprojectionVolumeRadius: 1
useSeparateProjectionVolume: 0

m_EditorClassIdentifier:
m_Version: 1
influenceShape: 0
dimmer: 1
multiplier: 1
weight: 1
influenceSphereRadius: 3
sphereReprojectionVolumeRadius: 1
useSeparateProjectionVolume: 0

m_EditorClassIdentifier:
m_Version: 1
influenceShape: 0
dimmer: 1
multiplier: 1
weight: 1
influenceSphereRadius: 3
sphereReprojectionVolumeRadius: 1
useSeparateProjectionVolume: 0

m_EditorClassIdentifier:
m_Version: 1
influenceShape: 0
dimmer: 1
multiplier: 1
weight: 1
influenceSphereRadius: 3
sphereReprojectionVolumeRadius: 1
useSeparateProjectionVolume: 0

m_EditorClassIdentifier:
m_Version: 1
influenceShape: 0
dimmer: 1
multiplier: 1
weight: 1
influenceSphereRadius: 3
sphereReprojectionVolumeRadius: 1
useSeparateProjectionVolume: 0

m_EditorClassIdentifier:
m_Version: 1
influenceShape: 0
dimmer: 1
multiplier: 1
weight: 1
influenceSphereRadius: 3
sphereReprojectionVolumeRadius: 1
useSeparateProjectionVolume: 0

m_EditorClassIdentifier:
m_Version: 1
influenceShape: 0
dimmer: 1
multiplier: 1
weight: 1
influenceSphereRadius: 3
sphereReprojectionVolumeRadius: 1
useSeparateProjectionVolume: 0

m_EditorClassIdentifier:
m_Version: 1
influenceShape: 0
dimmer: 1
multiplier: 1
weight: 1
influenceSphereRadius: 3
sphereReprojectionVolumeRadius: 1
useSeparateProjectionVolume: 0

m_EditorClassIdentifier:
m_Version: 1
influenceShape: 0
dimmer: 1
multiplier: 1
weight: 1
influenceSphereRadius: 3
sphereReprojectionVolumeRadius: 1
useSeparateProjectionVolume: 0

m_EditorClassIdentifier:
m_Version: 1
influenceShape: 0
dimmer: 1
multiplier: 1
weight: 1
influenceSphereRadius: 3
sphereReprojectionVolumeRadius: 1
useSeparateProjectionVolume: 0

propertyPath: m_LocalEulerAnglesHint.x
value: 60.000004
objectReference: {fileID: 0}
- target: {fileID: 114482499083377642, guid: c07ace9ab142ca9469fa377877c2f1e7,
type: 2}
propertyPath: backgroundColorHDR.r
value: 0.05448028
objectReference: {fileID: 0}
- target: {fileID: 114482499083377642, guid: c07ace9ab142ca9469fa377877c2f1e7,
type: 2}
propertyPath: backgroundColorHDR.g
value: 0.05448028
objectReference: {fileID: 0}
- target: {fileID: 114482499083377642, guid: c07ace9ab142ca9469fa377877c2f1e7,
type: 2}
propertyPath: backgroundColorHDR.b
value: 0.05448028
objectReference: {fileID: 0}
m_RemovedComponents: []
m_ParentPrefab: {fileID: 100100000, guid: c07ace9ab142ca9469fa377877c2f1e7, type: 2}
m_IsPrefabParent: 0

m_EditorClassIdentifier:
m_Version: 1
influenceShape: 0
dimmer: 1
multiplier: 1
weight: 1
influenceSphereRadius: 3
sphereReprojectionVolumeRadius: 1
useSeparateProjectionVolume: 0

84
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/2xxx_Lighting/2301_Shadow_Mask/HDRP_Black_Sky.asset


m_EditorClassIdentifier:
active: 1
rotation:
m_OverrideState: 0
m_OverrideState: 1
m_OverrideState: 0
m_OverrideState: 1
m_OverrideState: 0
m_OverrideState: 1
m_OverrideState: 0
m_OverrideState: 1
m_OverrideState: 0
m_OverrideState: 1
skyHDRI:
hdriSky:
m_OverrideState: 1
m_Value: {fileID: 8900000, guid: 75f8ba90acb52d14d9ead53b2a9e4190, type: 3}
--- !u!114 &114436604167779146

m_OverrideState: 0
m_Value: 500
min: 0
cascadeShadowSplitCount:
m_OverrideState: 0
m_Value: 4
min: 1
max: 4
cascadeShadowSplit0:
m_OverrideState: 0
m_Value: 0.05
min: 0
max: 1
cascadeShadowSplit1:
m_OverrideState: 0
m_Value: 0.15
min: 0
max: 1
cascadeShadowSplit2:
m_OverrideState: 0
m_Value: 0.3
min: 0
max: 1
cascadeShadowBorder0:
m_OverrideState: 0
m_Value: 0
min: 0
cascadeShadowBorder1:
m_OverrideState: 0
m_Value: 0
min: 0
cascadeShadowBorder2:
m_OverrideState: 0
m_Value: 0
min: 0
cascadeShadowBorder3:
m_OverrideState: 0
m_Value: 0
min: 0
--- !u!114 &114660440207994068
MonoBehaviour:
m_ObjectHideFlags: 3

m_OverrideState: 1
m_Value: 10
min: 0
cascadeShadowSplitCount:
m_OverrideState: 1
m_Value: 4
min: 1
max: 4
cascadeShadowSplit0:
m_OverrideState: 1
m_Value: 0.05
min: 0
max: 1
cascadeShadowSplit1:
m_OverrideState: 1
m_Value: 0.15
min: 0
max: 1
cascadeShadowSplit2:
m_OverrideState: 1
m_Value: 0.3
min: 0
max: 1
cascadeShadowBorder0:
m_OverrideState: 0
m_Value: 0
min: 0
cascadeShadowBorder1:
m_OverrideState: 0
m_Value: 0
min: 0
cascadeShadowBorder2:
m_OverrideState: 0
m_Value: 0
min: 0
cascadeShadowBorder3:
m_OverrideState: 0
m_Value: 0
min: 0

40
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/2xxx_Lighting/2401_Light_on_Tesselation/HDRP_Default_Sky_SmallDist.asset


m_OverrideState: 1
m_Value: 20
min: 0
cascadeShadowSplitCount:
m_OverrideState: 0
m_Value: 4
min: 1
max: 4
cascadeShadowSplit0:
m_OverrideState: 0
m_Value: 0.05
min: 0
max: 1
cascadeShadowSplit1:
m_OverrideState: 0
m_Value: 0.15
min: 0
max: 1
cascadeShadowSplit2:
m_OverrideState: 0
m_Value: 0.3
min: 0
max: 1
cascadeShadowBorder0:
m_OverrideState: 0
m_Value: 0
min: 0
cascadeShadowBorder1:
m_OverrideState: 0
m_Value: 0
min: 0
cascadeShadowBorder2:
m_OverrideState: 0
m_Value: 0
min: 0
cascadeShadowBorder3:
m_OverrideState: 0
m_Value: 0
min: 0
--- !u!114 &114408460862325740
MonoBehaviour:
m_ObjectHideFlags: 3

active: 1
rotation:
m_OverrideState: 1
m_Value: 160
m_Value: 200
min: 0
max: 360
exposure:

m_OverrideState: 1
m_Value: 0
min: 0
skyHDRI:
hdriSky:
m_OverrideState: 1
m_Value: {fileID: 8900000, guid: fb0bf2eac2381484187ba8a68cdca165, type: 3}
--- !u!114 &114827887035766406

8
ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images.meta


fileFormatVersion: 2
guid: 7cb552a4872af4e66afe37ce1270e4b1
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

71
ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/InputSurfaceCommon.hlsl


#ifndef LIGHTWEIGHT_INPUT_SURFACE_COMMON_INCLUDED
#define LIGHTWEIGHT_INPUT_SURFACE_COMMON_INCLUDED
#include "Core.hlsl"
#include "CoreRP/ShaderLibrary/Packing.hlsl"
#include "CoreRP/ShaderLibrary/CommonMaterial.hlsl"
TEXTURE2D(_MainTex); SAMPLER(sampler_MainTex);
TEXTURE2D(_BumpMap); SAMPLER(sampler_BumpMap);
TEXTURE2D(_EmissionMap); SAMPLER(sampler_EmissionMap);
// Must match Lightweigth ShaderGraph master node
struct SurfaceData
{
half3 albedo;
half3 specular;
half metallic;
half smoothness;
half3 normalTS;
half3 emission;
half occlusion;
half alpha;
};
///////////////////////////////////////////////////////////////////////////////
// Material Property Helpers //
///////////////////////////////////////////////////////////////////////////////
half Alpha(half albedoAlpha, half4 color, half cutoff)
{
#if !defined(_SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A) && !defined(_GLOSSINESS_FROM_BASE_ALPHA)
half alpha = albedoAlpha * color.a;
#else
half alpha = color.a;
#endif
#if defined(_ALPHATEST_ON)
clip(alpha - cutoff);
#endif
return alpha;
}
half4 SampleAlbedoAlpha(float2 uv, TEXTURE2D_ARGS(albedoAlphaMap, sampler_albedoAlphaMap))
{
return SAMPLE_TEXTURE2D(albedoAlphaMap, sampler_albedoAlphaMap, uv);
}
half3 SampleNormal(float2 uv, TEXTURE2D_ARGS(bumpMap, sampler_bumpMap), half scale = 1.0h)
{
#if _NORMALMAP
half4 n = SAMPLE_TEXTURE2D(bumpMap, sampler_bumpMap, uv);
#if BUMP_SCALE_NOT_SUPPORTED
return UnpackNormal(n);
#else
return UnpackNormalScale(n, scale);
#endif
#else
return half3(0.0h, 0.0h, 1.0h);
#endif
}
half3 SampleEmission(float2 uv, half3 emissionColor, TEXTURE2D_ARGS(emissionMap, sampler_emissionMap))
{
#ifndef _EMISSION
return 0;
#else
return SAMPLE_TEXTURE2D(emissionMap, sampler_emissionMap, uv).rgb * emissionColor;
#endif
}
#endif // LIGHTWEIGHT_INPUT_SURFACE_COMMON_INCLUDED

97
ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/InputSurfacePBR.hlsl


#ifndef LIGHTWEIGHT_INPUT_SURFACE_PBR_INCLUDED
#define LIGHTWEIGHT_INPUT_SURFACE_PBR_INCLUDED
#include "Core.hlsl"
#include "CoreRP/ShaderLibrary/CommonMaterial.hlsl"
#include "InputSurfaceCommon.hlsl"
CBUFFER_START(UnityPerMaterial)
float4 _MainTex_ST;
half4 _Color;
half4 _SpecColor;
half4 _EmissionColor;
half _Cutoff;
half _Glossiness;
half _GlossMapScale;
half _Metallic;
half _BumpScale;
half _OcclusionStrength;
CBUFFER_END
TEXTURE2D(_OcclusionMap); SAMPLER(sampler_OcclusionMap);
TEXTURE2D(_MetallicGlossMap); SAMPLER(sampler_MetallicGlossMap);
TEXTURE2D(_SpecGlossMap); SAMPLER(sampler_SpecGlossMap);
#ifdef _SPECULAR_SETUP
#define SAMPLE_METALLICSPECULAR(uv) SAMPLE_TEXTURE2D(_SpecGlossMap, sampler_SpecGlossMap, uv)
#else
#define SAMPLE_METALLICSPECULAR(uv) SAMPLE_TEXTURE2D(_MetallicGlossMap, sampler_MetallicGlossMap, uv)
#endif
half4 SampleMetallicSpecGloss(float2 uv, half albedoAlpha)
{
half4 specGloss;
#ifdef _METALLICSPECGLOSSMAP
specGloss = SAMPLE_METALLICSPECULAR(uv);
#ifdef _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
specGloss.a = albedoAlpha * _GlossMapScale;
#else
specGloss.a *= _GlossMapScale;
#endif
#else // _METALLICSPECGLOSSMAP
#if _SPECULAR_SETUP
specGloss.rgb = _SpecColor.rgb;
#else
specGloss.rgb = _Metallic.rrr;
#endif
#ifdef _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
specGloss.a = albedoAlpha * _GlossMapScale;
#else
specGloss.a = _Glossiness;
#endif
#endif
return specGloss;
}
half SampleOcclusion(float2 uv)
{
#ifdef _OCCLUSIONMAP
#if (SHADER_TARGET < 30)
// SM20: instruction count limitation
// SM20: simpler occlusion
return SAMPLE_TEXTURE2D(_OcclusionMap, sampler_OcclusionMap, uv).g;
#else
half occ = SAMPLE_TEXTURE2D(_OcclusionMap, sampler_OcclusionMap, uv).g;
return LerpWhiteTo(occ, _OcclusionStrength);
#endif
#else
return 1.0;
#endif
}
inline void InitializeStandardLitSurfaceData(float2 uv, out SurfaceData outSurfaceData)
{
half4 albedoAlpha = SampleAlbedoAlpha(uv, TEXTURE2D_PARAM(_MainTex, sampler_MainTex));
outSurfaceData.alpha = Alpha(albedoAlpha.a, _Color, _Cutoff);
half4 specGloss = SampleMetallicSpecGloss(uv, albedoAlpha.a);
outSurfaceData.albedo = albedoAlpha.rgb * _Color.rgb;
#if _SPECULAR_SETUP
outSurfaceData.metallic = 1.0h;
outSurfaceData.specular = specGloss.rgb;
#else
outSurfaceData.metallic = specGloss.r;
outSurfaceData.specular = half3(0.0h, 0.0h, 0.0h);
#endif
outSurfaceData.smoothness = specGloss.a;
outSurfaceData.normalTS = SampleNormal(uv, TEXTURE2D_PARAM(_BumpMap, sampler_BumpMap), _BumpScale);
outSurfaceData.occlusion = SampleOcclusion(uv);
outSurfaceData.emission = SampleEmission(uv, _EmissionColor.rgb, TEXTURE2D_PARAM(_EmissionMap, sampler_EmissionMap));
}
#endif // LIGHTWEIGHT_INPUT_SURFACE_PBR_INCLUDED

9
ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/InputSurfacePBR.hlsl.meta


fileFormatVersion: 2
guid: c46f85bf266d7496d9b3659acfbdc711
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

33
ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/InputSurfaceSimple.hlsl


#ifndef LIGHTWEIGHT_INPUT_SURFACE_SIMPLE_INCLUDED
#define LIGHTWEIGHT_INPUT_SURFACE_SIMPLE_INCLUDED
#include "Core.hlsl"
#include "InputSurfaceCommon.hlsl"
CBUFFER_START(UnityPerMaterial)
float4 _MainTex_ST;
half4 _Color;
half4 _SpecColor;
half4 _EmissionColor;
half _Cutoff;
half _Shininess;
CBUFFER_END
TEXTURE2D(_SpecGlossMap); SAMPLER(sampler_SpecGlossMap);
half4 SampleSpecularGloss(half2 uv, half alpha, half4 specColor, TEXTURE2D_ARGS(specGlossMap, sampler_specGlossMap))
{
half4 specularGloss = half4(0.0h, 0.0h, 0.0h, 1.0h);
#ifdef _SPECGLOSSMAP
specularGloss = SAMPLE_TEXTURE2D(TEXTURE2D_PARAM(specGlossMap, sampler_specGlossMap), uv);
#elif defined(_SPECULAR_COLOR)
specularGloss = specColor;
#endif
#ifdef _GLOSSINESS_FROM_BASE_ALPHA
specularGloss.a = alpha;
#endif
return specularGloss;
}
#endif // LIGHTWEIGHT_INPUT_SURFACE_SIMPLE_INCLUDED

9
ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/InputSurfaceSimple.hlsl.meta


fileFormatVersion: 2
guid: ad863d097888f42c6bcf419efb2946c5
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

15
ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/InputSurfaceUnlit.hlsl


#ifndef LIGHTWEIGHT_INPUT_SURFACE_UNLIT_INCLUDED
#define LIGHTWEIGHT_INPUT_SURFACE_UNLIT_INCLUDED
#include "Core.hlsl"
#include "InputSurfaceCommon.hlsl"
CBUFFER_START(UnityPerMaterial)
float4 _MainTex_ST;
half4 _Color;
half _Cutoff;
half _Glossiness;
half _Metallic;
CBUFFER_END
#endif // LIGHTWEIGHT_INPUT_SURFACE_UNLIT_INCLUDED

9
ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/InputSurfaceUnlit.hlsl.meta


fileFormatVersion: 2
guid: e7ba75cc852b14b7f934978b5697bf1b
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

34
ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/LightweightPassDepthOnly.hlsl


#ifndef LIGHTWEIGHT_PASS_DEPTH_ONLY_INCLUDED
#define LIGHTWEIGHT_PASS_DEPTH_ONLY_INCLUDED
#include "LWRP/ShaderLibrary/Core.hlsl"
struct VertexInput
{
float4 position : POSITION;
float2 texcoord : TEXCOORD0;
UNITY_VERTEX_INPUT_INSTANCE_ID
};
struct VertexOutput
{
float2 uv : TEXCOORD0;
float4 clipPos : SV_POSITION;
};
VertexOutput DepthOnlyVertex(VertexInput v)
{
VertexOutput o = (VertexOutput)0;
UNITY_SETUP_INSTANCE_ID(v);
o.uv = TRANSFORM_TEX(v.texcoord, _MainTex);
o.clipPos = TransformObjectToHClip(v.position.xyz);
return o;
}
half4 DepthOnlyFragment(VertexOutput IN) : SV_TARGET
{
Alpha(SampleAlbedoAlpha(IN.uv, TEXTURE2D_PARAM(_MainTex, sampler_MainTex)).a, _Color, _Cutoff);
return 0;
}
#endif

9
ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/LightweightPassDepthOnly.hlsl.meta


fileFormatVersion: 2
guid: 0acd4fdbcf0cf654a9cdf3e9ccc2edce
timeCreated: 1488965025
licenseType: Pro
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

146
ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/LightweightPassLitSimple.hlsl


#ifndef LIGHTWEIGHT_PASS_LIT_INCLUDED
#define LIGHTWEIGHT_PASS_LIT_INCLUDED
#include "LWRP/ShaderLibrary/Lighting.hlsl"
struct LightweightVertexInput
{
float4 vertex : POSITION;
float3 normal : NORMAL;
float4 tangent : TANGENT;
float2 texcoord : TEXCOORD0;
float2 lightmapUV : TEXCOORD1;
UNITY_VERTEX_INPUT_INSTANCE_ID
};
struct LightweightVertexOutput
{
float2 uv : TEXCOORD0;
DECLARE_LIGHTMAP_OR_SH(lightmapUV, vertexSH, 1);
float4 posWSShininess : TEXCOORD2; // xyz: posWS, w: Shininess * 128
#ifdef _NORMALMAP
half4 normal : TEXCOORD3; // xyz: normal, w: viewDir.x
half4 tangent : TEXCOORD4; // xyz: tangent, w: viewDir.y
half4 binormal : TEXCOORD5; // xyz: binormal, w: viewDir.z
#else
half3 normal : TEXCOORD3;
half3 viewDir : TEXCOORD4;
#endif
half4 fogFactorAndVertexLight : TEXCOORD6; // x: fogFactor, yzw: vertex light
#ifdef _SHADOWS_ENABLED
float4 shadowCoord : TEXCOORD7;
#endif
float4 clipPos : SV_POSITION;
UNITY_VERTEX_INPUT_INSTANCE_ID
UNITY_VERTEX_OUTPUT_STEREO
};
void InitializeInputData(LightweightVertexOutput IN, half3 normalTS, out InputData inputData)
{
inputData.positionWS = IN.posWSShininess.xyz;
#ifdef _NORMALMAP
half3 viewDir = half3(IN.normal.w, IN.tangent.w, IN.binormal.w);
inputData.normalWS = TangentToWorldNormal(normalTS, IN.tangent.xyz, IN.binormal.xyz, IN.normal.xyz);
#else
half3 viewDir = IN.viewDir;
inputData.normalWS = FragmentNormalWS(IN.normal);
#endif
inputData.viewDirectionWS = FragmentViewDirWS(viewDir);
#ifdef _SHADOWS_ENABLED
inputData.shadowCoord = IN.shadowCoord;
#else
inputData.shadowCoord = float4(0, 0, 0, 0);
#endif
inputData.fogCoord = IN.fogFactorAndVertexLight.x;
inputData.vertexLighting = IN.fogFactorAndVertexLight.yzw;
inputData.bakedGI = SAMPLE_GI(IN.lightmapUV, IN.vertexSH, inputData.normalWS);
}
///////////////////////////////////////////////////////////////////////////////
// Vertex and Fragment functions //
///////////////////////////////////////////////////////////////////////////////
// Used in Standard (Simple Lighting) shader
LightweightVertexOutput LitPassVertexSimple(LightweightVertexInput v)
{
LightweightVertexOutput o = (LightweightVertexOutput)0;
UNITY_SETUP_INSTANCE_ID(v);
UNITY_TRANSFER_INSTANCE_ID(v, o);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
o.uv = TRANSFORM_TEX(v.texcoord, _MainTex);
o.posWSShininess.xyz = TransformObjectToWorld(v.vertex.xyz);
o.posWSShininess.w = _Shininess * 128.0;
o.clipPos = TransformWorldToHClip(o.posWSShininess.xyz);
half3 viewDir = VertexViewDirWS(GetCameraPositionWS() - o.posWSShininess.xyz);
#ifdef _NORMALMAP
o.normal.w = viewDir.x;
o.tangent.w = viewDir.y;
o.binormal.w = viewDir.z;
#else
o.viewDir = viewDir;
#endif
// initializes o.normal and if _NORMALMAP also o.tangent and o.binormal
OUTPUT_NORMAL(v, o);
// We either sample GI from lightmap or SH.
// Lightmap UV and vertex SH coefficients use the same interpolator ("float2 lightmapUV" for lightmap or "half3 vertexSH" for SH)
// see DECLARE_LIGHTMAP_OR_SH macro.
// The following funcions initialize the correct variable with correct data
OUTPUT_LIGHTMAP_UV(v.lightmapUV, unity_LightmapST, o.lightmapUV);
OUTPUT_SH(o.normal.xyz, o.vertexSH);
half3 vertexLight = VertexLighting(o.posWSShininess.xyz, o.normal.xyz);
half fogFactor = ComputeFogFactor(o.clipPos.z);
o.fogFactorAndVertexLight = half4(fogFactor, vertexLight);
#ifdef _SHADOWS_ENABLED
#if SHADOWS_SCREEN
o.shadowCoord = ComputeShadowCoord(o.clipPos);
#else
o.shadowCoord = TransformWorldToShadowCoord(o.posWSShininess.xyz);
#endif
#endif
return o;
}
// Used for StandardSimpleLighting shader
half4 LitPassFragmentSimple(LightweightVertexOutput IN) : SV_Target
{
UNITY_SETUP_INSTANCE_ID(IN);
float2 uv = IN.uv;
half4 diffuseAlpha = SampleAlbedoAlpha(uv, TEXTURE2D_PARAM(_MainTex, sampler_MainTex));
half3 diffuse = diffuseAlpha.rgb * _Color.rgb;
half alpha = diffuseAlpha.a * _Color.a;
AlphaDiscard(alpha, _Cutoff);
#ifdef _ALPHAPREMULTIPLY_ON
diffuse *= alpha;
#endif
half3 normalTS = SampleNormal(uv, TEXTURE2D_PARAM(_BumpMap, sampler_BumpMap));
half3 emission = SampleEmission(uv, _EmissionColor.rgb, TEXTURE2D_PARAM(_EmissionMap, sampler_EmissionMap));
half4 specularGloss = SampleSpecularGloss(uv, diffuseAlpha.a, _SpecColor, TEXTURE2D_PARAM(_SpecGlossMap, sampler_SpecGlossMap));
half shininess = IN.posWSShininess.w;
InputData inputData;
InitializeInputData(IN, normalTS, inputData);
return LightweightFragmentBlinnPhong(inputData, diffuse, specularGloss, shininess, emission, alpha);
};
#endif

9
ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/LightweightPassLitSimple.hlsl.meta


fileFormatVersion: 2
guid: ee447e65526c7db45a978c16b28827a9
timeCreated: 1488965025
licenseType: Pro
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

22
ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/LightweightPassMetaPBR.hlsl


#ifndef LIGHTWEIGHT_PASS_META_PBR_INCLUDED
#define LIGHTWEIGHT_PASS_META_PBR_INCLUDED
#include "LightweightPassMetaCommon.hlsl"
half4 LightweightFragmentMeta(MetaVertexOuput i) : SV_Target
{
SurfaceData surfaceData;
InitializeStandardLitSurfaceData(i.uv, surfaceData);
BRDFData brdfData;
InitializeBRDFData(surfaceData.albedo, surfaceData.metallic, surfaceData.specular, surfaceData.smoothness, surfaceData.alpha, brdfData);
MetaInput o;
o.Albedo = brdfData.diffuse + brdfData.specular * brdfData.roughness * 0.5;
o.SpecularColor = surfaceData.specular;
o.Emission = surfaceData.emission;
return MetaFragment(o);
}
#endif // LIGHTWEIGHT_PASS_META_PBR_INCLUDED

9
ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/LightweightPassMetaPBR.hlsl.meta


fileFormatVersion: 2
guid: dcf4e762d48204e33b575f8007e3d563
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

17
ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/LightweightPassMetaSimple.hlsl


#ifndef LIGHTWEIGHT_PASS_META_SIMPLE_INCLUDED
#define LIGHTWEIGHT_PASS_META_SIMPLE_INCLUDED
#include "LightweightPassMetaCommon.hlsl"
half4 LightweightFragmentMetaSimple(MetaVertexOuput i) : SV_Target
{
float2 uv = i.uv;
MetaInput o;
o.Albedo = _Color.rgb * SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, uv).rgb;
o.SpecularColor = SampleSpecularGloss(uv, 1.0h, _SpecColor, TEXTURE2D_PARAM(_SpecGlossMap, sampler_SpecGlossMap)).xyz;
o.Emission = SampleEmission(uv, _EmissionColor.rgb, TEXTURE2D_PARAM(_EmissionMap, sampler_EmissionMap));
return MetaFragment(o);
}
#endif // LIGHTWEIGHT_PASS_META_SIMPLE_INCLUDED

9
ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/LightweightPassMetaSimple.hlsl.meta


fileFormatVersion: 2
guid: ffc632d1e38ef4682807a89afb2b966f
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

33
ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/ParticlesPBR.hlsl


#ifndef LIGHTWEIGHT_PARTICLES_PBR_INCLUDED
#define LIGHTWEIGHT_PARTICLES_PBR_INCLUDED
#include "Particles.hlsl"
TEXTURE2D(_MetallicGlossMap); SAMPLER(sampler_MetallicGlossMap);
void InitializeSurfaceData(VertexOutputLit IN, out SurfaceData surfaceData)
{
half4 albedo = SampleAlbedo(IN, TEXTURE2D_PARAM(_MainTex, sampler_MainTex));
#if defined(_METALLICGLOSSMAP)
half2 metallicGloss = readTexture(TEXTURE2D_PARAM(_MetallicGlossMap, sampler_MetallicGlossMap), IN).ra * half2(1.0, _Glossiness);
#else
half2 metallicGloss = half2(_Metallic, _Glossiness);
#endif
half3 normalTS = SampleNormalTS(IN, TEXTURE2D_PARAM(_BumpMap, sampler_BumpMap), _BumpScale);
half3 emission = SampleEmission(IN, _EmissionColor.rgb, TEXTURE2D_PARAM(_EmissionMap, sampler_EmissionMap));
surfaceData.albedo = albedo.rgb;
surfaceData.specular = half3(0.0h, 0.0h, 0.0h);
surfaceData.normalTS = normalTS;
surfaceData.emission = emission;
surfaceData.metallic = metallicGloss.r;
surfaceData.smoothness = metallicGloss.g;
surfaceData.occlusion = 1.0;
surfaceData.alpha = AlphaBlendAndTest(albedo.a, _Cutoff);
surfaceData.albedo = AlphaModulate(surfaceData.albedo, surfaceData.alpha);
}
#endif // LIGHTWEIGHT_PARTICLES_PBR_INCLUDED

9
ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/ParticlesPBR.hlsl.meta


fileFormatVersion: 2
guid: a3129e299d0744bb7bd42c2cea7cea2b
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

48
ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/GettingStarted1.png

之前 之后
宽度: 998  |  高度: 572  |  大小: 27 KiB

部分文件因为文件数量过多而无法显示

正在加载...
取消
保存