浏览代码

Merge branch 'master' into gfx-tests-postfx

/main
Thomas 7 年前
当前提交
01ee049b
共有 151 个文件被更改,包括 1945 次插入1042 次删除
  1. 61
      TestProjects/GraphicsTests/Packages/manifest.json
  2. 49
      TestProjects/LWGraphicsTest/Packages/manifest.json
  3. 57
      TestProjects/ShaderGraph/Packages/manifest.json
  4. 13
      com.unity.render-pipelines.core/CoreRP/Debugging/MousePositionDebug.cs
  5. 205
      com.unity.render-pipelines.core/CoreRP/Editor/CoreEditorUtils.cs
  6. 5
      com.unity.render-pipelines.core/CoreRP/Editor/ShaderGenerator/ShaderTypeGeneration.cs
  7. 2
      com.unity.render-pipelines.core/CoreRP/ShaderLibrary/Common.hlsl
  8. 5
      com.unity.render-pipelines.core/CoreRP/ShaderLibrary/CommonMaterial.hlsl
  9. 13
      com.unity.render-pipelines.core/CoreRP/Utilities/CoreUtils.cs
  10. 36
      com.unity.render-pipelines.high-definition/CHANGELOG.md
  11. 5
      com.unity.render-pipelines.high-definition/HDRP/Debug/ColorPickerDebug.cs
  12. 24
      com.unity.render-pipelines.high-definition/HDRP/Debug/DebugColorPicker.shader
  13. 33
      com.unity.render-pipelines.high-definition/HDRP/Debug/DebugDisplay.cs
  14. 1
      com.unity.render-pipelines.high-definition/HDRP/Debug/DebugViewMaterialGBuffer.shader
  15. 1
      com.unity.render-pipelines.high-definition/HDRP/Debug/DebugViewTiles.shader
  16. 1
      com.unity.render-pipelines.high-definition/HDRP/Debug/LightingDebug.cs
  17. 9
      com.unity.render-pipelines.high-definition/HDRP/Debug/LightingDebug.cs.hlsl
  18. 103
      com.unity.render-pipelines.high-definition/HDRP/Editor/BuildProcessors/HDRPreprocessShaders.cs
  19. 2
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/HDLightEditor.Styles.cs
  20. 18
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/ReflectionMenuItem.cs
  21. 3
      com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Decal/DecalProjectorComponentEditor.cs
  22. 25
      com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Decal/DecalUI.cs
  23. 14
      com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/HDEditorUtils.cs
  24. 16
      com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/HDRenderPipelineMenuItems.cs
  25. 22
      com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/Settings/RenderPipelineSettingsUI.cs
  26. 3
      com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/Settings/SerializedRenderPipelineSettings.cs
  27. 94
      com.unity.render-pipelines.high-definition/HDRP/Editor/ShaderGraph/HDPBRPass.template
  28. 342
      com.unity.render-pipelines.high-definition/HDRP/Editor/ShaderGraph/HDPBRSubShader.cs
  29. 226
      com.unity.render-pipelines.high-definition/HDRP/Editor/ShaderGraph/HDSubShaderUtilities.cs
  30. 79
      com.unity.render-pipelines.high-definition/HDRP/Editor/ShaderGraph/HDUnlitPassForward.template
  31. 262
      com.unity.render-pipelines.high-definition/HDRP/Editor/ShaderGraph/HDUnlitSubShader.cs
  32. 13
      com.unity.render-pipelines.high-definition/HDRP/Editor/Upgraders/HDRPVersion.cs
  33. 14
      com.unity.render-pipelines.high-definition/HDRP/Editor/Upgraders/UpgradeMenuItem.cs
  34. 21
      com.unity.render-pipelines.high-definition/HDRP/HDRenderPipelineAsset.asset
  35. 24
      com.unity.render-pipelines.high-definition/HDRP/Lighting/DeferredDirectionalShadow.compute
  36. 8
      com.unity.render-pipelines.high-definition/HDRP/Lighting/LightLoop/LightLoop.cs
  37. 4
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/DBufferManager.cs
  38. 15
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/Decal.cs
  39. 1
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/Decal.cs.hlsl
  40. 32
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/Decal.shader
  41. 43
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/DecalData.hlsl
  42. 9
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/DecalProjectorComponent.cs
  43. 1
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/DecalProperties.hlsl
  44. 90
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/DecalSystem.cs
  45. 24
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/DecalUtilities.hlsl
  46. 12
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/ShaderPass/DecalSharePass.hlsl
  47. 14
      com.unity.render-pipelines.high-definition/HDRP/Material/LayeredLit/LayeredLit.shader
  48. 14
      com.unity.render-pipelines.high-definition/HDRP/Material/LayeredLit/LayeredLitTessellation.shader
  49. 112
      com.unity.render-pipelines.high-definition/HDRP/Material/Lit/Lit.hlsl
  50. 14
      com.unity.render-pipelines.high-definition/HDRP/Material/Lit/Lit.shader
  51. 2
      com.unity.render-pipelines.high-definition/HDRP/Material/Lit/LitBuiltinData.hlsl
  52. 14
      com.unity.render-pipelines.high-definition/HDRP/Material/Lit/LitTessellation.shader
  53. 2
      com.unity.render-pipelines.high-definition/HDRP/Material/Lit/ShaderPass/LitDepthPass.hlsl
  54. 2
      com.unity.render-pipelines.high-definition/HDRP/Material/Lit/ShaderPass/LitDistortionPass.hlsl
  55. 2
      com.unity.render-pipelines.high-definition/HDRP/Material/Lit/ShaderPass/LitSharePass.hlsl
  56. 2
      com.unity.render-pipelines.high-definition/HDRP/Material/Lit/ShaderPass/LitVelocityPass.hlsl
  57. 2
      com.unity.render-pipelines.high-definition/HDRP/Material/StackLit/ShaderPass/StackLitDepthPass.hlsl
  58. 2
      com.unity.render-pipelines.high-definition/HDRP/Material/StackLit/ShaderPass/StackLitDistortionPass.hlsl
  59. 2
      com.unity.render-pipelines.high-definition/HDRP/Material/StackLit/ShaderPass/StackLitSharePass.hlsl
  60. 38
      com.unity.render-pipelines.high-definition/HDRP/Material/StackLit/StackLit.hlsl
  61. 27
      com.unity.render-pipelines.high-definition/HDRP/Material/StackLit/StackLit.shader
  62. 2
      com.unity.render-pipelines.high-definition/HDRP/Material/StackLit/StackLitData.hlsl
  63. 4
      com.unity.render-pipelines.high-definition/HDRP/Material/StackLit/StackLitProperties.hlsl
  64. 4
      com.unity.render-pipelines.high-definition/HDRP/Material/SubsurfaceScattering/SubsurfaceScattering.hlsl
  65. 2
      com.unity.render-pipelines.high-definition/HDRP/Material/Unlit/ShaderPass/UnlitDepthPass.hlsl
  66. 2
      com.unity.render-pipelines.high-definition/HDRP/Material/Unlit/ShaderPass/UnlitDistortionPass.hlsl
  67. 2
      com.unity.render-pipelines.high-definition/HDRP/Material/Unlit/ShaderPass/UnlitSharePass.hlsl
  68. 2
      com.unity.render-pipelines.high-definition/HDRP/Material/Unlit/Unlit.hlsl
  69. 4
      com.unity.render-pipelines.high-definition/HDRP/Material/Unlit/Unlit.shader
  70. 106
      com.unity.render-pipelines.high-definition/HDRP/RenderPipeline/HDRenderPipeline.cs
  71. 13
      com.unity.render-pipelines.high-definition/HDRP/RenderPipeline/HDStringConstants.cs
  72. 1
      com.unity.render-pipelines.high-definition/HDRP/RenderPipeline/Settings/RenderPipelineSettings.cs
  73. 10
      com.unity.render-pipelines.high-definition/HDRP/RenderPipelineResources/CameraMotionVectors.shader
  74. 3
      com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPass.cs
  75. 3
      com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPass.cs.hlsl
  76. 30
      com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassDBuffer.hlsl
  77. 15
      com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassDepthOnly.hlsl
  78. 2
      com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassForward.hlsl
  79. 2
      com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassForwardUnlit.hlsl
  80. 2
      com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassGBuffer.hlsl
  81. 2
      com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassLightTransport.hlsl
  82. 12
      com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassVelocity.hlsl
  83. 4
      com.unity.render-pipelines.high-definition/HDRP/ShaderPass/VertMesh.hlsl
  84. 165
      com.unity.render-pipelines.lightweight/CHANGELOG.md
  85. 2
      com.unity.render-pipelines.lightweight/LWRP/Data/LightweightPipelineAsset.cs
  86. 58
      com.unity.render-pipelines.lightweight/LWRP/Editor/LightweightLightEditor.cs
  87. 16
      com.unity.render-pipelines.lightweight/LWRP/Editor/ShaderGraph/LightWeightPBRSubShader.cs
  88. 16
      com.unity.render-pipelines.lightweight/LWRP/Editor/ShaderGraph/LightWeightUnlitSubShader.cs
  89. 14
      com.unity.render-pipelines.lightweight/LWRP/Editor/ShaderGraph/lightweightPBRExtraPasses.template
  90. 13
      com.unity.render-pipelines.lightweight/LWRP/Editor/ShaderGraph/lightweightPBRForwardPass.template
  91. 14
      com.unity.render-pipelines.lightweight/LWRP/Editor/ShaderGraph/lightweightUnlitExtraPasses.template
  92. 13
      com.unity.render-pipelines.lightweight/LWRP/Editor/ShaderGraph/lightweightUnlitPass.template
  93. 38
      com.unity.render-pipelines.lightweight/LWRP/Editor/ShaderPreprocessor.cs
  94. 30
      com.unity.render-pipelines.lightweight/LWRP/LightweightForwardRenderer.cs
  95. 4
      com.unity.render-pipelines.lightweight/LWRP/LightweightPipeline.cs
  96. 30
      com.unity.render-pipelines.lightweight/LWRP/LightweightPipelineCore.cs
  97. 3
      com.unity.render-pipelines.lightweight/LWRP/Passes/DepthOnlyPass.cs
  98. 3
      com.unity.render-pipelines.lightweight/LWRP/Passes/DirectionalShadowsPass.cs
  99. 49
      com.unity.render-pipelines.lightweight/LWRP/Passes/ForwardLitPass.cs
  100. 3
      com.unity.render-pipelines.lightweight/LWRP/Passes/LocalShadowsPass.cs

61
TestProjects/GraphicsTests/Packages/manifest.json


{
"dependencies": {
"com.unity.postprocessing": "file:../../../com.unity.postprocessing",
"com.unity.render-pipelines.core": "file:../../../com.unity.render-pipelines.core",
"com.unity.shadergraph": "file:../../../com.unity.shadergraph",
"com.unity.render-pipelines.high-definition": "file:../../../com.unity.render-pipelines.high-definition",
"com.unity.render-pipelines.lightweight": "file:../../../com.unity.render-pipelines.lightweight"
},
"testables": [
"com.unity.render-pipelines.core",
"com.unity.render-pipelines.high-definition",
"com.unity.render-pipelines.lightweight"
]
"dependencies": {
"com.unity.ads": "2.0.8",
"com.unity.analytics": "2.0.16",
"com.unity.collab-proxy": "1.2.4-preview",
"com.unity.package-manager-ui": "2.0.0-preview.2",
"com.unity.postprocessing": "file:../../../com.unity.postprocessing",
"com.unity.purchasing": "2.0.1",
"com.unity.render-pipelines.core": "file:../../../com.unity.render-pipelines.core",
"com.unity.render-pipelines.high-definition": "file:../../../com.unity.render-pipelines.high-definition",
"com.unity.render-pipelines.lightweight": "file:../../../com.unity.render-pipelines.lightweight",
"com.unity.shadergraph": "file:../../../com.unity.shadergraph",
"com.unity.standardevents": "1.0.13",
"com.unity.textmeshpro": "1.2.1",
"com.unity.modules.ai": "1.0.0",
"com.unity.modules.animation": "1.0.0",
"com.unity.modules.assetbundle": "1.0.0",
"com.unity.modules.audio": "1.0.0",
"com.unity.modules.cloth": "1.0.0",
"com.unity.modules.director": "1.0.0",
"com.unity.modules.imageconversion": "1.0.0",
"com.unity.modules.imgui": "1.0.0",
"com.unity.modules.jsonserialize": "1.0.0",
"com.unity.modules.particlesystem": "1.0.0",
"com.unity.modules.physics": "1.0.0",
"com.unity.modules.physics2d": "1.0.0",
"com.unity.modules.screencapture": "1.0.0",
"com.unity.modules.terrain": "1.0.0",
"com.unity.modules.terrainphysics": "1.0.0",
"com.unity.modules.tilemap": "1.0.0",
"com.unity.modules.ui": "1.0.0",
"com.unity.modules.uielements": "1.0.0",
"com.unity.modules.umbra": "1.0.0",
"com.unity.modules.unityanalytics": "1.0.0",
"com.unity.modules.unitywebrequest": "1.0.0",
"com.unity.modules.unitywebrequestassetbundle": "1.0.0",
"com.unity.modules.unitywebrequestaudio": "1.0.0",
"com.unity.modules.unitywebrequesttexture": "1.0.0",
"com.unity.modules.unitywebrequestwww": "1.0.0",
"com.unity.modules.vehicles": "1.0.0",
"com.unity.modules.video": "1.0.0",
"com.unity.modules.vr": "1.0.0",
"com.unity.modules.wind": "1.0.0",
"com.unity.modules.xr": "1.0.0"
},
"testables": [
"com.unity.render-pipelines.core",
"com.unity.render-pipelines.high-definition",
"com.unity.render-pipelines.lightweight"
]
}

49
TestProjects/LWGraphicsTest/Packages/manifest.json


{
"dependencies": {
"com.unity.postprocessing": "file:../../../com.unity.postprocessing",
"com.unity.render-pipelines.core": "file:../../../com.unity.render-pipelines.core",
"com.unity.shadergraph": "file:../../../com.unity.shadergraph",
"com.unity.render-pipelines.lightweight": "file:../../../com.unity.render-pipelines.lightweight"
}
"dependencies": {
"com.unity.ads": "2.0.8",
"com.unity.analytics": "2.0.16",
"com.unity.collab-proxy": "1.2.4-preview",
"com.unity.package-manager-ui": "2.0.0-preview.2",
"com.unity.postprocessing": "file:../../../com.unity.postprocessing",
"com.unity.purchasing": "2.0.1",
"com.unity.render-pipelines.core": "file:../../../com.unity.render-pipelines.core",
"com.unity.render-pipelines.lightweight": "file:../../../com.unity.render-pipelines.lightweight",
"com.unity.shadergraph": "file:../../../com.unity.shadergraph",
"com.unity.standardevents": "1.0.13",
"com.unity.textmeshpro": "1.2.1",
"com.unity.modules.ai": "1.0.0",
"com.unity.modules.animation": "1.0.0",
"com.unity.modules.assetbundle": "1.0.0",
"com.unity.modules.audio": "1.0.0",
"com.unity.modules.cloth": "1.0.0",
"com.unity.modules.director": "1.0.0",
"com.unity.modules.imageconversion": "1.0.0",
"com.unity.modules.imgui": "1.0.0",
"com.unity.modules.jsonserialize": "1.0.0",
"com.unity.modules.particlesystem": "1.0.0",
"com.unity.modules.physics": "1.0.0",
"com.unity.modules.physics2d": "1.0.0",
"com.unity.modules.screencapture": "1.0.0",
"com.unity.modules.terrain": "1.0.0",
"com.unity.modules.terrainphysics": "1.0.0",
"com.unity.modules.tilemap": "1.0.0",
"com.unity.modules.ui": "1.0.0",
"com.unity.modules.uielements": "1.0.0",
"com.unity.modules.umbra": "1.0.0",
"com.unity.modules.unityanalytics": "1.0.0",
"com.unity.modules.unitywebrequest": "1.0.0",
"com.unity.modules.unitywebrequestassetbundle": "1.0.0",
"com.unity.modules.unitywebrequestaudio": "1.0.0",
"com.unity.modules.unitywebrequesttexture": "1.0.0",
"com.unity.modules.unitywebrequestwww": "1.0.0",
"com.unity.modules.vehicles": "1.0.0",
"com.unity.modules.video": "1.0.0",
"com.unity.modules.vr": "1.0.0",
"com.unity.modules.wind": "1.0.0",
"com.unity.modules.xr": "1.0.0"
}
}

57
TestProjects/ShaderGraph/Packages/manifest.json


{
"dependencies": {
"com.unity.postprocessing": "file:../../../com.unity.postprocessing",
"com.unity.render-pipelines.core": "file:../../../com.unity.render-pipelines.core",
"com.unity.shadergraph": "file:../../../com.unity.shadergraph",
"com.unity.render-pipelines.high-definition": "file:../../../com.unity.render-pipelines.high-definition",
"com.unity.render-pipelines.lightweight": "file:../../../com.unity.render-pipelines.lightweight"
},
"testables": [
"com.unity.render-pipelines.shadergraph"
]
"dependencies": {
"com.unity.ads": "2.0.8",
"com.unity.analytics": "2.0.16",
"com.unity.collab-proxy": "1.2.4-preview",
"com.unity.package-manager-ui": "2.0.0-preview.2",
"com.unity.postprocessing": "file:../../../com.unity.postprocessing",
"com.unity.purchasing": "2.0.1",
"com.unity.render-pipelines.core": "file:../../../com.unity.render-pipelines.core",
"com.unity.render-pipelines.high-definition": "file:../../../com.unity.render-pipelines.high-definition",
"com.unity.render-pipelines.lightweight": "file:../../../com.unity.render-pipelines.lightweight",
"com.unity.shadergraph": "file:../../../com.unity.shadergraph",
"com.unity.standardevents": "1.0.13",
"com.unity.textmeshpro": "1.2.1",
"com.unity.modules.ai": "1.0.0",
"com.unity.modules.animation": "1.0.0",
"com.unity.modules.assetbundle": "1.0.0",
"com.unity.modules.audio": "1.0.0",
"com.unity.modules.cloth": "1.0.0",
"com.unity.modules.director": "1.0.0",
"com.unity.modules.imageconversion": "1.0.0",
"com.unity.modules.imgui": "1.0.0",
"com.unity.modules.jsonserialize": "1.0.0",
"com.unity.modules.particlesystem": "1.0.0",
"com.unity.modules.physics": "1.0.0",
"com.unity.modules.physics2d": "1.0.0",
"com.unity.modules.screencapture": "1.0.0",
"com.unity.modules.terrain": "1.0.0",
"com.unity.modules.terrainphysics": "1.0.0",
"com.unity.modules.tilemap": "1.0.0",
"com.unity.modules.ui": "1.0.0",
"com.unity.modules.uielements": "1.0.0",
"com.unity.modules.umbra": "1.0.0",
"com.unity.modules.unityanalytics": "1.0.0",
"com.unity.modules.unitywebrequest": "1.0.0",
"com.unity.modules.unitywebrequestassetbundle": "1.0.0",
"com.unity.modules.unitywebrequestaudio": "1.0.0",
"com.unity.modules.unitywebrequesttexture": "1.0.0",
"com.unity.modules.unitywebrequestwww": "1.0.0",
"com.unity.modules.vehicles": "1.0.0",
"com.unity.modules.video": "1.0.0",
"com.unity.modules.vr": "1.0.0",
"com.unity.modules.wind": "1.0.0",
"com.unity.modules.xr": "1.0.0"
},
"testables": [
"com.unity.render-pipelines.shadergraph"
]
}

13
com.unity.render-pipelines.core/CoreRP/Debugging/MousePositionDebug.cs


public static void Cleanup()
{
if (s_Instance != null)
DestroyImmediate(s_Instance.gameObject);
{
// Either we call DestroyImmediate or Destroy we get an error :(
// GameViewEventCatcher is only use for SSR debugging currently so comment this code and uncomment it if you want to debug SSR
//DestroyImmediate(s_Instance.gameObject);
//Destroy(s_Instance.gameObject);
}
}
public static void Build()

#if UNITY_EDITOR
UnityEditor.SceneView.onSceneGUIDelegate -= OnSceneGUI;
UnityEditor.SceneView.onSceneGUIDelegate += OnSceneGUI;
GameViewEventCatcher.Build();
// Disabled as it cause error: GameViewEventCatcher is only use for SSR debugging currently so comment this code and uncomment it if you want to debug SSR
//GameViewEventCatcher.Build();
#endif
}

UnityEditor.SceneView.onSceneGUIDelegate -= OnSceneGUI;
GameViewEventCatcher.Cleanup();
// Disabled as it cause error: GameViewEventCatcher is only use for SSR debugging currently so comment this code and uncomment it if you want to debug SSR
//GameViewEventCatcher.Cleanup();
#endif
}

205
com.unity.render-pipelines.core/CoreRP/Editor/CoreEditorUtils.cs


namespace UnityEditor.Experimental.Rendering
{
using UnityObject = UnityEngine.Object;
public static class CoreEditorUtils
{
// GUIContent cache utilities

mode = EditorGUILayout.Popup(label, mode, options);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(property.objectReferenceValue, property.name);
}
}
public static void DrawCascadeSplitGUI<T>(ref SerializedProperty shadowCascadeSplit)

string[] versionText = readText[0].Split(' ');
return versionText[1];
}
}
static class ShadowCascadeSplitGUI
{
private const int kSliderbarTopMargin = 2;
private const int kSliderbarHeight = 24;
private const int kSliderbarBottomMargin = 2;
private const int kPartitionHandleWidth = 2;
private const int kPartitionHandleExtraHitAreaWidth = 2;
private static readonly Color[] kCascadeColors =
{
new Color(0.5f, 0.5f, 0.6f, 1.0f),
new Color(0.5f, 0.6f, 0.5f, 1.0f),
new Color(0.6f, 0.6f, 0.5f, 1.0f),
new Color(0.6f, 0.5f, 0.5f, 1.0f),
};
// using a LODGroup skin
private static readonly GUIStyle s_CascadeSliderBG = "LODSliderRange";
private static readonly GUIStyle s_TextCenteredStyle = new GUIStyle(EditorStyles.whiteMiniLabel)
{
alignment = TextAnchor.MiddleCenter
};
// Internal struct to bundle drag information
private class DragCache
{
public int m_ActivePartition; // the cascade partition that we are currently dragging/resizing
public float m_NormalizedPartitionSize; // the normalized size of the partition (0.0f < size < 1.0f)
public Vector2 m_LastCachedMousePosition; // mouse position the last time we registered a drag or mouse down.
public DragCache(int activePartition, float normalizedPartitionSize, Vector2 currentMousePos)
{
m_ActivePartition = activePartition;
m_NormalizedPartitionSize = normalizedPartitionSize;
m_LastCachedMousePosition = currentMousePos;
}
};
private static DragCache s_DragCache;
private static readonly int s_CascadeSliderId = "s_CascadeSliderId".GetHashCode();
private static SceneView s_RestoreSceneView;
private static SceneView.CameraMode s_OldSceneDrawMode;
private static bool s_OldSceneLightingMode;
/**
* Static function to handle the GUI and User input related to the cascade slider.
*
* @param normalizedCascadePartition The array of partition sizes in the range 0.0f - 1.0f; expects ONE entry if cascades = 2, and THREE if cascades=4
* The last entry will be automatically determined by summing up the array, and doing 1.0f - sum
*/
public static void HandleCascadeSliderGUI(ref float[] normalizedCascadePartitions)
static public void CheckOutFile(bool VCSEnabled, UnityObject mat)
EditorGUILayout.LabelField("Cascade splits");
// get the inspector width since we need it while drawing the partition rects.
// Only way currently is to reserve the block in the layout using GetRect(), and then immediately drawing the empty box
// to match the call to GetRect.
// From this point on, we move to non-layout based code.
var sliderRect = GUILayoutUtility.GetRect(GUIContent.none
, s_CascadeSliderBG
, GUILayout.Height(kSliderbarTopMargin + kSliderbarHeight + kSliderbarBottomMargin)
, GUILayout.ExpandWidth(true));
GUI.Box(sliderRect, GUIContent.none);
float currentX = sliderRect.x;
float cascadeBoxStartY = sliderRect.y + kSliderbarTopMargin;
float cascadeSliderWidth = sliderRect.width - (normalizedCascadePartitions.Length * kPartitionHandleWidth);
Color origTextColor = GUI.color;
Color origBackgroundColor = GUI.backgroundColor;
int colorIndex = -1;
// setup the array locally with the last partition
float[] adjustedCascadePartitions = new float[normalizedCascadePartitions.Length + 1];
System.Array.Copy(normalizedCascadePartitions, adjustedCascadePartitions, normalizedCascadePartitions.Length);
adjustedCascadePartitions[adjustedCascadePartitions.Length - 1] = 1.0f - normalizedCascadePartitions.Sum();
// check for user input on any of the partition handles
// this mechanism gets the current event in the queue... make sure that the mouse is over our control before consuming the event
int sliderControlId = GUIUtility.GetControlID(s_CascadeSliderId, FocusType.Passive);
Event currentEvent = Event.current;
int hotPartitionHandleIndex = -1; // the index of any partition handle that we are hovering over or dragging
// draw each cascade partition
for (int i = 0; i < adjustedCascadePartitions.Length; ++i)
if (VCSEnabled)
float currentPartition = adjustedCascadePartitions[i];
colorIndex = (colorIndex + 1) % kCascadeColors.Length;
GUI.backgroundColor = kCascadeColors[colorIndex];
float boxLength = (cascadeSliderWidth * currentPartition);
UnityEditor.VersionControl.Task task = UnityEditor.VersionControl.Provider.Checkout(mat, UnityEditor.VersionControl.CheckoutMode.Both);
// main cascade box
Rect partitionRect = new Rect(currentX, cascadeBoxStartY, boxLength, kSliderbarHeight);
GUI.Box(partitionRect, GUIContent.none, s_CascadeSliderBG);
currentX += boxLength;
// cascade box percentage text
GUI.color = Color.white;
Rect textRect = partitionRect;
var cascadeText = string.Format("{0}\n{1:F1}%", i, currentPartition * 100.0f);
GUI.Label(textRect, cascadeText, s_TextCenteredStyle);
// no need to draw the partition handle for last box
if (i == adjustedCascadePartitions.Length - 1)
break;
// partition handle
GUI.backgroundColor = Color.black;
Rect handleRect = partitionRect;
handleRect.x = currentX;
handleRect.width = kPartitionHandleWidth;
GUI.Box(handleRect, GUIContent.none, s_CascadeSliderBG);
// we want a thin handle visually (since wide black bar looks bad), but a slightly larger
// hit area for easier manipulation
Rect handleHitRect = handleRect;
handleHitRect.xMin -= kPartitionHandleExtraHitAreaWidth;
handleHitRect.xMax += kPartitionHandleExtraHitAreaWidth;
if (handleHitRect.Contains(currentEvent.mousePosition))
hotPartitionHandleIndex = i;
// add regions to slider where the cursor changes to Resize-Horizontal
if (s_DragCache == null)
if (!task.success)
EditorGUIUtility.AddCursorRect(handleHitRect, MouseCursor.ResizeHorizontal, sliderControlId);
Debug.Log(task.text + " " + task.resultCode);
currentX += kPartitionHandleWidth;
}
GUI.color = origTextColor;
GUI.backgroundColor = origBackgroundColor;
EventType eventType = currentEvent.GetTypeForControl(sliderControlId);
switch (eventType)
{
case EventType.MouseDown:
if (hotPartitionHandleIndex >= 0)
{
s_DragCache = new DragCache(hotPartitionHandleIndex, normalizedCascadePartitions[hotPartitionHandleIndex], currentEvent.mousePosition);
if (GUIUtility.hotControl == 0)
GUIUtility.hotControl = sliderControlId;
currentEvent.Use();
// Switch active scene view into shadow cascades visualization mode, once we start
// tweaking cascade splits.
if (s_RestoreSceneView == null)
{
s_RestoreSceneView = SceneView.lastActiveSceneView;
if (s_RestoreSceneView != null)
{
s_OldSceneDrawMode = s_RestoreSceneView.cameraMode;
s_OldSceneLightingMode = s_RestoreSceneView.m_SceneLighting;
s_RestoreSceneView.cameraMode = SceneView.GetBuiltinCameraMode(DrawCameraMode.ShadowCascades);
}
}
}
break;
case EventType.MouseUp:
// mouseUp event anywhere should release the hotcontrol (if it belongs to us), drags (if any)
if (GUIUtility.hotControl == sliderControlId)
{
GUIUtility.hotControl = 0;
currentEvent.Use();
}
s_DragCache = null;
// Restore previous scene view drawing mode once we stop tweaking cascade splits.
if (s_RestoreSceneView != null)
{
s_RestoreSceneView.cameraMode = s_OldSceneDrawMode;
s_RestoreSceneView.m_SceneLighting = s_OldSceneLightingMode;
s_RestoreSceneView = null;
}
break;
case EventType.MouseDrag:
if (GUIUtility.hotControl != sliderControlId)
break;
// convert the mouse movement to normalized cascade width. Make sure that we are safe to apply the delta before using it.
float delta = (currentEvent.mousePosition - s_DragCache.m_LastCachedMousePosition).x / cascadeSliderWidth;
bool isLeftPartitionHappy = ((adjustedCascadePartitions[s_DragCache.m_ActivePartition] + delta) > 0.0f);
bool isRightPartitionHappy = ((adjustedCascadePartitions[s_DragCache.m_ActivePartition + 1] - delta) > 0.0f);
if (isLeftPartitionHappy && isRightPartitionHappy)
{
s_DragCache.m_NormalizedPartitionSize += delta;
normalizedCascadePartitions[s_DragCache.m_ActivePartition] = s_DragCache.m_NormalizedPartitionSize;
if (s_DragCache.m_ActivePartition < normalizedCascadePartitions.Length - 1)
normalizedCascadePartitions[s_DragCache.m_ActivePartition + 1] -= delta;
GUI.changed = true;
}
s_DragCache.m_LastCachedMousePosition = currentEvent.mousePosition;
currentEvent.Use();
break;
}
}
}

5
com.unity.render-pipelines.core/CoreRP/Editor/ShaderGenerator/ShaderTypeGeneration.cs


}
}
shaderText += "\treturn value." + acc.name + swizzle + ";\n";
shaderText +=
//"\t"
" " // unity convention use space instead of tab...
+ "return value." + acc.name + swizzle + ";\n";
shaderText += "}\n";
}

2
com.unity.render-pipelines.core/CoreRP/ShaderLibrary/Common.hlsl


return (x * x) * (x * x);
}
TEMPLATE_3_FLT(RangeRemap, min, max, t, return saturate((t - min) / (max - min)))
// ----------------------------------------------------------------------------
// Texture utilities
// ----------------------------------------------------------------------------

5
com.unity.render-pipelines.core/CoreRP/ShaderLibrary/CommonMaterial.hlsl


return sqrt(roughness);
}
real RoughnessToPerceptualSmoothness(real roughness)
{
return 1.0 - sqrt(roughness);
}
real PerceptualSmoothnessToRoughness(real perceptualSmoothness)
{
return (1.0 - perceptualSmoothness) * (1.0 - perceptualSmoothness);

13
com.unity.render-pipelines.core/CoreRP/Utilities/CoreUtils.cs


return fogEnable;
}
static public void CheckOutFile(bool VSCEnabled, UnityObject mat)
{
if (VSCEnabled)
{
UnityEditor.VersionControl.Task task = UnityEditor.VersionControl.Provider.Checkout(mat, UnityEditor.VersionControl.CheckoutMode.Both);
if (!task.success)
{
Debug.Log(task.text + " " + task.resultCode);
}
}
}
}
}

36
com.unity.render-pipelines.high-definition/CHANGELOG.md


# Changelog
## [2018.2 undecided]
## [2018.3]
### Improvements
### Changed, Removals and deprecations
### Bug fixes
## [2018.2 / next ]
- Add Light -> Planar Reflection Probe command
- Added a false color mode in rendering debug
- Add support for mesh decals
- Add flag to disable projector decals on transparent geometry to save performance and decal texture atlas space
- Add ability to use decal diffuse map as mask only
- Add visualize all shadow masks in lighting debug
- Add export of normal and roughness buffer for forwardOnly and when in supportOnlyForward mode for forward
- Provide a define in lit.hlsl (FORWARD_MATERIAL_READ_FROM_WRITTEN_NORMAL_BUFFER) when output buffer normal is used to read the normal and roughness instead of caclulating it (can save performance, but lower quality due to compression)
- Add color swatch to decal material
### Improvements
### Changed, Removals and deprecations
- Change Render -> Planar Reflection creation to 3D Object -> Mirror
- Change "Enable Reflector" name on SpotLight to "Angle Affect Intensity"
- Change prototype of BSDFData ConvertSurfaceDataToBSDFData(SurfaceData surfaceData) to BSDFData ConvertSurfaceDataToBSDFData(uint2 positionSS, SurfaceData surfaceData)
### Bug fixes
- Fix issue with StackLit in deferred mode with deferredDirectionalShadow due to GBuffer not being cleared. Gbuffer is still not clear and issue was fix with the new Output of normal buffer.
## [2018.2 / 2.0.1-preview]
### Improvements
- Add stripper of shader variant when building a player. Save shader compile time.

- Add a DefaultHDMirrorMaterial material for PlanarReflection
- Added a script to be able to upgrade material to newer version of HDRP
- Removed useless duplication of ForwardError passes.
- Add option to not compile any DEBUG_DISPLAY shader in the player (Faster build) call Support Runtime Debug display
- Remove EmissiveIntensity parameter and change EmissiveColor to be HDR (Matching Builtin Unity behavior) - Data need to be updated
- Remove EmissiveIntensity parameter and change EmissiveColor to be HDR (Matching Builtin Unity behavior) - Data need to be updated - Launch Edit -> Single Step Upgrade Script -> Upgrade all Materials emissionColor
- Changed versioning variable name in HDAdditionalXXXData from m_version to version
- Create unique name when creating a game object in the rendering menu (i.e Density Volume(2))
- Re-organize various files and folder location to clean the repository

- Fix warning when creating Planar reflection
- Fix specular lighting debug mode (was rendering black)
- Allow projector decal with null material to allow to configure decal when HDRP is not set
- Decal atlas texture offset/scale is updated after allocations (used to be before so it was using date from previous frame)
## [2018.1 undecided]

5
com.unity.render-pipelines.high-definition/HDRP/Debug/ColorPickerDebug.cs


public ColorPickerDebugMode colorPickerMode = ColorPickerDebugMode.None;
public Color fontColor = new Color(1.0f, 0.0f, 0.0f);
public float colorThreshold0 = 0.0f;
public float colorThreshold1 = 200.0f;
public float colorThreshold2 = 9000.0f;
public float colorThreshold3 = 10000.0f;
public void OnValidate()
{
}

24
com.unity.render-pipelines.high-definition/HDRP/Debug/DebugColorPicker.shader


float3 _ColorPickerFontColor;
float _ApplyLinearToSRGB;
float _RequireToFlipInputTexture;
int _FalseColor;
float4 _FalseColorThresholds; // 4 increasing threshold
struct Attributes
{

output.texcoord = GetNormalizedFullScreenTriangleTexCoord(input.vertexID);
return output;
}
float3 FasleColorRemap(float lum, float4 thresholds)
{
//Gradient from 0 to 240 deg of HUE gradient
const float l = DegToRad(240) / TWO_PI;
float t = lerp(0.0, l / 3, RangeRemap(thresholds.x, thresholds.y, lum))
+ lerp(0.0, l / 3, RangeRemap(thresholds.y, thresholds.z, lum))
+ lerp(0.0, l / 3, RangeRemap(thresholds.z, thresholds.w, lum));
return HsvToRgb(float3(l - t, 1, 1));
}
float4 DisplayPixelInformationAtMousePosition(Varyings input, float4 result, float4 mouseResult, float4 mousePixelCoord)

}
float4 result = SAMPLE_TEXTURE2D(_DebugColorPickerTexture, sampler_DebugColorPickerTexture, input.texcoord);
//result.rgb = GetColorCodeFunction(result.x, _ColorPickerParam);
float4 mousePixelCoord = _MousePixelCoord;
if (_RequireToFlipInputTexture > 0.0)

// _DebugExposure will be set to zero if the debug view does not need it so we don't need to make a special case here. It's handled in only one place in C#
mouseResult = mouseResult / exp2(_DebugExposure);
float4 finalResult = DisplayPixelInformationAtMousePosition(input, result, mouseResult, mousePixelCoord);
if (_FalseColor)
result.rgb = FasleColorRemap(Luminance(result.rgb), _FalseColorThresholds);
float4 finalResult = result;
if (_ColorPickerMode != COLORPICKERDEBUGMODE_NONE)
finalResult = DisplayPixelInformationAtMousePosition(input, result, mouseResult, mousePixelCoord);
return finalResult;
}

33
com.unity.render-pipelines.high-definition/HDRP/Debug/DebugDisplay.cs


public LightingDebugSettings lightingDebugSettings = new LightingDebugSettings();
public MipMapDebugSettings mipMapDebugSettings = new MipMapDebugSettings();
public ColorPickerDebugSettings colorPickerDebugSettings = new ColorPickerDebugSettings();
public FalseColorDebugSettings falseColorDebugSettings = new FalseColorDebugSettings();
public DecalsDebugSettings decalsDebugSettings = new DecalsDebugSettings();
public static GUIContent[] lightingFullScreenDebugStrings = null;

RegisterDecalsDebug();
}
void RefreshRenderingDebug<T>(DebugUI.Field<T> field, T value)
{
UnregisterDebugItems(k_PanelRendering, m_DebugRenderingItems);
RegisterRenderingDebug();
}
public void RegisterLightingDebug()
{
var list = new List<DebugUI.Widget>();

public void RegisterRenderingDebug()
{
m_DebugRenderingItems = new DebugUI.Widget[]
var widgetList = new List<DebugUI.Widget>();
widgetList.AddRange(new DebugUI.Widget[]
{
new DebugUI.EnumField { displayName = "Fullscreen Debug Mode", getter = () => (int)fullScreenDebugMode, setter = value => fullScreenDebugMode = (FullScreenDebugMode)value, enumNames = renderingFullScreenDebugStrings, enumValues = renderingFullScreenDebugValues },
new DebugUI.EnumField { displayName = "MipMaps", getter = () => (int)mipMapDebugSettings.debugMipMapMode, setter = value => SetMipMapMode((DebugMipMapMode)value), autoEnum = typeof(DebugMipMapMode) },

children =
{
new DebugUI.EnumField { displayName = "Debug Mode", getter = () => (int)colorPickerDebugSettings.colorPickerMode, setter = value => colorPickerDebugSettings.colorPickerMode = (ColorPickerDebugMode)value, autoEnum = typeof(ColorPickerDebugMode) },
new DebugUI.FloatField { displayName = "Range Threshold 0", getter = () => colorPickerDebugSettings.colorThreshold0, setter = value => colorPickerDebugSettings.colorThreshold0 = value },
new DebugUI.FloatField { displayName = "Range Threshold 1", getter = () => colorPickerDebugSettings.colorThreshold1, setter = value => colorPickerDebugSettings.colorThreshold1 = value },
new DebugUI.FloatField { displayName = "Range Threshold 2", getter = () => colorPickerDebugSettings.colorThreshold2, setter = value => colorPickerDebugSettings.colorThreshold2 = value },
new DebugUI.FloatField { displayName = "Range Threshold 3", getter = () => colorPickerDebugSettings.colorThreshold3, setter = value => colorPickerDebugSettings.colorThreshold3 = value },
};
});
widgetList.Add(new DebugUI.BoolField { displayName = "False Color Mode", getter = () => falseColorDebugSettings.falseColor, setter = value => falseColorDebugSettings.falseColor = value, onValueChanged = RefreshRenderingDebug });
if (falseColorDebugSettings.falseColor)
{
widgetList.Add(new DebugUI.Container{
flags = DebugUI.Flags.EditorOnly,
children =
{
new DebugUI.FloatField { displayName = "Range Threshold 0", getter = () => falseColorDebugSettings.colorThreshold0, setter = value => falseColorDebugSettings.colorThreshold0 = Mathf.Min(value, falseColorDebugSettings.colorThreshold1) },
new DebugUI.FloatField { displayName = "Range Threshold 1", getter = () => falseColorDebugSettings.colorThreshold1, setter = value => falseColorDebugSettings.colorThreshold1 = Mathf.Clamp(value, falseColorDebugSettings.colorThreshold0, falseColorDebugSettings.colorThreshold2) },
new DebugUI.FloatField { displayName = "Range Threshold 2", getter = () => falseColorDebugSettings.colorThreshold2, setter = value => falseColorDebugSettings.colorThreshold2 = Mathf.Clamp(value, falseColorDebugSettings.colorThreshold1, falseColorDebugSettings.colorThreshold3) },
new DebugUI.FloatField { displayName = "Range Threshold 3", getter = () => falseColorDebugSettings.colorThreshold3, setter = value => falseColorDebugSettings.colorThreshold3 = Mathf.Max(value, falseColorDebugSettings.colorThreshold2) },
}
});
}
m_DebugRenderingItems = widgetList.ToArray();
var panel = DebugManager.instance.GetPanel(k_PanelRendering, true);
panel.children.Add(m_DebugRenderingItems);
}

1
com.unity.render-pipelines.high-definition/HDRP/Debug/DebugViewMaterialGBuffer.shader


Pass
{
ZWrite Off
Cull Off
HLSLPROGRAM
#pragma target 4.5

1
com.unity.render-pipelines.high-definition/HDRP/Debug/DebugViewTiles.shader


Pass
{
ZWrite Off
Cull Off
ZTest Always
Blend SrcAlpha OneMinusSrcAlpha

1
com.unity.render-pipelines.high-definition/HDRP/Debug/LightingDebug.cs


SpecularLighting,
LuxMeter,
VisualizeCascade,
VisualizeShadowMasks,
IndirectDiffuseOcclusion,
IndirectSpecularOcclusion,
ScreenSpaceTracingRefraction,

9
com.unity.render-pipelines.high-definition/HDRP/Debug/LightingDebug.cs.hlsl


#define DEBUGLIGHTINGMODE_SPECULAR_LIGHTING (2)
#define DEBUGLIGHTINGMODE_LUX_METER (3)
#define DEBUGLIGHTINGMODE_VISUALIZE_CASCADE (4)
#define DEBUGLIGHTINGMODE_INDIRECT_DIFFUSE_OCCLUSION (5)
#define DEBUGLIGHTINGMODE_INDIRECT_SPECULAR_OCCLUSION (6)
#define DEBUGLIGHTINGMODE_SCREEN_SPACE_TRACING_REFRACTION (7)
#define DEBUGLIGHTINGMODE_SCREEN_SPACE_TRACING_REFLECTION (8)
#define DEBUGLIGHTINGMODE_VISUALIZE_SHADOW_MASKS (5)
#define DEBUGLIGHTINGMODE_INDIRECT_DIFFUSE_OCCLUSION (6)
#define DEBUGLIGHTINGMODE_INDIRECT_SPECULAR_OCCLUSION (7)
#define DEBUGLIGHTINGMODE_SCREEN_SPACE_TRACING_REFRACTION (8)
#define DEBUGLIGHTINGMODE_SCREEN_SPACE_TRACING_REFLECTION (9)
//
// UnityEngine.Experimental.Rendering.HDPipeline.DebugScreenSpaceTracing: static fields

103
com.unity.render-pipelines.high-definition/HDRP/Editor/BuildProcessors/HDRPreprocessShaders.cs


{
class HDRPreprocessShaders : IPreprocessShaders
{
// returns true if the variant should be stripped.
delegate bool VariantStrippingFunc(Shader shader, ShaderSnippetData snippet, ShaderCompilerData inputData);
ShaderKeyword m_ShadowMask;
ShaderKeyword m_Transparent;
ShaderKeyword m_DebugDisplay;
ShaderKeyword m_TileLighting;
ShaderKeyword m_ClusterLighting;
//ShaderKeyword m_FeatureSSS;
public HDRPreprocessShaders()
{
// TODO: Grab correct configuration/quality asset.

m_StripperFuncs = new Dictionary<string, VariantStrippingFunc>();
m_StripperFuncs.Add("HDRenderPipeline/Lit", LitShaderStripper);
m_StripperFuncs.Add("HDRenderPipeline/LitTessellation", LitShaderStripper);
m_StripperFuncs.Add("HDRenderPipeline/LayeredLit", LitShaderStripper);
m_StripperFuncs.Add("HDRenderPipeline/LayeredLitTessellation", LitShaderStripper);
m_StripperFuncs.Add("HDRenderPipeline/Unlit", UnlitShaderStripper);
m_Transparent = new ShaderKeyword("_SURFACE_TYPE_TRANSPARENT");
m_DebugDisplay = new ShaderKeyword("DEBUG_DISPLAY");
m_TileLighting = new ShaderKeyword("USE_FPTL_LIGHTLIST");
m_ClusterLighting = new ShaderKeyword("USE_CLUSTERED_LIGHTLIST");
//m_FeatureSSS = new ShaderKeyword("_MATERIAL_FEATURE_SUBSURFACE_SCATTERING");
}
bool UnlitShaderStripper(Shader shader, ShaderSnippetData snippet, ShaderCompilerData inputData)
{
bool isSceneSelectionPass = snippet.passName == "SceneSelectionPass";
if (isSceneSelectionPass)
return true;
return false;
}
bool LitShaderStripper(Shader shader, ShaderSnippetData snippet, ShaderCompilerData inputData)
{
bool isSceneSelectionPass = snippet.passName == "SceneSelectionPass";
if (isSceneSelectionPass)
return true;
List<BaseShaderPreprocessor> materialList = HDEditorUtils.GetBaseShaderPreprocessorList();
bool isGBufferPass = snippet.passName == "GBuffer";
bool isForwardPass = snippet.passName == "Forward";
bool isTransparentForwardPass = snippet.passName == "TransparentDepthPostpass" || snippet.passName == "TransparentBackface" || snippet.passName == "TransparentDepthPrepass";
bool isMotionPass = snippet.passName == "Motion Vectors";
// NOTE: All these keyword should be automatically stripped so there's no need to handle them ourselves.
// LIGHTMAP_ON, DIRLIGHTMAP_COMBINED, DYNAMICLIGHTMAP_ON, LIGHTMAP_SHADOW_MIXING, SHADOWS_SHADOWMASK
// FOG_LINEAR, FOG_EXP, FOG_EXP2
// STEREO_INSTANCING_ON, STEREO_MULTIVIEW_ON, STEREO_CUBEMAP_RENDER_ON, UNITY_SINGLE_PASS_STEREO
// INSTANCING_ON
if (!m_CurrentHDRPAsset.renderPipelineSettings.supportMotionVectors && isMotionPass)
return true;
// When using forward only, we never need GBuffer pass (only Forward)
if (m_CurrentHDRPAsset.renderPipelineSettings.supportOnlyForward && isGBufferPass)
return true;
if (inputData.shaderKeywordSet.IsEnabled(m_Transparent))
// Fill the dictionary with material to handle
foreach (BaseShaderPreprocessor material in materialList)
// If transparent, we never need GBuffer pass.
if (isGBufferPass)
return true;
// We will also use cluster instead of tile
if (inputData.shaderKeywordSet.IsEnabled(m_TileLighting))
return true;
material.AddStripperFuncs(m_StripperFuncs);
else // Opaque
{
// If opaque, we never need transparent specific passes (even in forward only mode)
if (isTransparentForwardPass)
return true;
if (!m_CurrentHDRPAsset.renderPipelineSettings.supportOnlyForward && inputData.shaderKeywordSet.IsEnabled(m_ClusterLighting))
return true;
if (!m_CurrentHDRPAsset.renderPipelineSettings.supportOnlyForward)
{
// If opaque and not forward only, then we only need the forward debug pass.
if (isForwardPass && !inputData.shaderKeywordSet.IsEnabled(m_DebugDisplay))
return true;
}
}
// TODO: Expose development build flag.
//if (developmentBuild && inputData.shaderKeywordSet.IsEnabled(m_DebugDisplay))
// return true;
// TODO: Tests for later
// We need to find a way to strip useless shader features for passes/shader stages that don't need them (example, vertex shaders won't ever need SSS Feature flag)
// This causes several problems:
// - Runtime code that "finds" shader variants based on feature flags might not find them anymore... thus fall backing to the "let's give a score to variant" code path that may find the wrong variant.
// - Another issue is that if a feature is declared without a "_" fall-back, if we strip the other variants, none may be left to use! This needs to be changed on our side.
//if (snippet.shaderType == ShaderType.Vertex && inputData.shaderKeywordSet.IsEnabled(m_FeatureSSS))
// return true;
return false;
}
public int callbackOrder { get { return 0; } }

for (int i = 0; i < inputData.Count; ++i)
{
ShaderCompilerData input = inputData[i];
if (stripperFunc(shader, snippet, input))
if (stripperFunc(m_CurrentHDRPAsset, shader, snippet, input))
{
inputData.RemoveAt(i);
i--;

// Currently if a certain snippet is completely stripped (for example if you remove a whole pass) other passes might get broken
// To work around that, we make sure that we always have at least one variant.
// TODO: Remove this one it is fixed
if (inputData.Count == 0)
inputData.Add(workaround);
}

2
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/HDLightEditor.Styles.cs


public readonly GUIContent shape = new GUIContent("Type", "Specifies the current type of light. Possible types are Directional, Spot, Point, Rectangle and Line lights.");
public readonly GUIContent[] shapeNames;
public readonly GUIContent enableSpotReflector = new GUIContent("Enable spot reflector", "When true it simulate a spot light with reflector (mean the intensity of the light will be more focus with narrower angle), otherwise light outside of the cone is simply absorbed (mean intensity is constent whatever the size of the cone).");
public readonly GUIContent enableSpotReflector = new GUIContent("Angle affect intensity", "When true it simulate a spot light with reflector (mean the intensity of the light will be more focus with narrower angle), otherwise light outside of the cone is simply absorbed (mean intensity is constent whatever the size of the cone).");
// Additional shadow data
public readonly GUIContent shadowResolution = new GUIContent("Resolution", "Controls the rendered resolution of the shadow maps. A higher resolution will increase the fidelity of shadows at the cost of GPU performance and memory usage.");

18
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/ReflectionMenuItem.cs


{
public class ReflectionMenuItems
{
[MenuItem("GameObject/Rendering/Planar Reflection", priority = CoreUtils.gameObjectMenuPriority)]
static void CreatePlanarReflectionGameObject(MenuCommand menuCommand)
[MenuItem("GameObject/3D Object/Mirror", priority = CoreUtils.gameObjectMenuPriority)]
static void CreateMirrorGameObject(MenuCommand menuCommand)
{
GameObject plane = GameObject.CreatePrimitive(PrimitiveType.Plane);
GameObjectUtility.SetParentAndAlign(plane, menuCommand.context as GameObject);

{
plane.GetComponent<MeshRenderer>().sharedMaterial = material;
}
}
[MenuItem("GameObject/Light/Planar Reflection Probe", priority = CoreUtils.gameObjectMenuPriority)]
static void CreatePlanarReflectionGameObject(MenuCommand menuCommand)
{
var parent = menuCommand.context as GameObject;
var go = CoreEditorUtils.CreateGameObject(parent, "Planar Reflection");
var planarProbe = go.AddComponent<PlanarReflectionProbe>();
planarProbe.influenceVolume.boxBaseSize = new Vector3(1, 0.01f, 1);
// Ensure it gets re-parented if this was a context click (otherwise does nothing)
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject);
// Register the creation in the undo system
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name);
Selection.activeObject = go;
}
}
}

3
com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Decal/DecalProjectorComponentEditor.cs


private SerializedProperty m_FadeScaleProperty;
private SerializedProperty m_UVScaleProperty;
private SerializedProperty m_UVBiasProperty;
private SerializedProperty m_AffectsTransparencyProperty;
public class DecalBoundsHandle : BoxBoundsHandle
{

m_FadeScaleProperty = serializedObject.FindProperty("m_FadeScale");
m_UVScaleProperty = serializedObject.FindProperty("m_UVScale");
m_UVBiasProperty = serializedObject.FindProperty("m_UVBias");
m_AffectsTransparencyProperty = serializedObject.FindProperty("m_AffectsTransparency");
}
private void OnDisable()

EditorGUILayout.Slider(m_FadeScaleProperty, 0.0f, 1.0f, new GUIContent("Fade scale"));
EditorGUILayout.PropertyField(m_UVScaleProperty);
EditorGUILayout.PropertyField(m_UVBiasProperty);
EditorGUILayout.PropertyField(m_AffectsTransparencyProperty);
if (EditorGUI.EndChangeCheck())
{
serializedObject.ApplyModifiedProperties();

25
com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Decal/DecalUI.cs


{
public static string InputsText = "Inputs";
public static GUIContent baseColorText = new GUIContent("Base Color + Blend", "Albedo (RGB) and Blend Factor (A)");
public static GUIContent baseColorText = new GUIContent("Albedo (RGB) and Blend Factor (A)", "Albedo (RGB) and Blend Factor (A)");
public static GUIContent baseColorText2 = new GUIContent("Blend Factor (A)", "Blend Factor (A)");
public static GUIContent BlendText = new GUIContent("Decal Blend", "Whole decal blend");
public static GUIContent AlbedoModeText = new GUIContent("Albedo contribution", "Base color + Blend, Blend only");
protected MaterialProperty baseColor = new MaterialProperty();
protected const string kBaseColor = "_BaseColor";
protected MaterialProperty normalMap = new MaterialProperty();
protected const string kNormalMap = "_NormalMap";

protected MaterialProperty decalBlend = new MaterialProperty();
protected const string kDecalBlend = "_DecalBlend";
protected MaterialProperty albedoMode = new MaterialProperty();
protected const string kAlbedoMode = "_AlbedoMode";
protected MaterialEditor m_MaterialEditor;

{
baseColor = FindProperty(kBaseColor, props);
albedoMode = FindProperty(kAlbedoMode, props);
// always instanced
SerializedProperty instancing = m_MaterialEditor.serializedObject.FindProperty("m_EnableInstancingVariants");
instancing.boolValue = true;

static public void SetupMaterialKeywordsAndPass(Material material)
{
CoreUtils.SetKeyword(material, "_ALBEDOCONTRIBUTION", material.GetFloat(kAlbedoMode) == 1.0f);
CoreUtils.SetKeyword(material, "_COLORMAP", material.GetTexture(kBaseColorMap));
CoreUtils.SetKeyword(material, "_NORMALMAP", material.GetTexture(kNormalMap));
CoreUtils.SetKeyword(material, "_MASKMAP", material.GetTexture(kMaskMap));

EditorGUILayout.LabelField(Styles.InputsText, EditorStyles.boldLabel);
EditorGUI.indentLevel++;
m_MaterialEditor.TexturePropertySingleLine(Styles.baseColorText, baseColorMap);
m_MaterialEditor.ShaderProperty(albedoMode, Styles.AlbedoModeText);
if (material.GetFloat(kAlbedoMode) == 1.0f)
{
m_MaterialEditor.TexturePropertySingleLine(Styles.baseColorText, baseColorMap, baseColor);
}
else
{
m_MaterialEditor.TexturePropertySingleLine(Styles.baseColorText2, baseColorMap, baseColor);
}
m_MaterialEditor.TexturePropertySingleLine(Styles.normalMapText, normalMap);
m_MaterialEditor.TexturePropertySingleLine(Styles.maskMapText, maskMap);
m_MaterialEditor.ShaderProperty(decalBlend, Styles.decalBlendText);

14
com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/HDEditorUtils.cs


}
return false;
}
public static List<BaseShaderPreprocessor> GetBaseShaderPreprocessorList()
{
var baseType = typeof(BaseShaderPreprocessor);
var assembly = baseType.Assembly;
var types = assembly.GetTypes()
.Where(t => t.IsSubclassOf(baseType))
.Select(Activator.CreateInstance)
.Cast<BaseShaderPreprocessor>()
.ToList();
return types;
}
}
}

16
com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/HDRenderPipelineMenuItems.cs


{
var materials = Resources.FindObjectsOfTypeAll<Material>();
bool VSCEnabled = (UnityEditor.VersionControl.Provider.enabled && UnityEditor.VersionControl.Provider.isActive);
bool VCSEnabled = (UnityEditor.VersionControl.Provider.enabled && UnityEditor.VersionControl.Provider.isActive);
CoreUtils.CheckOutFile(VSCEnabled, mat);
CoreEditorUtils.CheckOutFile(VCSEnabled, mat);
LayeredLitGUI.SynchronizeAllLayers(mat);
EditorUtility.SetDirty(mat);
}

for (var i = 0; i < openedScenes.Length; ++i)
openedScenes[i] = SceneManager.GetSceneAt(i).path;
bool VSCEnabled = (UnityEditor.VersionControl.Provider.enabled && UnityEditor.VersionControl.Provider.isActive);
bool VCSEnabled = (UnityEditor.VersionControl.Provider.enabled && UnityEditor.VersionControl.Provider.isActive);
try
{

{
var scenePath = AssetDatabase.GUIDToAssetPath(scenes[i]);
var sceneAsset = AssetDatabase.LoadAssetAtPath<SceneAsset>(scenePath);
CoreUtils.CheckOutFile(VSCEnabled, sceneAsset);
CoreEditorUtils.CheckOutFile(VCSEnabled, sceneAsset);
EditorSceneManager.OpenScene(scenePath);
var sceneName = Path.GetFileNameWithoutExtension(scenePath);

{
var matIds = AssetDatabase.FindAssets("t:Material");
bool VSCEnabled = (UnityEditor.VersionControl.Provider.enabled && UnityEditor.VersionControl.Provider.isActive);
bool VCSEnabled = (UnityEditor.VersionControl.Provider.enabled && UnityEditor.VersionControl.Provider.isActive);
for (int i = 0, length = matIds.Length; i < length; i++)
{

string.Format("{0} / {1} materials cleaned.", i, length),
(i / (float)(length - 1)) * progressScale + progressOffset);
CoreUtils.CheckOutFile(VSCEnabled, mat);
CoreEditorUtils.CheckOutFile(VCSEnabled, mat);
var h = Debug.unityLogger.logHandler;
Debug.unityLogger.logHandler = new UnityContextualLogHandler(mat);
HDEditorUtils.ResetMaterialKeywords(mat);

{
var materials = Resources.FindObjectsOfTypeAll<Material>();
bool VSCEnabled = (UnityEditor.VersionControl.Provider.enabled && UnityEditor.VersionControl.Provider.isActive);
bool VCSEnabled = (UnityEditor.VersionControl.Provider.enabled && UnityEditor.VersionControl.Provider.isActive);
bool anyMaterialDirty = false; // Will be true if any material is dirty.

string.Format("{0}{1} / {2} materials cleaned.", descriptionPrefix, i, length),
(i / (float)(length - 1)) * progressScale + progressOffset);
CoreUtils.CheckOutFile(VSCEnabled, materials[i]);
CoreEditorUtils.CheckOutFile(VCSEnabled, materials[i]);
if (HDEditorUtils.ResetMaterialKeywords(materials[i]))
{

22
com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/Settings/RenderPipelineSettingsUI.cs


{
EditorGUILayout.LabelField(_.GetContent("Render Pipeline Settings"), EditorStyles.boldLabel);
++EditorGUI.indentLevel;
EditorGUILayout.PropertyField(d.supportShadowMask, _.GetContent("Support Shadow Mask"));
EditorGUILayout.PropertyField(d.supportSSR, _.GetContent("Support SSR"));
EditorGUILayout.PropertyField(d.supportSSAO, _.GetContent("Support SSAO"));
EditorGUILayout.PropertyField(d.supportDBuffer, _.GetContent("Support Decal Buffer"));
EditorGUILayout.PropertyField(d.supportMSAA, _.GetContent("Support Multi Sampling Anti-Aliasing"));
EditorGUILayout.PropertyField(d.MSAASampleCount, _.GetContent("MSAA Sample Count"));
EditorGUILayout.PropertyField(d.supportShadowMask, _.GetContent("Support Shadow Mask|Enable memory (Extra Gbuffer in deferred) and shader variant for shadow mask."));
EditorGUILayout.PropertyField(d.supportSSR, _.GetContent("Support SSR|Enable memory use by SSR effect."));
EditorGUILayout.PropertyField(d.supportSSAO, _.GetContent("Support SSAO|Enable memory use by SSAO effect."));
EditorGUILayout.PropertyField(d.supportDBuffer, _.GetContent("Support Decal Buffer|Enable memory and variant of decal buffer."));
EditorGUILayout.PropertyField(d.supportMSAA, _.GetContent("Support Multi Sampling Anti-Aliasing|This feature doesn't work currently."));
EditorGUILayout.PropertyField(d.MSAASampleCount, _.GetContent("MSAA Sample Count|Allow to select the level of MSAA."));
EditorGUILayout.PropertyField(d.supportOnlyForward, _.GetContent("Support Only Forward"));
EditorGUILayout.PropertyField(d.supportMotionVectors, _.GetContent("Support Motion Vectors"));
EditorGUILayout.PropertyField(d.supportOnlyForward, _.GetContent("Support Only Forward|Remove all the memory and shader variant of GBuffer. The renderer can be switch to deferred anymore."));
EditorGUILayout.PropertyField(d.supportMotionVectors, _.GetContent("Support Motion Vectors|Motion vector are use for Motion Blur, TAA, temporal re-projection of various effect like SSR."));
EditorGUILayout.PropertyField(d.enableUltraQualitySSS, _.GetContent("Increase SSS Sample Count"));
EditorGUILayout.PropertyField(d.supportVolumetric, _.GetContent("Support volumetric"));
EditorGUILayout.PropertyField(d.enableUltraQualitySSS, _.GetContent("Increase SSS Sample Count|This allow better SSS quality. Warning: Slow feature, don't use for game."));
EditorGUILayout.PropertyField(d.supportVolumetric, _.GetContent("Support volumetric|Enable memory and shader variant for volumetric."));
EditorGUILayout.PropertyField(d.supportRuntimeDebugDisplay, _.GetContent("Support runtime debug display|Remove all debug display shader variant only in the player. Allow faster build."));
--EditorGUI.indentLevel;
}
}

3
com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/Settings/SerializedRenderPipelineSettings.cs


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

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

94
com.unity.render-pipelines.high-definition/HDRP/Editor/ShaderGraph/HDPBRPass.template


//#pragma enable_d3d11_debug_symbols
//-------------------------------------------------------------------------------------
// Variant Definitions
// Variant Definitions (active field translations to HDRP defines)
${VariantDefines}
$AlphaTest: #define _ALPHATEST_ON 1
$Material.SubsurfaceScattering: #define _MATERIAL_FEATURE_SUBSURFACE_SCATTERING 1
$Material.Transmission: #define _MATERIAL_FEATURE_TRANSMISSION 1
$Material.Anisotropy: #define _MATERIAL_FEATURE_ANISOTROPY 1
$Material.ClearCoat: #define _MATERIAL_FEATURE_CLEAR_COAT 1
$Material.Iridescence: #define _MATERIAL_FEATURE_IRIDESCENCE 1
$Material.SpecularColor: #define _MATERIAL_FEATURE_SPECULAR_COLOR 1
$SurfaceType.Transparent: #define _SURFACE_TYPE_TRANSPARENT 1
$BlendMode.Alpha: #define _BLENDMODE_ALPHA 1
$BlendMode.Add: #define _BLENDMODE_ADD 1
//-------------------------------------------------------------------------------------
// End Variant
//-------------------------------------------------------------------------------------

// Use surface gradient normal mapping as it handle correctly triplanar normal mapping and multiple UVSet
// this modifies the normal calculation
// #define SURFACE_GRADIENT
// This shader support vertex modification (or not)
// TODO - move to PBR shader control
// #define HAVE_VERTEX_MODIFICATION
// If we use subsurface scattering, enable output split lighting (for forward pass)
#if defined(_MATID_SSS) && !defined(_SURFACE_TYPE_TRANSPARENT)

$VaryingsMeshToPS.texCoord3: #define VARYINGS_NEED_TEXCOORD3
$VaryingsMeshToPS.color: #define VARYINGS_NEED_COLOR
$VaryingsMeshToPS.cullFace: #define VARYINGS_NEED_CULLFACE
$features.modifyMesh: #define HAVE_MESH_MODIFICATION
#include "ShaderGraphLibrary/Functions.hlsl"
#include "HDRP/ShaderVariables.hlsl"
#ifdef DEBUG_DISPLAY
#include "HDRP/Debug/DebugDisplay.hlsl"

// End graph generated code
//-------------------------------------------------------------------------------------
// TODO: Do we want to build include functionality for sharing these preprocessed functions across templates?
#ifdef HAVE_MESH_MODIFICATION
// TODO: we should share this between template files somehow
VertexDescriptionInputs AttributesMeshToVertexDescriptionInputs(AttributesMesh input)
{
VertexDescriptionInputs output;
ZERO_INITIALIZE(VertexDescriptionInputs, output);
$VertexDescriptionInputs.ObjectSpaceNormal: output.ObjectSpaceNormal = input.normalOS;
$VertexDescriptionInputs.WorldSpaceNormal: output.WorldSpaceNormal = TransformObjectToWorldNormal(input.normalOS);
$VertexDescriptionInputs.ViewSpaceNormal: output.ViewSpaceNormal = TransformWorldToViewDir(output.WorldSpaceNormal);
$VertexDescriptionInputs.TangentSpaceNormal: output.TangentSpaceNormal = float3(0.0f, 0.0f, 1.0f);
$VertexDescriptionInputs.ObjectSpaceTangent: output.ObjectSpaceTangent = input.tangentOS;
$VertexDescriptionInputs.WorldSpaceTangent: output.WorldSpaceTangent = TransformObjectToWorldDir(input.tangentOS.xyz);
$VertexDescriptionInputs.ViewSpaceTangent: output.ViewSpaceTangent = TransformWorldToViewDir(output.WorldSpaceTangent);
$VertexDescriptionInputs.TangentSpaceTangent: output.TangentSpaceTangent = float3(1.0f, 0.0f, 0.0f);
$VertexDescriptionInputs.ObjectSpaceBiTangent: output.ObjectSpaceBiTangent = normalize(cross(input.normalOS, input.tangentOS) * (input.tangentOS.w > 0.0f ? 1.0f : -1.0f) * GetOddNegativeScale());
$VertexDescriptionInputs.WorldSpaceBiTangent: output.WorldSpaceBiTangent = TransformObjectToWorldDir(output.ObjectSpaceBiTangent);
$VertexDescriptionInputs.ViewSpaceBiTangent: output.ViewSpaceBiTangent = TransformWorldToViewDir(output.WorldSpaceBiTangent);
$VertexDescriptionInputs.TangentSpaceBiTangent: output.TangentSpaceBiTangent = float3(0.0f, 1.0f, 0.0f);
$VertexDescriptionInputs.ObjectSpacePosition: output.ObjectSpacePosition = input.positionOS;
$VertexDescriptionInputs.WorldSpacePosition: output.WorldSpacePosition = TransformObjectToWorld(input.positionOS);
$VertexDescriptionInputs.ViewSpacePosition: output.ViewSpacePosition = TransformWorldToView(output.WorldSpacePosition);
$VertexDescriptionInputs.TangentSpacePosition: output.TangentSpacePosition = float3(0.0f, 0.0f, 0.0f);
$VertexDescriptionInputs.WorldSpaceViewDirection: output.WorldSpaceViewDirection = GetWorldSpaceNormalizeViewDir(output.WorldSpacePosition);
$VertexDescriptionInputs.ObjectSpaceViewDirection: output.ObjectSpaceViewDirection = TransformWorldToObjectDir(output.WorldSpaceViewDirection);
$VertexDescriptionInputs.ViewSpaceViewDirection: output.ViewSpaceViewDirection = TransformWorldToViewDir(output.WorldSpaceViewDirection);
$VertexDescriptionInputs.TangentSpaceViewDirection: float3x3 tangentSpaceTransform = float3x3(output.WorldSpaceTangent,output.WorldSpaceBiTangent,output.WorldSpaceNormal);
$VertexDescriptionInputs.TangentSpaceViewDirection: output.TangentSpaceViewDirection = mul(tangentSpaceTransform, output.WorldSpaceViewDirection);
$VertexDescriptionInputs.ScreenPosition: output.ScreenPosition = ComputeScreenPos(TransformWorldToHClip(output.WorldSpacePosition), _ProjectionParams.x);
$VertexDescriptionInputs.uv0: output.uv0 = float4(input.uv0, 0.0f, 0.0f);
$VertexDescriptionInputs.uv1: output.uv1 = float4(input.uv1, 0.0f, 0.0f);
$VertexDescriptionInputs.uv2: output.uv2 = float4(input.uv2, 0.0f, 0.0f);
$VertexDescriptionInputs.uv3: output.uv3 = float4(input.uv3, 0.0f, 0.0f);
$VertexDescriptionInputs.VertexColor: output.VertexColor = input.color;
return output;
}
AttributesMesh ApplyMeshModification(AttributesMesh input)
{
// build graph inputs
VertexDescriptionInputs vertexDescriptionInputs = AttributesMeshToVertexDescriptionInputs(input);
// evaluate vertex graph
VertexDescription vertexDescription = VertexDescriptionFunction(vertexDescriptionInputs);
// copy graph output to the results
$VertexDescription.Position: input.positionOS = vertexDescription.Position;
return input;
}
#endif // HAVE_MESH_MODIFICATION
// TODO: Do we want to build include functionality for sharing these preprocessed functions across templates?
FragInputs BuildFragInputs(VaryingsMeshToPS input)
{
FragInputs output;

$SurfaceDescriptionInputs.ViewSpaceNormal: output.ViewSpaceNormal = mul(output.WorldSpaceNormal, (float3x3) UNITY_MATRIX_I_V); // transposed multiplication by inverse matrix to handle normal scale
$SurfaceDescriptionInputs.TangentSpaceNormal: output.TangentSpaceNormal = float3(0.0f, 0.0f, 1.0f);
$SurfaceDescriptionInputs.WorldSpaceTangent: output.WorldSpaceTangent = input.worldToTangent[0].xyz;
$SurfaceDescriptionInputs.WorldSpaceTangent: output.WorldSpaceTangent = input.worldToTangent[0].xyz;
$SurfaceDescriptionInputs.ObjectSpaceTangent: output.ObjectSpaceTangent = mul((float3x3) unity_WorldToObject, output.WorldSpaceTangent);
$SurfaceDescriptionInputs.ViewSpaceTangent: output.ViewSpaceTangent = mul((float3x3) UNITY_MATRIX_V, output.WorldSpaceTangent);
$SurfaceDescriptionInputs.TangentSpaceTangent: output.TangentSpaceTangent = float3(1.0f, 0.0f, 0.0f);

$SurfaceDescriptionInputs.TangentSpacePosition: output.TangentSpacePosition = float3(0.0f, 0.0f, 0.0f);
// TODO: positionSS is SV_Position, graph input expects screenPosition to be 0..1 across the active viewport (?)
$SurfaceDescriptionInputs.screenPosition: output.screenPosition = input.positionSS;
$SurfaceDescriptionInputs.ScreenPosition: output.ScreenPosition = ComputeScreenPos(TransformWorldToHClip(input.positionWS), _ProjectionParams.x);
$SurfaceDescriptionInputs.uv0: output.uv0 = float4(input.texCoord0, 0.0f, 0.0f);
$SurfaceDescriptionInputs.uv1: output.uv1 = float4(input.texCoord1, 0.0f, 0.0f);

$SurfaceDescriptionInputs.vertexColor: output.vertexColor = input.color;
$SurfaceDescriptionInputs.VertexColor: output.VertexColor = input.color;
$SurfaceDescriptionInputs.FaceSign: output.FaceSign = input.isFrontFace;
return output;
}

// Perform alpha test very early to save performance (a killed pixel will not sample textures)
// TODO: split graph evaluation to grab just alpha dependencies first? tricky..
#ifdef _ALPHATEST_ON
DoAlphaTest(surfaceDescription.Alpha, surfaceDescription.AlphaClipThreshold);
#endif
$AlphaTest: DoAlphaTest(surfaceDescription.Alpha, surfaceDescription.AlphaClipThreshold);
BuildSurfaceData(fragInputs, surfaceDescription, V, surfaceData);

// It is safe to call this function here as surfaceData have been filled
// We want to know if we must enable transmission on GI for SSS material, if the material have no SSS, this code will be remove by the compiler.
BSDFData bsdfData = ConvertSurfaceDataToBSDFData(surfaceData);
BSDFData bsdfData = ConvertSurfaceDataToBSDFData(posInput.positionSS.xy, surfaceData);
if (HasFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_TRANSMISSION))
{
// For now simply recall the function with inverted normal, the compiler should be able to optimize the lightmap case to not resample the directional lightmap

342
com.unity.render-pipelines.high-definition/HDRP/Editor/ShaderGraph/HDPBRSubShader.cs


using System.Collections.Generic;
using System.Collections;
using System.IO;
using System.Linq;
using UnityEditor.Graphing;

PBRMasterNode.AlphaSlotId,
PBRMasterNode.AlphaThresholdSlotId
},
VertexShaderSlots = new List<int>()
{
PBRMasterNode.PositionSlotId
}
};
Pass m_PassGBufferWithPrepass = new Pass()

PBRMasterNode.AlphaSlotId,
PBRMasterNode.AlphaThresholdSlotId
},
VertexShaderSlots = new List<int>()
{
PBRMasterNode.PositionSlotId
}
};
Pass m_PassMETA = new Pass()

"AttributesMesh.uv1",
"AttributesMesh.color",
"AttributesMesh.uv2", // SHADERPASS_LIGHT_TRANSPORT always uses uv2
// "FragInputs.worldToTangent",
// "FragInputs.positionWS",
},
PixelShaderSlots = new List<int>()
{

PBRMasterNode.OcclusionSlotId,
PBRMasterNode.AlphaSlotId,
PBRMasterNode.AlphaThresholdSlotId
}
},
// VertexShaderSlots = new List<int>()
// {
// PBRMasterNode.PositionSlotId
// }
};
Pass m_PassShadowCaster = new Pass()

{
PBRMasterNode.AlphaSlotId,
PBRMasterNode.AlphaThresholdSlotId
},
VertexShaderSlots = new List<int>()
{
PBRMasterNode.PositionSlotId
}
};

{
PBRMasterNode.AlphaSlotId,
PBRMasterNode.AlphaThresholdSlotId
},
VertexShaderSlots = new List<int>()
{
PBRMasterNode.PositionSlotId
}
};

{
"FragInputs.positionWS",
},
PixelShaderSlots = new List<int>()
{
PBRMasterNode.AlphaSlotId,
PBRMasterNode.AlphaThresholdSlotId
},
StencilOverride = new List<string>()
{
"// If velocity pass (motion vectors) is enabled we tag the stencil so it don't perform CameraMotionVelocity",

" Comp Always",
" Pass Replace",
"}"
}
},
PixelShaderSlots = new List<int>()
{
PBRMasterNode.AlphaSlotId,
PBRMasterNode.AlphaThresholdSlotId
},
VertexShaderSlots = new List<int>()
{
PBRMasterNode.PositionSlotId
},
};
Pass m_PassDistortion = new Pass()

{
PBRMasterNode.AlphaSlotId,
PBRMasterNode.AlphaThresholdSlotId
}
},
VertexShaderSlots = new List<int>()
{
PBRMasterNode.PositionSlotId
},
};
Pass m_PassTransparentDepthPrepass = new Pass()

{
PBRMasterNode.AlphaSlotId,
PBRMasterNode.AlphaThresholdSlotId
}
},
VertexShaderSlots = new List<int>()
{
PBRMasterNode.PositionSlotId
},
};
Pass m_PassTransparentBackface = new Pass()

PBRMasterNode.OcclusionSlotId,
PBRMasterNode.AlphaSlotId,
PBRMasterNode.AlphaThresholdSlotId
}
},
VertexShaderSlots = new List<int>()
{
PBRMasterNode.PositionSlotId
},
};
Pass m_PassForward = new Pass()

PBRMasterNode.OcclusionSlotId,
PBRMasterNode.AlphaSlotId,
PBRMasterNode.AlphaThresholdSlotId
}
},
VertexShaderSlots = new List<int>()
{
PBRMasterNode.PositionSlotId
},
};
Pass m_PassTransparentDepthPostpass = new Pass()

{
PBRMasterNode.AlphaSlotId,
PBRMasterNode.AlphaThresholdSlotId
}
},
VertexShaderSlots = new List<int>()
{
PBRMasterNode.PositionSlotId
},
private static string GetVariantDefines(PBRMasterNode masterNode)
private static HashSet<string> GetActiveFieldsFromMasterNode(INode iMasterNode, Pass pass)
ShaderGenerator defines = new ShaderGenerator();
HashSet<string> activeFields = new HashSet<string>();
PBRMasterNode masterNode = iMasterNode as PBRMasterNode;
if (masterNode == null)
{
return activeFields;
}
// TODO:
// _MATERIAL_FEATURE_SUBSURFACE_SCATTERING
// _MATERIAL_FEATURE_TRANSMISSION
// _MATERIAL_FEATURE_ANISOTROPY
// _MATERIAL_FEATURE_CLEAR_COAT
// _MATERIAL_FEATURE_IRIDESCENCE
if (masterNode.twoSided.isOn)
{
activeFields.Add("DoubleSided");
if (pass.ShaderPassName != "SHADERPASS_VELOCITY") // HACK to get around lack of a good interpolator dependency system
{ // we need to be able to build interpolators using multiple input structs
// also: should only require isFrontFace if Normals are required...
activeFields.Add("DoubleSided.Mirror"); // TODO: change this depending on what kind of normal flip you want..
activeFields.Add("FragInputs.isFrontFace"); // will need this for determining normal flip mode
}
}
switch (masterNode.model)
{

defines.AddShaderChunk("#define _MATERIAL_FEATURE_SPECULAR_COLOR 1", true);
activeFields.Add("Material.SpecularColor");
break;
default:
// TODO: error!

// #pragma shader_feature _ALPHATEST_ON
defines.AddShaderChunk("#define _ALPHATEST_ON 1", true);
activeFields.Add("AlphaTest");
}
// if (kTesselationMode != TessellationMode.None)

// #pragma shader_feature _ _MAPPING_PLANAR _MAPPING_TRIPLANAR // MOVE to a node
// #pragma shader_feature _NORMALMAP_TANGENT_SPACE
// #pragma shader_feature _ _REQUIRE_UV2 _REQUIRE_UV3
//
// #pragma shader_feature _NORMALMAP
if (masterNode.IsSlotConnected(PBRMasterNode.NormalSlotId))
{
defines.AddShaderChunk("#define _NORMALMAP 1", true);
}
// #pragma shader_feature _MASKMAP
// #pragma shader_feature _BENTNORMALMAP

// #pragma shader_feature _TANGENTMAP
// #pragma shader_feature _ANISOTROPYMAP
// #pragma shader_feature _DETAIL_MAP // MOVE to a node
// #pragma shader_feature _SUBSURFACE_RADIUS_MAP
// #pragma shader_feature _THICKNESSMAP
// #pragma shader_feature _SPECULARCOLORMAP

if (masterNode.surfaceType != SurfaceType.Opaque)
{
// transparent-only defines
defines.AddShaderChunk("#define _SURFACE_TYPE_TRANSPARENT 1", true);
activeFields.Add("SurfaceType.Transparent");
defines.AddShaderChunk("#define _BLENDMODE_ALPHA 1", true);
activeFields.Add("BlendMode.Alpha");
defines.AddShaderChunk("#define _BLENDMODE_ADD 1", true);
activeFields.Add("BlendMode.Add");
}
// else if (masterNode.alphaMode == PBRMasterNode.AlphaMode.PremultiplyAlpha) // TODO
// {

{
// opaque-only defines
}
// MaterialId are used as shader feature to allow compiler to optimize properly
// Note _MATID_STANDARD is not define as there is always the default case "_". We assign default as _MATID_STANDARD, so we never test _MATID_STANDARD
// #pragma shader_feature _ _MATID_SSS _MATID_ANISO _MATID_SPECULAR _MATID_CLEARCOAT
// enable dithering LOD crossfade
// #pragma multi_compile _ LOD_FADE_CROSSFADE

return defines.GetShaderString(2);
return activeFields;
private static bool GenerateShaderPass(PBRMasterNode masterNode, Pass pass, GenerationMode mode, SurfaceMaterialOptions materialOptions, ShaderGenerator result, List<string> sourceAssetDependencyPaths)
private static bool GenerateShaderPassLit(AbstractMaterialNode masterNode, Pass pass, GenerationMode mode, SurfaceMaterialOptions materialOptions, ShaderGenerator result, List<string> sourceAssetDependencyPaths)
{
var templateLocation = Path.Combine(Path.Combine(Path.Combine(HDEditorUtils.GetHDRenderPipelinePath(), "Editor"), "ShaderGraph"), pass.TemplateName);
if (!File.Exists(templateLocation))

if (sourceAssetDependencyPaths != null)
sourceAssetDependencyPaths.Add(templateLocation);
// grab all of the active nodes
var activeNodeList = ListPool<INode>.Get();
NodeUtils.DepthFirstCollectNodesFromNode(activeNodeList, masterNode, NodeUtils.IncludeSelf.Include, pass.PixelShaderSlots);
// grab all of the active nodes (for pixel and vertex graphs)
var vertexNodes = ListPool<INode>.Get();
NodeUtils.DepthFirstCollectNodesFromNode(vertexNodes, masterNode, NodeUtils.IncludeSelf.Include, pass.VertexShaderSlots);
var pixelNodes = ListPool<INode>.Get();
NodeUtils.DepthFirstCollectNodesFromNode(pixelNodes, masterNode, NodeUtils.IncludeSelf.Include, pass.PixelShaderSlots);
var graphRequirements = ShaderGraphRequirements.FromNodes(activeNodeList, ShaderStageCapability.Fragment);
var pixelRequirements = ShaderGraphRequirements.FromNodes(pixelNodes, ShaderStageCapability.Fragment, false); // TODO: is ShaderStageCapability.Fragment correct?
var vertexRequirements = ShaderGraphRequirements.FromNodes(vertexNodes, ShaderStageCapability.Vertex, false);
// Function Registry tracks functions to remove duplicates, it wraps a string builder that stores the combined function string
// TODO: this can be a shared function for all HDRP master nodes -- From here through GraphUtil.GenerateSurfaceDescription(..)
// TODO: this can be a shared function -- From here through GraphUtil.GenerateSurfaceDescription(..)
var activeSlots = new List<MaterialSlot>();
foreach (var id in pass.PixelShaderSlots)
{
MaterialSlot slot = masterNode.FindSlot<MaterialSlot>(id);
if (slot != null)
{
activeSlots.Add(slot);
}
}
var pixelSlots = HDSubShaderUtilities.FindMaterialSlotsOnNode(pass.PixelShaderSlots, masterNode);
var vertexSlots = HDSubShaderUtilities.FindMaterialSlotsOnNode(pass.VertexShaderSlots, masterNode);
// properties used by either pixel and vertex shader
PropertyCollector sharedProperties = new PropertyCollector();
string graphInputStructName = "SurfaceDescriptionInputs";
string graphOutputStructName = "SurfaceDescription";
string graphEvalFunctionName = "SurfaceDescriptionFunction";
ShaderStringBuilder graphEvalFunction = new ShaderStringBuilder();
ShaderStringBuilder graphOutputs = new ShaderStringBuilder();
PropertyCollector graphProperties = new PropertyCollector();
string pixelGraphInputStructName = "SurfaceDescriptionInputs";
string pixelGraphOutputStructName = "SurfaceDescription";
string pixelGraphEvalFunctionName = "SurfaceDescriptionFunction";
ShaderStringBuilder pixelGraphEvalFunction = new ShaderStringBuilder();
ShaderStringBuilder pixelGraphOutputs = new ShaderStringBuilder();
// dependency tracker -- set of active fields
HashSet<string> activeFields = GetActiveFieldsFromMasterNode(masterNode, pass);
// build initial requirements
HDRPShaderStructs.AddActiveFieldsFromPixelGraphRequirements(activeFields, pixelRequirements);
HashSet<string> activeFields = new HashSet<string>();
GraphUtil.GenerateSurfaceDescriptionStruct(graphOutputs, activeSlots, true);
//GraphUtil.GenerateSurfaceDescriptionStruct(graphOutputs, activeSlots, true, graphOutputStructName, activeFields);
GraphUtil.GenerateSurfaceDescriptionStruct(pixelGraphOutputs, pixelSlots, true, pixelGraphOutputStructName, activeFields);
activeNodeList,
pixelNodes,
graphEvalFunction,
pixelGraphEvalFunction,
graphProperties,
graphRequirements, // TODO : REMOVE UNUSED
sharedProperties,
pixelRequirements, // TODO : REMOVE UNUSED
graphEvalFunctionName,
graphOutputStructName,
pixelGraphEvalFunctionName,
pixelGraphOutputStructName,
activeSlots,
graphInputStructName);
pixelSlots,
pixelGraphInputStructName);
string vertexGraphInputStructName = "VertexDescriptionInputs";
string vertexGraphOutputStructName = "VertexDescription";
string vertexGraphEvalFunctionName = "VertexDescriptionFunction";
ShaderStringBuilder vertexGraphEvalFunction = new ShaderStringBuilder();
ShaderStringBuilder vertexGraphOutputs = new ShaderStringBuilder();
// check for vertex animation -- enables HAVE_VERTEX_MODIFICATION
bool vertexActive = false;
if (masterNode.IsSlotConnected(PBRMasterNode.PositionSlotId))
{
vertexActive = true;
activeFields.Add("features.modifyMesh");
HDRPShaderStructs.AddActiveFieldsFromVertexGraphRequirements(activeFields, vertexRequirements);
// -------------------------------------
// Generate Output structure for Vertex Description function
GraphUtil.GenerateVertexDescriptionStruct(vertexGraphOutputs, vertexSlots, vertexGraphOutputStructName, activeFields);
// -------------------------------------
// Generate Vertex Description function
GraphUtil.GenerateVertexDescriptionFunction(
masterNode.owner as AbstractMaterialGraph,
vertexGraphEvalFunction,
functionRegistry,
sharedProperties,
mode,
vertexNodes,
vertexSlots,
vertexGraphInputStructName,
vertexGraphEvalFunctionName,
vertexGraphOutputStructName);
}
var blendCode = new ShaderStringBuilder();
var cullCode = new ShaderStringBuilder();

var colorMaskCode = new ShaderStringBuilder();
HDSubShaderUtilities.BuildRenderStatesFromPassAndMaterialOptions(pass, materialOptions, blendCode, cullCode, zTestCode, zWriteCode, stencilCode, colorMaskCode);
if (masterNode.twoSided.isOn)
{
activeFields.Add("DoubleSided");
if (pass.ShaderPassName != "SHADERPASS_VELOCITY") // HACK to get around lack of a good interpolator dependency system
{ // we need to be able to build interpolators using multiple input structs
// also: should only require isFrontFace if Normals are required...
activeFields.Add("DoubleSided.Mirror"); // TODO: change this depending on what kind of normal flip you want..
activeFields.Add("FragInputs.isFrontFace"); // will need this for determining normal flip mode
}
}
HDRPShaderStructs.AddRequiredFields(pass.RequiredFields, activeFields);
if (pass.PixelShaderSlots != null)
{
foreach (var slotId in pass.PixelShaderSlots)
{
var slot = masterNode.FindSlot<MaterialSlot>(slotId);
if (slot != null)
{
var rawSlotName = slot.RawDisplayName().ToString();
var descriptionVar = string.Format("{0}.{1}", graphOutputStructName, rawSlotName);
activeFields.Add(descriptionVar);
}
}
}
// apply dependencies to the active fields, and build interpolators (TODO: split this function)
var graphInputs = new ShaderGenerator();
graphInputs,
graphRequirements,
pass.RequiredFields,
CoordinateSpace.World,
activeFields);
// debug output all active fields

}
}
// build graph inputs structures
ShaderGenerator pixelGraphInputs = new ShaderGenerator();
ShaderSpliceUtil.BuildType(typeof(HDRPShaderStructs.SurfaceDescriptionInputs), activeFields, pixelGraphInputs);
ShaderGenerator vertexGraphInputs = new ShaderGenerator();
ShaderSpliceUtil.BuildType(typeof(HDRPShaderStructs.VertexDescriptionInputs), activeFields, vertexGraphInputs);
ShaderGenerator defines = new ShaderGenerator();
{
defines.AddShaderChunk(string.Format("#define SHADERPASS {0}", pass.ShaderPassName), true);

// build graph code
var graph = new ShaderGenerator();
graph.AddShaderChunk("// Graph Inputs");
graph.Indent();
graph.AddGenerator(graphInputs);
graph.Deindent();
graph.AddShaderChunk("// Graph Outputs");
graph.Indent();
graph.AddShaderChunk(graphOutputs.ToString());
//graph.AddGenerator(graphOutputs);
graph.Deindent();
graph.AddShaderChunk("// Graph Properties (uniform inputs)");
graph.AddShaderChunk(graphProperties.GetPropertiesDeclaration(1));
graph.AddShaderChunk("// Graph Node Functions");
graph.AddShaderChunk(graphNodeFunctions.ToString());
graph.AddShaderChunk("// Graph Evaluation");
graph.Indent();
graph.AddShaderChunk(graphEvalFunction.ToString());
//graph.AddGenerator(graphEvalFunction);
graph.Deindent();
{
graph.AddShaderChunk("// Shared Graph Properties (uniform inputs)");
graph.AddShaderChunk(sharedProperties.GetPropertiesDeclaration(1));
if (vertexActive)
{
graph.AddShaderChunk("// Vertex Graph Inputs");
graph.Indent();
graph.AddGenerator(vertexGraphInputs);
graph.Deindent();
graph.AddShaderChunk("// Vertex Graph Outputs");
graph.Indent();
graph.AddShaderChunk(vertexGraphOutputs.ToString());
graph.Deindent();
}
graph.AddShaderChunk("// Pixel Graph Inputs");
graph.Indent();
graph.AddGenerator(pixelGraphInputs);
graph.Deindent();
graph.AddShaderChunk("// Pixel Graph Outputs");
graph.Indent();
graph.AddShaderChunk(pixelGraphOutputs.ToString());
graph.Deindent();
graph.AddShaderChunk("// Shared Graph Node Functions");
graph.AddShaderChunk(graphNodeFunctions.ToString());
if (vertexActive)
{
graph.AddShaderChunk("// Vertex Graph Evaluation");
graph.Indent();
graph.AddShaderChunk(vertexGraphEvalFunction.ToString());
graph.Deindent();
}
graph.AddShaderChunk("// Pixel Graph Evaluation");
graph.Indent();
graph.AddShaderChunk(pixelGraphEvalFunction.ToString());
graph.Deindent();
}
// build the hash table of all named fragments TODO: could make this Dictionary<string, ShaderGenerator / string> ?
Dictionary<string, string> namedFragments = new Dictionary<string, string>();

namedFragments.Add("${Stencil}", stencilCode.ToString());
namedFragments.Add("${ColorMask}", colorMaskCode.ToString());
namedFragments.Add("${LOD}", materialOptions.lod.ToString());
namedFragments.Add("${VariantDefines}", GetVariantDefines(masterNode));
// process the template to generate the shader code for this pass TODO: could make this a shared function
string[] templateLines = File.ReadAllLines(templateLocation);

if (opaque)
{
GenerateShaderPass(masterNode, m_PassGBuffer, mode, materialOptions, subShader, sourceAssetDependencyPaths);
GenerateShaderPass(masterNode, m_PassGBufferWithPrepass, mode, materialOptions, subShader, sourceAssetDependencyPaths);
GenerateShaderPassLit(masterNode, m_PassGBuffer, mode, materialOptions, subShader, sourceAssetDependencyPaths);
GenerateShaderPassLit(masterNode, m_PassGBufferWithPrepass, mode, materialOptions, subShader, sourceAssetDependencyPaths);
GenerateShaderPass(masterNode, m_PassMETA, mode, materialOptions, subShader, sourceAssetDependencyPaths);
GenerateShaderPass(masterNode, m_PassShadowCaster, mode, materialOptions, subShader, sourceAssetDependencyPaths);
GenerateShaderPassLit(masterNode, m_PassMETA, mode, materialOptions, subShader, sourceAssetDependencyPaths);
GenerateShaderPassLit(masterNode, m_PassShadowCaster, mode, materialOptions, subShader, sourceAssetDependencyPaths);
GenerateShaderPass(masterNode, m_PassDepthOnly, mode, materialOptions, subShader, sourceAssetDependencyPaths);
GenerateShaderPass(masterNode, m_PassMotionVectors, mode, materialOptions, subShader, sourceAssetDependencyPaths);
GenerateShaderPassLit(masterNode, m_PassDepthOnly, mode, materialOptions, subShader, sourceAssetDependencyPaths);
GenerateShaderPassLit(masterNode, m_PassMotionVectors, mode, materialOptions, subShader, sourceAssetDependencyPaths);
GenerateShaderPass(masterNode, m_PassDistortion, mode, materialOptions, subShader, sourceAssetDependencyPaths);
GenerateShaderPassLit(masterNode, m_PassDistortion, mode, materialOptions, subShader, sourceAssetDependencyPaths);
GenerateShaderPass(masterNode, m_PassTransparentDepthPrepass, mode, materialOptions, subShader, sourceAssetDependencyPaths);
GenerateShaderPassLit(masterNode, m_PassTransparentDepthPrepass, mode, materialOptions, subShader, sourceAssetDependencyPaths);
GenerateShaderPass(masterNode, m_PassTransparentBackface, mode, materialOptions, subShader, sourceAssetDependencyPaths);
GenerateShaderPassLit(masterNode, m_PassTransparentBackface, mode, materialOptions, subShader, sourceAssetDependencyPaths);
GenerateShaderPass(masterNode, m_PassForward, mode, materialOptions, subShader, sourceAssetDependencyPaths);
GenerateShaderPassLit(masterNode, m_PassForward, mode, materialOptions, subShader, sourceAssetDependencyPaths);
GenerateShaderPass(masterNode, m_PassTransparentDepthPostpass, mode, materialOptions, subShader, sourceAssetDependencyPaths);
GenerateShaderPassLit(masterNode, m_PassTransparentDepthPostpass, mode, materialOptions, subShader, sourceAssetDependencyPaths);
}
}
subShader.Deindent();

226
com.unity.render-pipelines.high-definition/HDRP/Editor/ShaderGraph/HDSubShaderUtilities.cs


};
};
struct SurfaceDescriptionInputs
// this describes the input to the pixel shader graph eval
public struct SurfaceDescriptionInputs
{
[Optional] Vector3 ObjectSpaceNormal;
[Optional] Vector3 ViewSpaceNormal;

[Optional] Vector3 WorldSpacePosition;
[Optional] Vector3 TangentSpacePosition;
[Optional] Vector4 screenPosition;
[Optional] Vector4 ScreenPosition;
[Optional] Vector4 vertexColor;
[Optional] Vector4 VertexColor;
[Optional] float FaceSign;
public static Dependency[] dependencies = new Dependency[]
{

new Dependency("SurfaceDescriptionInputs.TangentSpaceViewDirection", "SurfaceDescriptionInputs.WorldSpaceBiTangent"),
new Dependency("SurfaceDescriptionInputs.TangentSpaceViewDirection", "SurfaceDescriptionInputs.WorldSpaceNormal"),
new Dependency("SurfaceDescriptionInputs.screenPosition", "FragInputs.positionSS"),
new Dependency("SurfaceDescriptionInputs.ScreenPosition", "SurfaceDescriptionInputs.WorldSpacePosition"),
new Dependency("SurfaceDescriptionInputs.vertexColor", "FragInputs.color"),
new Dependency("SurfaceDescriptionInputs.VertexColor", "FragInputs.color"),
new Dependency("SurfaceDescriptionInputs.FaceSign", "FragInputs.isFrontFace"),
};
};
// this describes the input to the pixel shader graph eval
public struct VertexDescriptionInputs
{
[Optional] Vector3 ObjectSpaceNormal;
[Optional] Vector3 ViewSpaceNormal;
[Optional] Vector3 WorldSpaceNormal;
[Optional] Vector3 TangentSpaceNormal;
[Optional] Vector3 ObjectSpaceTangent;
[Optional] Vector3 ViewSpaceTangent;
[Optional] Vector3 WorldSpaceTangent;
[Optional] Vector3 TangentSpaceTangent;
[Optional] Vector3 ObjectSpaceBiTangent;
[Optional] Vector3 ViewSpaceBiTangent;
[Optional] Vector3 WorldSpaceBiTangent;
[Optional] Vector3 TangentSpaceBiTangent;
[Optional] Vector3 ObjectSpaceViewDirection;
[Optional] Vector3 ViewSpaceViewDirection;
[Optional] Vector3 WorldSpaceViewDirection;
[Optional] Vector3 TangentSpaceViewDirection;
[Optional] Vector3 ObjectSpacePosition;
[Optional] Vector3 ViewSpacePosition;
[Optional] Vector3 WorldSpacePosition;
[Optional] Vector3 TangentSpacePosition;
[Optional] Vector4 ScreenPosition;
[Optional] Vector4 uv0;
[Optional] Vector4 uv1;
[Optional] Vector4 uv2;
[Optional] Vector4 uv3;
[Optional] Vector4 VertexColor;
public static Dependency[] dependencies = new Dependency[]
{ // TODO: NOCHECKIN: these dependencies are not correct for vertex pass
new Dependency("VertexDescriptionInputs.ObjectSpaceNormal", "AttributesMesh.normalOS"),
new Dependency("VertexDescriptionInputs.WorldSpaceNormal", "AttributesMesh.normalOS"),
new Dependency("VertexDescriptionInputs.ViewSpaceNormal", "VertexDescriptionInputs.WorldSpaceNormal"),
new Dependency("VertexDescriptionInputs.ObjectSpaceTangent", "AttributesMesh.tangentOS"),
new Dependency("VertexDescriptionInputs.WorldSpaceTangent", "AttributesMesh.tangentOS"),
new Dependency("VertexDescriptionInputs.ViewSpaceTangent", "VertexDescriptionInputs.WorldSpaceTangent"),
new Dependency("VertexDescriptionInputs.ObjectSpaceBiTangent", "AttributesMesh.normalOS"),
new Dependency("VertexDescriptionInputs.ObjectSpaceBiTangent", "AttributesMesh.tangentOS"),
new Dependency("VertexDescriptionInputs.WorldSpaceBiTangent", "VertexDescriptionInputs.ObjectSpaceBiTangent"),
new Dependency("VertexDescriptionInputs.ViewSpaceBiTangent", "VertexDescriptionInputs.WorldSpaceBiTangent"),
new Dependency("VertexDescriptionInputs.ObjectSpacePosition", "AttributesMesh.positionOS"),
new Dependency("VertexDescriptionInputs.WorldSpacePosition", "AttributesMesh.positionOS"),
new Dependency("VertexDescriptionInputs.ViewSpacePosition", "VertexDescriptionInputs.WorldSpacePosition"),
new Dependency("VertexDescriptionInputs.WorldSpaceViewDirection", "VertexDescriptionInputs.WorldSpacePosition"),
new Dependency("VertexDescriptionInputs.ObjectSpaceViewDirection", "VertexDescriptionInputs.WorldSpaceViewDirection"),
new Dependency("VertexDescriptionInputs.ViewSpaceViewDirection", "VertexDescriptionInputs.WorldSpaceViewDirection"),
new Dependency("VertexDescriptionInputs.TangentSpaceViewDirection", "VertexDescriptionInputs.WorldSpaceViewDirection"),
new Dependency("VertexDescriptionInputs.TangentSpaceViewDirection", "VertexDescriptionInputs.WorldSpaceTangent"),
new Dependency("VertexDescriptionInputs.TangentSpaceViewDirection", "VertexDescriptionInputs.WorldSpaceBiTangent"),
new Dependency("VertexDescriptionInputs.TangentSpaceViewDirection", "VertexDescriptionInputs.WorldSpaceNormal"),
new Dependency("VertexDescriptionInputs.ScreenPosition", "VertexDescriptionInputs.WorldSpacePosition"),
new Dependency("VertexDescriptionInputs.uv0", "AttributesMesh.uv0"),
new Dependency("VertexDescriptionInputs.uv1", "AttributesMesh.uv1"),
new Dependency("VertexDescriptionInputs.uv2", "AttributesMesh.uv2"),
new Dependency("VertexDescriptionInputs.uv3", "AttributesMesh.uv3"),
new Dependency("VertexDescriptionInputs.VertexColor", "AttributesMesh.color"),
static void AddActiveFieldsFromGraphRequirements(HashSet<string> activeFields, ShaderGraphRequirements requirements)
// TODO: move this out of HDRPShaderStructs
static public void AddActiveFieldsFromVertexGraphRequirements(HashSet<string> activeFields, ShaderGraphRequirements requirements)
activeFields.Add("SurfaceDescriptionInputs.screenPosition");
activeFields.Add("VertexDescriptionInputs.ScreenPosition");
activeFields.Add("SurfaceDescriptionInputs.vertexColor");
activeFields.Add("VertexDescriptionInputs.VertexColor");
}
if (requirements.requiresNormal != 0)
{
if ((requirements.requiresNormal & NeededCoordinateSpace.Object) > 0)
activeFields.Add("VertexDescriptionInputs.ObjectSpaceNormal");
if ((requirements.requiresNormal & NeededCoordinateSpace.View) > 0)
activeFields.Add("VertexDescriptionInputs.ViewSpaceNormal");
if ((requirements.requiresNormal & NeededCoordinateSpace.World) > 0)
activeFields.Add("VertexDescriptionInputs.WorldSpaceNormal");
if ((requirements.requiresNormal & NeededCoordinateSpace.Tangent) > 0)
activeFields.Add("VertexDescriptionInputs.TangentSpaceNormal");
}
if (requirements.requiresTangent != 0)
{
if ((requirements.requiresTangent & NeededCoordinateSpace.Object) > 0)
activeFields.Add("VertexDescriptionInputs.ObjectSpaceTangent");
if ((requirements.requiresTangent & NeededCoordinateSpace.View) > 0)
activeFields.Add("VertexDescriptionInputs.ViewSpaceTangent");
if ((requirements.requiresTangent & NeededCoordinateSpace.World) > 0)
activeFields.Add("VertexDescriptionInputs.WorldSpaceTangent");
if ((requirements.requiresTangent & NeededCoordinateSpace.Tangent) > 0)
activeFields.Add("VertexDescriptionInputs.TangentSpaceTangent");
}
if (requirements.requiresBitangent != 0)
{
if ((requirements.requiresBitangent & NeededCoordinateSpace.Object) > 0)
activeFields.Add("VertexDescriptionInputs.ObjectSpaceBiTangent");
if ((requirements.requiresBitangent & NeededCoordinateSpace.View) > 0)
activeFields.Add("VertexDescriptionInputs.ViewSpaceBiTangent");
if ((requirements.requiresBitangent & NeededCoordinateSpace.World) > 0)
activeFields.Add("VertexDescriptionInputs.WorldSpaceBiTangent");
if ((requirements.requiresBitangent & NeededCoordinateSpace.Tangent) > 0)
activeFields.Add("VertexDescriptionInputs.TangentSpaceBiTangent");
}
if (requirements.requiresViewDir != 0)
{
if ((requirements.requiresViewDir & NeededCoordinateSpace.Object) > 0)
activeFields.Add("VertexDescriptionInputs.ObjectSpaceViewDirection");
if ((requirements.requiresViewDir & NeededCoordinateSpace.View) > 0)
activeFields.Add("VertexDescriptionInputs.ViewSpaceViewDirection");
if ((requirements.requiresViewDir & NeededCoordinateSpace.World) > 0)
activeFields.Add("VertexDescriptionInputs.WorldSpaceViewDirection");
if ((requirements.requiresViewDir & NeededCoordinateSpace.Tangent) > 0)
activeFields.Add("VertexDescriptionInputs.TangentSpaceViewDirection");
}
if (requirements.requiresPosition != 0)
{
if ((requirements.requiresPosition & NeededCoordinateSpace.Object) > 0)
activeFields.Add("VertexDescriptionInputs.ObjectSpacePosition");
if ((requirements.requiresPosition & NeededCoordinateSpace.View) > 0)
activeFields.Add("VertexDescriptionInputs.ViewSpacePosition");
if ((requirements.requiresPosition & NeededCoordinateSpace.World) > 0)
activeFields.Add("VertexDescriptionInputs.WorldSpacePosition");
if ((requirements.requiresPosition & NeededCoordinateSpace.Tangent) > 0)
activeFields.Add("VertexDescriptionInputs.TangentSpacePosition");
}
foreach (var channel in requirements.requiresMeshUVs.Distinct())
{
activeFields.Add("VertexDescriptionInputs." + channel.GetUVName());
}
}
// TODO: move this out of HDRPShaderStructs
static public void AddActiveFieldsFromPixelGraphRequirements(HashSet<string> activeFields, ShaderGraphRequirements requirements)
{
if (requirements.requiresScreenPosition)
{
activeFields.Add("SurfaceDescriptionInputs.ScreenPosition");
}
if (requirements.requiresVertexColor)
{
activeFields.Add("SurfaceDescriptionInputs.VertexColor");
}
if (requirements.requiresFaceSign)
{
activeFields.Add("SurfaceDescriptionInputs.FaceSign");
}
if (requirements.requiresNormal != 0)

}
}
// TODO : split this function into buildActiveFields and buildHLSLTypeDeclaration functions
public static void Generate(
ShaderGenerator codeResult,
ShaderGenerator graphInputsResult,
ShaderGraphRequirements graphRequirements,
public static void AddRequiredFields(
CoordinateSpace preferedCoordinateSpace,
if (preferedCoordinateSpace == CoordinateSpace.Tangent)
preferedCoordinateSpace = CoordinateSpace.World;
// build initial requirements
AddActiveFieldsFromGraphRequirements(activeFields, graphRequirements);
if (passRequiredFields != null)
{
foreach (var requiredField in passRequiredFields)

}
}
public static void Generate(
ShaderGenerator codeResult,
HashSet<string> activeFields)
{
// propagate requirements using dependencies
{
ShaderSpliceUtil.ApplyDependencies(

FragInputs.dependencies,
VaryingsMeshToPS.standardDependencies,
SurfaceDescriptionInputs.dependencies,
VertexDescriptionInputs.dependencies
});
}

ShaderSpliceUtil.BuildType(typeof(VaryingsMeshToDS), activeFields, codeResult);
ShaderSpliceUtil.BuildPackedType(typeof(VaryingsMeshToPS), activeFields, codeResult);
ShaderSpliceUtil.BuildPackedType(typeof(VaryingsMeshToDS), activeFields, codeResult);
ShaderSpliceUtil.BuildType(typeof(SurfaceDescriptionInputs), activeFields, graphInputsResult);
}
};

public static class HDSubShaderUtilities
{
public static List<MaterialSlot> FindMaterialSlotsOnNode(IEnumerable<int> slots, AbstractMaterialNode node)
{
var activeSlots = new List<MaterialSlot>();
if (slots != null)
{
foreach (var id in slots)
{
MaterialSlot slot = node.FindSlot<MaterialSlot>(id);
if (slot != null)
{
activeSlots.Add(slot);
}
}
}
return activeSlots;
}
public static void BuildRenderStatesFromPassAndMaterialOptions(
Pass pass,
SurfaceMaterialOptions materialOptions,

79
com.unity.render-pipelines.high-definition/HDRP/Editor/ShaderGraph/HDUnlitPassForward.template


#define UNITY_MATERIAL_UNLIT // Need to be define before including Material.hlsl
#include "CoreRP/ShaderLibrary/Common.hlsl"
// #include "CoreRP/ShaderLibrary/Wind.hlsl"
#include "CoreRP/ShaderLibrary/Wind.hlsl"
#include "ShaderGraphLibrary/Functions.hlsl"

$VaryingsMeshToPS.texCoord3: #define VARYINGS_NEED_TEXCOORD3
$VaryingsMeshToPS.color: #define VARYINGS_NEED_COLOR
$VaryingsMeshToPS.cullFace: #define VARYINGS_NEED_CULLFACE
$features.modifyMesh: #define HAVE_MESH_MODIFICATION
#include "ShaderGraphLibrary/Functions.hlsl"
#include "HDRP/ShaderVariables.hlsl"
#ifdef DEBUG_DISPLAY
#include "HDRP/Debug/DebugDisplay.hlsl"

// End graph generated code
//-------------------------------------------------------------------------------------
// TODO: Do we want to build include functionality for sharing these preprocessed functions across templates?
#ifdef HAVE_MESH_MODIFICATION
// TODO: we should share this between template files somehow
VertexDescriptionInputs AttributesMeshToVertexDescriptionInputs(AttributesMesh input)
{
VertexDescriptionInputs output;
ZERO_INITIALIZE(VertexDescriptionInputs, output);
$VertexDescriptionInputs.ObjectSpaceNormal: output.ObjectSpaceNormal = input.normalOS;
$VertexDescriptionInputs.WorldSpaceNormal: output.WorldSpaceNormal = TransformObjectToWorldNormal(input.normalOS);
$VertexDescriptionInputs.ViewSpaceNormal: output.ViewSpaceNormal = TransformWorldToViewDir(output.WorldSpaceNormal);
$VertexDescriptionInputs.TangentSpaceNormal: output.TangentSpaceNormal = float3(0.0f, 0.0f, 1.0f);
$VertexDescriptionInputs.ObjectSpaceTangent: output.ObjectSpaceTangent = input.tangentOS;
$VertexDescriptionInputs.WorldSpaceTangent: output.WorldSpaceTangent = TransformObjectToWorldDir(input.tangentOS.xyz);
$VertexDescriptionInputs.ViewSpaceTangent: output.ViewSpaceTangent = TransformWorldToViewDir(output.WorldSpaceTangent);
$VertexDescriptionInputs.TangentSpaceTangent: output.TangentSpaceTangent = float3(1.0f, 0.0f, 0.0f);
$VertexDescriptionInputs.ObjectSpaceBiTangent: output.ObjectSpaceBiTangent = normalize(cross(input.normalOS, input.tangentOS) * (input.tangentOS.w > 0.0f ? 1.0f : -1.0f) * GetOddNegativeScale());
$VertexDescriptionInputs.WorldSpaceBiTangent: output.WorldSpaceBiTangent = TransformObjectToWorldDir(output.ObjectSpaceBiTangent);
$VertexDescriptionInputs.ViewSpaceBiTangent: output.ViewSpaceBiTangent = TransformWorldToViewDir(output.WorldSpaceBiTangent);
$VertexDescriptionInputs.TangentSpaceBiTangent: output.TangentSpaceBiTangent = float3(0.0f, 1.0f, 0.0f);
$VertexDescriptionInputs.ObjectSpacePosition: output.ObjectSpacePosition = input.positionOS;
$VertexDescriptionInputs.WorldSpacePosition: output.WorldSpacePosition = TransformObjectToWorld(input.positionOS);
$VertexDescriptionInputs.ViewSpacePosition: output.ViewSpacePosition = TransformWorldToView(output.WorldSpacePosition);
$VertexDescriptionInputs.TangentSpacePosition: output.TangentSpacePosition = float3(0.0f, 0.0f, 0.0f);
$VertexDescriptionInputs.WorldSpaceViewDirection: output.WorldSpaceViewDirection = GetWorldSpaceNormalizeViewDir(output.WorldSpacePosition);
$VertexDescriptionInputs.ObjectSpaceViewDirection: output.ObjectSpaceViewDirection = TransformWorldToObjectDir(output.WorldSpaceViewDirection);
$VertexDescriptionInputs.ViewSpaceViewDirection: output.ViewSpaceViewDirection = TransformWorldToViewDir(output.WorldSpaceViewDirection);
$VertexDescriptionInputs.TangentSpaceViewDirection: float3x3 tangentSpaceTransform = float3x3(output.WorldSpaceTangent,output.WorldSpaceBiTangent,output.WorldSpaceNormal);
$VertexDescriptionInputs.TangentSpaceViewDirection: output.TangentSpaceViewDirection = mul(tangentSpaceTransform, output.WorldSpaceViewDirection);
$VertexDescriptionInputs.ScreenPosition: output.ScreenPosition = ComputeScreenPos(TransformWorldToHClip(output.WorldSpacePosition), _ProjectionParams.x);
$VertexDescriptionInputs.uv0: output.uv0 = float4(input.uv0, 0.0f, 0.0f);
$VertexDescriptionInputs.uv1: output.uv1 = float4(input.uv1, 0.0f, 0.0f);
$VertexDescriptionInputs.uv2: output.uv2 = float4(input.uv2, 0.0f, 0.0f);
$VertexDescriptionInputs.uv3: output.uv3 = float4(input.uv3, 0.0f, 0.0f);
$VertexDescriptionInputs.VertexColor: output.VertexColor = input.color;
return output;
}
AttributesMesh ApplyMeshModification(AttributesMesh input)
{
// build graph inputs
VertexDescriptionInputs vertexDescriptionInputs = AttributesMeshToVertexDescriptionInputs(input);
// evaluate vertex graph
VertexDescription vertexDescription = VertexDescriptionFunction(vertexDescriptionInputs);
// copy graph output to the results
$VertexDescription.Position: input.positionOS = vertexDescription.Position;
return input;
}
#endif // HAVE_MESH_MODIFICATION
// TODO: Do we want to build include functionality for sharing these preprocessed functions across templates?
FragInputs BuildFragInputs(VaryingsMeshToPS input)
{
FragInputs output;

$SurfaceDescriptionInputs.ViewSpaceNormal: output.ViewSpaceNormal = mul(output.WorldSpaceNormal, (float3x3) UNITY_MATRIX_I_V); // transposed multiplication by inverse matrix to handle normal scale
$SurfaceDescriptionInputs.TangentSpaceNormal: output.TangentSpaceNormal = float3(0.0f, 0.0f, 1.0f);
$SurfaceDescriptionInputs.WorldSpaceTangent: output.WorldSpaceTangent = input.worldToTangent[0].xyz;
$SurfaceDescriptionInputs.WorldSpaceTangent: output.WorldSpaceTangent = input.worldToTangent[0].xyz;
$SurfaceDescriptionInputs.ObjectSpaceTangent: output.ObjectSpaceTangent = mul((float3x3) unity_WorldToObject, output.WorldSpaceTangent);
$SurfaceDescriptionInputs.ViewSpaceTangent: output.ViewSpaceTangent = mul((float3x3) UNITY_MATRIX_V, output.WorldSpaceTangent);
$SurfaceDescriptionInputs.TangentSpaceTangent: output.TangentSpaceTangent = float3(1.0f, 0.0f, 0.0f);

$SurfaceDescriptionInputs.TangentSpaceViewDirection: output.TangentSpaceViewDirection = mul(tangentSpaceTransform, output.WorldSpaceViewDirection);
// TODO: FragInputs.positionWS is badly named -- it's camera relative, not in world space
// we have to fix it up here to match graph input expectations
$SurfaceDescriptionInputs.WorldSpacePosition: output.WorldSpacePosition = input.positionWS + _WorldSpaceCameraPos;
$SurfaceDescriptionInputs.ObjectSpacePosition: output.ObjectSpacePosition = mul(unity_WorldToObject, float4(input.positionWS + _WorldSpaceCameraPos, 1.0f)).xyz;
$SurfaceDescriptionInputs.ViewSpacePosition: float4 posViewSpace = mul(UNITY_MATRIX_V, float4(input.positionWS, 1.0f));

$SurfaceDescriptionInputs.screenPosition: output.screenPosition = input.positionSS;
// TODO: positionSS is SV_Position, graph input expects screenPosition to be 0..1 across the active viewport (?)
$SurfaceDescriptionInputs.ScreenPosition: output.ScreenPosition = ComputeScreenPos(TransformWorldToHClip(input.positionWS), _ProjectionParams.x);
$SurfaceDescriptionInputs.uv0: output.uv0 = float4(input.texCoord0, 0.0f, 0.0f);
$SurfaceDescriptionInputs.uv1: output.uv1 = float4(input.texCoord1, 0.0f, 0.0f);

$SurfaceDescriptionInputs.vertexColor: output.vertexColor = input.color;
$SurfaceDescriptionInputs.VertexColor: output.VertexColor = input.color;
$SurfaceDescriptionInputs.FaceSign: output.FaceSign = input.isFrontFace;
return output;
}

// Perform alpha test very early to save performance (a killed pixel will not sample textures)
// TODO: split graph evaluation to grab just alpha dependencies first? tricky..
#ifdef _ALPHATEST_ON
DoAlphaTest(surfaceDescription.Alpha, surfaceDescription.AlphaClipThreshold);
#endif
$AlphaTest: DoAlphaTest(surfaceDescription.Alpha, surfaceDescription.AlphaClipThreshold);
BuildSurfaceData(fragInputs, surfaceDescription, V, surfaceData);

262
com.unity.render-pipelines.high-definition/HDRP/Editor/ShaderGraph/HDUnlitSubShader.cs


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace UnityEditor.Experimental.Rendering.HDPipeline
{
// [Serializable] ??
public class HDUnlitSubShader : IUnlitSubShader
{
Pass m_PassDepthOnly = new Pass()

{
UnlitMasterNode.AlphaSlotId,
UnlitMasterNode.AlphaThresholdSlotId
},
VertexShaderSlots = new List<int>()
{
PBRMasterNode.PositionSlotId
}
};

UnlitMasterNode.ColorSlotId,
UnlitMasterNode.AlphaSlotId,
UnlitMasterNode.AlphaThresholdSlotId
},
VertexShaderSlots = new List<int>()
{
PBRMasterNode.PositionSlotId
}
};

UnlitMasterNode.ColorSlotId,
UnlitMasterNode.AlphaSlotId,
UnlitMasterNode.AlphaThresholdSlotId
},
VertexShaderSlots = new List<int>()
{
PBRMasterNode.PositionSlotId
}
};

{
PBRMasterNode.AlphaSlotId,
PBRMasterNode.AlphaThresholdSlotId
}
},
VertexShaderSlots = new List<int>()
{
PBRMasterNode.PositionSlotId
},
private static string GetVariantDefines(UnlitMasterNode masterNode)
private static HashSet<string> GetActiveFieldsFromMasterNode(INode iMasterNode, Pass pass)
ShaderGenerator defines = new ShaderGenerator();
HashSet<string> activeFields = new HashSet<string>();
// #pragma shader_feature _ALPHATEST_ON
UnlitMasterNode masterNode = iMasterNode as UnlitMasterNode;
if (masterNode == null)
{
return null;
}
if (masterNode.twoSided.isOn)
{
activeFields.Add("DoubleSided");
if (pass.ShaderPassName != "SHADERPASS_VELOCITY") // HACK to get around lack of a good interpolator dependency system
{ // we need to be able to build interpolators using multiple input structs
// also: should only require isFrontFace if Normals are required...
activeFields.Add("DoubleSided.Mirror"); // TODO: change this depending on what kind of normal flip you want..
activeFields.Add("FragInputs.isFrontFace"); // will need this for determining normal flip mode
}
}
defines.AddShaderChunk("#define _ALPHATEST_ON 1", true);
activeFields.Add("AlphaTest");
}
// if (kTesselationMode != TessellationMode.None)

// #pragma shader_feature _HEIGHTMAP
// #pragma shader_feature _TANGENTMAP
// #pragma shader_feature _ANISOTROPYMAP
// #pragma shader_feature _DETAIL_MAP // MOVE to a node
// #pragma shader_feature _SUBSURFACE_RADIUS_MAP
// #pragma shader_feature _THICKNESSMAP
// #pragma shader_feature _SPECULARCOLORMAP

if (masterNode.surfaceType != SurfaceType.Opaque)
{
// transparent-only defines
defines.AddShaderChunk("#define _SURFACE_TYPE_TRANSPARENT 1", true);
activeFields.Add("SurfaceType.Transparent");
defines.AddShaderChunk("#define _BLENDMODE_ALPHA 1", true);
activeFields.Add("BlendMode.Alpha");
defines.AddShaderChunk("#define _BLENDMODE_ADD 1", true);
activeFields.Add("BlendMode.Add");
}
// else if (masterNode.alphaMode == PBRMasterNode.AlphaMode.PremultiplyAlpha) // TODO
// {

// TODO: We should have this keyword only if VelocityInGBuffer is enable, how to do that ?
//#pragma multi_compile VELOCITYOUTPUT_OFF VELOCITYOUTPUT_ON
return defines.GetShaderString(2);
return activeFields;
private static bool GenerateShaderPass(UnlitMasterNode masterNode, Pass pass, GenerationMode mode, SurfaceMaterialOptions materialOptions, ShaderGenerator result, List<string> sourceAssetDependencyPaths)
private static bool GenerateShaderPassUnlit(AbstractMaterialNode masterNode, Pass pass, GenerationMode mode, SurfaceMaterialOptions materialOptions, ShaderGenerator result, List<string> sourceAssetDependencyPaths)
{
var templateLocation = Path.Combine(Path.Combine(Path.Combine(HDEditorUtils.GetHDRenderPipelinePath(), "Editor"), "ShaderGraph"), pass.TemplateName);
if (!File.Exists(templateLocation))

}
sourceAssetDependencyPaths.Add(templateLocation);
if (sourceAssetDependencyPaths != null)
sourceAssetDependencyPaths.Add(templateLocation);
// grab all of the active nodes (for pixel and vertex graphs)
var vertexNodes = ListPool<INode>.Get();
NodeUtils.DepthFirstCollectNodesFromNode(vertexNodes, masterNode, NodeUtils.IncludeSelf.Include, pass.VertexShaderSlots);
// grab all of the active nodes
var activeNodeList = ListPool<INode>.Get();
NodeUtils.DepthFirstCollectNodesFromNode(activeNodeList, masterNode, NodeUtils.IncludeSelf.Include, pass.PixelShaderSlots);
var pixelNodes = ListPool<INode>.Get();
NodeUtils.DepthFirstCollectNodesFromNode(pixelNodes, masterNode, NodeUtils.IncludeSelf.Include, pass.PixelShaderSlots);
var graphRequirements = ShaderGraphRequirements.FromNodes(activeNodeList, ShaderStageCapability.All, true, true);
var pixelRequirements = ShaderGraphRequirements.FromNodes(pixelNodes, ShaderStageCapability.Fragment, false); // TODO: is ShaderStageCapability.Fragment correct?
var vertexRequirements = ShaderGraphRequirements.FromNodes(vertexNodes, ShaderStageCapability.Vertex, false);
// Function Registry tracks functions to remove duplicates, it wraps a string builder that stores the combined function string
// TODO: this can be a shared function for all HDRP master nodes -- From here through GraphUtil.GenerateSurfaceDescription(..)
// TODO: this can be a shared function -- From here through GraphUtil.GenerateSurfaceDescription(..)
var activeSlots = new List<MaterialSlot>();
foreach (var id in pass.PixelShaderSlots)
{
MaterialSlot slot = masterNode.FindSlot<MaterialSlot>(id);
if (slot != null)
{
activeSlots.Add(slot);
}
}
var pixelSlots = HDSubShaderUtilities.FindMaterialSlotsOnNode(pass.PixelShaderSlots, masterNode);
var vertexSlots = HDSubShaderUtilities.FindMaterialSlotsOnNode(pass.VertexShaderSlots, masterNode);
// properties used by either pixel and vertex shader
PropertyCollector sharedProperties = new PropertyCollector();
string graphInputStructName = "SurfaceDescriptionInputs";
string graphOutputStructName = "SurfaceDescription";
string graphEvalFunctionName = "SurfaceDescriptionFunction";
var graphEvalFunction = new ShaderStringBuilder();
var graphOutputs = new ShaderStringBuilder();
PropertyCollector graphProperties = new PropertyCollector();
string pixelGraphInputStructName = "SurfaceDescriptionInputs";
string pixelGraphOutputStructName = "SurfaceDescription";
string pixelGraphEvalFunctionName = "SurfaceDescriptionFunction";
ShaderStringBuilder pixelGraphEvalFunction = new ShaderStringBuilder();
ShaderStringBuilder pixelGraphOutputs = new ShaderStringBuilder();
// dependency tracker -- set of active fields
HashSet<string> activeFields = GetActiveFieldsFromMasterNode(masterNode, pass);
// build initial requirements
HDRPShaderStructs.AddActiveFieldsFromPixelGraphRequirements(activeFields, pixelRequirements);
HashSet<string> activeFields = new HashSet<string>();
GraphUtil.GenerateSurfaceDescriptionStruct(graphOutputs, activeSlots, true);
GraphUtil.GenerateSurfaceDescriptionStruct(pixelGraphOutputs, pixelSlots, true, pixelGraphOutputStructName, activeFields);
activeNodeList,
pixelNodes,
graphEvalFunction,
pixelGraphEvalFunction,
graphProperties,
graphRequirements, // TODO : REMOVE UNUSED
sharedProperties,
pixelRequirements, // TODO : REMOVE UNUSED
graphEvalFunctionName,
graphOutputStructName,
pixelGraphEvalFunctionName,
pixelGraphOutputStructName,
activeSlots,
graphInputStructName);
pixelSlots,
pixelGraphInputStructName);
string vertexGraphInputStructName = "VertexDescriptionInputs";
string vertexGraphOutputStructName = "VertexDescription";
string vertexGraphEvalFunctionName = "VertexDescriptionFunction";
ShaderStringBuilder vertexGraphEvalFunction = new ShaderStringBuilder();
ShaderStringBuilder vertexGraphOutputs = new ShaderStringBuilder();
// check for vertex animation -- enables HAVE_VERTEX_MODIFICATION
bool vertexActive = false;
if (masterNode.IsSlotConnected(PBRMasterNode.PositionSlotId))
{
vertexActive = true;
activeFields.Add("features.modifyMesh");
HDRPShaderStructs.AddActiveFieldsFromVertexGraphRequirements(activeFields, vertexRequirements);
// -------------------------------------
// Generate Output structure for Vertex Description function
GraphUtil.GenerateVertexDescriptionStruct(vertexGraphOutputs, vertexSlots, vertexGraphOutputStructName, activeFields);
// -------------------------------------
// Generate Vertex Description function
GraphUtil.GenerateVertexDescriptionFunction(
masterNode.owner as AbstractMaterialGraph,
vertexGraphEvalFunction,
functionRegistry,
sharedProperties,
mode,
vertexNodes,
vertexSlots,
vertexGraphInputStructName,
vertexGraphEvalFunctionName,
vertexGraphOutputStructName);
}
var blendCode = new ShaderStringBuilder();
var cullCode = new ShaderStringBuilder();

var colorMaskCode = new ShaderStringBuilder();
HDSubShaderUtilities.BuildRenderStatesFromPassAndMaterialOptions(pass, materialOptions, blendCode, cullCode, zTestCode, zWriteCode, stencilCode, colorMaskCode);
if (masterNode.twoSided.isOn)
{
activeFields.Add("DoubleSided");
if (pass.ShaderPassName != "SHADERPASS_VELOCITY") // HACK to get around lack of a good interpolator dependency system
{ // we need to be able to build interpolators using multiple input structs
// also: should only require isFrontFace if Normals are required...
activeFields.Add("DoubleSided.Mirror"); // TODO: change this depending on what kind of normal flip you want..
activeFields.Add("FragInputs.isFrontFace"); // will need this for determining normal flip mode
}
}
HDRPShaderStructs.AddRequiredFields(pass.RequiredFields, activeFields);
if (pass.PixelShaderSlots != null)
{
foreach (var slotId in pass.PixelShaderSlots)
{
var slot = masterNode.FindSlot<MaterialSlot>(slotId);
if (slot != null)
{
var rawSlotName = slot.RawDisplayName().ToString();
var descriptionVar = string.Format("{0}.{1}", graphOutputStructName, rawSlotName);
activeFields.Add(descriptionVar);
}
}
}
// apply dependencies to the active fields, and build interpolators (TODO: split this function)
var graphInputs = new ShaderGenerator();
graphInputs,
graphRequirements,
pass.RequiredFields,
CoordinateSpace.World,
activeFields);
// debug output all active fields

}
}
// build graph inputs structures
ShaderGenerator pixelGraphInputs = new ShaderGenerator();
ShaderSpliceUtil.BuildType(typeof(HDRPShaderStructs.SurfaceDescriptionInputs), activeFields, pixelGraphInputs);
ShaderGenerator vertexGraphInputs = new ShaderGenerator();
ShaderSpliceUtil.BuildType(typeof(HDRPShaderStructs.VertexDescriptionInputs), activeFields, vertexGraphInputs);
ShaderGenerator defines = new ShaderGenerator();
{
defines.AddShaderChunk(string.Format("#define SHADERPASS {0}", pass.ShaderPassName), true);

// build graph code
var graph = new ShaderGenerator();
graph.AddShaderChunk("// Graph Inputs");
graph.Indent();
graph.AddGenerator(graphInputs);
graph.Deindent();
graph.AddShaderChunk("// Graph Outputs");
graph.Indent();
graph.AddShaderChunk(graphOutputs.ToString());
//graph.AddGenerator(graphOutputs);
graph.Deindent();
graph.AddShaderChunk("// Graph Properties (uniform inputs)");
graph.AddShaderChunk(graphProperties.GetPropertiesDeclaration(1));
graph.AddShaderChunk("// Graph Node Functions");
graph.AddShaderChunk(graphNodeFunctions.ToString());
graph.AddShaderChunk("// Graph Evaluation");
graph.Indent();
graph.AddShaderChunk(graphEvalFunction.ToString());
//graph.AddGenerator(graphEvalFunction);
graph.Deindent();
{
graph.AddShaderChunk("// Shared Graph Properties (uniform inputs)");
graph.AddShaderChunk(sharedProperties.GetPropertiesDeclaration(1));
if (vertexActive)
{
graph.AddShaderChunk("// Vertex Graph Inputs");
graph.Indent();
graph.AddGenerator(vertexGraphInputs);
graph.Deindent();
graph.AddShaderChunk("// Vertex Graph Outputs");
graph.Indent();
graph.AddShaderChunk(vertexGraphOutputs.ToString());
graph.Deindent();
}
graph.AddShaderChunk("// Pixel Graph Inputs");
graph.Indent();
graph.AddGenerator(pixelGraphInputs);
graph.Deindent();
graph.AddShaderChunk("// Pixel Graph Outputs");
graph.Indent();
graph.AddShaderChunk(pixelGraphOutputs.ToString());
graph.Deindent();
graph.AddShaderChunk("// Shared Graph Node Functions");
graph.AddShaderChunk(graphNodeFunctions.ToString());
if (vertexActive)
{
graph.AddShaderChunk("// Vertex Graph Evaluation");
graph.Indent();
graph.AddShaderChunk(vertexGraphEvalFunction.ToString());
graph.Deindent();
}
graph.AddShaderChunk("// Pixel Graph Evaluation");
graph.Indent();
graph.AddShaderChunk(pixelGraphEvalFunction.ToString());
graph.Deindent();
}
// build the hash table of all named fragments TODO: could make this Dictionary<string, ShaderGenerator / string> ?
Dictionary<string, string> namedFragments = new Dictionary<string, string>();

namedFragments.Add("${Stencil}", stencilCode.ToString());
namedFragments.Add("${ColorMask}", colorMaskCode.ToString());
namedFragments.Add("${LOD}", materialOptions.lod.ToString());
namedFragments.Add("${VariantDefines}", GetVariantDefines(masterNode));
// process the template to generate the shader code for this pass TODO: could make this a shared function
string[] templateLines = File.ReadAllLines(templateLocation);

// bool transparent = (masterNode.surfaceType != SurfaceType.Opaque);
bool distortionActive = false;
GenerateShaderPass(masterNode, m_PassDepthOnly, mode, materialOptions, subShader, sourceAssetDependencyPaths);
GenerateShaderPass(masterNode, m_PassForward, mode, materialOptions, subShader, sourceAssetDependencyPaths);
GenerateShaderPass(masterNode, m_PassMETA, mode, materialOptions, subShader, sourceAssetDependencyPaths);
GenerateShaderPassUnlit(masterNode, m_PassDepthOnly, mode, materialOptions, subShader, sourceAssetDependencyPaths);
GenerateShaderPassUnlit(masterNode, m_PassForward, mode, materialOptions, subShader, sourceAssetDependencyPaths);
GenerateShaderPassUnlit(masterNode, m_PassMETA, mode, materialOptions, subShader, sourceAssetDependencyPaths);
GenerateShaderPass(masterNode, m_PassDistortion, mode, materialOptions, subShader, sourceAssetDependencyPaths);
GenerateShaderPassUnlit(masterNode, m_PassDistortion, mode, materialOptions, subShader, sourceAssetDependencyPaths);
}
}
subShader.Deindent();

13
com.unity.render-pipelines.high-definition/HDRP/Editor/Upgraders/HDRPVersion.cs


[InitializeOnLoad]
public class HDRPVersion
{
static public float hdrpVersion = 1.0f;
static public int hdrpVersion = 1;
static public float GetCurrentHDRPProjectVersion()
static public int GetCurrentHDRPProjectVersion()
version[0] = "0.9"; // Note: When we don't know what a project is, assume worst case
try
{

{
Debug.LogWarning("Unable to read from ProjectSettings/HDRPProjectVersion.txt - Assign default version value");
// Don't display warning
//Debug.LogWarning("Unable to read from ProjectSettings/HDRPProjectVersion.txt - Assign default version value");
// When we don't find HDRPProjectVersion file we return the current value. Because this happen when you create new project.
return hdrpVersion;
return float.Parse(version[0]);
return int.Parse(version[0]);
}
static public void WriteCurrentHDRPProjectVersion()

14
com.unity.render-pipelines.high-definition/HDRP/Editor/Upgraders/UpgradeMenuItem.cs


string.Format("{0} / {1} materials subsurface updated.", i, length),
i / (float)(length - 1));
bool VSCEnabled = (UnityEditor.VersionControl.Provider.enabled && UnityEditor.VersionControl.Provider.isActive);
bool VCSEnabled = (UnityEditor.VersionControl.Provider.enabled && UnityEditor.VersionControl.Provider.isActive);
if (mat.shader.name == "HDRenderPipeline/LitTessellation" ||
mat.shader.name == "HDRenderPipeline/Lit" ||

if (mat.HasProperty("_SSSAndTransmissionType"))
{
CoreUtils.CheckOutFile(VSCEnabled, mat);
CoreEditorUtils.CheckOutFile(VCSEnabled, mat);
int materialSSSAndTransmissionID = mat.GetInt("_SSSAndTransmissionType");

string.Format("{0} / {1} materials updated.", i, length),
i / (float)(length - 1));
bool VSCEnabled = (UnityEditor.VersionControl.Provider.enabled && UnityEditor.VersionControl.Provider.isActive);
bool VCSEnabled = (UnityEditor.VersionControl.Provider.enabled && UnityEditor.VersionControl.Provider.isActive);
if (mat.shader.name == "HDRenderPipeline/LitTessellation" ||
mat.shader.name == "HDRenderPipeline/Lit")

{
CoreUtils.CheckOutFile(VSCEnabled, mat);
CoreEditorUtils.CheckOutFile(VCSEnabled, mat);
float valueMax = mat.GetFloat("_HeightMax");
float valueMin = mat.GetFloat("_HeightMin");

if (mat.HasProperty("_HeightPoMAmplitude0"))
{
CoreUtils.CheckOutFile(VSCEnabled, mat);
CoreEditorUtils.CheckOutFile(VCSEnabled, mat);
for (int x = 0; x < numLayer; ++x)
{

static void UpdateMaterialToNewerVersion(string caption, UpdateMaterial updateMaterial, UpdateMaterialFile updateMaterialFile = null)
{
bool VSCEnabled = (UnityEditor.VersionControl.Provider.enabled && UnityEditor.VersionControl.Provider.isActive);
bool VCSEnabled = (UnityEditor.VersionControl.Provider.enabled && UnityEditor.VersionControl.Provider.isActive);
var matIds = AssetDatabase.FindAssets("t:Material");
List<string> materialFiles = new List<string>(); // Contain the list dirty files

if (dirty)
{
// Checkout the file and tag it as dirty
CoreUtils.CheckOutFile(VSCEnabled, mat);
CoreEditorUtils.CheckOutFile(VCSEnabled, mat);
EditorUtility.SetDirty(mat);
materialFiles.Add(path);
}

21
com.unity.render-pipelines.high-definition/HDRP/HDRenderPipelineAsset.asset


--- !u!114 &11400000
MonoBehaviour:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1

m_EditorClassIdentifier:
version: 1
m_RenderPipelineResources: {fileID: 11400000, guid: 3ce144cff5783da45aa5d4fdc2da14b7,
type: 2}
m_FrameSettings:

enableSSAO: 1
enableSubsurfaceScattering: 1
enableTransmission: 1
enableAtmosphericScattering: 1
enableVolumetric: 1
diffuseGlobalDimmer: 1
specularGlobalDimmer: 1
enableForwardRenderingOnly: 0

enableObjectMotionVectors: 1
enableDBuffer: 1
enableAtmosphericScattering: 1
enableRoughRefraction: 1
enableTransparentPostpass: 1
enableDistortion: 1

enableOpaqueObjects: 1
enableTransparentObjects: 1
enableMSAA: 0
enableShadowMask: 0
enableShadowMask: 1
lightLoopSettings:
enableTileAndCluster: 1
enableComputeLightEvaluation: 1

supportSSR: 1
supportSSAO: 1
supportSubsurfaceScattering: 1
supportForwardOnly: 0
supportOnlyForward: 0
supportVolumetric: 1
supportRuntimeDebugDisplay: 1
supportDBuffer: 1
supportMSAA: 0
msaaSampleCount: 1

cookieTexArraySize: 16
pointCookieSize: 512
cubeCookieTexArraySize: 16
reflectionProbeCacheSize: 128
reflectionCubemapSize: 128
reflectionProbeCacheSize: 128
reflectionCubemapSize: 128
maxPlanarReflectionProbes: 128
skyReflectionSize: 256
skyLightingOverrideLayerMask:
serializedVersion: 2

shadowAtlasHeight: 4096
decalSettings:
drawDistance: 1000
atlasSize: 8192
atlasWidth: 4096
atlasHeight: 4096
allowShaderVariantStripping: 1
diffusionProfileSettings: {fileID: 11400000, guid: 404820c4cf36ad944862fa59c56064f0,
type: 2}

24
com.unity.render-pipelines.high-definition/HDRP/Lighting/DeferredDirectionalShadow.compute


// Each #kernel tells which function to compile; you can have many kernels
#pragma kernel DeferredDirectionalShadow DEFERRED_DIRECTIONAL=DeferredDirectionalShadow
#pragma kernel DeferredDirectionalShadow_Contact DEFERRED_DIRECTIONAL=DeferredDirectionalShadow_Contact ENABLE_CONTACT_SHADOWS
#pragma kernel DeferredDirectionalShadow_Normals DEFERRED_DIRECTIONAL=DeferredDirectionalShadow_Normals ENABLE_NORMALS
#pragma kernel DeferredDirectionalShadow_Contact_Normals DEFERRED_DIRECTIONAL=DeferredDirectionalShadow_Contact_Normals ENABLE_CONTACT_SHADOWS ENABLE_NORMALS
#ifdef ENABLE_NORMALS
# define LIGHTLOOP_TILE_PASS 1
# define USE_FPTL_LIGHTLIST 1 // deferred opaque always use FPTL
# define UNITY_MATERIAL_LIT
#else
# define SHADOW_USE_ONLY_VIEW_BASED_BIASING 1 // Enable only light view vector based biasing. If undefined, biasing will be based on the normal and calling code must provide a valid normal.
#endif
#ifdef SHADER_API_PSSL
# pragma argument( scheduler=minpressure ) // instruct the shader compiler to prefer minimizing vgpr usage

#include "../ShaderVariables.hlsl"
#include "../Material/NormalBuffer.hlsl"
#include "Lighting.hlsl"
#pragma only_renderers d3d11 ps4 xboxone vulkan metal switch

PositionInputs posInput = GetPositionInput(pixelCoord.xy, _ScreenSize.zw, depth, UNITY_MATRIX_I_VP, UNITY_MATRIX_V, tileCoord);
#ifdef ENABLE_NORMALS
BSDFData bsdfData;
BakeLightingData unused;
DECODE_FROM_GBUFFER(posInput.positionSS, UINT_MAX, bsdfData, unused.bakeDiffuseLighting);
float3 nrm = bsdfData.normalWS;
#else
float3 nrm = 0.0.xxx;
#endif
NormalData normalData;
DecodeFromNormalBuffer(posInput.positionSS, normalData);
float3 normalWS = normalData.normalWS;
float shadow = GetDirectionalShadowAttenuation(shadowContext, posInput.positionWS, nrm, _DirectionalShadowIndex, _LightDirection);
float shadow = GetDirectionalShadowAttenuation(shadowContext, posInput.positionWS, normalWS, _DirectionalShadowIndex, _LightDirection);
#ifdef ENABLE_CONTACT_SHADOWS
float contactShadow = 1.0f;

8
com.unity.render-pipelines.high-definition/HDRP/Lighting/LightLoop/LightLoop.cs


static int s_deferredDirectionalShadowKernel;
static int s_deferredDirectionalShadow_Contact_Kernel;
static int s_deferredDirectionalShadow_Normals_Kernel;
static int s_deferredDirectionalShadow_Contact_Normals_Kernel;
static ComputeBuffer s_LightVolumeDataBuffer = null;
static ComputeBuffer s_ConvexBoundsBuffer = null;

s_deferredDirectionalShadowKernel = deferredDirectionalShadowComputeShader.FindKernel("DeferredDirectionalShadow");
s_deferredDirectionalShadow_Contact_Kernel = deferredDirectionalShadowComputeShader.FindKernel("DeferredDirectionalShadow_Contact");
s_deferredDirectionalShadow_Normals_Kernel = deferredDirectionalShadowComputeShader.FindKernel("DeferredDirectionalShadow_Normals");
s_deferredDirectionalShadow_Contact_Normals_Kernel = deferredDirectionalShadowComputeShader.FindKernel("DeferredDirectionalShadow_Contact_Normals");
for (int variant = 0; variant < LightDefinitions.s_NumFeatureVariants; variant++)
{

bool enableContactShadows = m_FrameSettings.enableContactShadows && contactShadows.enable && contactShadows.length > 0.0f;
int kernel;
if (enableContactShadows)
kernel = m_FrameSettings.enableForwardRenderingOnly ? s_deferredDirectionalShadow_Contact_Kernel : s_deferredDirectionalShadow_Contact_Normals_Kernel;
kernel = s_deferredDirectionalShadow_Contact_Kernel;
kernel = m_FrameSettings.enableForwardRenderingOnly ? s_deferredDirectionalShadowKernel : s_deferredDirectionalShadow_Normals_Kernel;
kernel = s_deferredDirectionalShadowKernel;
m_ShadowMgr.BindResources(cmd, deferredDirectionalShadowComputeShader, kernel);

4
com.unity.render-pipelines.high-definition/HDRP/Material/Decal/DBufferManager.cs


{
public class DBufferManager : MRTBufferManager
{
public int vsibleDecalCount { get; set; }
public bool EnableDBUffer { get; set; }
RTHandleSystem.RTHandle m_HTile;

{
if (hdCamera.frameSettings.enableDBuffer)
{
cmd.SetGlobalInt(HDShaderIDs._EnableDBuffer, vsibleDecalCount > 0 ? 1 : 0);
cmd.SetGlobalInt(HDShaderIDs._EnableDBuffer, EnableDBUffer ? 1 : 0);
cmd.SetGlobalVector(HDShaderIDs._DecalAtlasResolution, new Vector2(HDUtils.hdrpSettings.decalSettings.atlasWidth, HDUtils.hdrpSettings.decalSettings.atlasHeight));
BindBufferAsTextures(cmd);
}

15
com.unity.render-pipelines.high-definition/HDRP/Material/Decal/Decal.cs


sRGBFlags = m_sRGBFlags;
}
}
// normalToWorld.m03 - total blend factor
// normalToWorld.m13 - diffuse texture index in atlas
// normalToWorld.m23 - normal texture index in atlas
// normalToWorld.m33 - mask texture index in atlas
// normal to world only uses 3x3 for actual matrix so some data is packed in the unused space
// blend:
// float decalBlend = decalData.normalToWorld[0][3];
// albedo contribution on/off:
// float albedoContribution = decalData.normalToWorld[1][3];
// tiling:
// float2 uvScale = float2(decalData.normalToWorld[3][0], decalData.normalToWorld[3][1]);
// float2 uvBias = float2(decalData.normalToWorld[3][2], decalData.normalToWorld[3][3]);
[GenerateHLSL]
public struct DecalData
{

public Vector4 normalScaleBias;
public Vector4 maskScaleBias;
public Vector4 baseColor;
};
}

1
com.unity.render-pipelines.high-definition/HDRP/Material/Decal/Decal.cs.hlsl


float4 diffuseScaleBias;
float4 normalScaleBias;
float4 maskScaleBias;
float4 baseColor;
};
//

32
com.unity.render-pipelines.high-definition/HDRP/Material/Decal/Decal.shader


{
Properties
{
_BaseColor("_BaseColor", Color) = (1,1,1,1)
[ToggleUI] _AlbedoMode("_AlbedoMode", Range(0.0, 1.0)) = 1.0
}
HLSLINCLUDE

#pragma shader_feature _COLORMAP
#pragma shader_feature _NORMALMAP
#pragma shader_feature _MASKMAP
#pragma shader_feature _ALBEDOCONTRIBUTION
#pragma multi_compile_instancing
//-------------------------------------------------------------------------------------

Pass
{
Name "DBuffer" // Name is not used
Tags { "LightMode" = "DBuffer" } // This will be only for opaque object based on the RenderQueue index
Name "DBufferProjector" // Name is not used
Tags { "LightMode" = "DBufferProjector" } // This will be only for opaque object based on the RenderQueue index
// back faces with zfail, for cases when camera is inside the decal volume
Cull Front

HLSLPROGRAM
#define SHADERPASS SHADERPASS_DBUFFER
#define SHADERPASS SHADERPASS_DBUFFER_PROJECTOR
#include "../../ShaderVariables.hlsl"
#include "Decal.hlsl"
#include "ShaderPass/DecalSharePass.hlsl"

ENDHLSL
}
Pass
{
Name "DBufferMesh" // Name is not used
Tags{"LightMode" = "DBufferMesh"} // This will be only for opaque object based on the RenderQueue index
Cull Back
ZWrite Off
ZTest LEqual
// using alpha compositing https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch23.html
Blend SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
HLSLPROGRAM
#define SHADERPASS SHADERPASS_DBUFFER_MESH
#include "../../ShaderVariables.hlsl"
#include "Decal.hlsl"
#include "ShaderPass/DecalSharePass.hlsl"
#include "DecalData.hlsl"
#include "../../ShaderPass/ShaderPassDBuffer.hlsl"
ENDHLSL
}
}
CustomEditor "Experimental.Rendering.HDPipeline.DecalUI"
}

43
com.unity.render-pipelines.high-definition/HDRP/Material/Decal/DecalData.hlsl


//-------------------------------------------------------------------------------------
#include "CoreRP/ShaderLibrary/Packing.hlsl"
#include "CoreRP/ShaderLibrary/Sampling/SampleUVMapping.hlsl"
#include "CoreRP/ShaderLibrary/EntityLighting.hlsl"
#include "../MaterialUtilities.hlsl"
#if (SHADERPASS == SHADERPASS_DBUFFER_PROJECTOR)
#elif (SHADERPASS == SHADERPASS_DBUFFER_MESH)
void GetSurfaceData(FragInputs input, out DecalSurfaceData surfaceData)
#endif
surfaceData.baseColor = float4(0,0,0,0);
surfaceData.baseColor = _BaseColor;
#if (SHADERPASS == SHADERPASS_DBUFFER_PROJECTOR)
texCoordDS = texCoordDS * scale + offset;
float2 texCoords = texCoordDS * scale + offset;
#elif (SHADERPASS == SHADERPASS_DBUFFER_MESH)
float totalBlend = _DecalBlend;
float2 texCoords = input.texCoord0;
#endif
surfaceData.baseColor = SAMPLE_TEXTURE2D(_BaseColorMap, sampler_BaseColorMap, texCoordDS.xy);
surfaceData.baseColor.w *= totalBlend;
totalBlend = surfaceData.baseColor.w; // base alpha affects all other channels;
surfaceData.HTileMask |= DBUFFERHTILEBIT_DIFFUSE;
surfaceData.baseColor *= SAMPLE_TEXTURE2D(_BaseColorMap, sampler_BaseColorMap, texCoords);
#endif
surfaceData.baseColor.w *= totalBlend;
totalBlend = surfaceData.baseColor.w; // base alpha affects all other channels;
// outside _COLORMAP because we still have base color
#if _ALBEDOCONTRIBUTION
surfaceData.HTileMask |= DBUFFERHTILEBIT_DIFFUSE;
#else
surfaceData.baseColor.w = 0; // dont blend any albedo
surfaceData.normalWS.xyz = mul((float3x3)normalToWorld, UnpackNormalmapRGorAG(SAMPLE_TEXTURE2D(_NormalMap, sampler_NormalMap, texCoordDS))) * 0.5f + 0.5f;
float3 normalTS = UnpackNormalmapRGorAG(SAMPLE_TEXTURE2D(_NormalMap, sampler_NormalMap, texCoords));
#if (SHADERPASS == SHADERPASS_DBUFFER_PROJECTOR)
float3 normalWS = mul((float3x3)normalToWorld, normalTS);
#elif (SHADERPASS == SHADERPASS_DBUFFER_MESH)
float3 normalWS;
GetNormalWS(input, 0, normalTS, normalWS);
#endif
surfaceData.normalWS.xyz = normalWS * 0.5f + 0.5f;
surfaceData.mask = SAMPLE_TEXTURE2D(_MaskMap, sampler_MaskMap, texCoordDS.xy);
surfaceData.mask = SAMPLE_TEXTURE2D(_MaskMap, sampler_MaskMap, texCoords);
surfaceData.mask.z = surfaceData.mask.w;
surfaceData.mask.w = totalBlend;
surfaceData.HTileMask |= DBUFFERHTILEBIT_MASK;

9
com.unity.render-pipelines.high-definition/HDRP/Material/Decal/DecalProjectorComponent.cs


public float m_FadeScale = 0.9f;
public Vector2 m_UVScale = new Vector2(1, 1);
public Vector2 m_UVBias = new Vector2(0, 0);
public bool m_AffectsTransparency = false;
private Material m_OldMaterial = null;
private DecalSystem.DecalHandle m_Handle = null;

}
Vector4 uvScaleBias = new Vector4(m_UVScale.x, m_UVScale.y, m_UVBias.x, m_UVBias.y);
m_Handle = DecalSystem.instance.AddDecal(transform, m_DrawDistance, m_FadeScale, uvScaleBias, m_Material);
m_Handle = DecalSystem.instance.AddDecal(transform, m_DrawDistance, m_FadeScale, uvScaleBias, m_AffectsTransparency, m_Material);
}
public void OnDisable()

if (m_Handle != null)
DecalSystem.instance.RemoveDecal(m_Handle);
Vector4 uvScaleBias = new Vector4(m_UVScale.x, m_UVScale.y, m_UVBias.x, m_UVBias.y);
m_Handle = DecalSystem.instance.AddDecal(transform, m_DrawDistance, m_FadeScale, uvScaleBias, m_Material);
m_Handle = DecalSystem.instance.AddDecal(transform, m_DrawDistance, m_FadeScale, uvScaleBias, m_AffectsTransparency, m_Material);
m_OldMaterial = m_Material;
// notify the editor that material has changed so it can update the shader foldout

if (transform.hasChanged == true)
{
Vector4 uvScaleBias = new Vector4(m_UVScale.x, m_UVScale.y, m_UVBias.x, m_UVBias.y);
DecalSystem.instance.UpdateCachedData(transform, m_DrawDistance, m_FadeScale, uvScaleBias, m_Handle);
DecalSystem.instance.UpdateCachedData(transform, m_DrawDistance, m_FadeScale, uvScaleBias, m_AffectsTransparency, m_Handle);
transform.hasChanged = false;
}
}

DrawGizmo(true);
// if this object is selected there is a chance the transform was changed so update culling info
Vector4 uvScaleBias = new Vector4(m_UVScale.x, m_UVScale.y, m_UVBias.x, m_UVBias.y);
DecalSystem.instance.UpdateCachedData(transform, m_DrawDistance, m_FadeScale, uvScaleBias, m_Handle);
DecalSystem.instance.UpdateCachedData(transform, m_DrawDistance, m_FadeScale, uvScaleBias, m_AffectsTransparency, m_Handle);
}
public void OnDrawGizmos()

1
com.unity.render-pipelines.high-definition/HDRP/Material/Decal/DecalProperties.hlsl


SAMPLER(sampler_MaskMap);
float _DecalBlend;
float4 _BaseColor;
#endif

90
com.unity.render-pipelines.high-definition/HDRP/Material/Decal/DecalSystem.cs


static public DecalData[] m_DecalDatas = new DecalData[kDecalBlockSize];
static public SFiniteLightBound[] m_Bounds = new SFiniteLightBound[kDecalBlockSize];
static public LightVolumeData[] m_LightVolumes = new LightVolumeData[kDecalBlockSize];
static public TextureScaleBias[] m_DiffuseTextureScaleBias = new TextureScaleBias[kDecalBlockSize];
static public TextureScaleBias[] m_NormalTextureScaleBias = new TextureScaleBias[kDecalBlockSize];
static public TextureScaleBias[] m_MaskTextureScaleBias = new TextureScaleBias[kDecalBlockSize];
static public Vector4[] m_BaseColor = new Vector4[kDecalBlockSize];
static public int m_DecalDatasCount = 0;
static public float[] m_BoundingDistances = new float[1];

return 0;
}
}
public void Initialize(Texture texture, Vector4 scaleBias)
{
m_Texture = texture;
m_ScaleBias = scaleBias;
}
}
private List<TextureScaleBias> m_TextureList = new List<TextureScaleBias>();

{
if (m_Material == null)
return;
m_Diffuse.m_Texture = m_Material.GetTexture("_BaseColorMap");
m_Normal.m_Texture = m_Material.GetTexture("_NormalMap");
m_Mask.m_Texture = m_Material.GetTexture("_MaskMap");
m_Diffuse.Initialize(m_Material.GetTexture("_BaseColorMap"), Vector4.zero);
m_Normal.Initialize(m_Material.GetTexture("_NormalMap"), Vector4.zero);
m_Mask.Initialize(m_Material.GetTexture("_MaskMap"), Vector4.zero);
m_AlbedoContribution = m_Material.GetFloat("_AlbedoMode");
m_BaseColor = m_Material.GetVector("_BaseColor");
}
public DecalSet(Material material)

return res;
}
public void UpdateCachedData(Transform transform, float drawDistance, float fadeScale, Vector4 uvScaleBias, DecalHandle handle)
public void UpdateCachedData(Transform transform, float drawDistance, float fadeScale, Vector4 uvScaleBias, bool affectsTransparency, DecalHandle handle)
{
if (m_Material == null)
return;

: instance.DrawDistance;
m_CachedDrawDistances[index].y = fadeScale;
m_CachedUVScaleBias[index] = uvScaleBias;
m_CachedAffectsTransparency[index] = affectsTransparency;
public DecalHandle AddDecal(Transform transform, float drawDistance, float fadeScale, Vector4 uvScaleBias, int materialID)
public DecalHandle AddDecal(Transform transform, float drawDistance, float fadeScale, Vector4 uvScaleBias, bool affectsTransparency, int materialID)
{
// increase array size if no space left
if (m_DecalsCount == m_Handles.Length)

Matrix4x4[] newCachedNormalToWorld = new Matrix4x4[m_DecalsCount + kDecalBlockSize];
Vector2[] newCachedDrawDistances = new Vector2[m_DecalsCount + kDecalBlockSize];
Vector4[] newCachedUVScaleBias = new Vector4[m_DecalsCount + kDecalBlockSize];
bool[] newCachedAffectsTransparency = new bool[m_DecalsCount + kDecalBlockSize];
m_ResultIndices = new int[m_DecalsCount + kDecalBlockSize];
m_Handles.CopyTo(newHandles, 0);

m_CachedDrawDistances.CopyTo(newCachedDrawDistances, 0);
m_CachedUVScaleBias.CopyTo(newCachedUVScaleBias, 0);
m_CachedAffectsTransparency.CopyTo(newCachedAffectsTransparency, 0);
m_Handles = newHandles;
m_BoundingSpheres = newSpheres;

m_CachedUVScaleBias = newCachedUVScaleBias;
m_CachedAffectsTransparency = newCachedAffectsTransparency;
UpdateCachedData(transform, drawDistance, fadeScale, uvScaleBias, decalHandle);
UpdateCachedData(transform, drawDistance, fadeScale, uvScaleBias, affectsTransparency, decalHandle);
m_DecalsCount++;
return decalHandle;
}

m_CachedNormalToWorld[removeAtIndex] = m_CachedNormalToWorld[m_DecalsCount - 1];
m_CachedDrawDistances[removeAtIndex] = m_CachedDrawDistances[m_DecalsCount - 1];
m_CachedUVScaleBias[removeAtIndex] = m_CachedUVScaleBias[m_DecalsCount - 1];
m_CachedAffectsTransparency[removeAtIndex] = m_CachedAffectsTransparency[m_DecalsCount - 1];
m_DecalsCount--;
handle.m_Index = kInvalidIndex;
}

return;
if (m_NumResults == 0)
return;
// only add if anything in this decal set is visible.
AddToTextureList(ref instance.m_TextureList);
bool anyAffectTransparency = false;
AssignCurrentBatches(ref decalToWorldBatch, ref normalToWorldBatch, batchCount);

normalToWorldBatch[instanceCount] = m_CachedNormalToWorld[decalIndex];
float fadeFactor = Mathf.Clamp((cullDistance - distanceToDecal) / (cullDistance * (1.0f - m_CachedDrawDistances[decalIndex].y)), 0.0f, 1.0f);
normalToWorldBatch[instanceCount].m03 = fadeFactor * m_Blend; // vector3 rotation matrix so bottom row and last column can be used for other data to save space
normalToWorldBatch[instanceCount].m13 = m_AlbedoContribution;
m_DecalDatas[m_DecalDatasCount].worldToDecal = decalToWorldBatch[instanceCount].inverse;
m_DecalDatas[m_DecalDatasCount].normalToWorld = normalToWorldBatch[instanceCount];
m_DecalDatas[m_DecalDatasCount].diffuseScaleBias = m_Diffuse.m_ScaleBias;
m_DecalDatas[m_DecalDatasCount].normalScaleBias = m_Normal.m_ScaleBias;
m_DecalDatas[m_DecalDatasCount].maskScaleBias = m_Mask.m_ScaleBias;
GetDecalVolumeDataAndBound(decalToWorldBatch[instanceCount], worldToView);
m_DecalDatasCount++;
if(m_CachedAffectsTransparency[decalIndex])
{
m_DecalDatas[m_DecalDatasCount].worldToDecal = decalToWorldBatch[instanceCount].inverse;
m_DecalDatas[m_DecalDatasCount].normalToWorld = normalToWorldBatch[instanceCount];
m_DecalDatas[m_DecalDatasCount].baseColor = m_BaseColor;
// we have not allocated the textures in atlas yet, so only store references to them
m_DiffuseTextureScaleBias[m_DecalDatasCount] = m_Diffuse;
m_NormalTextureScaleBias[m_DecalDatasCount] = m_Normal;
m_MaskTextureScaleBias[m_DecalDatasCount] = m_Mask;
GetDecalVolumeDataAndBound(decalToWorldBatch[instanceCount], worldToView);
m_DecalDatasCount++;
anyAffectTransparency = true;
}
instanceCount++;
if (instanceCount == kDrawIndexedBatchSize)

AssignCurrentBatches(ref decalToWorldBatch, ref normalToWorldBatch, batchCount);
}
}
}
// only add if any projectors in this decal set affect transparency, doesn't actually allocate textures in the atlas yet, this is because we want all the textures in the list so we can optimize the packing
if( anyAffectTransparency)
{
AddToTextureList(ref instance.m_TextureList);
}
}

private Matrix4x4[] m_CachedNormalToWorld = new Matrix4x4[kDecalBlockSize];
private Vector2[] m_CachedDrawDistances = new Vector2[kDecalBlockSize]; // x - draw distance, y - fade scale
private Vector4[] m_CachedUVScaleBias = new Vector4[kDecalBlockSize]; // xy - scale, zw bias
private bool[] m_CachedAffectsTransparency = new bool[kDecalBlockSize];
private float m_AlbedoContribution = 0;
private Vector4 m_BaseColor;
TextureScaleBias m_Diffuse = new TextureScaleBias();
TextureScaleBias m_Normal = new TextureScaleBias();

public DecalHandle AddDecal(Transform transform, float drawDistance, float fadeScale, Vector4 uvScaleBias, Material material)
public DecalHandle AddDecal(Transform transform, float drawDistance, float fadeScale, Vector4 uvScaleBias, bool affectsTransparency, Material material)
{
DecalSet decalSet = null;
int key = material != null ? material.GetInstanceID() : kNullMaterialIndex;

m_DecalSets.Add(key, decalSet);
}
return decalSet.AddDecal(transform, drawDistance, fadeScale, uvScaleBias, key);
return decalSet.AddDecal(transform, drawDistance, fadeScale, uvScaleBias, affectsTransparency, key);
}
public void RemoveDecal(DecalHandle handle)

}
}
public void UpdateCachedData(Transform transform, float drawDistance, float fadeScale, Vector4 uvScaleBias, DecalHandle handle)
public void UpdateCachedData(Transform transform, float drawDistance, float fadeScale, Vector4 uvScaleBias, bool affectsTransparency, DecalHandle handle)
{
if (!DecalHandle.IsValid(handle))
return;

if (m_DecalSets.TryGetValue(key, out decalSet))
{
decalSet.UpdateCachedData(transform, drawDistance, fadeScale, uvScaleBias, handle);
decalSet.UpdateCachedData(transform, drawDistance, fadeScale, uvScaleBias, affectsTransparency, handle);
}
}

}
}
private void UpdateDecalDatasWithAtlasInfo()
{
for (int decalDataIndex = 0; decalDataIndex < m_DecalDatasCount; decalDataIndex++)
{
m_DecalDatas[decalDataIndex].diffuseScaleBias = m_DiffuseTextureScaleBias[decalDataIndex].m_ScaleBias;
m_DecalDatas[decalDataIndex].normalScaleBias = m_NormalTextureScaleBias[decalDataIndex].m_ScaleBias;
m_DecalDatas[decalDataIndex].maskScaleBias = m_MaskTextureScaleBias[decalDataIndex].m_ScaleBias;
}
}
public void UpdateTextureAtlas(CommandBuffer cmd)
{
m_AllocationSuccess = true;

}
}
m_PrevAllocationSuccess = m_AllocationSuccess;
// now that textures have been stored in the atlas we can update their location info in decal data
UpdateDecalDatasWithAtlasInfo();
}
public void CreateDrawData()

m_DecalDatas = new DecalData[newDecalDatasSize];
m_Bounds = new SFiniteLightBound[newDecalDatasSize];
m_LightVolumes = new LightVolumeData[newDecalDatasSize];
m_DiffuseTextureScaleBias = new TextureScaleBias[newDecalDatasSize];
m_NormalTextureScaleBias = new TextureScaleBias[newDecalDatasSize];
m_MaskTextureScaleBias = new TextureScaleBias[newDecalDatasSize];
m_BaseColor = new Vector4[newDecalDatasSize];
}
foreach (var pair in m_DecalSets)
{

24
com.unity.render-pipelines.high-definition/HDRP/Material/Decal/DecalUtilities.hlsl


matMask |= mapMask;
}
void ApplyBlendDiffuse(inout float4 dst, inout int matMask, float2 texCoords, int mapMask, inout float blend, float lod)
void ApplyBlendDiffuse(inout float4 dst, inout int matMask, float2 texCoords, float4 src, int mapMask, inout float blend, float lod, int diffuseTextureBound)
float4 src = SAMPLE_TEXTURE2D_LOD(_DecalAtlas2D, _trilinear_clamp_sampler_DecalAtlas2D, texCoords, lod);
if(diffuseTextureBound)
{
src *= SAMPLE_TEXTURE2D_LOD(_DecalAtlas2D, _trilinear_clamp_sampler_DecalAtlas2D, texCoords, lod);
}
src.w *= blend;
blend = src.w; // diffuse texture alpha affects all other channels
dst.xyz = src.xyz * src.w + dst.xyz * (1.0f - src.w);

float lodMask = ComputeTextureLOD(sampleMaskDdx, sampleMaskDdy, _DecalAtlasResolution);
float decalBlend = decalData.normalToWorld[0][3];
float4 src = decalData.baseColor;
int diffuseTextureBound = (decalData.diffuseScaleBias.x > 0) && (decalData.diffuseScaleBias.y > 0);
ApplyBlendDiffuse(DBuffer0, mask, sampleDiffuse, src, DBUFFERHTILEBIT_DIFFUSE, decalBlend, lodDiffuse, diffuseTextureBound);
alpha = alpha < decalBlend ? decalBlend : alpha; // use decal alpha if it is higher than transparent alpha
if((decalData.diffuseScaleBias.x > 0) && (decalData.diffuseScaleBias.y > 0))
{
ApplyBlendDiffuse(DBuffer0, mask, sampleDiffuse, DBUFFERHTILEBIT_DIFFUSE, decalBlend, lodDiffuse);
alpha = alpha < decalBlend ? decalBlend : alpha; // use decal alpha if it is higher than transparent alpha
}
float albedoContribution = decalData.normalToWorld[1][3];
if (albedoContribution == 0.0f)
{
mask = 0; // diffuse will not get modified
}
if ((decalData.normalScaleBias.x > 0) && (decalData.normalScaleBias.y > 0))
{
ApplyBlendNormal(DBuffer1, mask, sampleNormal, DBUFFERHTILEBIT_NORMAL, (float3x3)decalData.normalToWorld, decalBlend, lodNormal);

12
com.unity.render-pipelines.high-definition/HDRP/Material/Decal/ShaderPass/DecalSharePass.hlsl


#error Undefine_SHADERPASS
#endif
#if (SHADERPASS == SHADERPASS_DBUFFER_MESH)
#define ATTRIBUTES_NEED_NORMAL
#define ATTRIBUTES_NEED_TANGENT // Always present as we require it also in case of anisotropic lighting
#define ATTRIBUTES_NEED_TEXCOORD0
#define VARYINGS_NEED_POSITION_WS
#define VARYINGS_NEED_TANGENT_TO_WORLD
#define VARYINGS_NEED_TEXCOORD0
#endif
#include "../../ShaderPass/VaryingMesh.hlsl"
#include "HDRP/ShaderPass/VaryingMesh.hlsl"

14
com.unity.render-pipelines.high-definition/HDRP/Material/LayeredLit/LayeredLit.shader


HLSLPROGRAM
// Note: Require _ObjectId and _PassValue variables
#define SHADERPASS SHADERPASS_DEPTH_ONLY
#define SCENESELECTIONPASS // This will drive the output of the scene selection shader
#include "../../ShaderVariables.hlsl"

ZWrite On
ColorMask 0
HLSLPROGRAM
HLSLPROGRAM
// In deferred, depth only pass don't output anything.
// In forward it output the normal buffer
#pragma multi_compile _ WRITE_NORMAL_BUFFER
#ifdef WRITE_NORMAL_BUFFER // If enabled we need all regular interpolator
#include "../Lit/ShaderPass/LitSharePass.hlsl"
#else
#endif
#include "LayeredLitData.hlsl"
#include "../../ShaderPass/ShaderPassDepthOnly.hlsl"

14
com.unity.render-pipelines.high-definition/HDRP/Material/LayeredLit/LayeredLitTessellation.shader


HLSLPROGRAM
// Note: Require _ObjectId and _PassValue variables
#pragma hull Hull
#pragma domain Domain

ZWrite On
ColorMask 0
// In deferred, depth only pass don't output anything.
// In forward it output the normal buffer
#pragma multi_compile _ WRITE_NORMAL_BUFFER
#ifdef WRITE_NORMAL_BUFFER // If enabled we need all regular interpolator
#include "../Lit/ShaderPass/LitSharePass.hlsl"
#else
#endif
#include "LayeredLitData.hlsl"
#include "../../ShaderPass/ShaderPassDepthOnly.hlsl"

112
com.unity.render-pipelines.high-definition/HDRP/Material/Lit/Lit.hlsl


// SurfaceData is define in Lit.cs which generate Lit.cs.hlsl
#include "Lit.cs.hlsl"
#include "../SubsurfaceScattering/SubsurfaceScattering.hlsl"
#include "../NormalBuffer.hlsl"
#include "CoreRP/ShaderLibrary/VolumeRendering.hlsl"
//-----------------------------------------------------------------------------

#define CLEAR_COAT_IETA (1.0 / CLEAR_COAT_IOR) // IETA is the inverse eta which is the ratio of IOR of two interface
#define CLEAR_COAT_F0 0.04 // IORToFresnel0(CLEAR_COAT_IOR)
#define CLEAR_COAT_ROUGHNESS 0.001
#define CLEAR_COAT_PERCEPTUAL_SMOOTHNESS RoughnessToPerceptualSmoothness(CLEAR_COAT_ROUGHNESS)
#define CLEAR_COAT_PERCEPTUAL_ROUGHNESS RoughnessToPerceptualRoughness(CLEAR_COAT_ROUGHNESS)
//-----------------------------------------------------------------------------

// #define LIT_DISPLAY_REFERENCE_AREA
// #define LIT_DISPLAY_REFERENCE_IBL
#endif
// In forward we can chose between reading the normal from the normalBufferTexture or computing it again
// This is tradeoff between performance and quality. As we store the normal conpressed, recomputing again is higher quality.
// Uncomment this to get speed (to measure), let it comment to get quality
// #define FORWARD_MATERIAL_READ_FROM_WRITTEN_NORMAL_BUFFER
//-----------------------------------------------------------------------------
// Ligth and material classification for the deferred rendering path

return sssData;
}
NormalData ConvertSurfaceDataToNormalData(SurfaceData surfaceData)
{
NormalData normalData;
// Note: We can't handle clear coat material here, we have only one slot to store smoothness
// and the buffer is the GBuffer1.
normalData.normalWS = surfaceData.normalWS;
normalData.perceptualRoughness = PerceptualSmoothnessToPerceptualRoughness(surfaceData.perceptualSmoothness);
return normalData;
}
void UpdateSurfaceDataFromNormalData(uint2 positionSS, inout BSDFData bsdfData)
{
NormalData normalData;
DecodeFromNormalBuffer(positionSS, normalData);
bsdfData.normalWS = normalData.normalWS;
bsdfData.perceptualRoughness = normalData.perceptualRoughness;
}
BSDFData ConvertSurfaceDataToBSDFData(SurfaceData surfaceData)
BSDFData ConvertSurfaceDataToBSDFData(uint2 positionSS, SurfaceData surfaceData)
{
BSDFData bsdfData;
ZERO_INITIALIZE(BSDFData, bsdfData);

bsdfData.specularOcclusion = surfaceData.specularOcclusion;
bsdfData.normalWS = surfaceData.normalWS;
bsdfData.perceptualRoughness = PerceptualSmoothnessToPerceptualRoughness(surfaceData.perceptualSmoothness);
// Check if we read value of normal and roughness from buffer. This is a tradeoff
#ifdef FORWARD_MATERIAL_READ_FROM_WRITTEN_NORMAL_BUFFER
#if (SHADERPASS == SHADERPASS_FORWARD) && !defined(_SURFACE_TYPE_TRANSPARENT)
UpdateSurfaceDataFromNormalData(positionSS, bsdfData);
#endif
#endif
// There is no metallic with SSS and specular color mode
float metallic = HasFeatureFlag(surfaceData.materialFeatures, MATERIALFEATUREFLAGS_LIT_SPECULAR_COLOR | MATERIALFEATUREFLAGS_LIT_SUBSURFACE_SCATTERING | MATERIALFEATUREFLAGS_LIT_TRANSMISSION) ? 0.0 : surfaceData.metallic;

// Warning: the contents are later overwritten for Standard and SSS!
outGBuffer0 = float4(surfaceData.baseColor, surfaceData.specularOcclusion);
// The sign of the Z component of the normal MUST round-trip through the G-Buffer, otherwise
// the reconstruction of the tangent frame for anisotropic GGX creates a seam along the Z axis.
// The constant was eye-balled to not cause artifacts.
// TODO: find a proper solution. E.g. we could re-shuffle the faces of the octahedron
// s.t. the sign of the Z component round-trips.
const float seamThreshold = 1.0/1024.0;
surfaceData.normalWS.z = CopySign(max(seamThreshold, abs(surfaceData.normalWS.z)), surfaceData.normalWS.z);
// RT1 - 8:8:8:8
// Our tangent encoding is based on our normal.
float2 octNormalWS = PackNormalOctQuadEncode(surfaceData.normalWS);
float3 packNormalWS = PackFloat2To888(saturate(octNormalWS * 0.5 + 0.5));
// We store perceptualRoughness instead of roughness because it is perceptually linear.
outGBuffer1 = float4(packNormalWS, PerceptualSmoothnessToPerceptualRoughness(surfaceData.perceptualSmoothness));
// This encode normalWS and PerceptualSmoothness into GBuffer1
EncodeIntoNormalBuffer(ConvertSurfaceDataToNormalData(surfaceData), positionSS, outGBuffer1);
// RT2 - 8:8:8:8
uint materialFeatureId;

// Decompress feature-agnostic data from the G-Buffer.
float3 baseColor = inGBuffer0.rgb;
float3 packNormalWS = inGBuffer1.rgb;
float2 octNormalWS = Unpack888ToFloat2(packNormalWS);
bsdfData.normalWS = UnpackNormalOctQuadEncode(octNormalWS * 2.0 - 1.0);
bsdfData.perceptualRoughness = inGBuffer1.a;
NormalData normalData;
DecodeFromNormalBuffer(inGBuffer1, positionSS, normalData);
bsdfData.normalWS = normalData.normalWS;
bsdfData.perceptualRoughness = normalData.perceptualRoughness;
bakeDiffuseLighting = inGBuffer3.rgb;

preLightData.transparentTransmittance = exp(-bsdfData.absorptionCoefficient * refraction.dist);
// Empirical remap to try to match a bit the refraction probe blurring for the fallback
// Use IblPerceptualRoughness so we can handle approx of clear coat.
preLightData.transparentSSMipLevel = pow(preLightData.iblPerceptualRoughness, 1.3) * uint(max(_ColorPyramidScale.z - 1, 0));
preLightData.transparentSSMipLevel = PositivePow(preLightData.iblPerceptualRoughness, 1.3) * uint(max(_ColorPyramidScale.z - 1, 0));
#endif
return preLightData;

// TODO: Fade pixels marked as foreground in stencil
float weight = weightNDC.x * weightNDC.y * hitWeight;
float hitDeviceDepth = LOAD_TEXTURE2D_LOD(_DepthPyramidTexture, hit.positionSS, 0).r;
float hitLinearDepth = LinearEyeDepth(hitDeviceDepth, _ZBufferParams);
float hitDeviceDepth = LOAD_TEXTURE2D_LOD(_DepthPyramidTexture, hit.positionSS, 0).r;
float hitLinearDepth = LinearEyeDepth(hitDeviceDepth, _ZBufferParams);
float2 samplingPositionNDC = hit.positionNDC;
#if HAS_REFRACTION
if (GPUImageBasedLightingType == GPUIMAGEBASEDLIGHTINGTYPE_REFRACTION
&& hitLinearDepth < posInput.linearDepth)
samplingPositionNDC = posInput.positionNDC;
#endif
// Reproject color pyramid
float4 hitVelocityBuffer = LOAD_TEXTURE2D_LOD(
_CameraMotionVectorsTexture,
hit.positionSS,
0.0
);
float2 hitVelocityNDC;
DecodeVelocity(hitVelocityBuffer, hitVelocityNDC);
float2 hitVelocityNDC = 0;
if (GPUImageBasedLightingType == GPUIMAGEBASEDLIGHTINGTYPE_REFLECTION)
{
// Reproject color pyramid
float4 hitVelocityBuffer = LOAD_TEXTURE2D_LOD(
_CameraMotionVectorsTexture,
hit.positionSS,
0.0
);
DecodeVelocity(hitVelocityBuffer, hitVelocityNDC);
}
(hit.positionNDC - hitVelocityNDC) * _ColorPyramidScale.xy + _ColorPyramidSize.zw * 0.5,
(samplingPositionNDC - hitVelocityNDC) * _ColorPyramidScale.xy + _ColorPyramidSize.zw * 0.5,
if (projectionModel == PROJECTIONMODEL_HI_Z)
if (GPUImageBasedLightingType == GPUIMAGEBASEDLIGHTINGTYPE_REFLECTION && projectionModel == PROJECTIONMODEL_HI_Z)
{
float4 currentVelocityBuffer = LOAD_TEXTURE2D_LOD(
_CameraMotionVectorsTexture,

if (_DebugLightingSubMode != DEBUGSCREENSPACETRACING_COLOR)
diffuseLighting = lighting.indirect.specularReflected;
break;
case DEBUGLIGHTINGMODE_VISUALIZE_SHADOW_MASKS:
#ifdef SHADOWS_SHADOWMASK
diffuseLighting = float3(
bakeLightingData.bakeShadowMask.r / 2 + bakeLightingData.bakeShadowMask.g / 2,
bakeLightingData.bakeShadowMask.g / 2 + bakeLightingData.bakeShadowMask.b / 2,
bakeLightingData.bakeShadowMask.b / 2 + bakeLightingData.bakeShadowMask.a / 2
);
specularLighting = float3(0, 0, 0);
#endif
break ;
}
}
else if (_DebugMipMapMode != DEBUGMIPMAPMODE_NONE)

14
com.unity.render-pipelines.high-definition/HDRP/Material/Lit/Lit.shader


HLSLPROGRAM
// Note: Require _ObjectId and _PassValue variables
// We reuse depth prepass for the scene selection, allow to handle alpha correctly as well as tessellation and vertex animation
#define SHADERPASS SHADERPASS_DEPTH_ONLY
#define SCENESELECTIONPASS // This will drive the output of the scene selection shader

ZWrite On
ColorMask 0
HLSLPROGRAM
HLSLPROGRAM
// In deferred, depth only pass don't output anything.
// In forward it output the normal buffer
#pragma multi_compile _ WRITE_NORMAL_BUFFER
#ifdef WRITE_NORMAL_BUFFER // If enabled we need all regular interpolator
#include "ShaderPass/LitSharePass.hlsl"
#else
#endif
#include "LitData.hlsl"
#include "../../ShaderPass/ShaderPassDepthOnly.hlsl"

2
com.unity.render-pipelines.high-definition/HDRP/Material/Lit/LitBuiltinData.hlsl


// It is safe to call this function here as surfaceData have been filled
// We want to know if we must enable transmission on GI for SSS material, if the material have no SSS, this code will be remove by the compiler.
BSDFData bsdfData = ConvertSurfaceDataToBSDFData(surfaceData);
BSDFData bsdfData = ConvertSurfaceDataToBSDFData(input.positionSS.xy, surfaceData);
if (HasFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_TRANSMISSION))
{
// For now simply recall the function with inverted normal, the compiler should be able to optimize the lightmap case to not resample the directional lightmap

14
com.unity.render-pipelines.high-definition/HDRP/Material/Lit/LitTessellation.shader


HLSLPROGRAM
// Note: Require _ObjectId and _PassValue variables
#pragma hull Hull
#pragma domain Domain

ZWrite On
ColorMask 0
// In deferred, depth only pass don't output anything.
// In forward it output the normal buffer
#pragma multi_compile _ WRITE_NORMAL_BUFFER
#ifdef WRITE_NORMAL_BUFFER // If enabled we need all regular interpolator
#include "ShaderPass/LitSharePass.hlsl"
#else
#endif
#include "LitData.hlsl"
#include "../../ShaderPass/ShaderPassDepthOnly.hlsl"

2
com.unity.render-pipelines.high-definition/HDRP/Material/Lit/ShaderPass/LitDepthPass.hlsl


#endif
// This include will define the various Attributes/Varyings structure
#include "../../ShaderPass/VaryingMesh.hlsl"
#include "HDRP/ShaderPass/VaryingMesh.hlsl"

2
com.unity.render-pipelines.high-definition/HDRP/Material/Lit/ShaderPass/LitDistortionPass.hlsl


#endif
// This include will define the various Attributes/Varyings structure
#include "../../ShaderPass/VaryingMesh.hlsl"
#include "HDRP/ShaderPass/VaryingMesh.hlsl"

2
com.unity.render-pipelines.high-definition/HDRP/Material/Lit/ShaderPass/LitSharePass.hlsl


#endif
// This include will define the various Attributes/Varyings structure
#include "../../ShaderPass/VaryingMesh.hlsl"
#include "HDRP/ShaderPass/VaryingMesh.hlsl"

2
com.unity.render-pipelines.high-definition/HDRP/Material/Lit/ShaderPass/LitVelocityPass.hlsl


#endif
// This include will define the various Attributes/Varyings structure
#include "../../ShaderPass/VaryingMesh.hlsl"
#include "HDRP/ShaderPass/VaryingMesh.hlsl"

2
com.unity.render-pipelines.high-definition/HDRP/Material/StackLit/ShaderPass/StackLitDepthPass.hlsl


#endif //..._ALPHATEST_ON
// This include will define the various Attributes/Varyings structure
#include "../../ShaderPass/VaryingMesh.hlsl"
#include "HDRP/ShaderPass/VaryingMesh.hlsl"

2
com.unity.render-pipelines.high-definition/HDRP/Material/StackLit/ShaderPass/StackLitDistortionPass.hlsl


#define VARYINGS_NEED_TEXCOORD0
// This include will define the various Attributes/Varyings structure
#include "../../ShaderPass/VaryingMesh.hlsl"
#include "HDRP/ShaderPass/VaryingMesh.hlsl"

2
com.unity.render-pipelines.high-definition/HDRP/Material/StackLit/ShaderPass/StackLitSharePass.hlsl


#endif
// This include will define the various Attributes/Varyings structure
#include "../../ShaderPass/VaryingMesh.hlsl"
#include "HDRP/ShaderPass/VaryingMesh.hlsl"

38
com.unity.render-pipelines.high-definition/HDRP/Material/StackLit/StackLit.hlsl


// SurfaceData is defined in StackLit.cs which generates StackLit.cs.hlsl
#include "StackLit.cs.hlsl"
#include "../SubsurfaceScattering/SubsurfaceScattering.hlsl"
#include "../NormalBuffer.hlsl"
//#include "CoreRP/ShaderLibrary/VolumeRendering.hlsl"
//NEWLITTODO : wireup CBUFFERs for ambientocclusion, and other uniforms and samplers used:

//-----------------------------------------------------------------------------
// Definition
//-----------------------------------------------------------------------------
// Required for SSS
#define GBufferType0 float4
// Needed for MATERIAL_FEATURE_MASK_FLAGS.
#include "../../Lighting/LightLoop/LightLoop.cs.hlsl"

return sssData;
}
NormalData ConvertSurfaceDataToNormalData(SurfaceData surfaceData)
{
NormalData normalData;
// When using clear cloat we want to use the coat normal for the various deferred effect
// as it is the most dominant one
if (HasFeatureFlag(surfaceData.materialFeatures, MATERIALFEATUREFLAGS_STACK_LIT_COAT))
{
normalData.normalWS = surfaceData.coatNormalWS;
normalData.perceptualRoughness = surfaceData.coatPerceptualSmoothness;
}
else
{
normalData.normalWS = surfaceData.normalWS;
// Do average mix in case of dual lobe
normalData.perceptualRoughness = PerceptualSmoothnessToPerceptualRoughness(lerp(surfaceData.perceptualSmoothnessA, surfaceData.perceptualSmoothnessB, surfaceData.lobeMix));
}
return normalData;
}
BSDFData ConvertSurfaceDataToBSDFData(SurfaceData surfaceData)
BSDFData ConvertSurfaceDataToBSDFData(uint2 positionSS, SurfaceData surfaceData)
{
BSDFData bsdfData;
ZERO_INITIALIZE(BSDFData, bsdfData);

//if (_DebugLightingSubMode != DEBUGSCREENSPACETRACING_COLOR)
// diffuseLighting = lighting.indirect.specularReflected;
break;
case DEBUGLIGHTINGMODE_VISUALIZE_SHADOW_MASKS:
#ifdef SHADOWS_SHADOWMASK
diffuseLighting = float3(
bakeLightingData.bakeShadowMask.r / 2 + bakeLightingData.bakeShadowMask.g / 2,
bakeLightingData.bakeShadowMask.g / 2 + bakeLightingData.bakeShadowMask.b / 2,
bakeLightingData.bakeShadowMask.b / 2 + bakeLightingData.bakeShadowMask.a / 2
);
specularLighting = float3(0, 0, 0);
#endif
break ;
}
}
else if (_DebugMipMapMode != DEBUGMIPMAPMODE_NONE)

27
com.unity.render-pipelines.high-definition/HDRP/Material/StackLit/StackLit.shader


// This tags allow to use the shader replacement features
Tags{ "RenderPipeline" = "HDRenderPipeline" "RenderType" = "HDStackLitShader" }
// Caution: The outline selection in the editor use the vertex shader/hull/domain shader of the first pass declare. So it should not be the meta pass.
Pass
{
Name "SceneSelectionPass" // Name is not used
Tags { "LightMode" = "SceneSelectionPass" }
Cull Off
HLSLPROGRAM
// Note: Require _ObjectId and _PassValue variables
// We reuse depth prepass for the scene selection, allow to handle alpha correctly as well as tessellation and vertex animation
#define SHADERPASS SHADERPASS_DEPTH_ONLY
#define SCENESELECTIONPASS // This will drive the output of the scene selection shader
#include "../../ShaderVariables.hlsl"
#include "../../Material/Material.hlsl"
#include "ShaderPass/StackLitDepthPass.hlsl"
#include "StackLitData.hlsl"
#include "../../ShaderPass/ShaderPassDepthOnly.hlsl"
ENDHLSL
}
Pass
{

HLSLPROGRAM
#define WRITE_NORMAL_BUFFER
#include "ShaderPass/StackLitDepthPass.hlsl"
// As we enabled WRITE_NORMAL_BUFFER we need all regular interpolator
#include "ShaderPass/StackLitSharePass.hlsl"
#include "StackLitData.hlsl"
#include "../../ShaderPass/ShaderPassDepthOnly.hlsl"

2
com.unity.render-pipelines.high-definition/HDRP/Material/StackLit/StackLitData.hlsl


// It is safe to call this function here as surfaceData have been filled
// We want to know if we must enable transmission on GI for SSS material, if the material have no SSS, this code will be remove by the compiler.
BSDFData bsdfData = ConvertSurfaceDataToBSDFData(surfaceData);
BSDFData bsdfData = ConvertSurfaceDataToBSDFData(input.positionSS.xy, surfaceData);
if (HasFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_STACK_LIT_TRANSMISSION))
{
// For now simply recall the function with inverted normal, the compiler should be able to optimize the lightmap case to not resample the directional lightmap

4
com.unity.render-pipelines.high-definition/HDRP/Material/StackLit/StackLitProperties.hlsl


// TODO: Fix the code in legacy unity so we can customize the behavior for GI
float3 _EmissionColor;
// Following two variables are feeded by the C++ Editor for Scene selection
int _ObjectId;
int _PassValue;
CBUFFER_END

4
com.unity.render-pipelines.high-definition/HDRP/Material/SubsurfaceScattering/SubsurfaceScattering.hlsl


uint diffusionProfile;
};
#define SSSBufferType0 float4
#define SSSBufferType0 float4 // Must match GBufferType0 in deferred
// SSSBuffer texture declaration
TEXTURE2D(_SSSBufferTexture0);

}
// OUTPUT_SSSBUFFER start from SV_Target2 as SV_Target0 and SV_Target1 are used for lighting buffer
#define OUTPUT_SSSBUFFER(NAME) out GBufferType0 MERGE_NAME(NAME, 0) : SV_Target2
#define OUTPUT_SSSBUFFER(NAME) out SSSBufferType0 MERGE_NAME(NAME, 0) : SV_Target2
#define ENCODE_INTO_SSSBUFFER(SURFACE_DATA, UNPOSITIONSS, NAME) EncodeIntoSSSBuffer(ConvertSurfaceDataToSSSData(SURFACE_DATA), UNPOSITIONSS, MERGE_NAME(NAME, 0))
#define DECODE_FROM_SSSBUFFER(UNPOSITIONSS, SSS_DATA) DecodeFromSSSBuffer(UNPOSITIONSS, SSS_DATA)

2
com.unity.render-pipelines.high-definition/HDRP/Material/Unlit/ShaderPass/UnlitDepthPass.hlsl


#endif
// This include will define the various Attributes/Varyings structure
#include "../../ShaderPass/VaryingMesh.hlsl"
#include "HDRP/ShaderPass/VaryingMesh.hlsl"

2
com.unity.render-pipelines.high-definition/HDRP/Material/Unlit/ShaderPass/UnlitDistortionPass.hlsl


#define VARYINGS_NEED_TEXCOORD0
// This include will define the various Attributes/Varyings structure
#include "../../ShaderPass/VaryingMesh.hlsl"
#include "HDRP/ShaderPass/VaryingMesh.hlsl"

2
com.unity.render-pipelines.high-definition/HDRP/Material/Unlit/ShaderPass/UnlitSharePass.hlsl


#define VARYINGS_NEED_TEXCOORD0
// This include will define the various Attributes/Varyings structure
#include "../../ShaderPass/VaryingMesh.hlsl"
#include "HDRP/ShaderPass/VaryingMesh.hlsl"

2
com.unity.render-pipelines.high-definition/HDRP/Material/Unlit/Unlit.hlsl


// conversion function for forward
//-----------------------------------------------------------------------------
BSDFData ConvertSurfaceDataToBSDFData(SurfaceData data)
BSDFData ConvertSurfaceDataToBSDFData(uint2 positionSS, SurfaceData data)
{
BSDFData output;
output.color = data.color;

4
com.unity.render-pipelines.high-definition/HDRP/Material/Unlit/Unlit.shader


HLSLPROGRAM
// Note: Require _ObjectId and _PassValue variables
#define SHADERPASS SHADERPASS_DEPTH_ONLY
#define SCENESELECTIONPASS // This will drive the output of the scene selection shader
#include "../../Material/Material.hlsl"

Cull[_CullMode]
ZWrite On
ColorMask 0 // We don't have WRITE_NORMAL_BUFFER for unlit, but as we bind a buffer we shouldn't write into it.
HLSLPROGRAM

106
com.unity.render-pipelines.high-definition/HDRP/RenderPipeline/HDRenderPipeline.cs


readonly GBufferManager m_GbufferManager;
readonly DBufferManager m_DbufferManager;
readonly SubsurfaceScatteringManager m_SSSBufferManager = new SubsurfaceScatteringManager();
readonly NormalBufferManager m_NormalBufferManager = new NormalBufferManager();
// Renderer Bake configuration can vary depends on if shadow mask is enabled or no
RendererConfiguration m_currentRendererConfigurationBakedLighting = HDUtils.k_RendererConfigurationBakedLighting;

m_DbufferManager = new DBufferManager();
m_SSSBufferManager.Build(asset);
m_NormalBufferManager.Build(asset);
// Initialize various compute shader resources
m_applyDistortionKernel = m_applyDistortionCS.FindKernel("KMain");

m_DbufferManager.CreateBuffers();
m_SSSBufferManager.InitSSSBuffers(m_GbufferManager, m_Asset.renderPipelineSettings);
m_NormalBufferManager.InitNormalBuffers(m_GbufferManager, m_Asset.renderPipelineSettings);
m_CameraColorBuffer = RTHandles.Alloc(Vector2.one, filterMode: FilterMode.Point, colorFormat: RenderTextureFormat.ARGBHalf, sRGB: false, enableRandomWrite: true, enableMSAA: true, name: "CameraColor");
m_CameraSssDiffuseLightingBuffer = RTHandles.Alloc(Vector2.one, filterMode: FilterMode.Point, colorFormat: RenderTextureFormat.RGB111110Float, sRGB: false, enableRandomWrite: true, enableMSAA: true, name: "CameraSSSDiffuseLighting");

CoreUtils.Destroy(m_ErrorMaterial);
m_SSSBufferManager.Cleanup();
m_NormalBufferManager.Cleanup();
m_SkyManager.Cleanup();
m_VolumetricLightingSystem.Cleanup();
m_IBLFilterGGX.Cleanup();

m_ReflectionProbeCullResults.Cull();
m_DbufferManager.vsibleDecalCount = 0;
m_DbufferManager.EnableDBUffer = false;
m_DbufferManager.vsibleDecalCount = DecalSystem.m_DecalsVisibleThisFrame;
m_DbufferManager.EnableDBUffer = true; // mesh decals are renderers managed by c++ runtime and we have no way to query if any are visible, so set to true
DecalSystem.instance.UpdateCachedMaterialData(); // textures, alpha or fade distances could've changed
DecalSystem.instance.CreateDrawData(); // prepare data is separate from draw
DecalSystem.instance.UpdateTextureAtlas(cmd); // as this is only used for transparent pass, would've been nice not to have to do this if no transparent renderers are visible, needs to happen after CreateDrawData

ClearBuffers(hdCamera, cmd);
// TODO: Add stereo occlusion mask
bool forcePrepassForDecals = m_DbufferManager.vsibleDecalCount > 0;
RenderDepthPrepass(m_CullResults, hdCamera, renderContext, cmd, forcePrepassForDecals);
RenderDepthPrepass(m_CullResults, hdCamera, renderContext, cmd, m_DbufferManager.EnableDBUffer);
RenderDBuffer(hdCamera, cmd);
RenderDBuffer(hdCamera, cmd, renderContext, m_CullResults);
// We can now bind the normal buffer to be use by any effect
m_NormalBufferManager.BindNormalBuffers(cmd);
// In both forward and deferred, everything opaque should have been rendered at this point so we can safely copy the depth buffer for later processing.
CopyDepthBufferIfNeeded(cmd);
RenderDepthPyramid(hdCamera, cmd, renderContext, FullScreenDebugMode.DepthPyramid);

// by using the pass "ForwardOnly". In this case the .shader should not have "Forward" but only a "ForwardOnly" pass.
// It must also have a "DepthForwardOnly" and no "DepthOnly" pass as forward material (either deferred or forward only rendering) have always a depth pass.
// If a forward material have no depth prepass, then lighting can be incorrect (deferred sahdowing, SSAO), this may be acceptable depends on usage
bool addFullDepthPrepass = forcePrepass || hdCamera.frameSettings.enableForwardRenderingOnly || hdCamera.frameSettings.enableDepthPrepassWithDeferredRendering;
// Whatever the configuration we always render first the opaque object as opaque alpha tested are more costly to render and could be reject by early-z
// (but not Hi-z as it is disable with clip instruction). This is handled automatically with the RenderQueue value (OpaqueAlphaTested have a different value and thus are sorted after Opaque)
using (new ProfilingSample(cmd, !addFullDepthPrepass ? "Depth Prepass alpha test" : "Depth Prepass", CustomSamplerId.DepthPrepass.GetSampler()))
// Forward material always output normal buffer (unless they don't participate to shading)
// Deferred material never output normal buffer
// Note: Unlit object use a ForwardOnly pass and don't have normal, they will write 0 in the normal buffer. This should be safe
// as they will not use the result of lighting anyway. However take care of effect that will try to filter normal buffer.
// TODO: maybe we can use a stencil to tag when Forward unlit touch normal buffer
if (hdCamera.frameSettings.enableForwardRenderingOnly)
HDUtils.SetRenderTarget(cmd, hdCamera, m_CameraDepthStencilBuffer);
if (addFullDepthPrepass) // Always true in case of forward rendering, use in case of deferred rendering if requesting a full depth prepass
using (new ProfilingSample(cmd, "Depth Prepass (forward)", CustomSamplerId.DepthPrepass.GetSampler()))
// We render first the opaque object as opaque alpha tested are more costly to render and could be reject by early-z (but not Hi-z as it is disable with clip instruction)
// This is handled automatically with the RenderQueue value (OpaqueAlphaTested have a different value and thus are sorted after Opaque)
cmd.EnableShaderKeyword("WRITE_NORMAL_BUFFER");
HDUtils.SetRenderTarget(cmd, hdCamera, m_NormalBufferManager.GetBuffersRTI(), m_CameraDepthStencilBuffer);
// Full forward: Output normal buffer for both forward and forwardOnly
else // Deferred rendering with partial depth prepass
}
else if (hdCamera.frameSettings.enableDepthPrepassWithDeferredRendering || forcePrepass)
{
using (new ProfilingSample(cmd, "Depth Prepass (deferred)", CustomSamplerId.DepthPrepass.GetSampler()))
// We always do a DepthForwardOnly pass with all the opaque (including alpha test)
cmd.DisableShaderKeyword("WRITE_NORMAL_BUFFER"); // Note: This only disable the output of normal buffer for Lit shader, not the other shader that don't use multicompile
HDUtils.SetRenderTarget(cmd, hdCamera, m_CameraDepthStencilBuffer);
// First deferred material
RenderOpaqueRenderList(cull, hdCamera, renderContext, cmd, m_DepthOnlyPassNames, 0, HDRenderQueue.k_RenderQueue_AllOpaque);
HDUtils.SetRenderTarget(cmd, hdCamera, m_NormalBufferManager.GetBuffersRTI(), m_CameraDepthStencilBuffer);
// Then forward only material that output normal buffer
}
}
else // Deferred with partial depth prepass
{
using (new ProfilingSample(cmd, "Depth Prepass (deferred incomplete)", CustomSamplerId.DepthPrepass.GetSampler()))
{
cmd.DisableShaderKeyword("WRITE_NORMAL_BUFFER");
HDUtils.SetRenderTarget(cmd, hdCamera, m_CameraDepthStencilBuffer);
// Alpha tested materials always have a prepass.
// First deferred alpha tested materials. Alpha tested object have always a prepass even if enableDepthPrepassWithDeferredRendering is disabled
HDUtils.SetRenderTarget(cmd, hdCamera, m_NormalBufferManager.GetBuffersRTI(), m_CameraDepthStencilBuffer);
// Then forward only material that output normal buffer
RenderOpaqueRenderList(cull, hdCamera, renderContext, cmd, m_DepthForwardOnlyPassNames, 0, HDRenderQueue.k_RenderQueue_AllOpaque);
}
}

}
}
void RenderDBuffer(HDCamera hdCamera, CommandBuffer cmd)
void RenderDBuffer(HDCamera hdCamera, CommandBuffer cmd, ScriptableRenderContext renderContext, CullResults cullResults)
{
if (!hdCamera.frameSettings.enableDBuffer)
return;

m_DbufferManager.ClearTargets(cmd, hdCamera);
HDUtils.SetRenderTarget(cmd, hdCamera, m_DbufferManager.GetBuffersRTI(), m_CameraDepthStencilBuffer); // do not clear anymore
m_DbufferManager.SetHTile(m_DbufferManager.bufferCount, cmd);
renderContext.ExecuteCommandBuffer(cmd);
cmd.Clear();
DrawRendererSettings drawSettings = new DrawRendererSettings(hdCamera.camera, HDShaderPassNames.s_EmptyName)
{
rendererConfiguration = 0,
sorting = { flags = SortFlags.CommonOpaque }
};
drawSettings.SetShaderPassName(0, HDShaderPassNames.s_MeshDecalsName);
FilterRenderersSettings filterRenderersSettings = new FilterRenderersSettings(true)
{
renderQueueRange = HDRenderQueue.k_RenderQueue_AllOpaque
};
renderContext.DrawRenderers(cullResults.visibleRenderers, ref drawSettings, filterRenderersSettings);
DecalSystem.instance.RenderIntoDBuffer(cmd);
m_DbufferManager.UnSetHTile(cmd);
m_DbufferManager.SetHTileTexture(cmd); // mask per 8x8 tile used for optimization when looking up dbuffer values

// In case of forward SSS we will bind all the required target. It is up to the shader to write into it or not.
if (hdCamera.frameSettings.enableSubsurfaceScattering)
{
RenderTargetIdentifier[] m_MRTWithSSS =
new RenderTargetIdentifier[2 + m_SSSBufferManager.sssBufferCount];
RenderTargetIdentifier[] m_MRTWithSSS = new RenderTargetIdentifier[2 + m_SSSBufferManager.sssBufferCount];
m_MRTWithSSS[0] = m_CameraColorBuffer; // Store the specular color
m_MRTWithSSS[1] = m_CameraSssDiffuseLightingBuffer;
for (int i = 0; i < m_SSSBufferManager.sssBufferCount; ++i)

else
{
HDUtils.SetRenderTarget(cmd, hdCamera, m_CameraColorBuffer, m_CameraDepthStencilBuffer);
if ((hdCamera.frameSettings.enableDBuffer) && (DecalSystem.m_DecalsVisibleThisFrame > 0)) // enable d-buffer flag value is being interpreted more like enable decals in general now that we have clustered
if ((hdCamera.frameSettings.enableDBuffer) && (DecalSystem.m_DecalDatasCount > 0)) // enable d-buffer flag value is being interpreted more like enable decals in general now that we have clustered
// decal datas count is 0 if no decals affect transparency
{
DecalSystem.instance.SetAtlas(cmd); // for clustered decals
}

public void PushColorPickerDebugTexture(CommandBuffer cmd, RTHandleSystem.RTHandle textureID, HDCamera hdCamera)
{
if (m_CurrentDebugDisplaySettings.colorPickerDebugSettings.colorPickerMode != ColorPickerDebugMode.None)
if (m_CurrentDebugDisplaySettings.colorPickerDebugSettings.colorPickerMode != ColorPickerDebugMode.None || m_DebugDisplaySettings.falseColorDebugSettings.falseColor)
{
using (new ProfilingSample(cmd, "Push To Color Picker"))
{

// TODO TEMP: Not sure I want to keep this special case. Gotta see how to get rid of it (not sure it will work correctly for non-full viewports.
public void PushColorPickerDebugTexture(HDCamera hdCamera, CommandBuffer cmd, RenderTargetIdentifier textureID)
{
if (m_CurrentDebugDisplaySettings.colorPickerDebugSettings.colorPickerMode != ColorPickerDebugMode.None)
if (m_CurrentDebugDisplaySettings.colorPickerDebugSettings.colorPickerMode != ColorPickerDebugMode.None || m_DebugDisplaySettings.falseColorDebugSettings.falseColor)
{
using (new ProfilingSample(cmd, "Push To Color Picker"))
{

DecalSystem.instance.RenderDebugOverlay(hdCamera, cmd, m_CurrentDebugDisplaySettings, ref x, ref y, overlaySize, hdCamera.actualWidth);
if (m_CurrentDebugDisplaySettings.colorPickerDebugSettings.colorPickerMode != ColorPickerDebugMode.None)
if (m_CurrentDebugDisplaySettings.colorPickerDebugSettings.colorPickerMode != ColorPickerDebugMode.None || m_CurrentDebugDisplaySettings.falseColorDebugSettings.falseColor)
FalseColorDebugSettings falseColorDebugSettings = m_CurrentDebugDisplaySettings.falseColorDebugSettings;
var falseColorThresholds = new Vector4(falseColorDebugSettings.colorThreshold0, falseColorDebugSettings.colorThreshold1, falseColorDebugSettings.colorThreshold2, falseColorDebugSettings.colorThreshold3);
// Here we have three cases:
// - Material debug is enabled, this is the buffer we display

cmd.SetGlobalTexture(HDShaderIDs._DebugColorPickerTexture, m_DebugColorPickerBuffer); // No SetTexture with RenderTarget identifier... so use SetGlobalTexture
// TODO: Replace with command buffer call when available
m_DebugColorPicker.SetColor(HDShaderIDs._ColorPickerFontColor, colorPickerDebugSettings.fontColor);
var colorPickerParam = new Vector4(colorPickerDebugSettings.colorThreshold0, colorPickerDebugSettings.colorThreshold1, colorPickerDebugSettings.colorThreshold2, colorPickerDebugSettings.colorThreshold3);
m_DebugColorPicker.SetVector(HDShaderIDs._ColorPickerParam, colorPickerParam);
m_DebugColorPicker.SetInt(HDShaderIDs._FalseColorEnabled, falseColorDebugSettings.falseColor ? 1 : 0);
m_DebugColorPicker.SetVector(HDShaderIDs._FalseColorThresholds, falseColorThresholds);
// The material display debug perform sRGBToLinear conversion as the final blit currently hardcode a linearToSrgb conversion. As when we read with color picker this is not done,
// we perform it inside the color picker shader. But we shouldn't do it for HDR buffer.
m_DebugColorPicker.SetFloat(HDShaderIDs._ApplyLinearToSRGB, m_CurrentDebugDisplaySettings.IsDebugMaterialDisplayEnabled() ? 1.0f : 0.0f);

13
com.unity.render-pipelines.high-definition/HDRP/RenderPipeline/HDStringConstants.cs


public static readonly string s_TransparentDepthPostpassStr = "TransparentDepthPostpass";
public static readonly string s_MetaStr = "Meta";
public static readonly string s_ShadowCasterStr = "ShadowCaster";
public static readonly string s_MeshDecalsStr = "DBufferMesh";
// ShaderPass name
public static readonly ShaderPassName s_EmptyName = new ShaderPassName(s_EmptyStr);

public static readonly ShaderPassName s_TransparentDepthPrepassName = new ShaderPassName(s_TransparentDepthPrepassStr);
public static readonly ShaderPassName s_TransparentBackfaceName = new ShaderPassName(s_TransparentBackfaceStr);
public static readonly ShaderPassName s_TransparentDepthPostpassName = new ShaderPassName(s_TransparentDepthPostpassStr);
public static readonly ShaderPassName s_MeshDecalsName = new ShaderPassName(s_MeshDecalsStr);
// Legacy name
public static readonly ShaderPassName s_AlwaysName = new ShaderPassName("Always");

Shader.PropertyToID("_SSSBufferTexture3"),
};
public static readonly int[] _NormalBufferTexture =
{
Shader.PropertyToID("_NormalBufferTexture0"),
Shader.PropertyToID("_NormalBufferTexture1"),
Shader.PropertyToID("_NormalBufferTexture2"),
Shader.PropertyToID("_NormalBufferTexture3"),
};
public static readonly int _SSRefractionRayMarchBehindObjects = Shader.PropertyToID("_SSRefractionRayMarchBehindObjects");
public static readonly int _SSRefractionRayMaxScreenDistance = Shader.PropertyToID("_SSRefractionRayMaxScreenDistance");
public static readonly int _SSRefractionRayBlendScreenDistance = Shader.PropertyToID("_SSRefractionRayBlendScreenDistance");

public static readonly int _DepthPyramidScale = Shader.PropertyToID("_DepthPyramidScale");
public static readonly int _DebugColorPickerTexture = Shader.PropertyToID("_DebugColorPickerTexture");
public static readonly int _ColorPickerParam = Shader.PropertyToID("_ColorPickerParam");
public static readonly int _FalseColorEnabled = Shader.PropertyToID("_FalseColor");
public static readonly int _FalseColorThresholds = Shader.PropertyToID("_FalseColorThresholds");
public static readonly int _DebugFullScreenTexture = Shader.PropertyToID("_DebugFullScreenTexture");
public static readonly int _BlitTexture = Shader.PropertyToID("_BlitTexture");

1
com.unity.render-pipelines.high-definition/HDRP/RenderPipeline/Settings/RenderPipelineSettings.cs


public bool supportOnlyForward = false;
public bool enableUltraQualitySSS = false;
public bool supportVolumetric = true;
public bool supportRuntimeDebugDisplay = true;
// Engine
public bool supportDBuffer = false;

10
com.unity.render-pipelines.high-definition/HDRP/RenderPipelineResources/CameraMotionVectors.shader


#pragma target 4.5
#include "CoreRP/ShaderLibrary/Common.hlsl"
#include "../ShaderVariables.hlsl"
#include "../ShaderPass/FragInputs.hlsl"
#include "../ShaderPass/VaryingMesh.hlsl"
#include "../ShaderPass/VertMesh.hlsl"
#include "../Material/Builtin/BuiltinData.hlsl"
#include "HDRP/ShaderVariables.hlsl"
#include "HDRP/ShaderPass/FragInputs.hlsl"
#include "HDRP/ShaderPass/VaryingMesh.hlsl"
#include "HDRP/ShaderPass/VertMesh.hlsl"
#include "HDRP/Material/Builtin/BuiltinData.hlsl"
struct Attributes
{

3
com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPass.cs


SubsurfaceScattering,
VolumeVoxelization,
VolumetricLighting,
DBuffer
DbufferProjector,
DbufferMesh
}
}

3
com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPass.cs.hlsl


#define SHADERPASS_SUBSURFACE_SCATTERING (9)
#define SHADERPASS_VOLUME_VOXELIZATION (10)
#define SHADERPASS_VOLUMETRIC_LIGHTING (11)
#define SHADERPASS_DBUFFER (12)
#define SHADERPASS_DBUFFER_PROJECTOR (12)
#define SHADERPASS_DBUFFER_MESH (13)
#endif

30
com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassDBuffer.hlsl


#if SHADERPASS != SHADERPASS_DBUFFER
#if (SHADERPASS != SHADERPASS_DBUFFER_PROJECTOR) && (SHADERPASS != SHADERPASS_DBUFFER_MESH)
#error SHADERPASS_is_not_correctly_define
#endif

)
{
FragInputs input = UnpackVaryingsMeshToFragInputs(packedInput.vmesh);
float depth = LOAD_TEXTURE2D(_CameraDepthTexture, input.positionSS.xy).x;
PositionInputs posInput = GetPositionInput(input.positionSS.xy, _ScreenSize.zw, depth, UNITY_MATRIX_I_VP, UNITY_MATRIX_V);
DecalSurfaceData surfaceData;
#if (SHADERPASS == SHADERPASS_DBUFFER_PROJECTOR)
float depth = LOAD_TEXTURE2D(_CameraDepthTexture, input.positionSS.xy).x;
PositionInputs posInput = GetPositionInput(input.positionSS.xy, _ScreenSize.zw, depth, UNITY_MATRIX_I_VP, UNITY_MATRIX_V);
// Transform from world space to decal space (DS) to clip the decal.
// For this we must use absolute position.
// There is no lose of precision here as it doesn't involve the camera matrix

clip(positionDS); // clip negative value
clip(1.0 - positionDS); // Clip value above one
DecalSurfaceData surfaceData;
// have to do explicit test since compiler behavior is not defined for RW resources and discard instructions
if ((all(positionDS.xyz > 0.0f) && all(1.0f - positionDS.xyz > 0.0f)))
{
// have to do explicit test since compiler behavior is not defined for RW resources and discard instructions
if((all(positionDS.xyz > 0.0f) && all(1.0f - positionDS.xyz > 0.0f)))
{
uint oldVal = UnpackByte(_DecalHTile[posInput.positionSS.xy / 8]);
#elif (SHADERPASS == SHADERPASS_DBUFFER_MESH)
GetSurfaceData(input, surfaceData);
#endif
uint oldVal = UnpackByte(_DecalHTile[input.positionSS.xy / 8]);
_DecalHTile[posInput.positionSS.xy / 8] = PackByte(oldVal);
_DecalHTile[input.positionSS.xy / 8] = PackByte(oldVal);
#if (SHADERPASS == SHADERPASS_DBUFFER_PROJECTOR)
#endif
ENCODE_INTO_DBUFFER(surfaceData, outDBuffer);
}

15
com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassDepthOnly.hlsl


#endif // TESSELLATION_ON
void Frag( PackedVaryingsToPS packedInput,
#ifdef WRITE_NORMAL_BUFFER
OUTPUT_NORMALBUFFER(outNormalBuffer)
#else
#endif
#ifdef _DEPTHOFFSET_ON
, out float outputDepth : SV_Depth
#endif

BuiltinData builtinData;
GetSurfaceAndBuiltinData(input, V, posInput, surfaceData, builtinData);
// TODO: handle cubemap shadow
outColor = float4(0.0, 0.0, 0.0, 0.0);
#ifdef WRITE_NORMAL_BUFFER
ENCODE_INTO_NORMALBUFFER(surfaceData, posInput.positionSS, outNormalBuffer);
#elif defined(SCENESELECTIONPASS)
#ifdef SCENESELECTIONPASS
outColor = float4(_ObjectId, _PassValue, 1, 1);
outColor = float4(_ObjectId, _PassValue, 1.0, 1.0);
#else
outColor = float4(0.0, 0.0, 0.0, 0.0);
#endif
}

2
com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassForward.hlsl


ApplyDebugToSurfaceData(input.worldToTangent, surfaceData);
#endif
BSDFData bsdfData = ConvertSurfaceDataToBSDFData(surfaceData);
BSDFData bsdfData = ConvertSurfaceDataToBSDFData(input.positionSS.xy, surfaceData);
PreLightData preLightData = GetPreLightData(V, posInput, bsdfData);

2
com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassForwardUnlit.hlsl


GetSurfaceAndBuiltinData(input, V, posInput, surfaceData, builtinData);
// Not lit here (but emissive is allowed)
BSDFData bsdfData = ConvertSurfaceDataToBSDFData(surfaceData);
BSDFData bsdfData = ConvertSurfaceDataToBSDFData(input.positionSS.xy, surfaceData);
// TODO: we must not access bsdfData here, it break the genericity of the code!
float4 outColor = ApplyBlendMode(bsdfData.color + builtinData.emissiveColor, builtinData.opacity);

2
com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassGBuffer.hlsl


ApplyDebugToSurfaceData(input.worldToTangent, surfaceData);
#endif
BSDFData bsdfData = ConvertSurfaceDataToBSDFData(surfaceData);
BSDFData bsdfData = ConvertSurfaceDataToBSDFData(input.positionSS.xy, surfaceData);
PreLightData preLightData = GetPreLightData(V, posInput, bsdfData);

2
com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassLightTransport.hlsl


// no debug apply during light transport pass
BSDFData bsdfData = ConvertSurfaceDataToBSDFData(surfaceData);
BSDFData bsdfData = ConvertSurfaceDataToBSDFData(input.positionSS.xy, surfaceData);
LightTransportData lightTransportData = GetLightTransportData(surfaceData, builtinData, bsdfData);
// This shader is call two times. Once for getting emissiveColor, the other time to get diffuseColor

12
com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassVelocity.hlsl


else
{
bool hasDeformation = unity_MotionVectorsParams.x > 0.0; // Skin or morph target
//Need to apply any vertex animation to the previous worldspace position, if we want it to show up in the velocity buffer
// Need to apply any vertex animation to the previous worldspace position, if we want it to show up in the velocity buffer
#if defined(HAVE_MESH_MODIFICATION)
AttributesMesh previousMesh = inputMesh;
if (hasDeformation)
previousMesh.positionOS = inputPass.previousPositionOS;
previousMesh = ApplyMeshModification(previousMesh);
float3 previousPositionWS = mul(unity_MatrixPreviousM, float4(previousMesh.positionOS, 1.0)).xyz;
#else
#endif
#ifdef ATTRIBUTES_NEED_NORMAL
float3 normalWS = TransformPreviousObjectToWorldNormal(inputMesh.normalOS);
#else

4
com.unity.render-pipelines.high-definition/HDRP/ShaderPass/VertMesh.hlsl


// TODO: Here we will also have all the vertex deformation (GPU skinning, vertex animation, morph target...) or we will need to generate a compute shaders instead (better! but require work to deal with unpacking like fp16)
VaryingsMeshType VertMesh(AttributesMesh input)
{
#if defined(HAVE_MESH_MODIFICATION)
input = ApplyMeshModification(input);
#endif
VaryingsMeshType output;
UNITY_SETUP_INSTANCE_ID(input);

165
com.unity.render-pipelines.lightweight/CHANGELOG.md


# Changelog
All notable changes to this package will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
## [Unreleased]
### Fixed
- Occlusion strength not being applied on LW standard shaders
- CopyDepth pass is being called even when a depth from prepass is available
- GLES2 shader compiler error in IntegrationTests
- Can't set RenderScale and ShadowDistance by script
## [2.0.1-preview]
### Fixed
- VR Single Pass Instancing shadows
## [2.0.0-preview]
### Added
- Explicit render target load/store actions were added to improve tile utilization
- Camera opaque color can be requested on the pipeline asset. It can be accessed in the shader by defining a _CameraOpaqueTexture. This can be used as an alternative to GrabPass.
- Dynamic Batching can be enabled in the pipeline asset
- Pipeline now strips unused or invalid variants and passes based on selected pipeline capabilities in the asset. This reduces build and memory consuption on target.
- Shader stripping settings were added to pipeline asset
### Changed
#### Pipeline
- Pipeline code is now more modular and extensible. A ForwardRenderer class is initialized by the pipeline with RenderingData and it's responsible for enqueueing and executing passes. In the future pluggable renderers will be supported.
- On mobile 1 directional light + up to 4 local lights (point or spot) are computed
- On other platforms 1 directional light + up to 8 local lights are computed
- Multiple shadow casting lights are supported. Currently only 1 directional + 4 spots light shadows.
#### Shading Framework
- Directional Lights are always considered a main light in shader. They have a fast shading path with no branching and no indexing.
- GetMainLight() is provided in shader to initialize Light struct with main light shading data.
- Directional lights have a dedicated shadowmap for performance reasons. Shadow coord always comes from interpolator.
- MainLigthRealtimeShadowAttenuation(float4 shadowCoord) is provided to compute main light realtime shadows.
- Spot and Point lights are always shaded in the light loop. Branching on uniform and indexing happens when shading them.
- GetLight(half index, float3 positionWS) is provided in shader to initialize Light struct for spot and point lights.
- Spot light shadows are baked into a single shadow atlas.
- Shadow coord for spot lights is always computed on fragment.
- Use LocalLightShadowAttenuation(int lightIndex, float3 positionWS) to comppute realtime shadows for spot lights.
### Fixed
- Issue that was causing VR on Android to render black
- Camera viewport issues
- UWP build issues
- Prevent nested camera rendering in the pipeline
### Improvements
### Added
### Bugfixes
- Fixed SRP Shader library issue that was causing all constants to be highp in mobile
- Fixed shader error that prevented LWRP to build to UWP
- Fixed shader compilation errors in Linux due to case sensitive includes
- Fixed Rendering Texture flipping issue
- Fixed Standard Particles shader cutout and blending modes
- Fixed crash caused by using projectors
- Fixed issue that was causing Shadow Strength to not be computed on mobile
- Fixed Material Upgrader issue that caused editor to SoftLocks
- Fixed GI in Unlit shader
- Fixed null reference in the Unlit material shader GUI
### Fixed
- SRP Shader library issue that was causing all constants to be highp in mobile
- shader error that prevented LWRP to build to UWP
- shader compilation errors in Linux due to case sensitive includes
- Rendering Texture flipping issue
- Standard Particles shader cutout and blending modes
- crash caused by using projectors
- issue that was causing Shadow Strength to not be computed on mobile
- Material Upgrader issue that caused editor to SoftLocks
- GI in Unlit shader
- Null reference in the Unlit material shader GUI
### Improvements
### Changed
### Bugfixes
- Fixed shadows on GLES 2.0
- Fixed CPU performance regression in shadow rendering
- Fixed alpha clip shadow issues
- Fixed unmatched command buffer error message
- Fixed null reference exception caused by missing resource in LWRP
- Fixed issue that was causing Camera clear flags was being ignored in mobile
### Fixed
- Shadows on GLES 2.0
- CPU performance regression in shadow rendering
- Alpha clip shadow issues
- Unmatched command buffer error message
- Null reference exception caused by missing resource in LWRP
- Issue that was causing Camera clear flags was being ignored in mobile
### Improvements
### Added
- Shadowmap uses 16bit format instead of 32bit.
### Changed
- Shadowmap uses 16bit format instead of 32bit.
### Bugfixes
- Fixed Subtractive Mode
### Fixed
- Subtractive Mode
### Improvements
- Refactored lightweight standard shaders and shader library to improve ease of use.
### Added
- HDR RT now uses what format is configured in Tier settings.
- Optimized tile LOAD op on mobile.
### Changed
- HDR RT now uses what format is configured in Tier settings.
- Refactored lightweight standard shaders and shader library to improve ease of use.
- Optimized tile LOAD op on mobile.
### Bugfixes
- Fixed realtime shadows on OpenGL
- Fixed shader compiler errors in GLES 2.0
- Fixed issue sorting issues when BeforeTransparent custom fx was enabled.
- Fixed VR single pass rendering.
- Fixed viewport rendering issues when rendering to backbuffer.
- Fixed viewport rendering issues when rendering to with MSAA turned off.
- Fixed multi-camera rendering.
### Fixed
- Realtime shadows on OpenGL
- Shader compiler errors in GLES 2.0
- Issue sorting issues when BeforeTransparent custom fx was enabled.
- VR single pass rendering.
- Viewport rendering issues when rendering to backbuffer.
- Viewport rendering issues when rendering to with MSAA turned off.
- Multi-camera rendering.
### Improvements
- Shaders ported to the new SRP shader library.
- Constant Buffer Refactor to use new Batcher
### Added
- UI Improvements (Rendering features not supported by LW are hidden)
### Changed
- Shaders were ported to the new SRP shader library.
- Constant Buffer refactor to use new Batcher
- UI Improvements (Rendering features not supported by LW are hidden)
### Bugfixes
### Fixed
### Improvements
- Realtime shadow filtering was improved.
### Added
### Bugfixes
### Changed
- Realtime shadow filtering was improved.
### Fixed

2
com.unity.render-pipelines.lightweight/LWRP/Data/LightweightPipelineAsset.cs


public float renderScale
{
get { return m_RenderScale; }
set { m_RenderScale = value; }
}
public bool supportsDynamicBatching

public float shadowDistance
{
get { return m_ShadowDistance; }
set { m_ShadowDistance = value; }
}
public int cascadeCount

58
com.unity.render-pipelines.lightweight/LWRP/Editor/LightweightLightEditor.cs


[CustomEditorForRenderPipeline(typeof(Light), typeof(LightweightPipelineAsset))]
class LightweightLightEditor : LightEditor
{
AnimBool m_AnimShowSpotOptions = new AnimBool();
AnimBool m_AnimShowPointOptions = new AnimBool();
AnimBool m_AnimShowDirOptions = new AnimBool();
AnimBool m_AnimShowAreaOptions = new AnimBool();
AnimBool m_AnimShowRuntimeOptions = new AnimBool();
AnimBool m_AnimShowShadowOptions = new AnimBool();
AnimBool m_AnimBakedShadowAngleOptions = new AnimBool();
AnimBool m_AnimBakedShadowRadiusOptions = new AnimBool();
AnimBool m_AnimShowLightBounceIntensity = new AnimBool();
AnimBool m_AnimSpotOptions = new AnimBool();
AnimBool m_AnimPointOptions = new AnimBool();
AnimBool m_AnimDirOptions = new AnimBool();
AnimBool m_AnimAreaOptions = new AnimBool();
AnimBool m_AnimRuntimeOptions = new AnimBool();
AnimBool m_AnimShadowOptions = new AnimBool();
AnimBool m_AnimShadowAngleOptions = new AnimBool();
AnimBool m_AnimShadowRadiusOptions = new AnimBool();
AnimBool m_AnimLightBounceIntensity = new AnimBool();
class Styles
{

// When we are switching between two light types that don't show the range (directional and area lights)
// we want the fade group to stay hidden.
using (var group = new EditorGUILayout.FadeGroupScope(1.0f - m_AnimShowDirOptions.faded))
using (var group = new EditorGUILayout.FadeGroupScope(1.0f - m_AnimDirOptions.faded))
settings.DrawRange(m_AnimShowAreaOptions.target);
settings.DrawRange(m_AnimAreaOptions.target);
using (var group = new EditorGUILayout.FadeGroupScope(m_AnimShowSpotOptions.faded))
using (var group = new EditorGUILayout.FadeGroupScope(m_AnimSpotOptions.faded))
using (var group = new EditorGUILayout.FadeGroupScope(m_AnimShowAreaOptions.faded))
using (var group = new EditorGUILayout.FadeGroupScope(m_AnimAreaOptions.faded))
if (group.visible)
settings.DrawArea();

using (var group = new EditorGUILayout.FadeGroupScope(1.0f - m_AnimShowAreaOptions.faded))
using (var group = new EditorGUILayout.FadeGroupScope(1.0f - m_AnimAreaOptions.faded))
using (var group = new EditorGUILayout.FadeGroupScope(m_AnimShowLightBounceIntensity.faded))
using (var group = new EditorGUILayout.FadeGroupScope(m_AnimLightBounceIntensity.faded))
if (group.visible)
settings.DrawBounceIntensity();

void UpdateShowOptions(bool initialize)
{
SetOptions(m_AnimShowSpotOptions, initialize, spotOptionsValue);
SetOptions(m_AnimShowPointOptions, initialize, pointOptionsValue);
SetOptions(m_AnimShowDirOptions, initialize, dirOptionsValue);
SetOptions(m_AnimShowAreaOptions, initialize, areaOptionsValue);
SetOptions(m_AnimShowShadowOptions, initialize, shadowOptionsValue);
SetOptions(m_AnimShowRuntimeOptions, initialize, runtimeOptionsValue);
SetOptions(m_AnimBakedShadowAngleOptions, initialize, bakedShadowAngle);
SetOptions(m_AnimBakedShadowRadiusOptions, initialize, bakedShadowRadius);
SetOptions(m_AnimShowLightBounceIntensity, initialize, showLightBounceIntensity);
SetOptions(m_AnimSpotOptions, initialize, spotOptionsValue);
SetOptions(m_AnimPointOptions, initialize, pointOptionsValue);
SetOptions(m_AnimDirOptions, initialize, dirOptionsValue);
SetOptions(m_AnimAreaOptions, initialize, areaOptionsValue);
SetOptions(m_AnimShadowOptions, initialize, shadowOptionsValue);
SetOptions(m_AnimRuntimeOptions, initialize, runtimeOptionsValue);
SetOptions(m_AnimShadowAngleOptions, initialize, bakedShadowAngle);
SetOptions(m_AnimShadowRadiusOptions, initialize, bakedShadowRadius);
SetOptions(m_AnimLightBounceIntensity, initialize, showLightBounceIntensity);
}
void DrawSpotAngle()

void ShadowsGUI()
{
// Shadows drop-down. Area lights can only be baked and always have shadows.
float show = 1.0f - m_AnimShowAreaOptions.faded;
float show = 1.0f - m_AnimAreaOptions.faded;
show *= m_AnimShowShadowOptions.faded;
show *= m_AnimShadowOptions.faded;
using (var group = new EditorGUILayout.FadeGroupScope(show * m_AnimBakedShadowRadiusOptions.faded))
using (var group = new EditorGUILayout.FadeGroupScope(show * m_AnimShadowRadiusOptions.faded))
using (var group = new EditorGUILayout.FadeGroupScope(show * m_AnimBakedShadowAngleOptions.faded))
using (var group = new EditorGUILayout.FadeGroupScope(show * m_AnimShadowAngleOptions.faded))
using (var group = new EditorGUILayout.FadeGroupScope(show * m_AnimShowRuntimeOptions.faded))
using (var group = new EditorGUILayout.FadeGroupScope(show * m_AnimRuntimeOptions.faded))
if (group.visible)
settings.DrawRuntimeShadow();
EditorGUI.indentLevel -= 1;

16
com.unity.render-pipelines.lightweight/LWRP/Editor/ShaderGraph/LightWeightPBRSubShader.cs


// Get Slot and Node lists per stage
var vertexSlots = pass.VertexShaderSlots.Select(masterNode.FindSlot<MaterialSlot>).ToList();
var vertexNodes = ListPool<AbstractMaterialNode>.Get();
var vertexNodes = ListPool<INode>.Get();
NodeUtils.DepthFirstCollectNodesFromNode(vertexNodes, masterNode, NodeUtils.IncludeSelf.Include, pass.VertexShaderSlots);
var pixelSlots = pass.PixelShaderSlots.Select(masterNode.FindSlot<MaterialSlot>).ToList();

if (surfaceRequirements.requiresScreenPosition)
surfaceDescriptionInputStruct.AppendLine("float4 {0};", ShaderGeneratorNames.ScreenPosition);
if (surfaceRequirements.requiresFaceSign)
surfaceDescriptionInputStruct.AppendLine("float {0};", ShaderGeneratorNames.FaceSign);
foreach (var channel in surfaceRequirements.requiresMeshUVs.Distinct())
surfaceDescriptionInputStruct.AppendLine("half4 {0};", channel.GetUVName());
}

pixelShaderSurfaceRemap.AppendLine("{0} = surf.{0};", slot.shaderOutputName);
}
// -------------------------------------
// Extra pixel shader work
var faceSign = new ShaderStringBuilder();
if (pixelRequirements.requiresFaceSign)
faceSign.AppendLine(", half FaceSign : VFACE");
// ----------------------------------------------------- //
// FINALIZE //
// ----------------------------------------------------- //

resultPass = resultPass.Replace("${VertexShaderDescriptionInputs}", vertexShaderDescriptionInputs.ToString());
resultPass = resultPass.Replace("${VertexShaderOutputs}", vertexShaderOutputs.ToString());
resultPass = resultPass.Replace("${FaceSign}", faceSign.ToString());
resultPass = resultPass.Replace("${PixelShader}", pixelShader.ToString());
resultPass = resultPass.Replace("${PixelShaderSurfaceInputs}", pixelShaderSurfaceInputs.ToString());
resultPass = resultPass.Replace("${PixelShaderSurfaceRemap}", pixelShaderSurfaceRemap.ToString());

// Get Slot and Node lists per stage
var vertexSlots = pass.VertexShaderSlots.Select(masterNode.FindSlot<MaterialSlot>).ToList();
var vertexNodes = ListPool<AbstractMaterialNode>.Get();
var vertexNodes = ListPool<INode>.Get();
NodeUtils.DepthFirstCollectNodesFromNode(vertexNodes, masterNode, NodeUtils.IncludeSelf.Include, pass.VertexShaderSlots);
// -------------------------------------

16
com.unity.render-pipelines.lightweight/LWRP/Editor/ShaderGraph/LightWeightUnlitSubShader.cs


// Get Slot and Node lists per stage
var vertexSlots = pass.VertexShaderSlots.Select(masterNode.FindSlot<MaterialSlot>).ToList();
var vertexNodes = ListPool<AbstractMaterialNode>.Get();
var vertexNodes = ListPool<INode>.Get();
NodeUtils.DepthFirstCollectNodesFromNode(vertexNodes, masterNode, NodeUtils.IncludeSelf.Include, pass.VertexShaderSlots);
var pixelSlots = pass.PixelShaderSlots.Select(masterNode.FindSlot<MaterialSlot>).ToList();

if (surfaceRequirements.requiresScreenPosition)
surfaceDescriptionInputStruct.AppendLine("float4 {0};", ShaderGeneratorNames.ScreenPosition);
if (surfaceRequirements.requiresFaceSign)
surfaceDescriptionInputStruct.AppendLine("float {0};", ShaderGeneratorNames.FaceSign);
foreach (var channel in surfaceRequirements.requiresMeshUVs.Distinct())
surfaceDescriptionInputStruct.AppendLine("half4 {0};", channel.GetUVName());
}

pixelShaderSurfaceRemap.AppendLine("{0} = surf.{0};", slot.shaderOutputName);
}
// -------------------------------------
// Extra pixel shader work
var faceSign = new ShaderStringBuilder();
if (pixelRequirements.requiresFaceSign)
faceSign.AppendLine(", half FaceSign : VFACE");
// ----------------------------------------------------- //
// FINALIZE //
// ----------------------------------------------------- //

resultPass = resultPass.Replace("${VertexShaderDescriptionInputs}", vertexShaderDescriptionInputs.ToString());
resultPass = resultPass.Replace("${VertexShaderOutputs}", vertexShaderOutputs.ToString());
resultPass = resultPass.Replace("${FaceSign}", faceSign.ToString());
resultPass = resultPass.Replace("${PixelShader}", pixelShader.ToString());
resultPass = resultPass.Replace("${PixelShaderSurfaceInputs}", pixelShaderSurfaceInputs.ToString());
resultPass = resultPass.Replace("${PixelShaderSurfaceRemap}", pixelShaderSurfaceRemap.ToString());

// Get Slot and Node lists per stage
var vertexSlots = pass.VertexShaderSlots.Select(masterNode.FindSlot<MaterialSlot>).ToList();
var vertexNodes = ListPool<AbstractMaterialNode>.Get();
var vertexNodes = ListPool<INode>.Get();
NodeUtils.DepthFirstCollectNodesFromNode(vertexNodes, masterNode, NodeUtils.IncludeSelf.Include, pass.VertexShaderSlots);
// -------------------------------------

14
com.unity.render-pipelines.lightweight/LWRP/Editor/ShaderGraph/lightweightPBRExtraPasses.template


{
float2 uv : TEXCOORD0;
float4 clipPos : SV_POSITION;
UNITY_VERTEX_INPUT_INSTANCE_ID
UNITY_VERTEX_OUTPUT_STEREO
};
// x: global clip space bias, y: normal world space bias

{
VertexOutput o;
UNITY_SETUP_INSTANCE_ID(v);
UNITY_TRANSFER_INSTANCE_ID(v, o);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
// Vertex transformations performed by graph
${VertexShader}

return o;
}
half4 ShadowPassFragment() : SV_TARGET
half4 ShadowPassFragment(VertexOutput IN) : SV_TARGET
UNITY_SETUP_INSTANCE_ID(IN);
return 0;
}

{
float2 uv : TEXCOORD0;
float4 clipPos : SV_POSITION;
UNITY_VERTEX_INPUT_INSTANCE_ID
UNITY_VERTEX_OUTPUT_STEREO
};
VertexOutput vert(GraphVertexInput v)

UNITY_TRANSFER_INSTANCE_ID(v, o);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
// Vertex transformations performed by graph
${VertexShader}

return o;
}
half4 frag() : SV_TARGET
half4 frag(VertexOutput IN) : SV_TARGET
UNITY_SETUP_INSTANCE_ID(IN);
return 0;
}
ENDHLSL

13
com.unity.render-pipelines.lightweight/LWRP/Editor/ShaderGraph/lightweightPBRForwardPass.template


// Interpolators defined by graph
${VertexOutputStruct}
UNITY_VERTEX_INPUT_INSTANCE_ID
UNITY_VERTEX_OUTPUT_STEREO
GraphVertexOutput o = (GraphVertexOutput)0;
UNITY_SETUP_INSTANCE_ID(v);
UNITY_TRANSFER_INSTANCE_ID(v, o);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
// Vertex transformations performed by graph
${VertexShader}
VertexDescriptionInputs vdi = (VertexDescriptionInputs)0;

VertexDescription vd = PopulateVertexData(vdi);
v.vertex.xyz = vd.Position;
GraphVertexOutput o = (GraphVertexOutput)0;
UNITY_SETUP_INSTANCE_ID(v);
UNITY_TRANSFER_INSTANCE_ID(v, o);
// Vertex shader outputs defined by graph
${VertexShaderOutputs}

return o;
}
half4 frag (GraphVertexOutput IN) : SV_Target
half4 frag (GraphVertexOutput IN ${FaceSign}) : SV_Target
{
UNITY_SETUP_INSTANCE_ID(IN);

14
com.unity.render-pipelines.lightweight/LWRP/Editor/ShaderGraph/lightweightUnlitExtraPasses.template


{
float2 uv : TEXCOORD0;
float4 clipPos : SV_POSITION;
UNITY_VERTEX_INPUT_INSTANCE_ID
UNITY_VERTEX_OUTPUT_STEREO
};
// x: global clip space bias, y: normal world space bias

{
VertexOutput o;
UNITY_SETUP_INSTANCE_ID(v);
UNITY_TRANSFER_INSTANCE_ID(v, o);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
// Vertex transformations performed by graph
${VertexShader}

return o;
}
half4 ShadowPassFragment() : SV_TARGET
half4 ShadowPassFragment(VertexOutput IN) : SV_TARGET
UNITY_SETUP_INSTANCE_ID(IN);
return 0;
}

{
float2 uv : TEXCOORD0;
float4 clipPos : SV_POSITION;
UNITY_VERTEX_INPUT_INSTANCE_ID
UNITY_VERTEX_OUTPUT_STEREO
};
VertexOutput vert(GraphVertexInput v)

UNITY_TRANSFER_INSTANCE_ID(v, o);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
// Vertex transformations performed by graph
${VertexShader}

return o;
}
half4 frag() : SV_TARGET
half4 frag(VertexOutput IN) : SV_TARGET
UNITY_SETUP_INSTANCE_ID(IN);
return 0;
}
ENDHLSL

13
com.unity.render-pipelines.lightweight/LWRP/Editor/ShaderGraph/lightweightUnlitPass.template


// Interpolators defined by graph
${VertexOutputStruct}
UNITY_VERTEX_INPUT_INSTANCE_ID
UNITY_VERTEX_OUTPUT_STEREO
GraphVertexOutput o = (GraphVertexOutput)0;
UNITY_SETUP_INSTANCE_ID(v);
UNITY_TRANSFER_INSTANCE_ID(v, o);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
// Vertex transformations performed by graph
${VertexShader}
VertexDescriptionInputs vdi = (VertexDescriptionInputs)0;

VertexDescription vd = PopulateVertexData(vdi);
v.vertex.xyz = vd.Position;
GraphVertexOutput o = (GraphVertexOutput)0;
UNITY_SETUP_INSTANCE_ID(v);
UNITY_TRANSFER_INSTANCE_ID(v, o);
o.position = TransformObjectToHClip(v.vertex.xyz);
// Vertex shader outputs defined by graph

half4 frag (GraphVertexOutput IN) : SV_Target
half4 frag (GraphVertexOutput IN ${FaceSign}) : SV_Target
{
UNITY_SETUP_INSTANCE_ID(IN);

38
com.unity.render-pipelines.lightweight/LWRP/Editor/ShaderPreprocessor.cs


namespace UnityEditor.Experimental.Rendering.LightweightPipeline
{
public static class LightweightKeyword
{
public static readonly ShaderKeyword AdditionalLights = new ShaderKeyword(LightweightKeywordStrings.AdditionalLights);
public static readonly ShaderKeyword VertexLights = new ShaderKeyword(LightweightKeywordStrings.VertexLights);
public static readonly ShaderKeyword MixedLightingSubtractive = new ShaderKeyword(LightweightKeywordStrings.MixedLightingSubtractive);
public static readonly ShaderKeyword MainLightCookie = new ShaderKeyword(LightweightKeywordStrings.MainLightCookie);
public static readonly ShaderKeyword DirectionalShadows = new ShaderKeyword(LightweightKeywordStrings.DirectionalShadows);
public static readonly ShaderKeyword LocalShadows = new ShaderKeyword(LightweightKeywordStrings.LocalShadows);
public static readonly ShaderKeyword SoftShadows = new ShaderKeyword(LightweightKeywordStrings.SoftShadows);
public static readonly ShaderKeyword Lightmap = new ShaderKeyword("LIGHTMAP_ON");
public static readonly ShaderKeyword DirectionalLightmap = new ShaderKeyword("DIRLIGHTMAP_COMBINED");
}
public class ShaderPreprocessor : IPreprocessShaders
{
#if LOG_VARIANTS

bool StripUnusedVariant(PipelineCapabilities capabilities, ShaderCompilerData compilerData)
{
if (compilerData.shaderKeywordSet.IsEnabled(LightweightKeywords.AdditionalLights) &&
if (compilerData.shaderKeywordSet.IsEnabled(LightweightKeyword.AdditionalLights) &&
if (compilerData.shaderKeywordSet.IsEnabled(LightweightKeywords.VertexLights) &&
if (compilerData.shaderKeywordSet.IsEnabled(LightweightKeyword.VertexLights) &&
if (compilerData.shaderKeywordSet.IsEnabled(LightweightKeywords.DirectionalShadows) &&
if (compilerData.shaderKeywordSet.IsEnabled(LightweightKeyword.DirectionalShadows) &&
if (compilerData.shaderKeywordSet.IsEnabled(LightweightKeywords.LocalShadows) &&
if (compilerData.shaderKeywordSet.IsEnabled(LightweightKeyword.LocalShadows) &&
if (compilerData.shaderKeywordSet.IsEnabled(LightweightKeywords.SoftShadows) &&
if (compilerData.shaderKeywordSet.IsEnabled(LightweightKeyword.SoftShadows) &&
!CoreUtils.HasFlag(capabilities, PipelineCapabilities.SoftShadows))
return true;

bool StripInvalidVariants(ShaderCompilerData compilerData)
{
bool isShadowVariant = compilerData.shaderKeywordSet.IsEnabled(LightweightKeywords.DirectionalShadows) ||
compilerData.shaderKeywordSet.IsEnabled(LightweightKeywords.LocalShadows);
bool isShadowVariant = compilerData.shaderKeywordSet.IsEnabled(LightweightKeyword.DirectionalShadows) ||
compilerData.shaderKeywordSet.IsEnabled(LightweightKeyword.LocalShadows);
if (compilerData.shaderKeywordSet.IsEnabled(LightweightKeywords.SoftShadows) && !isShadowVariant)
if (compilerData.shaderKeywordSet.IsEnabled(LightweightKeyword.SoftShadows) && !isShadowVariant)
if (compilerData.shaderKeywordSet.IsEnabled(LightweightKeywords.VertexLights) &&
!compilerData.shaderKeywordSet.IsEnabled(LightweightKeywords.AdditionalLights))
if (compilerData.shaderKeywordSet.IsEnabled(LightweightKeyword.VertexLights) &&
!compilerData.shaderKeywordSet.IsEnabled(LightweightKeyword.AdditionalLights))
if (compilerData.shaderKeywordSet.IsEnabled(LightweightKeywords.DirectionalLightmap) &&
!compilerData.shaderKeywordSet.IsEnabled(LightweightKeywords.Lightmap))
if (compilerData.shaderKeywordSet.IsEnabled(LightweightKeyword.DirectionalLightmap) &&
!compilerData.shaderKeywordSet.IsEnabled(LightweightKeyword.Lightmap))
return true;
return false;

30
com.unity.render-pipelines.lightweight/LWRP/LightweightForwardRenderer.cs


SetupPerObjectLightIndices(ref cullResults, ref renderingData.lightData);
RenderTextureDescriptor baseDescriptor = CreateRTDesc(ref renderingData.cameraData);
RenderTextureDescriptor shadowDescriptor = baseDescriptor;
shadowDescriptor.dimension = TextureDimension.Tex2D;
bool requiresCameraDepth = renderingData.cameraData.requiresDepthTexture;
bool requiresDepthPrepass = renderingData.shadowData.requiresScreenSpaceShadowResolve ||

if (renderingData.shadowData.renderDirectionalShadows)
{
EnqueuePass(cmd, RenderPassHandles.DirectionalShadows, baseDescriptor);
EnqueuePass(cmd, RenderPassHandles.DirectionalShadows, shadowDescriptor);
EnqueuePass(cmd, RenderPassHandles.LocalShadows, baseDescriptor);
EnqueuePass(cmd, RenderPassHandles.LocalShadows, shadowDescriptor);
bool requiresColorAttachment = RequiresColorAttachment(ref renderingData.cameraData, baseDescriptor) || requiresDepthAttachment;
bool requiresColorAttachment = RequiresIntermediateColorTexture(ref renderingData.cameraData, baseDescriptor, requiresDepthAttachment);
int depthHandle = (requiresColorAttachment) ? RenderTargetHandles.DepthAttachment : -1;
int depthHandle = (requiresDepthAttachment) ? RenderTargetHandles.DepthAttachment : -1;
EnqueuePass(cmd, RenderPassHandles.ForwardLit, baseDescriptor, colorHandles, depthHandle, renderingData.cameraData.msaaSamples);
context.ExecuteCommandBuffer(cmd);

// Note: Scene view camera always perform depth prepass
CommandBuffer cmd = CommandBufferPool.Get("Copy Depth to Camera");
CoreUtils.SetRenderTarget(cmd, BuiltinRenderTextureType.CameraTarget);
cmd.EnableShaderKeyword(LightweightKeywords.DepthNoMsaa);
cmd.DisableShaderKeyword(LightweightKeywords.DepthMsaa2);
cmd.DisableShaderKeyword(LightweightKeywords.DepthMsaa4);
cmd.EnableShaderKeyword(LightweightKeywordStrings.DepthNoMsaa);
cmd.DisableShaderKeyword(LightweightKeywordStrings.DepthMsaa2);
cmd.DisableShaderKeyword(LightweightKeywordStrings.DepthMsaa4);
cmd.Blit(GetSurface(RenderTargetHandles.DepthTexture), BuiltinRenderTextureType.CameraTarget, GetMaterial(MaterialHandles.DepthCopy));
context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);

public RenderTargetIdentifier GetSurface(int handle)
{
if (handle == -1)
return BuiltinRenderTextureType.CameraTarget;
if (handle < 0 || !m_ResourceMap.TryGetValue(handle, out renderTargetID))
if (!m_ResourceMap.TryGetValue(handle, out renderTargetID))
{
Debug.LogError(string.Format("Handle {0} has not any surface registered to it.", handle));
return new RenderTargetIdentifier();

m_ActiveRenderPassQueue.Add(pass);
}
bool RequiresColorAttachment(ref CameraData cameraData, RenderTextureDescriptor baseDescriptor)
bool RequiresIntermediateColorTexture(ref CameraData cameraData, RenderTextureDescriptor baseDescriptor, bool requiresCameraDepth)
if (cameraData.isOffscreenRender)
return false;
return cameraData.isSceneViewCamera || isScaledRender || cameraData.isHdrEnabled ||
cameraData.postProcessEnabled || cameraData.requiresOpaqueTexture || isTargetTexture2DArray;
return requiresCameraDepth || cameraData.isSceneViewCamera || isScaledRender || cameraData.isHdrEnabled ||
cameraData.postProcessEnabled || cameraData.requiresOpaqueTexture || isTargetTexture2DArray || !cameraData.isDefaultViewport;
}
bool CanCopyDepth(ref CameraData cameraData)

4
com.unity.render-pipelines.lightweight/LWRP/LightweightPipeline.cs


context.ExecuteCommandBuffer(cmd);
cmd.Clear();
#if UNITY_EDITOR
#endif
{
m_IsCameraRendering = true;
#if UNITY_EDITOR

m_Renderer.Setup(ref context, ref m_CullResults, ref renderingData);
m_Renderer.Execute(ref context, ref m_CullResults, ref renderingData);
}
#if UNITY_EDITOR
catch (Exception)
{
CommandBufferPool.Release(cmd);

#endif
{
m_IsCameraRendering = false;
}

30
com.unity.render-pipelines.lightweight/LWRP/LightweightPipelineCore.cs


using System.Collections.Generic;
using UnityEngine.Rendering;
using UnityEngine.Rendering.PostProcessing;
using UnityEngine.XR;
namespace UnityEngine.Experimental.Rendering.LightweightPipeline
{

}
}
public static class LightweightKeywords
public static class LightweightKeywordStrings
public static readonly string AdditionalLightsText = "_ADDITIONAL_LIGHTS";
public static readonly string VertexLightsText = "_VERTEX_LIGHTS";
public static readonly string MixedLightingSubtractiveText = "_MIXED_LIGHTING_SUBTRACTIVE";
public static readonly string MainLightCookieText = "_MAIN_LIGHT_COOKIE";
public static readonly string DirectionalShadowsText = "_SHADOWS_ENABLED";
public static readonly string LocalShadowsText = "_LOCAL_SHADOWS_ENABLED";
public static readonly string SoftShadowsText = "_SHADOWS_SOFT";
public static readonly string CascadeShadowsText = "_SHADOWS_CASCADE";
public static readonly string AdditionalLights = "_ADDITIONAL_LIGHTS";
public static readonly string VertexLights = "_VERTEX_LIGHTS";
public static readonly string MixedLightingSubtractive = "_MIXED_LIGHTING_SUBTRACTIVE";
public static readonly string MainLightCookie = "_MAIN_LIGHT_COOKIE";
public static readonly string DirectionalShadows = "_SHADOWS_ENABLED";
public static readonly string LocalShadows = "_LOCAL_SHADOWS_ENABLED";
public static readonly string SoftShadows = "_SHADOWS_SOFT";
public static readonly string CascadeShadows = "_SHADOWS_CASCADE";
public static readonly ShaderKeyword AdditionalLights = new ShaderKeyword(AdditionalLightsText);
public static readonly ShaderKeyword VertexLights = new ShaderKeyword(VertexLightsText);
public static readonly ShaderKeyword MixedLightingSubtractive = new ShaderKeyword(MixedLightingSubtractiveText);
public static readonly ShaderKeyword MainLightCookie = new ShaderKeyword(MainLightCookieText);
public static readonly ShaderKeyword DirectionalShadows = new ShaderKeyword(DirectionalShadowsText);
public static readonly ShaderKeyword LocalShadows = new ShaderKeyword(LocalShadowsText);
public static readonly ShaderKeyword SoftShadows = new ShaderKeyword(SoftShadowsText);
public static readonly ShaderKeyword Lightmap = new ShaderKeyword("LIGHTMAP_ON");
public static readonly ShaderKeyword DirectionalLightmap = new ShaderKeyword("DIRLIGHTMAP_COMBINED");
}
public partial class LightweightPipeline

3
com.unity.render-pipelines.lightweight/LWRP/Passes/DepthOnlyPass.cs


{
public class DepthOnlyPass : ScriptableRenderPass
{
const string k_SetupRenderTargetTag = "Setup Render Target";
const string k_DepthPrepassTag = "Depth Prepass";
int kDepthBufferBits = 32;

public override void Execute(ref ScriptableRenderContext context, ref CullResults cullResults, ref RenderingData renderingData)
{
CommandBuffer cmd = CommandBufferPool.Get(k_DepthPrepassTag);
using (new ProfilingSample(cmd, k_SetupRenderTargetTag))
using (new ProfilingSample(cmd, k_DepthPrepassTag))
{
SetRenderTarget(cmd, GetSurface(depthAttachmentHandle), RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store,
ClearFlag.Depth, Color.black);

3
com.unity.render-pipelines.lightweight/LWRP/Passes/DirectionalShadowsPass.cs


ShadowSliceData[] m_CascadeSlices;
Vector4[] m_CascadeSplitDistances;
const string k_SetupRenderTargetTag = "Setup Render Target";
const string k_RenderDirectionalShadowmapTag = "Render Directional Shadowmap";
public DirectionalShadowsPass(LightweightForwardRenderer renderer) : base(renderer)

return;
CommandBuffer cmd = CommandBufferPool.Get(k_RenderDirectionalShadowmapTag);
using (new ProfilingSample(cmd, k_SetupRenderTargetTag))
using (new ProfilingSample(cmd, k_RenderDirectionalShadowmapTag))
{
m_ShadowCasterCascadesCount = shadowData.directionalLightCascadeCount;

49
com.unity.render-pipelines.lightweight/LWRP/Passes/ForwardLitPass.cs


using System.Diagnostics;
using UnityEngine.Experimental.GlobalIllumination;
using UnityEngine.Rendering;
using UnityEngine.Rendering.PostProcessing;
using UnityEngine.XR;
namespace UnityEngine.Experimental.Rendering.LightweightPipeline
{

float[] m_OpaqueScalerValues = {1.0f, 0.5f, 0.25f, 0.25f};
int m_SampleOffsetShaderHandle;
const string k_SetupRenderTargetTag = "Setup Render Target";
const string k_RenderOpaquesTag = "Render Opaques";
const string k_RenderTransparentsTag = "Render Transparents";

{
int vertexLightsCount = lightData.totalAdditionalLightsCount - lightData.pixelAdditionalLightsCount;
CoreUtils.SetKeyword(cmd, LightweightKeywords.AdditionalLightsText, lightData.totalAdditionalLightsCount > 0);
CoreUtils.SetKeyword(cmd, LightweightKeywords.MixedLightingSubtractiveText, m_MixedLightingSetup == MixedLightingSetup.Subtractive);
CoreUtils.SetKeyword(cmd, LightweightKeywords.VertexLightsText, vertexLightsCount > 0);
CoreUtils.SetKeyword(cmd, LightweightKeywordStrings.AdditionalLights, lightData.totalAdditionalLightsCount > 0);
CoreUtils.SetKeyword(cmd, LightweightKeywordStrings.MixedLightingSubtractive, m_MixedLightingSetup == MixedLightingSetup.Subtractive);
CoreUtils.SetKeyword(cmd, LightweightKeywordStrings.VertexLights, vertexLightsCount > 0);
// CoreUtils.SetKeyword(cmd, LightweightKeywords.MainLightCookieText, mainLightIndex != -1 && LightweightUtils.IsSupportedCookieType(visibleLights[mainLightIndex].lightType) && visibleLights[mainLightIndex].light.cookie != null);
// CoreUtils.SetKeyword(cmd, LightweightKeywordStrings.MainLightCookieText, mainLightIndex != -1 && LightweightUtils.IsSupportedCookieType(visibleLights[mainLightIndex].lightType) && visibleLights[mainLightIndex].light.cookie != null);
LightShadows directionalShadowQuality = shadowData.renderedDirectionalShadowQuality;
LightShadows localShadowQuality = shadowData.renderedLocalShadowQuality;

shadowData.supportsSoftShadows;
CoreUtils.SetKeyword(cmd, LightweightKeywords.DirectionalShadowsText, directionalShadowQuality != LightShadows.None);
CoreUtils.SetKeyword(cmd, LightweightKeywords.LocalShadowsText, localShadowQuality != LightShadows.None);
CoreUtils.SetKeyword(cmd, LightweightKeywords.SoftShadowsText, hasSoftShadows);
CoreUtils.SetKeyword(cmd, LightweightKeywordStrings.DirectionalShadows, directionalShadowQuality != LightShadows.None);
CoreUtils.SetKeyword(cmd, LightweightKeywordStrings.LocalShadows, localShadowQuality != LightShadows.None);
CoreUtils.SetKeyword(cmd, LightweightKeywordStrings.SoftShadows, hasSoftShadows);
// TODO: Remove this. legacy particles support will be removed from Unity in 2018.3. This should be a shader_feature instead with prop exposed in the Standard particles shader.
CoreUtils.SetKeyword(cmd, "SOFTPARTICLES_ON", cameraData.requiresSoftParticles);

void RenderOpaques(ref ScriptableRenderContext context, ref CullResults cullResults, ref CameraData cameraData, RendererConfiguration rendererConfiguration, bool dynamicBatching)
{
CommandBuffer cmd = CommandBufferPool.Get(k_RenderOpaquesTag);
using (new ProfilingSample(cmd, k_SetupRenderTargetTag))
using (new ProfilingSample(cmd, k_RenderOpaquesTag))
// If rendering to an intermediate RT we resolve viewport on blit due to offset not being supported
// while rendering to a RT.
if (colorAttachmentHandle == -1 && cameraData.isDefaultViewport)
cmd.SetViewport(camera.pixelRect);
// TODO: We need a proper way to handle multiple camera/ camera stack. Issue is: multiple cameras can share a same RT
// (e.g, split screen games). However devs have to be dilligent with it and know when to clear/preserve color.
// For now we make it consistent by resolving viewport with a RT until we can have a proper camera management system
//if (colorAttachmentHandle == -1 && !cameraData.isDefaultViewport)
// cmd.SetViewport(camera.pixelRect);
context.ExecuteCommandBuffer(cmd);
cmd.Clear();

void RenderTransparents(ref ScriptableRenderContext context, ref CullResults cullResults, ref CameraData cameraData, RendererConfiguration rendererConfiguration, bool dynamicBatching)
{
CommandBuffer cmd = CommandBufferPool.Get(k_RenderTransparentsTag);
using (new ProfilingSample(cmd, k_SetupRenderTargetTag))
using (new ProfilingSample(cmd, k_RenderTransparentsTag))
{
Camera camera = cameraData.camera;
SetRenderTarget(cmd, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store, ClearFlag.None, Color.black);

CommandBuffer cmd = CommandBufferPool.Get("Final Blit Pass");
cmd.SetGlobalTexture("_BlitTex", sourceRT);
// We need to handle viewport on a RT. We do it by rendering a fullscreen quad + viewport
SetRenderTarget(cmd, BuiltinRenderTextureType.CameraTarget, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store, ClearFlag.All, Color.black);
SetRenderTarget(cmd, BuiltinRenderTextureType.CameraTarget, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store, ClearFlag.None, Color.black);
cmd.SetViewProjectionMatrices(Matrix4x4.identity, Matrix4x4.identity);
cmd.SetViewport(cameraData.camera.pixelRect);
LightweightPipeline.DrawFullScreen(cmd, material);

if (cameraData.msaaSamples > 1)
{
cmd.DisableShaderKeyword(LightweightKeywords.DepthNoMsaa);
cmd.DisableShaderKeyword(LightweightKeywordStrings.DepthNoMsaa);
cmd.DisableShaderKeyword(LightweightKeywords.DepthMsaa2);
cmd.EnableShaderKeyword(LightweightKeywords.DepthMsaa4);
cmd.DisableShaderKeyword(LightweightKeywordStrings.DepthMsaa2);
cmd.EnableShaderKeyword(LightweightKeywordStrings.DepthMsaa4);
cmd.EnableShaderKeyword(LightweightKeywords.DepthMsaa2);
cmd.DisableShaderKeyword(LightweightKeywords.DepthMsaa4);
cmd.EnableShaderKeyword(LightweightKeywordStrings.DepthMsaa2);
cmd.DisableShaderKeyword(LightweightKeywordStrings.DepthMsaa4);
cmd.EnableShaderKeyword(LightweightKeywords.DepthNoMsaa);
cmd.DisableShaderKeyword(LightweightKeywords.DepthMsaa2);
cmd.DisableShaderKeyword(LightweightKeywords.DepthMsaa4);
cmd.EnableShaderKeyword(LightweightKeywordStrings.DepthNoMsaa);
cmd.DisableShaderKeyword(LightweightKeywordStrings.DepthMsaa2);
cmd.DisableShaderKeyword(LightweightKeywordStrings.DepthMsaa4);
LightweightPipeline.CopyTexture(cmd, depthSurface, copyDepthSurface, m_DepthCopyMaterial);
}
context.ExecuteCommandBuffer(cmd);

3
com.unity.render-pipelines.lightweight/LWRP/Passes/LocalShadowsPass.cs


ShadowSliceData[] m_LocalLightSlices;
float[] m_LocalShadowStrength;
const string k_SetupRenderTargetTag = "Setup Render Target";
const string k_RenderLocalShadows = "Render Local Shadows";
public LocalShadowsPass(LightweightForwardRenderer renderer) : base(renderer)

int shadowSampling = 0;
CommandBuffer cmd = CommandBufferPool.Get(k_RenderLocalShadows);
using (new ProfilingSample(cmd, k_SetupRenderTargetTag))
using (new ProfilingSample(cmd, k_RenderLocalShadows))
{
// TODO: Add support to point light shadows. We make a simplification here that only works
// for spot lights and with max spot shadows per pass.

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

正在加载...
取消
保存